From 2585fa81a2aad89f874a0e2888e9e18dfd1bc5d9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 24 Nov 2025 22:48:11 +0300 Subject: [PATCH 0001/1406] update; if pio terminal (mon or cli) perviously created, then before re-open, reassign its display name with the new orig-window --- lua/platformio/utils.lua | 14 ++------------ plugin/platformio.lua | 2 +- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 6de993f0..b9b2867f 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -135,6 +135,7 @@ function M.ToggleTerminal(command, direction, resetLSP) if string.find(command, ' monitor') then if prev.mon then -- INFO: if previous monitor terminal already opened ==> reopen + prev.mon.display_name = 'piomon:' .. orig_window local win_type = vim.fn.win_gettype(prev.mon.window) local win_open = win_type == '' or win_type == 'popup' if prev.mon.window and (win_open and vim.api.nvim_win_get_buf(prev.mon.window) == prev.mon.bufnr) then @@ -148,18 +149,7 @@ function M.ToggleTerminal(command, direction, resetLSP) pioOpts.display_name = 'piomon:' .. orig_window else -- INFO: if previous cli terminal already opened ==> reopen if prev.cli then - prev.cli.on_close = function(t) - local ow = tonumber(M.strsplit(t.display_name, ':')[2]) - if ow and vim.api.nvim_win_is_valid(ow) then - vim.api.nvim_set_current_win(ow) - else - vim.api.nvim_set_current_win(0) - end - if resetLSP then - vim.cmd(':PioLSP') - end - end - + prev.cli.display_name = 'piocli:' .. orig_window local win_type = vim.fn.win_gettype(prev.cli.window) local win_open = win_type == '' or win_type == 'popup' if prev.cli.window and (win_open and vim.api.nvim_win_get_buf(prev.cli.window) == prev.cli.bufnr) then diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 35020c1b..5cf86b59 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -123,7 +123,6 @@ vim.api.nvim_create_user_command('PioTermList', function() }, }) telescope.load_extension('ui-select') - local utils = require('platformio.utils') local toggleterm_list = {} local terms = require('toggleterm.terminal').get_all(true) @@ -157,6 +156,7 @@ vim.api.nvim_create_user_command('PioTermList', function() kind = 'PioTerminals', }, function(chosen, _) if chosen then + chosen.term.display_name = chosen.termtype .. ':' .. vim.api.nvim_get_current_win() local win_type = vim.fn.win_gettype(chosen.term.window) local win_open = win_type == '' or win_type == 'popup' if chosen.term.window and (win_open and vim.api.nvim_win_get_buf(chosen.term.window) == chosen.term.bufnr) then From f5dbab2314553a3f995c1278cb29e4d98a337a03 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 19:30:00 +0300 Subject: [PATCH 0002/1406] update --- lua/platformio/init.lua | 138 ++++++++++++++++++++++----------- lua/platformio/lspAttach.lua | 94 ++++++++++++++++++++++ lua/platformio/lspClangd.lua | 142 ++++++++++++++++++++++++++++++++++ lua/platformio/lspKeymaps.lua | 132 +++++++++++++++++++++++++++++++ 4 files changed, 460 insertions(+), 46 deletions(-) create mode 100644 lua/platformio/lspAttach.lua create mode 100644 lua/platformio/lspClangd.lua create mode 100644 lua/platformio/lspKeymaps.lua diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index e1307d5a..221f95df 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -1,10 +1,15 @@ local M = {} M.config = { - lsp = 'ccls', - menu_key = nil, - menu_name = 'PlatformIO', + lspClangd = { + enabled = false, + attach = { + enabled = false, + keymaps = false, + }, + }, + menu_key = '\\', -- replace this menu key to your convenience + menu_name = 'PlatformIO', -- replace this menu name to your convenience debug = false, - clangd_source = 'ccls', menu_bindings = { { node = 'item', desc = '[L]ist terminals', shortcut = 'l', command = 'PioTermList' }, @@ -85,8 +90,6 @@ M.config = { { node = 'item', desc = '[U]pgrade PlatformIO Core', shortcut = 'u', command = 'Piocmdf upgrade' }, }, }, - -- }, -- - -- }, -- }, } @@ -151,53 +154,96 @@ local function validateMenu(menu) return true end +local function flatten(t, parent_key, result) + result = result or {} + for k, v in pairs(t) do + local key = parent_key and (parent_key .. '.' .. k) or k + if type(v) == 'table' then + flatten(v, key, result) + else + result[key] = v + end + end + return result +end + function M.setup(user_config) + -- print(vim.inspect(flatten(user_config))) + -- if vim.fn.has('nvim-0.11') == 1 then + -- vim.validate('config', user_config, 'table') + -- vim.validate('config.layout', user_config.layout, 'table') + -- else + -- vim.validate({ + -- config = { user_config, 'table' }, + -- layout = { user_config.layout, 'table' }, + -- }) + -- end + if next(user_config) ~= nil then - local valid_keys = { - lsp = true, - menu_key = true, - menu_name = true, - menu_bindings = true, - debug = true, - clangd_source = true, - } - local err = false - for key, value in pairs(user_config or {}) do - if not valid_keys[key] then - local error_message = string.format('Invalid PlatformIO settings key-value: %s = "%s"', key, value) - vim.api.nvim_echo({ { error_message, 'ErrorMsg' } }, true, {}) - err = true - end - end - if user_config.lsp and not (user_config.lsp == 'ccls' or user_config.lsp == 'clangd') then - vim.api.nvim_echo( - { { 'Invalid PlatformIO lsp "' .. user_config.lsp .. '", {allowed "clangd" or "ccls"} (default "' .. M.config.lsp .. '" will be used)', 'ErrorMsg' } }, - true, - {} - ) - user_config.lsp = M.config.lsp - end - if user_config.lsp == 'clangd' then - if user_config.clangd_source ~= 'ccls' and user_config.clangd_source ~= 'compiledb' then - vim.api.nvim_echo( - { { 'Invalid clangd source {allowed "ccls" or "compiledb"} (default "' .. M.config.clangd_source .. '" will be used)', 'ErrorMsg' } }, - true, - {} - ) - user_config.clangd_source = M.config.clangd_source + if next(user_config.lspClangd) ~= nil then + vim.validate('lspClangd', user_config.lspClangd.enabled, 'boolean', true) + if user_config.lspClangd.attach then + vim.validate('lspAttach', user_config.lspClangd.attach, 'table', true) + vim.validate('lspAttachEnabled', user_config.lspClangd.attach.enabled, 'boolean', true) + vim.validate('lspKeymaps', user_config.lspClangd.attach.keyMaps, 'boolean', true) end end - if not err then -- if no error, merge user_config to M.config - if user_config.menu_bindings then - if not validateMenu(user_config.menu_bindings) then - user_config.menu_bindings = nil -- if validation error, cancel merging menu_bindings with M.config - -- else - -- print('good validation') - end + vim.validate('menu_key', user_config.lspClangd_enable, 'string', true) + vim.validate('menu_name', user_config.menu_name, 'string', true) + vim.validate('debug', user_config.debug, 'boolean', true) + vim.validate('menu_bindings', user_config.menu_bindings, 'table', true) + -- local valid_keys = { + -- lspClangd_enabled = true, + -- lspAttach_enabled = true, + -- -- lsp = true, + -- menu_key = true, + -- menu_name = true, + -- menu_bindings = true, + -- debug = true, + -- -- clangd_source = true, + -- } + -- local err = false + -- for key, value in pairs(user_config or {}) do + -- if not valid_keys[key] then + -- local error_message = string.format('Invalid PlatformIO settings key-value: %s = "%s"', key, value) + -- vim.api.nvim_echo({ { error_message, 'ErrorMsg' } }, true, {}) + -- err = true + -- end + -- end + -- if user_config.lspClangd_enabled and not (user_config.lspClangd_enabled == false or user_config.lspClangd_enabled == true) then + -- vim.api.nvim_echo( + -- { { 'Invalid PlatformIO lsp "' .. user_config.lspClangd_enabled .. '", {allowed "false" or "true"} (default "disabled" will be used)', 'ErrorMsg' } }, + -- true, + -- {} + -- ) + -- user_config.lspClangd_enabled = M.config.lspClangd_enabled + -- end + -- + -- if user_config.lspAttach_enabled and not (user_config.lspAttach_enabled == false or user_config.lspAttach_enabled == true) then + -- vim.api.nvim_echo( + -- { { 'Invalid PlatformIO lsp "' .. user_config.lspAttach_enabled .. '", {allowed "false" or "true"} (default "disabled" will be used)', 'ErrorMsg' } }, + -- true, + -- {} + -- ) + -- user_config.lspAttach_enabled = M.config.lspAttach_enabled + -- end + + -- if not err then -- if no error, merge user_config to M.config + if user_config.menu_bindings then + if not validateMenu(user_config.menu_bindings) then + user_config.menu_bindings = nil -- if validation error, cancel merging menu_bindings with M.config + -- else + -- print('good validation') end - M.config = vim.tbl_deep_extend('force', M.config, user_config or {}) end + M.config = vim.tbl_deep_extend('force', M.config, user_config or {}) + -- end + end + + if M.config.lspClangd.enabled == true then + vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) + require('platformio.lspClangd') end require('platformio.piomenu').piomenu(M.config) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua new file mode 100644 index 00000000..38a39e6c --- /dev/null +++ b/lua/platformio/lspAttach.lua @@ -0,0 +1,94 @@ +-- INFO: LspAttach autocommand start +vim.api.nvim_create_autocmd('LspAttach', { + group = vim.api.nvim_create_augroup('platformio-lsp-attach', { clear = true }), + --desc = 'LSP actions', + callback = function(args) + local client = assert(vim.lsp.get_client_by_id(args.data.client_id)) + local bufnr = args.buf + + if client then + -- vim.lsp.set_log_level 'trace' + -- print('Attaching to: ' .. client.name .. ' attached to buffer ' .. bufnr) + vim.api.nvim_echo({ { 'Attaching to: ' .. client.name .. ' attached to buffer ' .. bufnr, 'Info' } }, true, {}) + ------------------------------------------------------------------ + if client.name == 'clangd' then + vim.api.nvim_buf_create_user_command(0, 'LspClangdSwitchSourceHeader', function() + local method_name = 'textDocument/switchSourceHeader' + local params = vim.lsp.util.make_text_document_params(bufnr) + client.request(method_name, params, function(err, result) + if err then + error(tostring(err)) + end + if not result then + vim.notify('corresponding file cannot be determined') + return + end + vim.cmd.edit(vim.uri_to_fname(result)) + end, bufnr) + end, { desc = 'Switch between source/header' }) + end + ------------------------------------------------------------------ + --- Skip this if you are using blink + local bok, _ = pcall(require, 'blink') + if not bok then + if client:supports_method('textDocument/completion', { bufnr = bufnr }) then + vim.lsp.completion.enable(true, client.id, args.buf, { autotrigger = true }) + end + vim.diagnostic.config({ + current_line = true, + virtual_lines = { + current_line = true, + }, + }) + vim.cmd([[set completeopt+=noselect]]) + end + + ------------------------------------------------------------------ + if client.server_capabilities.documentHighlightProvider then + local highlight_augroup = vim.api.nvim_create_augroup('kickstart-lsp-highlight', { clear = false }) + vim.api.nvim_create_autocmd({ 'CursorHold', 'CursorHoldI' }, { + buffer = bufnr, + group = highlight_augroup, + callback = vim.lsp.buf.document_highlight, + }) + -- + vim.api.nvim_create_autocmd({ 'CursorMoved', 'CursorMovedI' }, { + buffer = bufnr, + group = highlight_augroup, + callback = vim.lsp.buf.clear_references, + }) + -- + vim.api.nvim_create_autocmd('LspDetach', { + group = vim.api.nvim_create_augroup('kickstart-lsp-detach', { clear = true }), + callback = function(event) + vim.lsp.buf.clear_references() + vim.api.nvim_clear_autocmds({ group = 'kickstart-lsp-highlight', buffer = event.buf }) + end, + }) + -- + end + + -- if lspKeymaps enabled + local config = require('platformio').config + if config.lspClangd.attach.keymaps then + local lspkeymaps = require('platformio.lspkeymaps') + lspkeymaps.lspKeymaps(client, bufnr) + end + end + -- + vim.lsp.handlers['textDocument/publishDiagnostics'] = vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { + signs = true, + underline = true, + virtual_text = { + spacing = 5, + min = vim.diagnostic.severity.HINT, + }, + update_in_insert = true, + }) + -- + vim.cmd([[autocmd FileType * set formatoptions-=ro]]) + -- + end, +}) + +-- --> End LspAttach autocommand diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua new file mode 100644 index 00000000..09aabd5f --- /dev/null +++ b/lua/platformio/lspClangd.lua @@ -0,0 +1,142 @@ +--------------------------------------------------------------------------------- +-- INFO: Mason packages install for lint and formater + +local fok, fidget = pcall(require, 'fidget') +if fok then + fidget.setup({}) +end + +local tok, trouble = pcall(require, 'trouble') +if tok then + trouble.setup({}) +end + +-- mason.setup() +local mason = require('mason') + +mason.setup({ + PATH = 'append', + ui = { + border = 'single', + icons = { + package_installed = '✓', + package_pending = '➜', + package_uninstalled = '✗', + }, + }, +}) +-- List of packages you want Mason to ensure are installed +local ensure_installed = { + -- 'clang-format', +} + +-- Mason function to install or ensure formatters/linters are installed +local mr = require('mason-registry') +mr.refresh(function() + for _, tool in ipairs(ensure_installed) do + local ok, p = pcall(mr.get_package, tool) + if ok and p then + if not p:is_installed() then + if not p:is_installing() then + p:install({}, function(success, _) + if not success then + vim.defer_fn(function() + vim.notify(tool .. ' failed to install', vim.log.levels.ERROR) + end, 0) + end + end) + else + vim.defer_fn(function() + vim.notify(tool .. ' already installed', vim.log.levels.WARN) + end, 0) + end + end + else + vim.defer_fn(function() + vim.notify('Failed to get package: ' .. tool, vim.log.levels.WARN) + end, 0) + end + end +end) + +require('mason-lspconfig').setup({ + ensure_installed = { 'clangd' }, + -- automatic_enable = true, -- this will automatically enable LSP servers after install +}) + +local cmd = { + 'clangd', + '--all-scopes-completion', + '--background-index', + '--clang-tidy', + '--compile_args_from=filesystem', + '--compile-commands-dir=.', -- so this is in default directory (parent of /src) no need for it. + '--enable-config', + '--completion-parse=always', + '--completion-style=detailed', + '--header-insertion=iwyu', + '--header-insertion-decorators', + '-j=12', + '--log=verbose', -- for debugging + -- '--log=error', + '--offset-encoding=utf-8', + '--pch-storage=memory', + '--pretty', + '--query-driver=**', + '--ranking-model=decision_forest', +} + +local path = vim.fn.getcwd() +local fname = string.format('%s\\.clangd_cmd', path) +if vim.fn.filereadable(fname) == 1 then + local ok, result = pcall(vim.fn.readfile, fname) + if ok then + cmd = result + -- print(vim.inspect(cmd)) + end +end + +local capabilities = vim.lsp.protocol.make_client_capabilities() +local bok, _ = pcall(require, 'blink') +if bok then + capabilities = vim.tbl_deep_extend('force', capabilities, require('blink.cmp').get_lsp_capabilities({}, false)) +end +---@type vim.lsp.Config +local clangd = { + cmd = cmd, + filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, + root_markers = { + 'CMakeLists.txt', + '.clangd', + '.clang-tidy', + '.clang-format', + 'compile_commands.json', + 'compile_flags.txt', + 'configure.ac', + '.git', + vim.uv.cwd(), + }, + capabilities = capabilities, + workspace_required = true, + single_file_support = true, + init_options = { + usePlaceholders = true, + completeUnimported = true, + fallback_flags = { '-std=c++17' }, + clangdFileStatus = true, + compilationDatabasePath = vim.fn.getcwd(), + }, +} +vim.lsp.config('clangd', clangd) + +---------------------- +local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') +if mok then + mason_lspconfig.setup({}) +end + +local config = require('platformio').config +if config.lspClangd.attach.enabled then + require('platformio.lspAttach') +end +---------------------------------------------------------------------------------- diff --git a/lua/platformio/lspKeymaps.lua b/lua/platformio/lspKeymaps.lua new file mode 100644 index 00000000..f983781c --- /dev/null +++ b/lua/platformio/lspKeymaps.lua @@ -0,0 +1,132 @@ +local K = {} +--Lua functions in combination with the option expr = true handles keycodes automatically +function K.lspKeymaps(client, bufnr) + local bufkeymap = function(mode, lhs, rhs, desc) + vim.keymap.set(mode, lhs, rhs, { buffer = bufnr, silent = true, desc = desc }) -- noremap by default + end + -- Disable defaults + pcall(vim.keymap.del, 'n', 'gra') + pcall(vim.keymap.del, 'n', 'gri') + pcall(vim.keymap.del, 'n', 'grn') + pcall(vim.keymap.del, 'n', 'grr') + pcall(vim.keymap.del, 'n', 'gO') + pcall(vim.keymap.del, 'n', 'K') + -- + -- Quickfix list + bufkeymap('n', '[q', vim.cmd.cprev, 'Previous quickfix item') + bufkeymap('n', ']q', vim.cmd.cnext, 'Next quickfix item') + + -- Diagnostic keymaps + bufkeymap('n', '[d', 'vim.diagnostic.goto_prev()', 'Go to previous [d]iagnostic message') + bufkeymap('n', ']d', 'vim.diagnostic.goto_next()', 'Go to next [d]iagnostic message') + bufkeymap('n', 'gle', vim.diagnostic.open_float, 'Show diagnostic [e]rror messages') + -- bufkeymap('n', 'gle', 'Telescope diagnostics', 'Show diagnostic [e]rror messages') + bufkeymap('n', 'glq', vim.diagnostic.setloclist, 'Open diagnostic [q]uickfix list') + -- + -- stylua: ignore start + -- << local trouble = require("trouble").toggle + -- << bufkeymap('n', "tt", function() trouble() end, "Toggle Trouble") + -- << bufkeymap('n', "tq", function() trouble("quickfix") end, "Quickfix List") + -- << bufkeymap('n', "dr", function() trouble("lsp_references") end, "References") + -- << bufkeymap('n', "dd", function() trouble("document_diagnostics") end, "Document Diagnostics") + -- << bufkeymap('n', "dw", function() trouble("workspace_diagnostics") end, "Workspace Diagnostics") + -- stylua: ignore end + -- + if client.server_capabilities.hoverProvider then + bufkeymap('n', 'glk', vim.lsp.buf.hover, 'Hover Documentation') + end + if client.server_capabilities.signatureHelpProvider then + bufkeymap({ 'i', 'n' }, 'gls', vim.lsp.buf.signature_help, 'Show signature') + end + if client.server_capabilities.declarationProvider then + bufkeymap('n', 'glD', vim.lsp.buf.declaration, 'Goto [D]eclaration') + end + if client.server_capabilities.definitionProvider then + bufkeymap('n', 'gld', vim.lsp.buf.definition, 'Go to [d]efinition') + -- bufkeymap('n', 'gld', 'Telescope lsp_definitions', '[G]oto [D]efinition') + end + if client.server_capabilities.typeDefinitionProvider then + bufkeymap('n', 'glt', vim.lsp.buf.type_definition, 'Goto [t]ype definition') + -- bufkeymap('n', 'glt', 'Telescope lsp_type_definitions', 'Goto [t]ype definition') + end + if client.server_capabilities.implementationProvider then + bufkeymap('n', 'gli', vim.lsp.buf.implementation, 'Goto [i]mplementation') + -- bufkeymap('n', 'gli', 'Telescope lsp_implementations', 'Goto [i]mplementation') + end + + -- bufkeymap('n', 'glr', '(CodeAction, implementation, rename, references)', 'CodeAction, implementation, rename, references') + if client.server_capabilities.referencesProvider then + -- bufkeymap('n', 'gr', vim.lsp.buf.references, 'List references') + bufkeymap('n', 'glr', 'Telescope lsp_references', 'Goto [r]eferences') + -- bufkeymap('n', 'glr', 'Telescope lsp_references', '[G]oto [R]eferences') + end + if client.server_capabilities.renameProvider then + -- bufkeymap('n', '', vim.lsp.buf.rename, 'Rename symbol') + bufkeymap('n', 'glR', vim.lsp.buf.rename, '[R]ename') + end + if client.server_capabilities.codeActionProvider then + bufkeymap('n', 'gla', vim.lsp.buf.code_action, 'Code [a]ction') + end + + if client.server_capabilities.documentSymbolProvider then + bufkeymap('n', 'glwd', vim.lsp.buf.document_symbol, '[D]ocument symbols') + -- bufkeymap('n', 'glwd', Telescope lsp_document_symbols, '[D]ocument [S]ymbols') + end + if client:supports_method('workspace/symbol') then + -- if client.server_capabilities.workspaceSymbolProvider then + bufkeymap('n', 'glww', vim.lsp.buf.workspace_symbol, 'List [w]orkspace symbols') + -- bufkeymap('n', 'glww', require('telescope.builtin').lsp_dynamic_workspace_symbols, '[W]orkspace [S]ymbols') + end + if client.server_capabilities.workspace then + bufkeymap('n', 'glwa', vim.lsp.buf.add_workspace_folder, 'Workspace [a]dd folder') + bufkeymap('n', 'glwr', vim.lsp.buf.remove_workspace_folder, 'Workspace [r]emove folder') + bufkeymap('n', 'glwl', function() + print(vim.inspect(vim.lsp.buf.list_workspace_folders())) + end, '[W]orkspace [L]ist folders') + end + -- + if client.supports_method('textDocument/switchSourceHeader') then + bufkeymap('n', 'glws', 'LspClangdSwitchSourceHeader', '[S]witch Source/Header (C/C++)') + end + + if client.supports_method('textDocument/formatting') then + -- if client.server_capabilities.documentFormattingProvider then + bufkeymap({ 'n', 'x' }, 'glf', function() + vim.lsp.buf.format({ bufnr = bufnr, async = true }) + -- require('conform').format({ bufnr = bufnr, async = true }) + end, '[f]ormat buffer') + -- -- + -- vim.api.nvim_clear_autocmds({ + -- group = get_augroup(client), + -- buffer = buf_number, + -- }) + -- -- + -- LSP format the current buffer on save + --local fmt_group = vim.api.nvim_create_augroup('autoformat_cmds', { clear = true }) + -- vim.api.nvim_create_autocmd('BufWritePre', { + -- buffer = buf_number, + -- group = get_augroup(client), + -- desc = 'Fromat current buffer', + -- callback = function() + -- vim.lsp.buf.format { + -- bufnr = buf_number, + -- async = false, + -- timeout_ms = 10000, + -- id = client.id, + -- filter = function(c) + -- return c.id == client.id + -- end, + -- } + -- end, + -- }) + end + -- + if client.server_capabilities.inlayHintProvider and vim.lsp.inlay_hint then + bufkeymap('n', 'glh', function() + vim.lsp.inlay_hint.enable(not vim.lsp.inlay_hint.is_enabled({ bufnr = bufnr }), { bufnr = bufnr }) + end, '[h]ints toggle') + ------------------------------------------------------------------------------ + end +end + +return K From ba75f9d5dc5ad49d63d64e3f35499c46ec51e15c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 19:37:06 +0300 Subject: [PATCH 0003/1406] update --- lua/platformio/init.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index 221f95df..152e6dbe 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -181,7 +181,8 @@ function M.setup(user_config) if next(user_config) ~= nil then if next(user_config.lspClangd) ~= nil then - vim.validate('lspClangd', user_config.lspClangd.enabled, 'boolean', true) + vim.validate('lspClangd', user_config.lspClangd, 'table', true) + vim.validate('lspClangdEnabled', user_config.lspClangd.enabled, 'boolean', true) if user_config.lspClangd.attach then vim.validate('lspAttach', user_config.lspClangd.attach, 'table', true) vim.validate('lspAttachEnabled', user_config.lspClangd.attach.enabled, 'boolean', true) From 446e13b007fbb21c9657ada5362c75f1b2a924a8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 20:22:05 +0300 Subject: [PATCH 0004/1406] update --- lua/platformio/init.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index 152e6dbe..3da29a2c 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -179,6 +179,7 @@ function M.setup(user_config) -- }) -- end + print(vim.inspect(user_config)) if next(user_config) ~= nil then if next(user_config.lspClangd) ~= nil then vim.validate('lspClangd', user_config.lspClangd, 'table', true) From 38e49adfe3fe98d287ffd6604dfeb761786b7bef Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 20:30:36 +0300 Subject: [PATCH 0005/1406] update --- lua/platformio/init.lua | 62 ----------------------------------------- 1 file changed, 62 deletions(-) diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index 3da29a2c..5bae43c8 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -154,32 +154,7 @@ local function validateMenu(menu) return true end -local function flatten(t, parent_key, result) - result = result or {} - for k, v in pairs(t) do - local key = parent_key and (parent_key .. '.' .. k) or k - if type(v) == 'table' then - flatten(v, key, result) - else - result[key] = v - end - end - return result -end - function M.setup(user_config) - -- print(vim.inspect(flatten(user_config))) - -- if vim.fn.has('nvim-0.11') == 1 then - -- vim.validate('config', user_config, 'table') - -- vim.validate('config.layout', user_config.layout, 'table') - -- else - -- vim.validate({ - -- config = { user_config, 'table' }, - -- layout = { user_config.layout, 'table' }, - -- }) - -- end - - print(vim.inspect(user_config)) if next(user_config) ~= nil then if next(user_config.lspClangd) ~= nil then vim.validate('lspClangd', user_config.lspClangd, 'table', true) @@ -195,43 +170,7 @@ function M.setup(user_config) vim.validate('menu_name', user_config.menu_name, 'string', true) vim.validate('debug', user_config.debug, 'boolean', true) vim.validate('menu_bindings', user_config.menu_bindings, 'table', true) - -- local valid_keys = { - -- lspClangd_enabled = true, - -- lspAttach_enabled = true, - -- -- lsp = true, - -- menu_key = true, - -- menu_name = true, - -- menu_bindings = true, - -- debug = true, - -- -- clangd_source = true, - -- } - -- local err = false - -- for key, value in pairs(user_config or {}) do - -- if not valid_keys[key] then - -- local error_message = string.format('Invalid PlatformIO settings key-value: %s = "%s"', key, value) - -- vim.api.nvim_echo({ { error_message, 'ErrorMsg' } }, true, {}) - -- err = true - -- end - -- end - -- if user_config.lspClangd_enabled and not (user_config.lspClangd_enabled == false or user_config.lspClangd_enabled == true) then - -- vim.api.nvim_echo( - -- { { 'Invalid PlatformIO lsp "' .. user_config.lspClangd_enabled .. '", {allowed "false" or "true"} (default "disabled" will be used)', 'ErrorMsg' } }, - -- true, - -- {} - -- ) - -- user_config.lspClangd_enabled = M.config.lspClangd_enabled - -- end - -- - -- if user_config.lspAttach_enabled and not (user_config.lspAttach_enabled == false or user_config.lspAttach_enabled == true) then - -- vim.api.nvim_echo( - -- { { 'Invalid PlatformIO lsp "' .. user_config.lspAttach_enabled .. '", {allowed "false" or "true"} (default "disabled" will be used)', 'ErrorMsg' } }, - -- true, - -- {} - -- ) - -- user_config.lspAttach_enabled = M.config.lspAttach_enabled - -- end - -- if not err then -- if no error, merge user_config to M.config if user_config.menu_bindings then if not validateMenu(user_config.menu_bindings) then user_config.menu_bindings = nil -- if validation error, cancel merging menu_bindings with M.config @@ -240,7 +179,6 @@ function M.setup(user_config) end end M.config = vim.tbl_deep_extend('force', M.config, user_config or {}) - -- end end if M.config.lspClangd.enabled == true then From 6a639edbcc65c2ecba5cfa3a543e3bc98adfc1b1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 20:31:18 +0300 Subject: [PATCH 0006/1406] update --- minimal_config.lua | 644 ++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 575 insertions(+), 69 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index f00d500f..cc9d249b 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -1,79 +1,585 @@ --- insures lazy is installed -local lazypath = vim.loop.os_tmpdir() .. '/lazy/lazy.nvim' +-- pick a temp root +local tmp = vim.loop.os_tmpdir() .. "/nvim-temp" + +vim.env.XDG_DATA_HOME = tmp .. "/data" +vim.env.XDG_CACHE_HOME = tmp .. "/cache" +vim.env.XDG_STATE_HOME = tmp .. "/state" + +-- disable netrw at the very start of your init.lua +vim.g.loaded_netrw = 1 +vim.g.loaded_netrwPlugin = 1 + +-- optionally enable 24-bit colour +vim.opt.termguicolors = true + +vim.opt["number"] = true +vim.opt.tabstop = 2 -- Number of spaces tabs count for +vim.opt.softtabstop = 2 +vim.opt.shiftround = true -- Round indent +vim.opt.shiftwidth = 2 -- Size of an indent +vim.opt.smartindent = true -- Insert indents automatically +vim.opt.expandtab = true -- Use spaces instead of tabs + +vim.g.have_nerd_font = true +vim.g.mapleader = " " +vim.g.maplocalleader = " " + +vim.keymap.set("n", "e", "NvimTreeToggle", { desc = "NvimTreeToggle" }) +vim.keymap.set("n", "\\", "NvimTreeToggle", { desc = "NvimTreeToggle" }) + +-- Keybinds to make split navigation easier. +-- Use CTRL+ to switch between windows +vim.keymap.set("n", "", "", { desc = "Move focus to the left window" }) +vim.keymap.set("n", "", "", { desc = "Move focus to the right window" }) +vim.keymap.set("n", "", "", { desc = "Move focus to the lower window" }) +vim.keymap.set("n", "", "", { desc = "Move focus to the upper window" }) +---------------------------------------------------------------------------------------- + +local lazypath = vim.env.XDG_DATA_HOME .. "/lazy/lazy.nvim" + if not (vim.uv or vim.loop).fs_stat(lazypath) then - vim.fn.system({ - 'git', - 'clone', - '--filter=blob:none', - 'https://github.com/folke/lazy.nvim.git', - '--branch=stable', -- latest stable release - lazypath, - }) + vim.fn.system({ + "git", + "clone", + "--filter=blob:none", + "https://github.com/folke/lazy.nvim.git", + "--branch=stable", + lazypath, + }) end + vim.opt.rtp:prepend(lazypath) +---------------------------------------------------------------------------------------- local plugins = { - { - 'anurag3301/nvim-platformio.lua', - -- cmd = { 'Pioinit', 'Piorun', 'Piocmdh', 'Piocmdf', 'Piolib', 'Piomon', 'Piodebug', 'Piodb' }, - - -- optional: cond used to enable/disable platformio - -- based on existance of platformio.ini file and .pio folder in cwd. - -- You can enable platformio plugin, using :Pioinit command - cond = function() - -- local platformioRootDir = vim.fs.root(vim.fn.getcwd(), { 'platformio.ini' }) -- cwd and parents - local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.fn.getcwd() or nil - if platformioRootDir and vim.fs.find('.pio', { path = platformioRootDir, type = 'directory' })[1] then - -- if platformio.ini file and .pio folder exist in cwd, enable plugin to install plugin (if not istalled) and load it. - vim.g.platformioRootDir = platformioRootDir - elseif (vim.uv or vim.loop).fs_stat(vim.fn.stdpath('data') .. '/lazy/nvim-platformio.lua') == nil then - -- if nvim-platformio not installed, enable plugin to install it first time - vim.g.platformioRootDir = vim.fn.getcwd() - else -- if nvim-platformio.lua installed but disabled, create Pioinit command - vim.api.nvim_create_user_command('Pioinit', function() --available only if no platformio.ini and .pio in cwd - vim.api.nvim_create_autocmd('User', { - pattern = { 'LazyRestore', 'LazyLoad' }, - once = true, - callback = function(args) - if args.match == 'LazyRestore' then - require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) - elseif args.match == 'LazyLoad' then - vim.notify('PlatformIO loaded', vim.log.levels.INFO, { title = 'PlatformIO' }) - require("platformio").setup(vim.g.pioConfig) - vim.cmd('Pioinit') - end - end, - }) - vim.g.platformioRootDir = vim.fn.getcwd() - require('lazy').restore({ plguins = { 'nvim-platformio.lua' }, show = false }) - end, {}) - end - return vim.g.platformioRootDir ~= nil - end, + -- { + -- "saghen/blink.cmp", + -- dependencies = { "rafamadriz/friendly-snippets" }, + -- version = "1.*", + -- opts = { + -- appearance = { + -- use_nvim_cmp_as_default = false, + -- nerd_font_variant = "mono", + -- }, + -- completion = { + -- accept = { + -- auto_brackets = { + -- enabled = true, + -- }, + -- }, + -- menu = { + -- draw = { + -- treesitter = { "lsp" }, + -- }, + -- }, + -- documentation = { + -- auto_show = true, + -- auto_show_delay_ms = 200, + -- }, + -- ghost_text = { + -- enabled = vim.g.ai_cmp, + -- }, + -- }, + -- sources = { + -- default = { "lsp", "path", "snippets", "buffer" }, + -- }, + -- cmdline = { + -- enabled = false, + -- keymap = { + -- preset = "cmdline", + -- [""] = false, + -- [""] = false, + -- }, + -- sources = { + -- default = { "lsp", "path", "snippets", "buffer" }, + -- }, + -- completion = { + -- menu = { + -- auto_show = true, + -- }, + -- ghost_text = { + -- enabled = true, + -- }, + -- }, + -- }, + -- keymap = { + -- preset = "super-tab", + -- [""] = { "insert_next" }, + -- [""] = { "insert_prev" }, + -- [""] = { "select_and_accept" }, + -- [""] = { "hide", "show" }, + -- }, + -- }, + -- }, + -- + -- -- LSP config + -- { + -- "mason-org/mason-lspconfig.nvim", + -- opts = {}, + -- dependencies = { + -- { + -- "mason-org/mason.nvim", + -- config = function() + -- --------------------------------------------------------------------------------- + -- -- INFO: Mason packages install for lint and formater + -- + -- local fok, fidget = pcall(require, "fidget") + -- if fok then + -- fidget.setup({}) + -- end + -- + -- local tok, trouble = pcall(require, "trouble") + -- if tok then + -- trouble.setup({}) + -- end + -- + -- -- mason.setup() + -- local mason = require("mason") + -- + -- mason.setup({ + -- PATH = "append", + -- ui = { + -- border = "single", + -- icons = { + -- package_installed = "✓", + -- package_pending = "➜", + -- package_uninstalled = "✗", + -- }, + -- }, + -- }) + -- -- List of packages you want Mason to ensure are installed + -- local ensure_installed = { + -- "clang-format", + -- } + -- + -- -- Mason function to install or ensure formatters/linters are installed + -- local mr = require("mason-registry") + -- mr.refresh(function() + -- for _, tool in ipairs(ensure_installed) do + -- local ok, p = pcall(mr.get_package, tool) + -- if ok and p then + -- if not p:is_installed() then + -- if not p:is_installing() then + -- p:install({}, function(success, _) + -- if not success then + -- vim.defer_fn(function() + -- vim.notify(tool .. " failed to install", vim.log.levels.ERROR) + -- end, 0) + -- end + -- end) + -- else + -- vim.defer_fn(function() + -- vim.notify(tool .. " already installed", vim.log.levels.WARN) + -- end, 0) + -- end + -- end + -- else + -- vim.defer_fn(function() + -- vim.notify("Failed to get package: " .. tool, vim.log.levels.WARN) + -- end, 0) + -- end + -- end + -- end) + -- + -- require("mason-lspconfig").setup({ + -- ensure_installed = { "clangd" }, + -- -- automatic_enable = true, -- this will automatically enable LSP servers after install + -- }) + -- + -- local cmd = { + -- "clangd", + -- "--all-scopes-completion", + -- "--background-index", + -- "--clang-tidy", + -- "--compile_args_from=filesystem", + -- "--compile-commands-dir=.", -- so this is in default directory (parent of /src) no need for it. + -- "--enable-config", + -- "--completion-parse=always", + -- "--completion-style=detailed", + -- "--header-insertion=iwyu", + -- "--header-insertion-decorators", + -- "-j=12", + -- "--log=verbose", -- for debugging + -- -- '--log=error', + -- "--offset-encoding=utf-8", + -- "--pch-storage=memory", + -- "--pretty", + -- "--query-driver=**", + -- "--ranking-model=decision_forest", + -- } + -- + -- local path = vim.fn.getcwd() + -- local fname = string.format("%s\\.clangd_cmd", path) + -- if vim.fn.filereadable(fname) == 1 then + -- local ok, result = pcall(vim.fn.readfile, fname) + -- if ok then + -- cmd = result + -- -- print(vim.inspect(cmd)) + -- end + -- end + -- + -- local capabilities = vim.lsp.protocol.make_client_capabilities() + -- local bok, _ = pcall(require, "blink") + -- if bok then + -- capabilities = vim.tbl_deep_extend( + -- "force", + -- capabilities, + -- require("blink.cmp").get_lsp_capabilities({}, false) + -- ) + -- end + -- ---@type vim.lsp.Config + -- local clangd = { + -- cmd = cmd, + -- filetypes = { "c", "cpp", "objc", "objcpp", "cuda", "proto" }, + -- root_markers = { + -- "CMakeLists.txt", + -- ".clangd", + -- ".clang-tidy", + -- ".clang-format", + -- "compile_commands.json", + -- "compile_flags.txt", + -- "configure.ac", + -- ".git", + -- vim.uv.cwd(), + -- }, + -- capabilities = capabilities, + -- workspace_required = true, + -- single_file_support = true, + -- init_options = { + -- usePlaceholders = true, + -- completeUnimported = true, + -- fallback_flags = { "-std=c++17" }, + -- clangdFileStatus = true, + -- compilationDatabasePath = vim.fn.getcwd(), + -- }, + -- } + -- vim.lsp.config("clangd", clangd) + -- + -- ---------------------- + -- local mok, mason_lspconfig = pcall(require, "mason-lspconfig") + -- if mok then + -- mason_lspconfig.setup({}) + -- end + -- + -- ---------------------------------------------------------------------------------- + -- -- INFO: LspAttach autocommand start + -- vim.api.nvim_create_autocmd("LspAttach", { + -- group = vim.api.nvim_create_augroup("platformio-lsp-attach", { clear = true }), + -- --desc = 'LSP actions', + -- callback = function(args) + -- local client = assert(vim.lsp.get_client_by_id(args.data.client_id)) + -- local bufnr = args.buf + -- + -- if client then + -- -- vim.lsp.set_log_level 'trace' + -- print("Attaching to: " .. client.name .. " attached to buffer " .. bufnr) + -- ------------------------------------------------------------------ + -- if client.name == "clangd" then + -- vim.api.nvim_buf_create_user_command(0, "LspClangdSwitchSourceHeader", function() + -- local method_name = "textDocument/switchSourceHeader" + -- local params = vim.lsp.util.make_text_document_params(bufnr) + -- client.request(method_name, params, function(err, result) + -- if err then + -- error(tostring(err)) + -- end + -- if not result then + -- vim.notify("corresponding file cannot be determined") + -- return + -- end + -- vim.cmd.edit(vim.uri_to_fname(result)) + -- end, bufnr) + -- end, { desc = "Switch between source/header" }) + -- end + -- ------------------------------------------------------------------ + -- --- Skip this if you are using blink + -- if not bok then + -- if client:supports_method("textDocument/completion", { bufnr = bufnr }) then + -- vim.lsp.completion.enable(true, client.id, args.buf, { autotrigger = true }) + -- end + -- vim.diagnostic.config({ + -- current_line = true, + -- virtual_lines = { + -- current_line = true, + -- }, + -- }) + -- vim.cmd([[set completeopt+=noselect]]) + -- end + -- + -- ------------------------------------------------------------------ + -- if client.server_capabilities.documentHighlightProvider then + -- local highlight_augroup = + -- vim.api.nvim_create_augroup("kickstart-lsp-highlight", { clear = false }) + -- vim.api.nvim_create_autocmd({ "CursorHold", "CursorHoldI" }, { + -- buffer = bufnr, + -- group = highlight_augroup, + -- callback = vim.lsp.buf.document_highlight, + -- }) + -- -- + -- vim.api.nvim_create_autocmd({ "CursorMoved", "CursorMovedI" }, { + -- buffer = bufnr, + -- group = highlight_augroup, + -- callback = vim.lsp.buf.clear_references, + -- }) + -- -- + -- vim.api.nvim_create_autocmd("LspDetach", { + -- group = vim.api.nvim_create_augroup("kickstart-lsp-detach", { clear = true }), + -- callback = function(event) + -- vim.lsp.buf.clear_references() + -- vim.api.nvim_clear_autocmds({ + -- group = "kickstart-lsp-highlight", + -- buffer = event.buf, + -- }) + -- end, + -- }) + -- -- + -- end + -- local bufkeymap = function(mode, lhs, rhs, desc) + -- vim.keymap.set(mode, lhs, rhs, { buffer = bufnr, silent = true, desc = desc }) -- noremap by default + -- end + -- -- Disable defaults + -- pcall(vim.keymap.del, "n", "gra") + -- pcall(vim.keymap.del, "n", "gri") + -- pcall(vim.keymap.del, "n", "grn") + -- pcall(vim.keymap.del, "n", "grr") + -- pcall(vim.keymap.del, "n", "gO") + -- pcall(vim.keymap.del, "n", "K") + -- -- + -- -- Quickfix list + -- bufkeymap("n", "[q", vim.cmd.cprev, "Previous quickfix item") + -- bufkeymap("n", "]q", vim.cmd.cnext, "Next quickfix item") + -- + -- -- Diagnostic keymaps + -- bufkeymap( + -- "n", + -- "[d", + -- "vim.diagnostic.goto_prev()", + -- "Go to previous [d]iagnostic message" + -- ) + -- bufkeymap( + -- "n", + -- "]d", + -- "vim.diagnostic.goto_next()", + -- "Go to next [d]iagnostic message" + -- ) + -- bufkeymap("n", "gle", vim.diagnostic.open_float, "Show diagnostic [e]rror messages") + -- -- bufkeymap('n', 'gle', 'Telescope diagnostics', 'Show diagnostic [e]rror messages') + -- bufkeymap("n", "glq", vim.diagnostic.setloclist, "Open diagnostic [q]uickfix list") + -- -- + -- -- stylua: ignore start + -- -- << local trouble = require("trouble").toggle + -- -- << bufkeymap('n', "tt", function() trouble() end, "Toggle Trouble") + -- -- << bufkeymap('n', "tq", function() trouble("quickfix") end, "Quickfix List") + -- -- << bufkeymap('n', "dr", function() trouble("lsp_references") end, "References") + -- -- << bufkeymap('n', "dd", function() trouble("document_diagnostics") end, "Document Diagnostics") + -- -- << bufkeymap('n', "dw", function() trouble("workspace_diagnostics") end, "Workspace Diagnostics") + -- -- stylua: ignore end + -- -- + -- if client.server_capabilities.hoverProvider then + -- bufkeymap("n", "glk", vim.lsp.buf.hover, "Hover Documentation") + -- end + -- if client.server_capabilities.signatureHelpProvider then + -- bufkeymap({ "i", "n" }, "gls", vim.lsp.buf.signature_help, "Show signature") + -- end + -- if client.server_capabilities.declarationProvider then + -- bufkeymap("n", "glD", vim.lsp.buf.declaration, "Goto [D]eclaration") + -- end + -- if client.server_capabilities.definitionProvider then + -- bufkeymap("n", "gld", vim.lsp.buf.definition, "Go to [d]efinition") + -- -- bufkeymap('n', 'gld', 'Telescope lsp_definitions', '[G]oto [D]efinition') + -- end + -- if client.server_capabilities.typeDefinitionProvider then + -- bufkeymap("n", "glt", vim.lsp.buf.type_definition, "Goto [t]ype definition") + -- -- bufkeymap('n', 'glt', 'Telescope lsp_type_definitions', 'Goto [t]ype definition') + -- end + -- if client.server_capabilities.implementationProvider then + -- bufkeymap("n", "gli", vim.lsp.buf.implementation, "Goto [i]mplementation") + -- -- bufkeymap('n', 'gli', 'Telescope lsp_implementations', 'Goto [i]mplementation') + -- end + -- + -- -- bufkeymap('n', 'glr', '(CodeAction, implementation, rename, references)', 'CodeAction, implementation, rename, references') + -- if client.server_capabilities.referencesProvider then + -- -- bufkeymap('n', 'gr', vim.lsp.buf.references, 'List references') + -- bufkeymap("n", "glr", "Telescope lsp_references", "Goto [r]eferences") + -- -- bufkeymap('n', 'glr', 'Telescope lsp_references', '[G]oto [R]eferences') + -- end + -- if client.server_capabilities.renameProvider then + -- -- bufkeymap('n', '', vim.lsp.buf.rename, 'Rename symbol') + -- bufkeymap("n", "glR", vim.lsp.buf.rename, "[R]ename") + -- end + -- if client.server_capabilities.codeActionProvider then + -- bufkeymap("n", "gla", vim.lsp.buf.code_action, "Code [a]ction") + -- end + -- + -- if client.server_capabilities.documentSymbolProvider then + -- bufkeymap("n", "glwd", vim.lsp.buf.document_symbol, "[D]ocument symbols") + -- -- bufkeymap('n', 'glwd', Telescope lsp_document_symbols, '[D]ocument [S]ymbols') + -- end + -- if client:supports_method("workspace/symbol") then + -- -- if client.server_capabilities.workspaceSymbolProvider then + -- bufkeymap("n", "glww", vim.lsp.buf.workspace_symbol, "List [w]orkspace symbols") + -- -- bufkeymap('n', 'glww', require('telescope.builtin').lsp_dynamic_workspace_symbols, '[W]orkspace [S]ymbols') + -- end + -- if client.server_capabilities.workspace then + -- bufkeymap("n", "glwa", vim.lsp.buf.add_workspace_folder, "Workspace [a]dd folder") + -- bufkeymap( + -- "n", + -- "glwr", + -- vim.lsp.buf.remove_workspace_folder, + -- "Workspace [r]emove folder" + -- ) + -- bufkeymap("n", "glwl", function() + -- print(vim.inspect(vim.lsp.buf.list_workspace_folders())) + -- end, "[W]orkspace [L]ist folders") + -- end + -- -- + -- if client.supports_method("textDocument/switchSourceHeader") then + -- bufkeymap( + -- "n", + -- "glws", + -- "LspClangdSwitchSourceHeader", + -- "[S]witch Source/Header (C/C++)" + -- ) + -- end + -- + -- if client.supports_method("textDocument/formatting") then + -- -- if client.server_capabilities.documentFormattingProvider then + -- bufkeymap({ "n", "x" }, "glf", function() + -- vim.lsp.buf.format({ bufnr = bufnr, async = true }) + -- -- require('conform').format({ bufnr = bufnr, async = true }) + -- end, "[f]ormat buffer") + -- end + -- -- + -- if client.server_capabilities.inlayHintProvider and vim.lsp.inlay_hint then + -- bufkeymap("n", "glh", function() + -- vim.lsp.inlay_hint.enable( + -- not vim.lsp.inlay_hint.is_enabled({ bufnr = bufnr }), + -- { bufnr = bufnr } + -- ) + -- end, "[h]ints toggle") + -- ------------------------------------------------------------------------------ + -- end + -- end + -- -- + -- vim.lsp.handlers["textDocument/publishDiagnostics"] = + -- vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { + -- signs = true, + -- underline = true, + -- virtual_text = { + -- spacing = 5, + -- min = vim.diagnostic.severity.HINT, + -- }, + -- update_in_insert = true, + -- }) + -- -- + -- vim.cmd([[autocmd FileType * set formatoptions-=ro]]) + -- -- + -- end, + -- }) + -- -- --> End LspAttach autocommand + -- end, + -- }, + -- { + -- "folke/trouble.nvim", + -- event = "LspAttach", + -- opts = { + -- focus = true, + -- auto_open = false, + -- auto_jump = false, + -- auto_refresh = false, + -- }, + -- }, + -- { "j-hui/fidget.nvim", opts = {} }, -- status bottom right + -- }, + -- }, + -- + { + "nvim-tree/nvim-tree.lua", + version = "*", + lazy = false, + dependencies = { + "nvim-tree/nvim-web-devicons", + }, + config = function() + require("nvim-tree").setup({}) + end, + }, - -- Dependencies are lazy-loaded by default unless specified otherwise. - dependencies = { - { 'akinsho/toggleterm.nvim' }, - { 'nvim-telescope/telescope.nvim' }, - { 'nvim-telescope/telescope-ui-select.nvim' }, - { 'nvim-lua/plenary.nvim' }, - { 'folke/which-key.nvim' }, - { 'nvim-treesitter/nvim-treesitter' } - }, - }, + { + "batoaqaa/nvim-platformio.lua", + cond = function() + -- local platformioRootDir = vim.fs.root(vim.fn.getcwd(), { 'platformio.ini' }) -- cwd and parents + local platformioRootDir = (vim.fn.filereadable("platformio.ini") == 1) and vim.fn.getcwd() or nil + if platformioRootDir and vim.fs.find(".pio", { path = platformioRootDir, type = "directory" })[1] then + -- if platformio.ini file and .pio folder exist in cwd, enable plugin to install plugin (if not istalled) and load it. + vim.g.platformioRootDir = platformioRootDir + elseif (vim.uv or vim.loop).fs_stat(vim.fn.stdpath("data") .. "/lazy/nvim-platformio.lua") == nil then + -- if nvim-platformio not installed, enable plugin to install it first time + vim.g.platformioRootDir = vim.fn.getcwd() + else -- if nvim-platformio.lua installed but disabled, create Pioinit command + vim.api.nvim_create_user_command( + "Pioinit", + function() --available only if no platformio.ini and .pio in cwd + vim.api.nvim_create_autocmd("User", { + pattern = { "LazyRestore", "LazyLoad" }, + once = true, + callback = function(args) + if args.match == "LazyRestore" then + require("lazy").load({ plugins = { "nvim-platformio.lua" } }) + elseif args.match == "LazyLoad" then + vim.notify("PlatformIO loaded", vim.log.levels.INFO, { title = "PlatformIO" }) + vim.cmd("Pioinit") + end + end, + }) + vim.g.platformioRootDir = vim.fn.getcwd() + require("lazy").restore({ plguins = { "nvim-platformio.lua" }, show = false }) + end, + {} + ) + end + return vim.g.platformioRootDir ~= nil + end, + dependencies = { + { "akinsho/toggleterm.nvim" }, + { "nvim-telescope/telescope.nvim" }, + { "nvim-telescope/telescope-ui-select.nvim" }, + { "nvim-lua/plenary.nvim" }, + { "folke/which-key.nvim" }, + { + "mason-org/mason-lspconfig.nvim", + dependencies = { + { "mason-org/mason.nvim" }, + { "folke/trouble.nvim" }, + { "j-hui/fidget.nvim" }, -- status bottom right + }, + }, + }, + }, } +---------------------------------------------------------------------------------------- -require('lazy').setup(plugins, { - install = { - missing = true, - }, +require("lazy").setup(plugins, { + install = { + missing = true, + }, }) +---------------------------------------------------------------------------------------- -vim.opt['number'] = true - -vim.g.pioConfig ={ - lsp = 'clangd', - menu_key = '\\', -- replace this menu key to your convenience -} -local pok, platformio = pcall(require, 'platformio') -if pok then platformio.setup(vim.g.pioConfig) end +-- platformio config +local pioConfig = { + lspClangd = { + enabled = true, + attach = { + enabled = true, + keymaps = true, + }, + }, + -- menu_key = "\\", -- replace this menu key to your convenience + -- menu_name = "PlatformIO", -- replace this menu name to your convenience + -- debug = false, +} +local pok, platformio = pcall(require, "platformio") +if pok then + -- print("here" .. vim.inspect(pioConfig)) + platformio.setup(pioConfig) +end From 65e6e5cdd2a828dd1a5c982b0dc6960770a79350 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 20:33:23 +0300 Subject: [PATCH 0007/1406] update --- lua/platformio/init.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index 5bae43c8..d7548765 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -182,7 +182,7 @@ function M.setup(user_config) end if M.config.lspClangd.enabled == true then - vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) + -- vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) require('platformio.lspClangd') end From e746a86e33bcd9ba095f3de5e6c921c65051d5c9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 20:43:12 +0300 Subject: [PATCH 0008/1406] update --- minimal_config.lua | 1102 ++++++++++++++++++++++---------------------- 1 file changed, 561 insertions(+), 541 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index cc9d249b..f1936957 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -1,9 +1,9 @@ -- pick a temp root -local tmp = vim.loop.os_tmpdir() .. "/nvim-temp" +local tmp = vim.loop.os_tmpdir() .. '/nvim-temp' -vim.env.XDG_DATA_HOME = tmp .. "/data" -vim.env.XDG_CACHE_HOME = tmp .. "/cache" -vim.env.XDG_STATE_HOME = tmp .. "/state" +vim.env.XDG_DATA_HOME = tmp .. '/data' +vim.env.XDG_CACHE_HOME = tmp .. '/cache' +vim.env.XDG_STATE_HOME = tmp .. '/state' -- disable netrw at the very start of your init.lua vim.g.loaded_netrw = 1 @@ -12,7 +12,7 @@ vim.g.loaded_netrwPlugin = 1 -- optionally enable 24-bit colour vim.opt.termguicolors = true -vim.opt["number"] = true +vim.opt['number'] = true vim.opt.tabstop = 2 -- Number of spaces tabs count for vim.opt.softtabstop = 2 vim.opt.shiftround = true -- Round indent @@ -21,565 +21,585 @@ vim.opt.smartindent = true -- Insert indents automatically vim.opt.expandtab = true -- Use spaces instead of tabs vim.g.have_nerd_font = true -vim.g.mapleader = " " -vim.g.maplocalleader = " " +vim.g.mapleader = ' ' +vim.g.maplocalleader = ' ' -vim.keymap.set("n", "e", "NvimTreeToggle", { desc = "NvimTreeToggle" }) -vim.keymap.set("n", "\\", "NvimTreeToggle", { desc = "NvimTreeToggle" }) +-- Toggle virtual_text off when on the line with the error +vim.diagnostic.config({ + virtual_lines = true, + update_in_insert = true, + underline = true, + severity_sort = true, + float = { + focusable = true, + style = 'minimal', + border = 'rounded', + source = true, + header = '', + prefix = '', + }, + signs = { + text = { + [vim.diagnostic.severity.ERROR] = ' ', + [vim.diagnostic.severity.WARN] = ' ', + [vim.diagnostic.severity.HINT] = ' ', + [vim.diagnostic.severity.INFO] = ' ', + }, + }, +}) + +vim.keymap.set('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) +vim.keymap.set('n', '\\', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) -- Keybinds to make split navigation easier. -- Use CTRL+ to switch between windows -vim.keymap.set("n", "", "", { desc = "Move focus to the left window" }) -vim.keymap.set("n", "", "", { desc = "Move focus to the right window" }) -vim.keymap.set("n", "", "", { desc = "Move focus to the lower window" }) -vim.keymap.set("n", "", "", { desc = "Move focus to the upper window" }) +vim.keymap.set('n', '', '', { desc = 'Move focus to the left window' }) +vim.keymap.set('n', '', '', { desc = 'Move focus to the right window' }) +vim.keymap.set('n', '', '', { desc = 'Move focus to the lower window' }) +vim.keymap.set('n', '', '', { desc = 'Move focus to the upper window' }) ---------------------------------------------------------------------------------------- -local lazypath = vim.env.XDG_DATA_HOME .. "/lazy/lazy.nvim" +local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' if not (vim.uv or vim.loop).fs_stat(lazypath) then - vim.fn.system({ - "git", - "clone", - "--filter=blob:none", - "https://github.com/folke/lazy.nvim.git", - "--branch=stable", - lazypath, - }) + vim.fn.system({ + 'git', + 'clone', + '--filter=blob:none', + 'https://github.com/folke/lazy.nvim.git', + '--branch=stable', + lazypath, + }) end vim.opt.rtp:prepend(lazypath) ---------------------------------------------------------------------------------------- local plugins = { - -- { - -- "saghen/blink.cmp", - -- dependencies = { "rafamadriz/friendly-snippets" }, - -- version = "1.*", - -- opts = { - -- appearance = { - -- use_nvim_cmp_as_default = false, - -- nerd_font_variant = "mono", - -- }, - -- completion = { - -- accept = { - -- auto_brackets = { - -- enabled = true, - -- }, - -- }, - -- menu = { - -- draw = { - -- treesitter = { "lsp" }, - -- }, - -- }, - -- documentation = { - -- auto_show = true, - -- auto_show_delay_ms = 200, - -- }, - -- ghost_text = { - -- enabled = vim.g.ai_cmp, - -- }, - -- }, - -- sources = { - -- default = { "lsp", "path", "snippets", "buffer" }, - -- }, - -- cmdline = { - -- enabled = false, - -- keymap = { - -- preset = "cmdline", - -- [""] = false, - -- [""] = false, - -- }, - -- sources = { - -- default = { "lsp", "path", "snippets", "buffer" }, - -- }, - -- completion = { - -- menu = { - -- auto_show = true, - -- }, - -- ghost_text = { - -- enabled = true, - -- }, - -- }, - -- }, - -- keymap = { - -- preset = "super-tab", - -- [""] = { "insert_next" }, - -- [""] = { "insert_prev" }, - -- [""] = { "select_and_accept" }, - -- [""] = { "hide", "show" }, - -- }, - -- }, - -- }, - -- - -- -- LSP config - -- { - -- "mason-org/mason-lspconfig.nvim", - -- opts = {}, - -- dependencies = { - -- { - -- "mason-org/mason.nvim", - -- config = function() - -- --------------------------------------------------------------------------------- - -- -- INFO: Mason packages install for lint and formater - -- - -- local fok, fidget = pcall(require, "fidget") - -- if fok then - -- fidget.setup({}) - -- end - -- - -- local tok, trouble = pcall(require, "trouble") - -- if tok then - -- trouble.setup({}) - -- end - -- - -- -- mason.setup() - -- local mason = require("mason") - -- - -- mason.setup({ - -- PATH = "append", - -- ui = { - -- border = "single", - -- icons = { - -- package_installed = "✓", - -- package_pending = "➜", - -- package_uninstalled = "✗", - -- }, - -- }, - -- }) - -- -- List of packages you want Mason to ensure are installed - -- local ensure_installed = { - -- "clang-format", - -- } - -- - -- -- Mason function to install or ensure formatters/linters are installed - -- local mr = require("mason-registry") - -- mr.refresh(function() - -- for _, tool in ipairs(ensure_installed) do - -- local ok, p = pcall(mr.get_package, tool) - -- if ok and p then - -- if not p:is_installed() then - -- if not p:is_installing() then - -- p:install({}, function(success, _) - -- if not success then - -- vim.defer_fn(function() - -- vim.notify(tool .. " failed to install", vim.log.levels.ERROR) - -- end, 0) - -- end - -- end) - -- else - -- vim.defer_fn(function() - -- vim.notify(tool .. " already installed", vim.log.levels.WARN) - -- end, 0) - -- end - -- end - -- else - -- vim.defer_fn(function() - -- vim.notify("Failed to get package: " .. tool, vim.log.levels.WARN) - -- end, 0) - -- end - -- end - -- end) - -- - -- require("mason-lspconfig").setup({ - -- ensure_installed = { "clangd" }, - -- -- automatic_enable = true, -- this will automatically enable LSP servers after install - -- }) - -- - -- local cmd = { - -- "clangd", - -- "--all-scopes-completion", - -- "--background-index", - -- "--clang-tidy", - -- "--compile_args_from=filesystem", - -- "--compile-commands-dir=.", -- so this is in default directory (parent of /src) no need for it. - -- "--enable-config", - -- "--completion-parse=always", - -- "--completion-style=detailed", - -- "--header-insertion=iwyu", - -- "--header-insertion-decorators", - -- "-j=12", - -- "--log=verbose", -- for debugging - -- -- '--log=error', - -- "--offset-encoding=utf-8", - -- "--pch-storage=memory", - -- "--pretty", - -- "--query-driver=**", - -- "--ranking-model=decision_forest", - -- } - -- - -- local path = vim.fn.getcwd() - -- local fname = string.format("%s\\.clangd_cmd", path) - -- if vim.fn.filereadable(fname) == 1 then - -- local ok, result = pcall(vim.fn.readfile, fname) - -- if ok then - -- cmd = result - -- -- print(vim.inspect(cmd)) - -- end - -- end - -- - -- local capabilities = vim.lsp.protocol.make_client_capabilities() - -- local bok, _ = pcall(require, "blink") - -- if bok then - -- capabilities = vim.tbl_deep_extend( - -- "force", - -- capabilities, - -- require("blink.cmp").get_lsp_capabilities({}, false) - -- ) - -- end - -- ---@type vim.lsp.Config - -- local clangd = { - -- cmd = cmd, - -- filetypes = { "c", "cpp", "objc", "objcpp", "cuda", "proto" }, - -- root_markers = { - -- "CMakeLists.txt", - -- ".clangd", - -- ".clang-tidy", - -- ".clang-format", - -- "compile_commands.json", - -- "compile_flags.txt", - -- "configure.ac", - -- ".git", - -- vim.uv.cwd(), - -- }, - -- capabilities = capabilities, - -- workspace_required = true, - -- single_file_support = true, - -- init_options = { - -- usePlaceholders = true, - -- completeUnimported = true, - -- fallback_flags = { "-std=c++17" }, - -- clangdFileStatus = true, - -- compilationDatabasePath = vim.fn.getcwd(), - -- }, - -- } - -- vim.lsp.config("clangd", clangd) - -- - -- ---------------------- - -- local mok, mason_lspconfig = pcall(require, "mason-lspconfig") - -- if mok then - -- mason_lspconfig.setup({}) - -- end - -- - -- ---------------------------------------------------------------------------------- - -- -- INFO: LspAttach autocommand start - -- vim.api.nvim_create_autocmd("LspAttach", { - -- group = vim.api.nvim_create_augroup("platformio-lsp-attach", { clear = true }), - -- --desc = 'LSP actions', - -- callback = function(args) - -- local client = assert(vim.lsp.get_client_by_id(args.data.client_id)) - -- local bufnr = args.buf - -- - -- if client then - -- -- vim.lsp.set_log_level 'trace' - -- print("Attaching to: " .. client.name .. " attached to buffer " .. bufnr) - -- ------------------------------------------------------------------ - -- if client.name == "clangd" then - -- vim.api.nvim_buf_create_user_command(0, "LspClangdSwitchSourceHeader", function() - -- local method_name = "textDocument/switchSourceHeader" - -- local params = vim.lsp.util.make_text_document_params(bufnr) - -- client.request(method_name, params, function(err, result) - -- if err then - -- error(tostring(err)) - -- end - -- if not result then - -- vim.notify("corresponding file cannot be determined") - -- return - -- end - -- vim.cmd.edit(vim.uri_to_fname(result)) - -- end, bufnr) - -- end, { desc = "Switch between source/header" }) - -- end - -- ------------------------------------------------------------------ - -- --- Skip this if you are using blink - -- if not bok then - -- if client:supports_method("textDocument/completion", { bufnr = bufnr }) then - -- vim.lsp.completion.enable(true, client.id, args.buf, { autotrigger = true }) - -- end - -- vim.diagnostic.config({ - -- current_line = true, - -- virtual_lines = { - -- current_line = true, - -- }, - -- }) - -- vim.cmd([[set completeopt+=noselect]]) - -- end - -- - -- ------------------------------------------------------------------ - -- if client.server_capabilities.documentHighlightProvider then - -- local highlight_augroup = - -- vim.api.nvim_create_augroup("kickstart-lsp-highlight", { clear = false }) - -- vim.api.nvim_create_autocmd({ "CursorHold", "CursorHoldI" }, { - -- buffer = bufnr, - -- group = highlight_augroup, - -- callback = vim.lsp.buf.document_highlight, - -- }) - -- -- - -- vim.api.nvim_create_autocmd({ "CursorMoved", "CursorMovedI" }, { - -- buffer = bufnr, - -- group = highlight_augroup, - -- callback = vim.lsp.buf.clear_references, - -- }) - -- -- - -- vim.api.nvim_create_autocmd("LspDetach", { - -- group = vim.api.nvim_create_augroup("kickstart-lsp-detach", { clear = true }), - -- callback = function(event) - -- vim.lsp.buf.clear_references() - -- vim.api.nvim_clear_autocmds({ - -- group = "kickstart-lsp-highlight", - -- buffer = event.buf, - -- }) - -- end, - -- }) - -- -- - -- end - -- local bufkeymap = function(mode, lhs, rhs, desc) - -- vim.keymap.set(mode, lhs, rhs, { buffer = bufnr, silent = true, desc = desc }) -- noremap by default - -- end - -- -- Disable defaults - -- pcall(vim.keymap.del, "n", "gra") - -- pcall(vim.keymap.del, "n", "gri") - -- pcall(vim.keymap.del, "n", "grn") - -- pcall(vim.keymap.del, "n", "grr") - -- pcall(vim.keymap.del, "n", "gO") - -- pcall(vim.keymap.del, "n", "K") - -- -- - -- -- Quickfix list - -- bufkeymap("n", "[q", vim.cmd.cprev, "Previous quickfix item") - -- bufkeymap("n", "]q", vim.cmd.cnext, "Next quickfix item") - -- - -- -- Diagnostic keymaps - -- bufkeymap( - -- "n", - -- "[d", - -- "vim.diagnostic.goto_prev()", - -- "Go to previous [d]iagnostic message" - -- ) - -- bufkeymap( - -- "n", - -- "]d", - -- "vim.diagnostic.goto_next()", - -- "Go to next [d]iagnostic message" - -- ) - -- bufkeymap("n", "gle", vim.diagnostic.open_float, "Show diagnostic [e]rror messages") - -- -- bufkeymap('n', 'gle', 'Telescope diagnostics', 'Show diagnostic [e]rror messages') - -- bufkeymap("n", "glq", vim.diagnostic.setloclist, "Open diagnostic [q]uickfix list") - -- -- - -- -- stylua: ignore start - -- -- << local trouble = require("trouble").toggle - -- -- << bufkeymap('n', "tt", function() trouble() end, "Toggle Trouble") - -- -- << bufkeymap('n', "tq", function() trouble("quickfix") end, "Quickfix List") - -- -- << bufkeymap('n', "dr", function() trouble("lsp_references") end, "References") - -- -- << bufkeymap('n', "dd", function() trouble("document_diagnostics") end, "Document Diagnostics") - -- -- << bufkeymap('n', "dw", function() trouble("workspace_diagnostics") end, "Workspace Diagnostics") - -- -- stylua: ignore end - -- -- - -- if client.server_capabilities.hoverProvider then - -- bufkeymap("n", "glk", vim.lsp.buf.hover, "Hover Documentation") - -- end - -- if client.server_capabilities.signatureHelpProvider then - -- bufkeymap({ "i", "n" }, "gls", vim.lsp.buf.signature_help, "Show signature") - -- end - -- if client.server_capabilities.declarationProvider then - -- bufkeymap("n", "glD", vim.lsp.buf.declaration, "Goto [D]eclaration") - -- end - -- if client.server_capabilities.definitionProvider then - -- bufkeymap("n", "gld", vim.lsp.buf.definition, "Go to [d]efinition") - -- -- bufkeymap('n', 'gld', 'Telescope lsp_definitions', '[G]oto [D]efinition') - -- end - -- if client.server_capabilities.typeDefinitionProvider then - -- bufkeymap("n", "glt", vim.lsp.buf.type_definition, "Goto [t]ype definition") - -- -- bufkeymap('n', 'glt', 'Telescope lsp_type_definitions', 'Goto [t]ype definition') - -- end - -- if client.server_capabilities.implementationProvider then - -- bufkeymap("n", "gli", vim.lsp.buf.implementation, "Goto [i]mplementation") - -- -- bufkeymap('n', 'gli', 'Telescope lsp_implementations', 'Goto [i]mplementation') - -- end - -- - -- -- bufkeymap('n', 'glr', '(CodeAction, implementation, rename, references)', 'CodeAction, implementation, rename, references') - -- if client.server_capabilities.referencesProvider then - -- -- bufkeymap('n', 'gr', vim.lsp.buf.references, 'List references') - -- bufkeymap("n", "glr", "Telescope lsp_references", "Goto [r]eferences") - -- -- bufkeymap('n', 'glr', 'Telescope lsp_references', '[G]oto [R]eferences') - -- end - -- if client.server_capabilities.renameProvider then - -- -- bufkeymap('n', '', vim.lsp.buf.rename, 'Rename symbol') - -- bufkeymap("n", "glR", vim.lsp.buf.rename, "[R]ename") - -- end - -- if client.server_capabilities.codeActionProvider then - -- bufkeymap("n", "gla", vim.lsp.buf.code_action, "Code [a]ction") - -- end - -- - -- if client.server_capabilities.documentSymbolProvider then - -- bufkeymap("n", "glwd", vim.lsp.buf.document_symbol, "[D]ocument symbols") - -- -- bufkeymap('n', 'glwd', Telescope lsp_document_symbols, '[D]ocument [S]ymbols') - -- end - -- if client:supports_method("workspace/symbol") then - -- -- if client.server_capabilities.workspaceSymbolProvider then - -- bufkeymap("n", "glww", vim.lsp.buf.workspace_symbol, "List [w]orkspace symbols") - -- -- bufkeymap('n', 'glww', require('telescope.builtin').lsp_dynamic_workspace_symbols, '[W]orkspace [S]ymbols') - -- end - -- if client.server_capabilities.workspace then - -- bufkeymap("n", "glwa", vim.lsp.buf.add_workspace_folder, "Workspace [a]dd folder") - -- bufkeymap( - -- "n", - -- "glwr", - -- vim.lsp.buf.remove_workspace_folder, - -- "Workspace [r]emove folder" - -- ) - -- bufkeymap("n", "glwl", function() - -- print(vim.inspect(vim.lsp.buf.list_workspace_folders())) - -- end, "[W]orkspace [L]ist folders") - -- end - -- -- - -- if client.supports_method("textDocument/switchSourceHeader") then - -- bufkeymap( - -- "n", - -- "glws", - -- "LspClangdSwitchSourceHeader", - -- "[S]witch Source/Header (C/C++)" - -- ) - -- end - -- - -- if client.supports_method("textDocument/formatting") then - -- -- if client.server_capabilities.documentFormattingProvider then - -- bufkeymap({ "n", "x" }, "glf", function() - -- vim.lsp.buf.format({ bufnr = bufnr, async = true }) - -- -- require('conform').format({ bufnr = bufnr, async = true }) - -- end, "[f]ormat buffer") - -- end - -- -- - -- if client.server_capabilities.inlayHintProvider and vim.lsp.inlay_hint then - -- bufkeymap("n", "glh", function() - -- vim.lsp.inlay_hint.enable( - -- not vim.lsp.inlay_hint.is_enabled({ bufnr = bufnr }), - -- { bufnr = bufnr } - -- ) - -- end, "[h]ints toggle") - -- ------------------------------------------------------------------------------ - -- end - -- end - -- -- - -- vim.lsp.handlers["textDocument/publishDiagnostics"] = - -- vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { - -- signs = true, - -- underline = true, - -- virtual_text = { - -- spacing = 5, - -- min = vim.diagnostic.severity.HINT, - -- }, - -- update_in_insert = true, - -- }) - -- -- - -- vim.cmd([[autocmd FileType * set formatoptions-=ro]]) - -- -- - -- end, - -- }) - -- -- --> End LspAttach autocommand - -- end, - -- }, - -- { - -- "folke/trouble.nvim", - -- event = "LspAttach", - -- opts = { - -- focus = true, - -- auto_open = false, - -- auto_jump = false, - -- auto_refresh = false, - -- }, - -- }, - -- { "j-hui/fidget.nvim", opts = {} }, -- status bottom right - -- }, - -- }, - -- - { - "nvim-tree/nvim-tree.lua", - version = "*", - lazy = false, - dependencies = { - "nvim-tree/nvim-web-devicons", - }, - config = function() - require("nvim-tree").setup({}) - end, - }, + -- { + -- "saghen/blink.cmp", + -- dependencies = { "rafamadriz/friendly-snippets" }, + -- version = "1.*", + -- opts = { + -- appearance = { + -- use_nvim_cmp_as_default = false, + -- nerd_font_variant = "mono", + -- }, + -- completion = { + -- accept = { + -- auto_brackets = { + -- enabled = true, + -- }, + -- }, + -- menu = { + -- draw = { + -- treesitter = { "lsp" }, + -- }, + -- }, + -- documentation = { + -- auto_show = true, + -- auto_show_delay_ms = 200, + -- }, + -- ghost_text = { + -- enabled = vim.g.ai_cmp, + -- }, + -- }, + -- sources = { + -- default = { "lsp", "path", "snippets", "buffer" }, + -- }, + -- cmdline = { + -- enabled = false, + -- keymap = { + -- preset = "cmdline", + -- [""] = false, + -- [""] = false, + -- }, + -- sources = { + -- default = { "lsp", "path", "snippets", "buffer" }, + -- }, + -- completion = { + -- menu = { + -- auto_show = true, + -- }, + -- ghost_text = { + -- enabled = true, + -- }, + -- }, + -- }, + -- keymap = { + -- preset = "super-tab", + -- [""] = { "insert_next" }, + -- [""] = { "insert_prev" }, + -- [""] = { "select_and_accept" }, + -- [""] = { "hide", "show" }, + -- }, + -- }, + -- }, + -- + -- -- LSP config + -- { + -- "mason-org/mason-lspconfig.nvim", + -- opts = {}, + -- dependencies = { + -- { + -- "mason-org/mason.nvim", + -- config = function() + -- --------------------------------------------------------------------------------- + -- -- INFO: Mason packages install for lint and formater + -- + -- local fok, fidget = pcall(require, "fidget") + -- if fok then + -- fidget.setup({}) + -- end + -- + -- local tok, trouble = pcall(require, "trouble") + -- if tok then + -- trouble.setup({}) + -- end + -- + -- -- mason.setup() + -- local mason = require("mason") + -- + -- mason.setup({ + -- PATH = "append", + -- ui = { + -- border = "single", + -- icons = { + -- package_installed = "✓", + -- package_pending = "➜", + -- package_uninstalled = "✗", + -- }, + -- }, + -- }) + -- -- List of packages you want Mason to ensure are installed + -- local ensure_installed = { + -- "clang-format", + -- } + -- + -- -- Mason function to install or ensure formatters/linters are installed + -- local mr = require("mason-registry") + -- mr.refresh(function() + -- for _, tool in ipairs(ensure_installed) do + -- local ok, p = pcall(mr.get_package, tool) + -- if ok and p then + -- if not p:is_installed() then + -- if not p:is_installing() then + -- p:install({}, function(success, _) + -- if not success then + -- vim.defer_fn(function() + -- vim.notify(tool .. " failed to install", vim.log.levels.ERROR) + -- end, 0) + -- end + -- end) + -- else + -- vim.defer_fn(function() + -- vim.notify(tool .. " already installed", vim.log.levels.WARN) + -- end, 0) + -- end + -- end + -- else + -- vim.defer_fn(function() + -- vim.notify("Failed to get package: " .. tool, vim.log.levels.WARN) + -- end, 0) + -- end + -- end + -- end) + -- + -- require("mason-lspconfig").setup({ + -- ensure_installed = { "clangd" }, + -- -- automatic_enable = true, -- this will automatically enable LSP servers after install + -- }) + -- + -- local cmd = { + -- "clangd", + -- "--all-scopes-completion", + -- "--background-index", + -- "--clang-tidy", + -- "--compile_args_from=filesystem", + -- "--compile-commands-dir=.", -- so this is in default directory (parent of /src) no need for it. + -- "--enable-config", + -- "--completion-parse=always", + -- "--completion-style=detailed", + -- "--header-insertion=iwyu", + -- "--header-insertion-decorators", + -- "-j=12", + -- "--log=verbose", -- for debugging + -- -- '--log=error', + -- "--offset-encoding=utf-8", + -- "--pch-storage=memory", + -- "--pretty", + -- "--query-driver=**", + -- "--ranking-model=decision_forest", + -- } + -- + -- local path = vim.fn.getcwd() + -- local fname = string.format("%s\\.clangd_cmd", path) + -- if vim.fn.filereadable(fname) == 1 then + -- local ok, result = pcall(vim.fn.readfile, fname) + -- if ok then + -- cmd = result + -- -- print(vim.inspect(cmd)) + -- end + -- end + -- + -- local capabilities = vim.lsp.protocol.make_client_capabilities() + -- local bok, _ = pcall(require, "blink") + -- if bok then + -- capabilities = vim.tbl_deep_extend( + -- "force", + -- capabilities, + -- require("blink.cmp").get_lsp_capabilities({}, false) + -- ) + -- end + -- ---@type vim.lsp.Config + -- local clangd = { + -- cmd = cmd, + -- filetypes = { "c", "cpp", "objc", "objcpp", "cuda", "proto" }, + -- root_markers = { + -- "CMakeLists.txt", + -- ".clangd", + -- ".clang-tidy", + -- ".clang-format", + -- "compile_commands.json", + -- "compile_flags.txt", + -- "configure.ac", + -- ".git", + -- vim.uv.cwd(), + -- }, + -- capabilities = capabilities, + -- workspace_required = true, + -- single_file_support = true, + -- init_options = { + -- usePlaceholders = true, + -- completeUnimported = true, + -- fallback_flags = { "-std=c++17" }, + -- clangdFileStatus = true, + -- compilationDatabasePath = vim.fn.getcwd(), + -- }, + -- } + -- vim.lsp.config("clangd", clangd) + -- + -- ---------------------- + -- local mok, mason_lspconfig = pcall(require, "mason-lspconfig") + -- if mok then + -- mason_lspconfig.setup({}) + -- end + -- + -- ---------------------------------------------------------------------------------- + -- -- INFO: LspAttach autocommand start + -- vim.api.nvim_create_autocmd("LspAttach", { + -- group = vim.api.nvim_create_augroup("platformio-lsp-attach", { clear = true }), + -- --desc = 'LSP actions', + -- callback = function(args) + -- local client = assert(vim.lsp.get_client_by_id(args.data.client_id)) + -- local bufnr = args.buf + -- + -- if client then + -- -- vim.lsp.set_log_level 'trace' + -- print("Attaching to: " .. client.name .. " attached to buffer " .. bufnr) + -- ------------------------------------------------------------------ + -- if client.name == "clangd" then + -- vim.api.nvim_buf_create_user_command(0, "LspClangdSwitchSourceHeader", function() + -- local method_name = "textDocument/switchSourceHeader" + -- local params = vim.lsp.util.make_text_document_params(bufnr) + -- client.request(method_name, params, function(err, result) + -- if err then + -- error(tostring(err)) + -- end + -- if not result then + -- vim.notify("corresponding file cannot be determined") + -- return + -- end + -- vim.cmd.edit(vim.uri_to_fname(result)) + -- end, bufnr) + -- end, { desc = "Switch between source/header" }) + -- end + -- ------------------------------------------------------------------ + -- --- Skip this if you are using blink + -- if not bok then + -- if client:supports_method("textDocument/completion", { bufnr = bufnr }) then + -- vim.lsp.completion.enable(true, client.id, args.buf, { autotrigger = true }) + -- end + -- vim.diagnostic.config({ + -- current_line = true, + -- virtual_lines = { + -- current_line = true, + -- }, + -- }) + -- vim.cmd([[set completeopt+=noselect]]) + -- end + -- + -- ------------------------------------------------------------------ + -- if client.server_capabilities.documentHighlightProvider then + -- local highlight_augroup = + -- vim.api.nvim_create_augroup("kickstart-lsp-highlight", { clear = false }) + -- vim.api.nvim_create_autocmd({ "CursorHold", "CursorHoldI" }, { + -- buffer = bufnr, + -- group = highlight_augroup, + -- callback = vim.lsp.buf.document_highlight, + -- }) + -- -- + -- vim.api.nvim_create_autocmd({ "CursorMoved", "CursorMovedI" }, { + -- buffer = bufnr, + -- group = highlight_augroup, + -- callback = vim.lsp.buf.clear_references, + -- }) + -- -- + -- vim.api.nvim_create_autocmd("LspDetach", { + -- group = vim.api.nvim_create_augroup("kickstart-lsp-detach", { clear = true }), + -- callback = function(event) + -- vim.lsp.buf.clear_references() + -- vim.api.nvim_clear_autocmds({ + -- group = "kickstart-lsp-highlight", + -- buffer = event.buf, + -- }) + -- end, + -- }) + -- -- + -- end + -- local bufkeymap = function(mode, lhs, rhs, desc) + -- vim.keymap.set(mode, lhs, rhs, { buffer = bufnr, silent = true, desc = desc }) -- noremap by default + -- end + -- -- Disable defaults + -- pcall(vim.keymap.del, "n", "gra") + -- pcall(vim.keymap.del, "n", "gri") + -- pcall(vim.keymap.del, "n", "grn") + -- pcall(vim.keymap.del, "n", "grr") + -- pcall(vim.keymap.del, "n", "gO") + -- pcall(vim.keymap.del, "n", "K") + -- -- + -- -- Quickfix list + -- bufkeymap("n", "[q", vim.cmd.cprev, "Previous quickfix item") + -- bufkeymap("n", "]q", vim.cmd.cnext, "Next quickfix item") + -- + -- -- Diagnostic keymaps + -- bufkeymap( + -- "n", + -- "[d", + -- "vim.diagnostic.goto_prev()", + -- "Go to previous [d]iagnostic message" + -- ) + -- bufkeymap( + -- "n", + -- "]d", + -- "vim.diagnostic.goto_next()", + -- "Go to next [d]iagnostic message" + -- ) + -- bufkeymap("n", "gle", vim.diagnostic.open_float, "Show diagnostic [e]rror messages") + -- -- bufkeymap('n', 'gle', 'Telescope diagnostics', 'Show diagnostic [e]rror messages') + -- bufkeymap("n", "glq", vim.diagnostic.setloclist, "Open diagnostic [q]uickfix list") + -- -- + -- -- stylua: ignore start + -- -- << local trouble = require("trouble").toggle + -- -- << bufkeymap('n', "tt", function() trouble() end, "Toggle Trouble") + -- -- << bufkeymap('n', "tq", function() trouble("quickfix") end, "Quickfix List") + -- -- << bufkeymap('n', "dr", function() trouble("lsp_references") end, "References") + -- -- << bufkeymap('n', "dd", function() trouble("document_diagnostics") end, "Document Diagnostics") + -- -- << bufkeymap('n', "dw", function() trouble("workspace_diagnostics") end, "Workspace Diagnostics") + -- -- stylua: ignore end + -- -- + -- if client.server_capabilities.hoverProvider then + -- bufkeymap("n", "glk", vim.lsp.buf.hover, "Hover Documentation") + -- end + -- if client.server_capabilities.signatureHelpProvider then + -- bufkeymap({ "i", "n" }, "gls", vim.lsp.buf.signature_help, "Show signature") + -- end + -- if client.server_capabilities.declarationProvider then + -- bufkeymap("n", "glD", vim.lsp.buf.declaration, "Goto [D]eclaration") + -- end + -- if client.server_capabilities.definitionProvider then + -- bufkeymap("n", "gld", vim.lsp.buf.definition, "Go to [d]efinition") + -- -- bufkeymap('n', 'gld', 'Telescope lsp_definitions', '[G]oto [D]efinition') + -- end + -- if client.server_capabilities.typeDefinitionProvider then + -- bufkeymap("n", "glt", vim.lsp.buf.type_definition, "Goto [t]ype definition") + -- -- bufkeymap('n', 'glt', 'Telescope lsp_type_definitions', 'Goto [t]ype definition') + -- end + -- if client.server_capabilities.implementationProvider then + -- bufkeymap("n", "gli", vim.lsp.buf.implementation, "Goto [i]mplementation") + -- -- bufkeymap('n', 'gli', 'Telescope lsp_implementations', 'Goto [i]mplementation') + -- end + -- + -- -- bufkeymap('n', 'glr', '(CodeAction, implementation, rename, references)', 'CodeAction, implementation, rename, references') + -- if client.server_capabilities.referencesProvider then + -- -- bufkeymap('n', 'gr', vim.lsp.buf.references, 'List references') + -- bufkeymap("n", "glr", "Telescope lsp_references", "Goto [r]eferences") + -- -- bufkeymap('n', 'glr', 'Telescope lsp_references', '[G]oto [R]eferences') + -- end + -- if client.server_capabilities.renameProvider then + -- -- bufkeymap('n', '', vim.lsp.buf.rename, 'Rename symbol') + -- bufkeymap("n", "glR", vim.lsp.buf.rename, "[R]ename") + -- end + -- if client.server_capabilities.codeActionProvider then + -- bufkeymap("n", "gla", vim.lsp.buf.code_action, "Code [a]ction") + -- end + -- + -- if client.server_capabilities.documentSymbolProvider then + -- bufkeymap("n", "glwd", vim.lsp.buf.document_symbol, "[D]ocument symbols") + -- -- bufkeymap('n', 'glwd', Telescope lsp_document_symbols, '[D]ocument [S]ymbols') + -- end + -- if client:supports_method("workspace/symbol") then + -- -- if client.server_capabilities.workspaceSymbolProvider then + -- bufkeymap("n", "glww", vim.lsp.buf.workspace_symbol, "List [w]orkspace symbols") + -- -- bufkeymap('n', 'glww', require('telescope.builtin').lsp_dynamic_workspace_symbols, '[W]orkspace [S]ymbols') + -- end + -- if client.server_capabilities.workspace then + -- bufkeymap("n", "glwa", vim.lsp.buf.add_workspace_folder, "Workspace [a]dd folder") + -- bufkeymap( + -- "n", + -- "glwr", + -- vim.lsp.buf.remove_workspace_folder, + -- "Workspace [r]emove folder" + -- ) + -- bufkeymap("n", "glwl", function() + -- print(vim.inspect(vim.lsp.buf.list_workspace_folders())) + -- end, "[W]orkspace [L]ist folders") + -- end + -- -- + -- if client.supports_method("textDocument/switchSourceHeader") then + -- bufkeymap( + -- "n", + -- "glws", + -- "LspClangdSwitchSourceHeader", + -- "[S]witch Source/Header (C/C++)" + -- ) + -- end + -- + -- if client.supports_method("textDocument/formatting") then + -- -- if client.server_capabilities.documentFormattingProvider then + -- bufkeymap({ "n", "x" }, "glf", function() + -- vim.lsp.buf.format({ bufnr = bufnr, async = true }) + -- -- require('conform').format({ bufnr = bufnr, async = true }) + -- end, "[f]ormat buffer") + -- end + -- -- + -- if client.server_capabilities.inlayHintProvider and vim.lsp.inlay_hint then + -- bufkeymap("n", "glh", function() + -- vim.lsp.inlay_hint.enable( + -- not vim.lsp.inlay_hint.is_enabled({ bufnr = bufnr }), + -- { bufnr = bufnr } + -- ) + -- end, "[h]ints toggle") + -- ------------------------------------------------------------------------------ + -- end + -- end + -- -- + -- vim.lsp.handlers["textDocument/publishDiagnostics"] = + -- vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { + -- signs = true, + -- underline = true, + -- virtual_text = { + -- spacing = 5, + -- min = vim.diagnostic.severity.HINT, + -- }, + -- update_in_insert = true, + -- }) + -- -- + -- vim.cmd([[autocmd FileType * set formatoptions-=ro]]) + -- -- + -- end, + -- }) + -- -- --> End LspAttach autocommand + -- end, + -- }, + -- { + -- "folke/trouble.nvim", + -- event = "LspAttach", + -- opts = { + -- focus = true, + -- auto_open = false, + -- auto_jump = false, + -- auto_refresh = false, + -- }, + -- }, + -- { "j-hui/fidget.nvim", opts = {} }, -- status bottom right + -- }, + -- }, + -- + { + 'nvim-tree/nvim-tree.lua', + version = '*', + lazy = false, + dependencies = { + 'nvim-tree/nvim-web-devicons', + }, + config = function() + require('nvim-tree').setup({}) + end, + }, - { - "batoaqaa/nvim-platformio.lua", - cond = function() - -- local platformioRootDir = vim.fs.root(vim.fn.getcwd(), { 'platformio.ini' }) -- cwd and parents - local platformioRootDir = (vim.fn.filereadable("platformio.ini") == 1) and vim.fn.getcwd() or nil - if platformioRootDir and vim.fs.find(".pio", { path = platformioRootDir, type = "directory" })[1] then - -- if platformio.ini file and .pio folder exist in cwd, enable plugin to install plugin (if not istalled) and load it. - vim.g.platformioRootDir = platformioRootDir - elseif (vim.uv or vim.loop).fs_stat(vim.fn.stdpath("data") .. "/lazy/nvim-platformio.lua") == nil then - -- if nvim-platformio not installed, enable plugin to install it first time - vim.g.platformioRootDir = vim.fn.getcwd() - else -- if nvim-platformio.lua installed but disabled, create Pioinit command - vim.api.nvim_create_user_command( - "Pioinit", - function() --available only if no platformio.ini and .pio in cwd - vim.api.nvim_create_autocmd("User", { - pattern = { "LazyRestore", "LazyLoad" }, - once = true, - callback = function(args) - if args.match == "LazyRestore" then - require("lazy").load({ plugins = { "nvim-platformio.lua" } }) - elseif args.match == "LazyLoad" then - vim.notify("PlatformIO loaded", vim.log.levels.INFO, { title = "PlatformIO" }) - vim.cmd("Pioinit") - end - end, - }) - vim.g.platformioRootDir = vim.fn.getcwd() - require("lazy").restore({ plguins = { "nvim-platformio.lua" }, show = false }) - end, - {} - ) - end - return vim.g.platformioRootDir ~= nil - end, - dependencies = { - { "akinsho/toggleterm.nvim" }, - { "nvim-telescope/telescope.nvim" }, - { "nvim-telescope/telescope-ui-select.nvim" }, - { "nvim-lua/plenary.nvim" }, - { "folke/which-key.nvim" }, - { - "mason-org/mason-lspconfig.nvim", - dependencies = { - { "mason-org/mason.nvim" }, - { "folke/trouble.nvim" }, - { "j-hui/fidget.nvim" }, -- status bottom right - }, - }, - }, - }, + { + 'batoaqaa/nvim-platformio.lua', + cond = function() + -- local platformioRootDir = vim.fs.root(vim.fn.getcwd(), { 'platformio.ini' }) -- cwd and parents + local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.fn.getcwd() or nil + if platformioRootDir and vim.fs.find('.pio', { path = platformioRootDir, type = 'directory' })[1] then + -- if platformio.ini file and .pio folder exist in cwd, enable plugin to install plugin (if not istalled) and load it. + vim.g.platformioRootDir = platformioRootDir + elseif (vim.uv or vim.loop).fs_stat(vim.fn.stdpath('data') .. '/lazy/nvim-platformio.lua') == nil then + -- if nvim-platformio not installed, enable plugin to install it first time + vim.g.platformioRootDir = vim.fn.getcwd() + else -- if nvim-platformio.lua installed but disabled, create Pioinit command + vim.api.nvim_create_user_command('Pioinit', function() --available only if no platformio.ini and .pio in cwd + vim.api.nvim_create_autocmd('User', { + pattern = { 'LazyRestore', 'LazyLoad' }, + once = true, + callback = function(args) + if args.match == 'LazyRestore' then + require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) + elseif args.match == 'LazyLoad' then + vim.notify('PlatformIO loaded', vim.log.levels.INFO, { title = 'PlatformIO' }) + vim.cmd('Pioinit') + end + end, + }) + vim.g.platformioRootDir = vim.fn.getcwd() + require('lazy').restore({ plguins = { 'nvim-platformio.lua' }, show = false }) + end, {}) + end + return vim.g.platformioRootDir ~= nil + end, + dependencies = { + { 'akinsho/toggleterm.nvim' }, + { 'nvim-telescope/telescope.nvim' }, + { 'nvim-telescope/telescope-ui-select.nvim' }, + { 'nvim-lua/plenary.nvim' }, + { 'folke/which-key.nvim' }, + { + 'mason-org/mason-lspconfig.nvim', + dependencies = { + { 'mason-org/mason.nvim' }, + { 'folke/trouble.nvim' }, + { 'j-hui/fidget.nvim' }, -- status bottom right + }, + }, + }, + }, } ---------------------------------------------------------------------------------------- -require("lazy").setup(plugins, { - install = { - missing = true, - }, +require('lazy').setup(plugins, { + install = { + missing = true, + }, }) ---------------------------------------------------------------------------------------- -- platformio config local pioConfig = { - lspClangd = { - enabled = true, - attach = { - enabled = true, - keymaps = true, - }, - }, - -- menu_key = "\\", -- replace this menu key to your convenience - -- menu_name = "PlatformIO", -- replace this menu name to your convenience - -- debug = false, + lspClangd = { + enabled = true, + attach = { + enabled = true, + keymaps = true, + }, + }, + -- menu_key = "\\", -- replace this menu key to your convenience + -- menu_name = "PlatformIO", -- replace this menu name to your convenience + -- debug = false, } -local pok, platformio = pcall(require, "platformio") +local pok, platformio = pcall(require, 'platformio') if pok then - -- print("here" .. vim.inspect(pioConfig)) - platformio.setup(pioConfig) + -- print("here" .. vim.inspect(pioConfig)) + platformio.setup(pioConfig) end From 1a40b53adc2e0caf5c1176868bc593c8bc26ee3a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 21:05:14 +0300 Subject: [PATCH 0009/1406] update --- minimal_config.lua | 498 ++++++--------------------------------------- 1 file changed, 59 insertions(+), 439 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index f1936957..c8adb181 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -76,445 +76,65 @@ vim.opt.rtp:prepend(lazypath) ---------------------------------------------------------------------------------------- local plugins = { - -- { - -- "saghen/blink.cmp", - -- dependencies = { "rafamadriz/friendly-snippets" }, - -- version = "1.*", - -- opts = { - -- appearance = { - -- use_nvim_cmp_as_default = false, - -- nerd_font_variant = "mono", - -- }, - -- completion = { - -- accept = { - -- auto_brackets = { - -- enabled = true, - -- }, - -- }, - -- menu = { - -- draw = { - -- treesitter = { "lsp" }, - -- }, - -- }, - -- documentation = { - -- auto_show = true, - -- auto_show_delay_ms = 200, - -- }, - -- ghost_text = { - -- enabled = vim.g.ai_cmp, - -- }, - -- }, - -- sources = { - -- default = { "lsp", "path", "snippets", "buffer" }, - -- }, - -- cmdline = { - -- enabled = false, - -- keymap = { - -- preset = "cmdline", - -- [""] = false, - -- [""] = false, - -- }, - -- sources = { - -- default = { "lsp", "path", "snippets", "buffer" }, - -- }, - -- completion = { - -- menu = { - -- auto_show = true, - -- }, - -- ghost_text = { - -- enabled = true, - -- }, - -- }, - -- }, - -- keymap = { - -- preset = "super-tab", - -- [""] = { "insert_next" }, - -- [""] = { "insert_prev" }, - -- [""] = { "select_and_accept" }, - -- [""] = { "hide", "show" }, - -- }, - -- }, - -- }, - -- - -- -- LSP config - -- { - -- "mason-org/mason-lspconfig.nvim", - -- opts = {}, - -- dependencies = { - -- { - -- "mason-org/mason.nvim", - -- config = function() - -- --------------------------------------------------------------------------------- - -- -- INFO: Mason packages install for lint and formater - -- - -- local fok, fidget = pcall(require, "fidget") - -- if fok then - -- fidget.setup({}) - -- end - -- - -- local tok, trouble = pcall(require, "trouble") - -- if tok then - -- trouble.setup({}) - -- end - -- - -- -- mason.setup() - -- local mason = require("mason") - -- - -- mason.setup({ - -- PATH = "append", - -- ui = { - -- border = "single", - -- icons = { - -- package_installed = "✓", - -- package_pending = "➜", - -- package_uninstalled = "✗", - -- }, - -- }, - -- }) - -- -- List of packages you want Mason to ensure are installed - -- local ensure_installed = { - -- "clang-format", - -- } - -- - -- -- Mason function to install or ensure formatters/linters are installed - -- local mr = require("mason-registry") - -- mr.refresh(function() - -- for _, tool in ipairs(ensure_installed) do - -- local ok, p = pcall(mr.get_package, tool) - -- if ok and p then - -- if not p:is_installed() then - -- if not p:is_installing() then - -- p:install({}, function(success, _) - -- if not success then - -- vim.defer_fn(function() - -- vim.notify(tool .. " failed to install", vim.log.levels.ERROR) - -- end, 0) - -- end - -- end) - -- else - -- vim.defer_fn(function() - -- vim.notify(tool .. " already installed", vim.log.levels.WARN) - -- end, 0) - -- end - -- end - -- else - -- vim.defer_fn(function() - -- vim.notify("Failed to get package: " .. tool, vim.log.levels.WARN) - -- end, 0) - -- end - -- end - -- end) - -- - -- require("mason-lspconfig").setup({ - -- ensure_installed = { "clangd" }, - -- -- automatic_enable = true, -- this will automatically enable LSP servers after install - -- }) - -- - -- local cmd = { - -- "clangd", - -- "--all-scopes-completion", - -- "--background-index", - -- "--clang-tidy", - -- "--compile_args_from=filesystem", - -- "--compile-commands-dir=.", -- so this is in default directory (parent of /src) no need for it. - -- "--enable-config", - -- "--completion-parse=always", - -- "--completion-style=detailed", - -- "--header-insertion=iwyu", - -- "--header-insertion-decorators", - -- "-j=12", - -- "--log=verbose", -- for debugging - -- -- '--log=error', - -- "--offset-encoding=utf-8", - -- "--pch-storage=memory", - -- "--pretty", - -- "--query-driver=**", - -- "--ranking-model=decision_forest", - -- } - -- - -- local path = vim.fn.getcwd() - -- local fname = string.format("%s\\.clangd_cmd", path) - -- if vim.fn.filereadable(fname) == 1 then - -- local ok, result = pcall(vim.fn.readfile, fname) - -- if ok then - -- cmd = result - -- -- print(vim.inspect(cmd)) - -- end - -- end - -- - -- local capabilities = vim.lsp.protocol.make_client_capabilities() - -- local bok, _ = pcall(require, "blink") - -- if bok then - -- capabilities = vim.tbl_deep_extend( - -- "force", - -- capabilities, - -- require("blink.cmp").get_lsp_capabilities({}, false) - -- ) - -- end - -- ---@type vim.lsp.Config - -- local clangd = { - -- cmd = cmd, - -- filetypes = { "c", "cpp", "objc", "objcpp", "cuda", "proto" }, - -- root_markers = { - -- "CMakeLists.txt", - -- ".clangd", - -- ".clang-tidy", - -- ".clang-format", - -- "compile_commands.json", - -- "compile_flags.txt", - -- "configure.ac", - -- ".git", - -- vim.uv.cwd(), - -- }, - -- capabilities = capabilities, - -- workspace_required = true, - -- single_file_support = true, - -- init_options = { - -- usePlaceholders = true, - -- completeUnimported = true, - -- fallback_flags = { "-std=c++17" }, - -- clangdFileStatus = true, - -- compilationDatabasePath = vim.fn.getcwd(), - -- }, - -- } - -- vim.lsp.config("clangd", clangd) - -- - -- ---------------------- - -- local mok, mason_lspconfig = pcall(require, "mason-lspconfig") - -- if mok then - -- mason_lspconfig.setup({}) - -- end - -- - -- ---------------------------------------------------------------------------------- - -- -- INFO: LspAttach autocommand start - -- vim.api.nvim_create_autocmd("LspAttach", { - -- group = vim.api.nvim_create_augroup("platformio-lsp-attach", { clear = true }), - -- --desc = 'LSP actions', - -- callback = function(args) - -- local client = assert(vim.lsp.get_client_by_id(args.data.client_id)) - -- local bufnr = args.buf - -- - -- if client then - -- -- vim.lsp.set_log_level 'trace' - -- print("Attaching to: " .. client.name .. " attached to buffer " .. bufnr) - -- ------------------------------------------------------------------ - -- if client.name == "clangd" then - -- vim.api.nvim_buf_create_user_command(0, "LspClangdSwitchSourceHeader", function() - -- local method_name = "textDocument/switchSourceHeader" - -- local params = vim.lsp.util.make_text_document_params(bufnr) - -- client.request(method_name, params, function(err, result) - -- if err then - -- error(tostring(err)) - -- end - -- if not result then - -- vim.notify("corresponding file cannot be determined") - -- return - -- end - -- vim.cmd.edit(vim.uri_to_fname(result)) - -- end, bufnr) - -- end, { desc = "Switch between source/header" }) - -- end - -- ------------------------------------------------------------------ - -- --- Skip this if you are using blink - -- if not bok then - -- if client:supports_method("textDocument/completion", { bufnr = bufnr }) then - -- vim.lsp.completion.enable(true, client.id, args.buf, { autotrigger = true }) - -- end - -- vim.diagnostic.config({ - -- current_line = true, - -- virtual_lines = { - -- current_line = true, - -- }, - -- }) - -- vim.cmd([[set completeopt+=noselect]]) - -- end - -- - -- ------------------------------------------------------------------ - -- if client.server_capabilities.documentHighlightProvider then - -- local highlight_augroup = - -- vim.api.nvim_create_augroup("kickstart-lsp-highlight", { clear = false }) - -- vim.api.nvim_create_autocmd({ "CursorHold", "CursorHoldI" }, { - -- buffer = bufnr, - -- group = highlight_augroup, - -- callback = vim.lsp.buf.document_highlight, - -- }) - -- -- - -- vim.api.nvim_create_autocmd({ "CursorMoved", "CursorMovedI" }, { - -- buffer = bufnr, - -- group = highlight_augroup, - -- callback = vim.lsp.buf.clear_references, - -- }) - -- -- - -- vim.api.nvim_create_autocmd("LspDetach", { - -- group = vim.api.nvim_create_augroup("kickstart-lsp-detach", { clear = true }), - -- callback = function(event) - -- vim.lsp.buf.clear_references() - -- vim.api.nvim_clear_autocmds({ - -- group = "kickstart-lsp-highlight", - -- buffer = event.buf, - -- }) - -- end, - -- }) - -- -- - -- end - -- local bufkeymap = function(mode, lhs, rhs, desc) - -- vim.keymap.set(mode, lhs, rhs, { buffer = bufnr, silent = true, desc = desc }) -- noremap by default - -- end - -- -- Disable defaults - -- pcall(vim.keymap.del, "n", "gra") - -- pcall(vim.keymap.del, "n", "gri") - -- pcall(vim.keymap.del, "n", "grn") - -- pcall(vim.keymap.del, "n", "grr") - -- pcall(vim.keymap.del, "n", "gO") - -- pcall(vim.keymap.del, "n", "K") - -- -- - -- -- Quickfix list - -- bufkeymap("n", "[q", vim.cmd.cprev, "Previous quickfix item") - -- bufkeymap("n", "]q", vim.cmd.cnext, "Next quickfix item") - -- - -- -- Diagnostic keymaps - -- bufkeymap( - -- "n", - -- "[d", - -- "vim.diagnostic.goto_prev()", - -- "Go to previous [d]iagnostic message" - -- ) - -- bufkeymap( - -- "n", - -- "]d", - -- "vim.diagnostic.goto_next()", - -- "Go to next [d]iagnostic message" - -- ) - -- bufkeymap("n", "gle", vim.diagnostic.open_float, "Show diagnostic [e]rror messages") - -- -- bufkeymap('n', 'gle', 'Telescope diagnostics', 'Show diagnostic [e]rror messages') - -- bufkeymap("n", "glq", vim.diagnostic.setloclist, "Open diagnostic [q]uickfix list") - -- -- - -- -- stylua: ignore start - -- -- << local trouble = require("trouble").toggle - -- -- << bufkeymap('n', "tt", function() trouble() end, "Toggle Trouble") - -- -- << bufkeymap('n', "tq", function() trouble("quickfix") end, "Quickfix List") - -- -- << bufkeymap('n', "dr", function() trouble("lsp_references") end, "References") - -- -- << bufkeymap('n', "dd", function() trouble("document_diagnostics") end, "Document Diagnostics") - -- -- << bufkeymap('n', "dw", function() trouble("workspace_diagnostics") end, "Workspace Diagnostics") - -- -- stylua: ignore end - -- -- - -- if client.server_capabilities.hoverProvider then - -- bufkeymap("n", "glk", vim.lsp.buf.hover, "Hover Documentation") - -- end - -- if client.server_capabilities.signatureHelpProvider then - -- bufkeymap({ "i", "n" }, "gls", vim.lsp.buf.signature_help, "Show signature") - -- end - -- if client.server_capabilities.declarationProvider then - -- bufkeymap("n", "glD", vim.lsp.buf.declaration, "Goto [D]eclaration") - -- end - -- if client.server_capabilities.definitionProvider then - -- bufkeymap("n", "gld", vim.lsp.buf.definition, "Go to [d]efinition") - -- -- bufkeymap('n', 'gld', 'Telescope lsp_definitions', '[G]oto [D]efinition') - -- end - -- if client.server_capabilities.typeDefinitionProvider then - -- bufkeymap("n", "glt", vim.lsp.buf.type_definition, "Goto [t]ype definition") - -- -- bufkeymap('n', 'glt', 'Telescope lsp_type_definitions', 'Goto [t]ype definition') - -- end - -- if client.server_capabilities.implementationProvider then - -- bufkeymap("n", "gli", vim.lsp.buf.implementation, "Goto [i]mplementation") - -- -- bufkeymap('n', 'gli', 'Telescope lsp_implementations', 'Goto [i]mplementation') - -- end - -- - -- -- bufkeymap('n', 'glr', '(CodeAction, implementation, rename, references)', 'CodeAction, implementation, rename, references') - -- if client.server_capabilities.referencesProvider then - -- -- bufkeymap('n', 'gr', vim.lsp.buf.references, 'List references') - -- bufkeymap("n", "glr", "Telescope lsp_references", "Goto [r]eferences") - -- -- bufkeymap('n', 'glr', 'Telescope lsp_references', '[G]oto [R]eferences') - -- end - -- if client.server_capabilities.renameProvider then - -- -- bufkeymap('n', '', vim.lsp.buf.rename, 'Rename symbol') - -- bufkeymap("n", "glR", vim.lsp.buf.rename, "[R]ename") - -- end - -- if client.server_capabilities.codeActionProvider then - -- bufkeymap("n", "gla", vim.lsp.buf.code_action, "Code [a]ction") - -- end - -- - -- if client.server_capabilities.documentSymbolProvider then - -- bufkeymap("n", "glwd", vim.lsp.buf.document_symbol, "[D]ocument symbols") - -- -- bufkeymap('n', 'glwd', Telescope lsp_document_symbols, '[D]ocument [S]ymbols') - -- end - -- if client:supports_method("workspace/symbol") then - -- -- if client.server_capabilities.workspaceSymbolProvider then - -- bufkeymap("n", "glww", vim.lsp.buf.workspace_symbol, "List [w]orkspace symbols") - -- -- bufkeymap('n', 'glww', require('telescope.builtin').lsp_dynamic_workspace_symbols, '[W]orkspace [S]ymbols') - -- end - -- if client.server_capabilities.workspace then - -- bufkeymap("n", "glwa", vim.lsp.buf.add_workspace_folder, "Workspace [a]dd folder") - -- bufkeymap( - -- "n", - -- "glwr", - -- vim.lsp.buf.remove_workspace_folder, - -- "Workspace [r]emove folder" - -- ) - -- bufkeymap("n", "glwl", function() - -- print(vim.inspect(vim.lsp.buf.list_workspace_folders())) - -- end, "[W]orkspace [L]ist folders") - -- end - -- -- - -- if client.supports_method("textDocument/switchSourceHeader") then - -- bufkeymap( - -- "n", - -- "glws", - -- "LspClangdSwitchSourceHeader", - -- "[S]witch Source/Header (C/C++)" - -- ) - -- end - -- - -- if client.supports_method("textDocument/formatting") then - -- -- if client.server_capabilities.documentFormattingProvider then - -- bufkeymap({ "n", "x" }, "glf", function() - -- vim.lsp.buf.format({ bufnr = bufnr, async = true }) - -- -- require('conform').format({ bufnr = bufnr, async = true }) - -- end, "[f]ormat buffer") - -- end - -- -- - -- if client.server_capabilities.inlayHintProvider and vim.lsp.inlay_hint then - -- bufkeymap("n", "glh", function() - -- vim.lsp.inlay_hint.enable( - -- not vim.lsp.inlay_hint.is_enabled({ bufnr = bufnr }), - -- { bufnr = bufnr } - -- ) - -- end, "[h]ints toggle") - -- ------------------------------------------------------------------------------ - -- end - -- end - -- -- - -- vim.lsp.handlers["textDocument/publishDiagnostics"] = - -- vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { - -- signs = true, - -- underline = true, - -- virtual_text = { - -- spacing = 5, - -- min = vim.diagnostic.severity.HINT, - -- }, - -- update_in_insert = true, - -- }) - -- -- - -- vim.cmd([[autocmd FileType * set formatoptions-=ro]]) - -- -- - -- end, - -- }) - -- -- --> End LspAttach autocommand - -- end, - -- }, - -- { - -- "folke/trouble.nvim", - -- event = "LspAttach", - -- opts = { - -- focus = true, - -- auto_open = false, - -- auto_jump = false, - -- auto_refresh = false, - -- }, - -- }, - -- { "j-hui/fidget.nvim", opts = {} }, -- status bottom right - -- }, - -- }, + { + 'saghen/blink.cmp', + dependencies = { 'rafamadriz/friendly-snippets' }, + version = '1.*', + opts = { + appearance = { + use_nvim_cmp_as_default = false, + nerd_font_variant = 'mono', + }, + completion = { + accept = { + auto_brackets = { + enabled = true, + }, + }, + menu = { + draw = { + treesitter = { 'lsp' }, + }, + }, + documentation = { + auto_show = true, + auto_show_delay_ms = 200, + }, + ghost_text = { + enabled = vim.g.ai_cmp, + }, + }, + sources = { + default = { 'lsp', 'path', 'snippets', 'buffer' }, + }, + cmdline = { + enabled = false, + keymap = { + preset = 'cmdline', + [''] = false, + [''] = false, + }, + sources = { + default = { 'lsp', 'path', 'snippets', 'buffer' }, + }, + completion = { + menu = { + auto_show = true, + }, + ghost_text = { + enabled = true, + }, + }, + }, + keymap = { + preset = 'super-tab', + [''] = { 'insert_next' }, + [''] = { 'insert_prev' }, + [''] = { 'select_and_accept' }, + [''] = { 'hide', 'show' }, + }, + }, + }, -- { 'nvim-tree/nvim-tree.lua', From 1c2132e8753e2d47be75fc024dcee6827d0f3b7d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 21:30:56 +0300 Subject: [PATCH 0010/1406] update --- lua/platformio/boilerplate.lua | 46 +++++++++++++++++++++++++++++++++- lua/platformio/lspClangd.lua | 2 ++ minimal_config.lua | 1 + 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index ee349a71..bb7157d7 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -4,6 +4,7 @@ local uv = vim.loop local boilerplate = {} boilerplate['arduino'] = { + src_path = 'src', filename = 'main.cpp', content = [[ #include @@ -18,13 +19,56 @@ void loop() { ]], } +boilerplate['.clangd'] = { + src_path = '.', + filename = '.clangd', + content = [[ +CompileFlags: + Remove: [ + -misc-definitions-in-headers, + -fno-tree-switch-conversion, + -mtext-section-literals, + -mlong-calls, + -mlongcalls, + -fstrict-volatile-bitfields, + -free*, + -fipa-pta*, + -march=*, + -mabi=*, + -mcpu=*, + ] +Diagnostics: + Suppress: [ + "misc-definitions-in-headers", + "pp_including_mainfile_in_preamble", + "misc-unused-using-decls", + "unused-includes", + ] + ClangTidy: + Remove: [ + readability-*, + cert-err58-cpp, + llvmlibc-*, + fuchsia-*, + hicpp-avoid-c-arrays, + cppcoreguidelines-*, + llvm-*, + google-*, + bugprone-*, + hicpp-vararg, + modernize-*, + ] + +]], +} + function M.boilerplate_gen(framework) local entry = boilerplate[framework] if not entry then return end - local src_path = 'src' + local src_path = entry.src_path local stat = uv.fs_stat(src_path) if not stat or stat.type ~= 'directory' then diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 09aabd5f..147a056f 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -133,6 +133,8 @@ vim.lsp.config('clangd', clangd) local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') if mok then mason_lspconfig.setup({}) + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen('.clangd') end local config = require('platformio').config diff --git a/minimal_config.lua b/minimal_config.lua index c8adb181..dd0bcea8 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -19,6 +19,7 @@ vim.opt.shiftround = true -- Round indent vim.opt.shiftwidth = 2 -- Size of an indent vim.opt.smartindent = true -- Insert indents automatically vim.opt.expandtab = true -- Use spaces instead of tabs +vim.opt.clipboard = vim.env.SSH_TTY and '' or 'unnamedplus' -- Sync with system clipboard vim.g.have_nerd_font = true vim.g.mapleader = ' ' From c9ff71aeb5a24f6547f0534852ffb5c93a07c37c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 21:34:21 +0300 Subject: [PATCH 0011/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index bb7157d7..82bc6c5f 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -20,7 +20,7 @@ void loop() { } boilerplate['.clangd'] = { - src_path = '.', + src_path = './', filename = '.clangd', content = [[ CompileFlags: From 76ac1786f176171c2342eca8580e739bf7412afb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 21:47:08 +0300 Subject: [PATCH 0012/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 82bc6c5f..b2279f7d 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -93,7 +93,7 @@ function M.boilerplate_gen(framework) if not fd then return end - + print(entry.content) uv.fs_write(fd, entry.content) uv.fs_close(fd) end From 3a73caeba2f979e38231f9bb6f2c6e5eaa4f9646 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 21:52:38 +0300 Subject: [PATCH 0013/1406] update --- lua/platformio/lspClangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 147a056f..40fc7731 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -134,7 +134,7 @@ local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') if mok then mason_lspconfig.setup({}) local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen('.clangd') + boilerplate_gen([[.clangd]]) end local config = require('platformio').config From 9349a525a030016fa313541ff9eb361c758af8dc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 22:01:16 +0300 Subject: [PATCH 0014/1406] update --- lua/platformio/boilerplate.lua | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index b2279f7d..53a7a241 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -4,7 +4,9 @@ local uv = vim.loop local boilerplate = {} boilerplate['arduino'] = { - src_path = 'src', + + -- local platformioRootDir = vim.fs.root(vim.fn.getcwd(), { 'platformio.ini' }) -- cwd and parents + src_path = vim.fn.getcwd() .. 'src', filename = 'main.cpp', content = [[ #include @@ -20,7 +22,7 @@ void loop() { } boilerplate['.clangd'] = { - src_path = './', + src_path = vim.fn.getcwd(), filename = '.clangd', content = [[ CompileFlags: @@ -63,6 +65,7 @@ Diagnostics: } function M.boilerplate_gen(framework) + print('here') local entry = boilerplate[framework] if not entry then return From 61fa3cc2358d734a55c4019d0eeb7554a8f04d24 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 22:02:59 +0300 Subject: [PATCH 0015/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 53a7a241..92180734 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -91,12 +91,12 @@ function M.boilerplate_gen(framework) end end + print(entry.content) local file_path = src_path .. '/' .. entry.filename local fd = uv.fs_open(file_path, 'w', 420) if not fd then return end - print(entry.content) uv.fs_write(fd, entry.content) uv.fs_close(fd) end From 51efba67416a1ee12a82c7e84cab31864f38645f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 22:05:38 +0300 Subject: [PATCH 0016/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 92180734..96f1c337 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -65,7 +65,7 @@ Diagnostics: } function M.boilerplate_gen(framework) - print('here') + print(framework) local entry = boilerplate[framework] if not entry then return From 8af11441b1d77d7dcdd85e4172900faedc7b8a31 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 22:07:25 +0300 Subject: [PATCH 0017/1406] update --- lua/platformio/boilerplate.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 96f1c337..c33abaa2 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -67,6 +67,7 @@ Diagnostics: function M.boilerplate_gen(framework) print(framework) local entry = boilerplate[framework] + print(entry.content) if not entry then return end From 2fc8fb3668ea4a1d31e5c6e82eefe06a76ef3a3c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 22:08:51 +0300 Subject: [PATCH 0018/1406] update --- lua/platformio/boilerplate.lua | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index c33abaa2..58e9c598 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -65,12 +65,11 @@ Diagnostics: } function M.boilerplate_gen(framework) - print(framework) local entry = boilerplate[framework] - print(entry.content) if not entry then return end + print(entry.content) local src_path = entry.src_path local stat = uv.fs_stat(src_path) From 8c9cbabbe2ddb4e2c1d977da6151471a42c54739 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 22:10:43 +0300 Subject: [PATCH 0019/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 58e9c598..8e97f9b7 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -69,7 +69,7 @@ function M.boilerplate_gen(framework) if not entry then return end - print(entry.content) + print(entry.src_path) local src_path = entry.src_path local stat = uv.fs_stat(src_path) From 7b8c55fd7298948520e1255a3e84353b45457909 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 22:22:13 +0300 Subject: [PATCH 0020/1406] update --- lua/platformio/boilerplate.lua | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 8e97f9b7..b43294bf 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -6,7 +6,7 @@ local boilerplate = {} boilerplate['arduino'] = { -- local platformioRootDir = vim.fs.root(vim.fn.getcwd(), { 'platformio.ini' }) -- cwd and parents - src_path = vim.fn.getcwd() .. 'src', + src_path = 'src', --vim.fn.getcwd() .. 'src', filename = 'main.cpp', content = [[ #include @@ -22,7 +22,7 @@ void loop() { } boilerplate['.clangd'] = { - src_path = vim.fn.getcwd(), + src_path = 'src', --vim.fn.getcwd(), filename = '.clangd', content = [[ CompileFlags: @@ -69,7 +69,6 @@ function M.boilerplate_gen(framework) if not entry then return end - print(entry.src_path) local src_path = entry.src_path local stat = uv.fs_stat(src_path) From 4f6071c9e69b73bd9c41ca45a534c79723c1d72b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 22:25:00 +0300 Subject: [PATCH 0021/1406] update --- lua/platformio/boilerplate.lua | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index b43294bf..c0079198 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -73,9 +73,11 @@ function M.boilerplate_gen(framework) local src_path = entry.src_path local stat = uv.fs_stat(src_path) + print('0 ' .. entry.src_path) if not stat or stat.type ~= 'directory' then return end + print('1 ' .. entry.src_path) local handle = uv.fs_scandir(src_path) if handle then @@ -89,6 +91,7 @@ function M.boilerplate_gen(framework) end end end + print('2 ' .. entry.src_path) print(entry.content) local file_path = src_path .. '/' .. entry.filename From 4535d58b6090a3508f8f0bb282806b5e96913c2c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 22:33:20 +0300 Subject: [PATCH 0022/1406] update --- lua/platformio/boilerplate.lua | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index c0079198..fd571660 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -82,13 +82,20 @@ function M.boilerplate_gen(framework) local handle = uv.fs_scandir(src_path) if handle then while true do - local name = uv.fs_scandir_next(handle) + local name, type_str = uv.fs_scandir_next(handle) if not name then break end - if name ~= '.' and name ~= '..' then - return + + -- Process the entry + if type_str == 'directory' then + print('Found directory: ' .. name) + elseif type_str == 'file' then + print('Found file: ' .. name) end + -- if name ~= '.' and name ~= '..' then + -- return + -- end end end print('2 ' .. entry.src_path) From d328a197d6a1744dacf118bcec37cea537f261c2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 22:38:51 +0300 Subject: [PATCH 0023/1406] update --- lua/platformio/boilerplate.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index fd571660..1ad6cb67 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -6,7 +6,7 @@ local boilerplate = {} boilerplate['arduino'] = { -- local platformioRootDir = vim.fs.root(vim.fn.getcwd(), { 'platformio.ini' }) -- cwd and parents - src_path = 'src', --vim.fn.getcwd() .. 'src', + src_path = '.', --vim.fn.getcwd() .. 'src', filename = 'main.cpp', content = [[ #include @@ -22,7 +22,7 @@ void loop() { } boilerplate['.clangd'] = { - src_path = 'src', --vim.fn.getcwd(), + src_path = '.', --vim.fn.getcwd(), filename = '.clangd', content = [[ CompileFlags: From 4e111e8e4a9795795c5701663407ad65c7f5d722 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 22:42:01 +0300 Subject: [PATCH 0024/1406] update --- lua/platformio/boilerplate.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 1ad6cb67..bee06f84 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -6,7 +6,7 @@ local boilerplate = {} boilerplate['arduino'] = { -- local platformioRootDir = vim.fs.root(vim.fn.getcwd(), { 'platformio.ini' }) -- cwd and parents - src_path = '.', --vim.fn.getcwd() .. 'src', + src_path = './src', --vim.fn.getcwd() .. 'src', filename = 'main.cpp', content = [[ #include @@ -22,7 +22,7 @@ void loop() { } boilerplate['.clangd'] = { - src_path = '.', --vim.fn.getcwd(), + src_path = './src', --vim.fn.getcwd(), filename = '.clangd', content = [[ CompileFlags: From 22bf9fdd3a8d6527d51509791a155e089af8bbeb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 23:17:02 +0300 Subject: [PATCH 0025/1406] update --- lua/platformio/boilerplate.lua | 40 ++++++---------------------------- 1 file changed, 7 insertions(+), 33 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index bee06f84..f5e9d1bc 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -6,7 +6,7 @@ local boilerplate = {} boilerplate['arduino'] = { -- local platformioRootDir = vim.fs.root(vim.fn.getcwd(), { 'platformio.ini' }) -- cwd and parents - src_path = './src', --vim.fn.getcwd() .. 'src', + src_path = vim.fn.getcwd() .. '/src', filename = 'main.cpp', content = [[ #include @@ -22,7 +22,7 @@ void loop() { } boilerplate['.clangd'] = { - src_path = './src', --vim.fn.getcwd(), + src_path = vim.fn.getcwd(), filename = '.clangd', content = [[ CompileFlags: @@ -69,39 +69,13 @@ function M.boilerplate_gen(framework) if not entry then return end - - local src_path = entry.src_path - local stat = uv.fs_stat(src_path) - - print('0 ' .. entry.src_path) - if not stat or stat.type ~= 'directory' then + -- + local file_path = entry.src_path .. '/' .. entry.filename + if vim.uv.fs_stat(file_path) then + vim.print('file exists') return end - print('1 ' .. entry.src_path) - - local handle = uv.fs_scandir(src_path) - if handle then - while true do - local name, type_str = uv.fs_scandir_next(handle) - if not name then - break - end - - -- Process the entry - if type_str == 'directory' then - print('Found directory: ' .. name) - elseif type_str == 'file' then - print('Found file: ' .. name) - end - -- if name ~= '.' and name ~= '..' then - -- return - -- end - end - end - print('2 ' .. entry.src_path) - - print(entry.content) - local file_path = src_path .. '/' .. entry.filename + -- local fd = uv.fs_open(file_path, 'w', 420) if not fd then return From d05da6ed58352d7daed97a68a49e5ad1634c9517 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 23:19:44 +0300 Subject: [PATCH 0026/1406] update --- lua/platformio/boilerplate.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index f5e9d1bc..54792b4b 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -72,7 +72,6 @@ function M.boilerplate_gen(framework) -- local file_path = entry.src_path .. '/' .. entry.filename if vim.uv.fs_stat(file_path) then - vim.print('file exists') return end -- From d5b71cfb5ee26acec25002e140e66580633d9258 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 23:25:39 +0300 Subject: [PATCH 0027/1406] update --- lua/platformio/lspClangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 40fc7731..92041bc7 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -134,7 +134,7 @@ local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') if mok then mason_lspconfig.setup({}) local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen([[.clangd]]) + -- boilerplate_gen([[.clangd]]) end local config = require('platformio').config From eb0047885be0f1b63dae2a2a5a5d5c7c0f956382 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 31 Mar 2026 23:27:31 +0300 Subject: [PATCH 0028/1406] update --- lua/platformio/lspClangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 92041bc7..40fc7731 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -134,7 +134,7 @@ local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') if mok then mason_lspconfig.setup({}) local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - -- boilerplate_gen([[.clangd]]) + boilerplate_gen([[.clangd]]) end local config = require('platformio').config From 7c205f889cfdb965a1590efff49fbc9a0ec5d009 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 08:51:24 +0300 Subject: [PATCH 0029/1406] update --- lua/platformio/boilerplate.lua | 25 +++++++++++ lua/platformio/init.lua | 4 +- lua/platformio/lspClangd.lua | 81 ++++++++++++++-------------------- lua/platformio/piolsp.lua | 21 +++++++-- lua/platformio/utils.lua | 16 ++++--- 5 files changed, 88 insertions(+), 59 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 54792b4b..3ef3bc74 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -21,6 +21,31 @@ void loop() { ]], } +boilerplate['.clangd_cmd'] = { + src_path = vim.fn.getcwd(), + filename = '.clangd_cmd', + content = [[ +clangd +--all-scopes-completion +--background-index +--clang-tidy +--compile_args_from=filesystem +--compile-commands-dir=. +--enable-config +--completion-parse=always +--completion-style=detailed +--header-insertion=iwyu +--header-insertion-decorators +-j=12 +--log=verbose +--offset-encoding=utf-8 +--pch-storage=memory +--pretty +--query-driver=** +--ranking-model=decision_forest +]], +} + boilerplate['.clangd'] = { src_path = vim.fn.getcwd(), filename = '.clangd', diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index d7548765..1ec15ccc 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -181,12 +181,12 @@ function M.setup(user_config) M.config = vim.tbl_deep_extend('force', M.config, user_config or {}) end + require('platformio.piomenu').piomenu(M.config) + if M.config.lspClangd.enabled == true then -- vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) require('platformio.lspClangd') end - - require('platformio.piomenu').piomenu(M.config) end return M diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 40fc7731..6fe45d7b 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -1,36 +1,41 @@ --------------------------------------------------------------------------------- --- INFO: Mason packages install for lint and formater - -local fok, fidget = pcall(require, 'fidget') -if fok then - fidget.setup({}) +local ok, result +ok, result = pcall(require, 'fidget') +if ok then + result.setup({}) end -local tok, trouble = pcall(require, 'trouble') -if tok then - trouble.setup({}) +----------------------------------------------------------------------------------------- +ok, result = pcall(require, 'trouble') +if ok then + result.setup({}) end +----------------------------------------------------------------------------------------- +-- INFO: Mason packages install for lint and formater -- mason.setup() -local mason = require('mason') - -mason.setup({ - PATH = 'append', - ui = { - border = 'single', - icons = { - package_installed = '✓', - package_pending = '➜', - package_uninstalled = '✗', +ok, result = pcall(require, 'mason') +if ok then + result.setup({ + PATH = 'append', + ui = { + border = 'single', + icons = { + package_installed = '✓', + package_pending = '➜', + package_uninstalled = '✗', + }, }, - }, -}) + }) +end + -- List of packages you want Mason to ensure are installed local ensure_installed = { - -- 'clang-format', + 'clang-format', + 'biome', } --- Mason function to install or ensure formatters/linters are installed +-- call mason-registry function to install or ensure formatters/linters are installed local mr = require('mason-registry') mr.refresh(function() for _, tool in ipairs(ensure_installed) do @@ -64,32 +69,13 @@ require('mason-lspconfig').setup({ -- automatic_enable = true, -- this will automatically enable LSP servers after install }) -local cmd = { - 'clangd', - '--all-scopes-completion', - '--background-index', - '--clang-tidy', - '--compile_args_from=filesystem', - '--compile-commands-dir=.', -- so this is in default directory (parent of /src) no need for it. - '--enable-config', - '--completion-parse=always', - '--completion-style=detailed', - '--header-insertion=iwyu', - '--header-insertion-decorators', - '-j=12', - '--log=verbose', -- for debugging - -- '--log=error', - '--offset-encoding=utf-8', - '--pch-storage=memory', - '--pretty', - '--query-driver=**', - '--ranking-model=decision_forest', -} +----------------------------------------------------------------------------------------- +local cmd = { 'clangd' } local path = vim.fn.getcwd() local fname = string.format('%s\\.clangd_cmd', path) if vim.fn.filereadable(fname) == 1 then - local ok, result = pcall(vim.fn.readfile, fname) + ok, result = pcall(vim.fn.readfile, fname) if ok then cmd = result -- print(vim.inspect(cmd)) @@ -97,11 +83,11 @@ if vim.fn.filereadable(fname) == 1 then end local capabilities = vim.lsp.protocol.make_client_capabilities() -local bok, _ = pcall(require, 'blink') -if bok then +ok, _ = pcall(require, 'blink') +if ok then capabilities = vim.tbl_deep_extend('force', capabilities, require('blink.cmp').get_lsp_capabilities({}, false)) end ----@type vim.lsp.Config + local clangd = { cmd = cmd, filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, @@ -135,6 +121,7 @@ if mok then mason_lspconfig.setup({}) local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]]) + boilerplate_gen([[.clangd_cmd]]) end local config = require('platformio').config diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index b122cf42..e70fd7cf 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -13,6 +13,7 @@ local function escape_flags(flags) -- Escape parentheses (common in include paths) escaped = escaped:gsub('%(', '\\(') escaped = escaped:gsub('%)', '\\)') + escaped = escaped:gsub('%s+', '\\ ') table.insert(escaped_flags, escaped) end @@ -92,8 +93,10 @@ local function gitignore_lsp_configs(config_file) end file = io.open(gitignore_path, 'a') - file:write(config_file .. '\n') - file:close() + if file then + file:write(config_file .. '\n') + file:close() + end end function M.gen_clangd_config() @@ -102,6 +105,11 @@ function M.gen_clangd_config() end function M.piolsp() + if not utils.pio_install_check() then + return + end + utils.cd_pioini() + if config.lsp == 'clangd' and config.clangd_source == 'compiledb' then utils.shell_cmd_blocking('pio run -t compiledb') gitignore_lsp_configs('compile_commands.json') @@ -117,7 +125,14 @@ function M.piolsp() end end vim.notify('LSP config generation completed!', vim.log.levels.INFO) - vim.cmd('LspRestart') + + if vim.fn.has('nvim-0.12') then + if #vim.lsp.get_clients() > 0 then + vim.cmd('lsp restart') + end + else + vim.cmd('LspRestart') + end end return M diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 8b877a62..e0849e20 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -324,20 +324,22 @@ function M.file_exists(name) end end -function M.get_pioini_path() +function M.set_platformioRootDir() + if vim.g.platformioRootDir ~= nil then + return + end for _, path in pairs(paths) do if M.file_exists(path .. '/platformio.ini') then - return path + vim.g.platformioRootDir = path + return end end + vim.notify('Could not find platformio.ini, run :Pioinit to create a new project', vim.log.levels.ERROR) end function M.cd_pioini() - if vim.g.platformioRootDir ~= nil then - vim.cmd('cd ' .. vim.g.platformioRootDir) - else - vim.cmd('cd ' .. M.get_pioini_path()) - end + M.set_platformioRootDir() + vim.cmd('cd ' .. vim.g.platformioRootDir) end function M.pio_install_check() From 8dbb153a4cc1d9d9e755493e07be58e1920bde3c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 09:38:25 +0300 Subject: [PATCH 0030/1406] update --- lua/platformio/piolsp.lua | 98 ++------------------------------------- 1 file changed, 4 insertions(+), 94 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index e70fd7cf..d0bf6747 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -3,80 +3,6 @@ local M = {} local utils = require('platformio.utils') local config = require('platformio').config -local function escape_flags(flags) - local escaped_flags = {} - - for _, flag in ipairs(flags) do - local escaped = flag - escaped = escaped:gsub('\\', '\\\\') -- Escape backslashes first - escaped = escaped:gsub('"', '\\"') -- Escape double quotes (for -D macros) - -- Escape parentheses (common in include paths) - escaped = escaped:gsub('%(', '\\(') - escaped = escaped:gsub('%)', '\\)') - escaped = escaped:gsub('%s+', '\\ ') - table.insert(escaped_flags, escaped) - end - - return escaped_flags -end - -local function process_ccls() - local flags_allowed = { '%', '-W', '-std' } - - local f = io.open(vim.fs.joinpath(vim.g.platformioRootDir, '.ccls'), 'rb') - if not f then - vim.notify('.ccls file not found', vim.log.levels.ERROR) - return {} - end - - local compiler = f:read() - local build_flags = { compiler } - - for line in f:lines() do - if #line == 0 or string.sub(line, 1, 1) == '#' then - goto continue - end - - if utils.check_prefix(line, '-I') or utils.check_prefix(line, '-D') then - table.insert(build_flags, line) - end - if utils.check_prefix(line, '%cpp') then - splitted = utils.strsplit(line, ' ') - for _, flag in ipairs(splitted) do - for _, flag_check in ipairs(flags_allowed) do - if utils.check_prefix(flag, flag_check) then - table.insert(build_flags, flag) - end - end - end - end - - ::continue:: - end - - f:close() - - return escape_flags(build_flags) -end - -local function gen_compile_commands(build_flags) - local project_root = vim.g.platformioRootDir - local build_cmd = '' - for _, flag in ipairs(build_flags) do - build_cmd = build_cmd .. flag .. ' ' - end - - local entry = { { - directory = project_root, - file = vim.fs.joinpath(project_root, 'src', 'main.cpp'), - command = build_cmd, - } } - - local f = io.open(vim.fs.joinpath(project_root, 'compile_commands.json'), 'w') - f:write(vim.json.encode(entry, { indent = ' ', sort_keys = true })) - f:close() -end - local function gitignore_lsp_configs(config_file) local gitignore_path = vim.fs.joinpath(vim.g.platformioRootDir, '.gitignore') local file = io.open(gitignore_path, 'r') @@ -99,32 +25,14 @@ local function gitignore_lsp_configs(config_file) end end -function M.gen_clangd_config() - local build_flags = process_ccls() - gen_compile_commands(build_flags) -end - function M.piolsp() if not utils.pio_install_check() then return end utils.cd_pioini() - if config.lsp == 'clangd' and config.clangd_source == 'compiledb' then - utils.shell_cmd_blocking('pio run -t compiledb') - gitignore_lsp_configs('compile_commands.json') - else - utils.shell_cmd_blocking('pio project init --ide=vim') - - if config.lsp == 'clangd' then - M.gen_clangd_config() - gitignore_lsp_configs('compile_commands.json') - os.remove(vim.fs.joinpath(vim.g.platformioRootDir, '.ccls')) - else - gitignore_lsp_configs('.ccls') - end - end - vim.notify('LSP config generation completed!', vim.log.levels.INFO) + utils.shell_cmd_blocking('pio run -t compiledb') + gitignore_lsp_configs('compile_commands.json') if vim.fn.has('nvim-0.12') then if #vim.lsp.get_clients() > 0 then @@ -133,6 +41,8 @@ function M.piolsp() else vim.cmd('LspRestart') end + + vim.notify('LSP: compile_commands.jsoncon generation/update completed!', vim.log.levels.INFO) end return M From a35b27c8145a6bd9fb487a139978866080f95052 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 09:44:59 +0300 Subject: [PATCH 0031/1406] update --- lua/platformio/lspClangd.lua | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 6fe45d7b..2071b9a1 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -128,4 +128,12 @@ local config = require('platformio').config if config.lspClangd.attach.enabled then require('platformio.lspAttach') end + +if vim.fn.has('nvim-0.12') then + if #vim.lsp.get_clients() > 0 then + vim.cmd('lsp restart') + end +else + vim.cmd('LspRestart') +end ---------------------------------------------------------------------------------- From 0cc0285121a7928f0ff1acdd1893028018ce1b64 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 09:48:17 +0300 Subject: [PATCH 0032/1406] update --- lua/platformio/lspClangd.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 2071b9a1..605f1c19 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -70,6 +70,9 @@ require('mason-lspconfig').setup({ }) ----------------------------------------------------------------------------------------- +local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +boilerplate_gen([[.clangd]]) +boilerplate_gen([[.clangd_cmd]]) local cmd = { 'clangd' } local path = vim.fn.getcwd() @@ -119,9 +122,6 @@ vim.lsp.config('clangd', clangd) local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') if mok then mason_lspconfig.setup({}) - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen([[.clangd]]) - boilerplate_gen([[.clangd_cmd]]) end local config = require('platformio').config From 6c246a0e92a43b3245356b40d7851c5c4bcade9a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 09:50:33 +0300 Subject: [PATCH 0033/1406] update --- lua/platformio/lspClangd.lua | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 605f1c19..fafad14b 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -73,6 +73,7 @@ require('mason-lspconfig').setup({ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]]) boilerplate_gen([[.clangd_cmd]]) + local cmd = { 'clangd' } local path = vim.fn.getcwd() @@ -128,12 +129,4 @@ local config = require('platformio').config if config.lspClangd.attach.enabled then require('platformio.lspAttach') end - -if vim.fn.has('nvim-0.12') then - if #vim.lsp.get_clients() > 0 then - vim.cmd('lsp restart') - end -else - vim.cmd('LspRestart') -end ---------------------------------------------------------------------------------- From 3c5a46a37619ba1dbd768ab48d8d1383ed43eec9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 10:03:11 +0300 Subject: [PATCH 0034/1406] update --- minimal_config.lua | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/minimal_config.lua b/minimal_config.lua index dd0bcea8..7c65c5d9 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -206,6 +206,19 @@ require('lazy').setup(plugins, { }) ---------------------------------------------------------------------------------------- +vim.api.nvim_create_autocmd('User', { + pattern = 'LazyDone', -- Triggers after the UI enters and startup time is calculated + desc = 'Update lazy.nvim plugins in the background', + callback = function() + require('lazy').sync({ + wait = false, -- Makes the operation asynchronous + show = false, -- Prevents the Lazy UI from automatically opening + }) + -- You can add a notification here if you like + -- vim.notify("Lazy plugins sync started in background", vim.log.levels.INFO) + end, +}) + -- platformio config local pioConfig = { lspClangd = { From 333bb1a716254bfe0fce425b81bcbfaf1adb590a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 10:09:00 +0300 Subject: [PATCH 0035/1406] update --- lua/platformio/boilerplate.lua | 253 +++++++++++++++++++++++++++++++++ lua/platformio/lspClangd.lua | 1 + 2 files changed, 254 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 3ef3bc74..d4fd878d 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -46,6 +46,259 @@ clangd ]], } +boilerplate['.clang_format'] = { + src_path = vim.fn.getcwd(), + filename = '.clang_format', + content = [[ +--- +Language: Cpp +# BasedOnStyle: LLVM +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCaseColons: false +AlignEscapedNewlines: Right +AlignOperands: Align +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowBreakBeforeNoexceptSpecifier: Never +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortCompoundRequirementOnASingleLine: true +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: MultiLine +AttributeMacros: + - __capability +BinPackArguments: true +BinPackParameters: true +BitFieldColonSpacing: Both +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterExternBlock: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakAdjacentStringLiterals: true +BreakAfterAttributes: Leave +BreakAfterJavaFieldAnnotations: false +BreakArrays: true +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: Always +BreakBeforeBraces: Attach +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeColon +BreakInheritanceList: BeforeColon +BreakStringLiterals: true +ColumnLimit: 80 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: false +IndentExternBlock: AfterExternBlock +IndentGotoLabels: true +IndentPPDirectives: None +IndentRequiresClause: true +IndentWidth: 2 +IndentWrappedFunctionNames: false +InsertBraces: false +InsertNewlineAtEOF: false +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +KeepEmptyLinesAtEOF: false +LambdaBodyIndentation: Signature +LineEnding: DeriveLF +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PackConstructorInitializers: BinPack +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakScopeResolution: 500 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Right +PPIndentWidth: -1 +QualifierAlignment: Leave +ReferenceAlignment: Pointer +ReflowComments: true +RemoveBracesLLVM: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SkipMacroDefinitionBody: false +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false +SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterPlacementOperator: true + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: Never +SpacesInContainerLiterals: true +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + InCStyleCasts: false + InConditionalStatements: false + InEmptyParentheses: false + Other: false +SpacesInSquareBrackets: false +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 8 +UseTab: Never +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE +... + +]], +} + boilerplate['.clangd'] = { src_path = vim.fn.getcwd(), filename = '.clangd', diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index fafad14b..98965b87 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -73,6 +73,7 @@ require('mason-lspconfig').setup({ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]]) boilerplate_gen([[.clangd_cmd]]) +boilerplate_gen([[.clang_format]]) local cmd = { 'clangd' } From eac07f7c5bad863585a002e3ab2853242f1a47f6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 10:12:47 +0300 Subject: [PATCH 0036/1406] update --- lua/platformio/lspAttach.lua | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 38a39e6c..0b38eea4 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -10,6 +10,7 @@ vim.api.nvim_create_autocmd('LspAttach', { -- vim.lsp.set_log_level 'trace' -- print('Attaching to: ' .. client.name .. ' attached to buffer ' .. bufnr) vim.api.nvim_echo({ { 'Attaching to: ' .. client.name .. ' attached to buffer ' .. bufnr, 'Info' } }, true, {}) + ------------------------------------------------------------------ if client.name == 'clangd' then vim.api.nvim_buf_create_user_command(0, 'LspClangdSwitchSourceHeader', function() @@ -27,6 +28,7 @@ vim.api.nvim_create_autocmd('LspAttach', { end, bufnr) end, { desc = 'Switch between source/header' }) end + ------------------------------------------------------------------ --- Skip this if you are using blink local bok, _ = pcall(require, 'blink') @@ -68,14 +70,15 @@ vim.api.nvim_create_autocmd('LspAttach', { -- end - -- if lspKeymaps enabled + ------------------------------------------------------------------ local config = require('platformio').config if config.lspClangd.attach.keymaps then local lspkeymaps = require('platformio.lspkeymaps') lspkeymaps.lspKeymaps(client, bufnr) end end - -- + + ------------------------------------------------------------------ vim.lsp.handlers['textDocument/publishDiagnostics'] = vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { signs = true, underline = true, @@ -85,7 +88,8 @@ vim.api.nvim_create_autocmd('LspAttach', { }, update_in_insert = true, }) - -- + + ------------------------------------------------------------------ vim.cmd([[autocmd FileType * set formatoptions-=ro]]) -- end, From 08bb01001160447d8cd5daf155596198375b7be0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 10:19:25 +0300 Subject: [PATCH 0037/1406] update --- lua/platformio/lspClangd.lua | 10 +++++----- minimal_config.lua | 1 + 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 98965b87..cb91a194 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -39,11 +39,11 @@ local ensure_installed = { local mr = require('mason-registry') mr.refresh(function() for _, tool in ipairs(ensure_installed) do - local ok, p = pcall(mr.get_package, tool) - if ok and p then - if not p:is_installed() then - if not p:is_installing() then - p:install({}, function(success, _) + ok, result = pcall(mr.get_package, tool) + if ok and result then + if not result:is_installed() then + if not result:is_installing() then + result:install({}, function(success, _) if not success then vim.defer_fn(function() vim.notify(tool .. ' failed to install', vim.log.levels.ERROR) diff --git a/minimal_config.lua b/minimal_config.lua index 7c65c5d9..0f73cb0d 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -210,6 +210,7 @@ vim.api.nvim_create_autocmd('User', { pattern = 'LazyDone', -- Triggers after the UI enters and startup time is calculated desc = 'Update lazy.nvim plugins in the background', callback = function() + print('here') require('lazy').sync({ wait = false, -- Makes the operation asynchronous show = false, -- Prevents the Lazy UI from automatically opening From 79b9da3a510d17fac758337d309d18f393c84167 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 10:22:44 +0300 Subject: [PATCH 0038/1406] update --- minimal_config.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index 0f73cb0d..5ac865bd 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -207,7 +207,7 @@ require('lazy').setup(plugins, { ---------------------------------------------------------------------------------------- vim.api.nvim_create_autocmd('User', { - pattern = 'LazyDone', -- Triggers after the UI enters and startup time is calculated + pattern = 'LazyVimStarted', -- Triggers after the UI enters and startup time is calculated desc = 'Update lazy.nvim plugins in the background', callback = function() print('here') From 30ba7f689fb3771da43a2471ce7300af6c017df0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 10:24:26 +0300 Subject: [PATCH 0039/1406] update --- minimal_config.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index 5ac865bd..a75b928f 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -210,7 +210,6 @@ vim.api.nvim_create_autocmd('User', { pattern = 'LazyVimStarted', -- Triggers after the UI enters and startup time is calculated desc = 'Update lazy.nvim plugins in the background', callback = function() - print('here') require('lazy').sync({ wait = false, -- Makes the operation asynchronous show = false, -- Prevents the Lazy UI from automatically opening From 177f5ab9c13129dfc7680102c9c728acd7e61da5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 11:07:53 +0300 Subject: [PATCH 0040/1406] update --- README.md | 197 ++++++++++++++++++++++++++++++------------------------ 1 file changed, 109 insertions(+), 88 deletions(-) diff --git a/README.md b/README.md index 7971e09e..1ee27de5 100644 --- a/README.md +++ b/README.md @@ -7,17 +7,14 @@ ### Demo - - https://github.com/user-attachments/assets/fdbb6655-4b2d-4a2b-81d1-fd8af6e7d9f1 - -
Try the plugin with this minimal standalone config without modifying your existing nvim setup. **This is especially useful if you're encountering errors during installation or usage**. + ```sh -wget https://raw.githubusercontent.com/anurag3301/nvim-platformio.lua/main/minimal_config.lua +wget https://raw.githubusercontent.com/batoaqaa/nvim-platformio.lua/main/minimal_config.lua nvim -u minimal_config.lua # Now run :Pioinit @@ -26,102 +23,125 @@ nvim -u minimal_config.lua ## Installation #### PlatformIO Core -Follow the installation instructions in the [PlatformIO documentation](https://docs.platformio.org/en/latest/core/installation/index.html). +Follow the installation instructions in the [PlatformIO documentation](https://docs.platformio.org/en/latest/core/installation/index.html). #### Plugin + Install the plugin using lazy + ```lua return { - 'anurag3301/nvim-platformio.lua', + 'batoaqaa/nvim-platformio.lua', + -- cmd = { 'Pioinit', 'Piorun', 'Piocmdh', 'Piocmdf', 'Piolib', 'Piomon', 'Piodebug', 'Piodb' }, -- optional: cond used to enable/disable platformio -- based on existance of platformio.ini file and .pio folder in cwd. - -- You can enable platformio plugin, using :Pioinit command - cond = function() - -- local platformioRootDir = vim.fs.root(vim.fn.getcwd(), { 'platformio.ini' }) -- cwd and parents - local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.fn.getcwd() or nil - if platformioRootDir then - -- if platformio.ini file exist in cwd, enable plugin to install plugin (if not istalled) and load it. - vim.g.platformioRootDir = platformioRootDir - elseif (vim.uv or vim.loop).fs_stat(vim.fn.stdpath('data') .. '/lazy/nvim-platformio.lua') == nil then - -- if nvim-platformio not installed, enable plugin to install it first time - vim.g.platformioRootDir = vim.fn.getcwd() - else -- if nvim-platformio.lua installed but disabled, create Pioinit command - vim.api.nvim_create_user_command('Pioinit', function() --available only if no platformio.ini and .pio in cwd - vim.api.nvim_create_autocmd('User', { - pattern = { 'LazyRestore', 'LazyLoad' }, - once = true, - callback = function(args) - if args.match == 'LazyRestore' then - require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) - elseif args.match == 'LazyLoad' then - vim.notify('PlatformIO loaded', vim.log.levels.INFO, { title = 'PlatformIO' }) - require("platformio").setup(vim.g.pioConfig) - vim.cmd('Pioinit') - end - end, - }) + -- You can enable platformio plugin, using :Pioinit command + cond = function() + -- local platformioRootDir = vim.fs.root(vim.fn.getcwd(), { 'platformio.ini' }) -- cwd and parents + local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.fn.getcwd() or nil + if platformioRootDir and vim.fs.find('.pio', { path = platformioRootDir, type = 'directory' })[1] then + -- if platformio.ini file and .pio folder exist in cwd, enable plugin to install plugin (if not istalled) and load it. + vim.g.platformioRootDir = platformioRootDir + elseif (vim.uv or vim.loop).fs_stat(vim.fn.stdpath('data') .. '/lazy/nvim-platformio.lua') == nil then + -- if nvim-platformio not installed, enable plugin to install it first time vim.g.platformioRootDir = vim.fn.getcwd() - require('lazy').restore({ plguins = { 'nvim-platformio.lua' }, show = false }) - end, {}) - end - return vim.g.platformioRootDir ~= nil - end, - - -- Dependencies are lazy-loaded by default unless specified otherwise. - dependencies = { - { 'akinsho/toggleterm.nvim' }, - { 'nvim-telescope/telescope.nvim' }, - { 'nvim-telescope/telescope-ui-select.nvim' }, - { 'nvim-lua/plenary.nvim' }, - { 'folke/which-key.nvim' }, - { 'nvim-treesitter/nvim-treesitter' } - }, + else -- if nvim-platformio.lua installed but disabled, create Pioinit command + vim.api.nvim_create_user_command('Pioinit', function() --available only if no platformio.ini and .pio in cwd + vim.api.nvim_create_autocmd('User', { + pattern = { 'LazyRestore', 'LazyLoad' }, + once = true, + callback = function(args) + if args.match == 'LazyRestore' then + require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) + elseif args.match == 'LazyLoad' then + vim.notify('PlatformIO loaded', vim.log.levels.INFO, { title = 'PlatformIO' }) + vim.cmd('Pioinit') + end + end, + }) + vim.g.platformioRootDir = vim.fn.getcwd() + require('lazy').restore({ plguins = { 'nvim-platformio.lua' }, show = false }) + end, {}) + end + return vim.g.platformioRootDir ~= nil + end, + + dependencies = { + { 'akinsho/toggleterm.nvim' }, + { 'nvim-telescope/telescope.nvim' }, + { 'nvim-telescope/telescope-ui-select.nvim' }, + { 'nvim-lua/plenary.nvim' }, + { 'folke/which-key.nvim' }, + { + 'mason-org/mason-lspconfig.nvim', + dependencies = { + { 'mason-org/mason.nvim' }, + { 'folke/trouble.nvim' }, + { 'j-hui/fidget.nvim' }, -- status bottom right + }, + }, + }, + opts = { + }, } + ``` #### Usage `:h PlatformIO` ### Configuration + ```lua -vim.g.pioConfig ={ - lsp = 'clangd', -- value: clangd | ccls - menu_key = '\\', -- replace this menu key to your convenience - debug = false -- enable debug messages - clangd_source = 'ccls' -- value: ccls | compiledb, For detailed explation check :help platformio-clangd_source -} -local pok, platformio = pcall(require, 'platformio') -if pok then platformio.setup(vim.g.pioConfig) end + vim.g.pioConfig ={ + lspClangd = { + enabled = true, + attach = { + enabled = true, + keymaps = true, + }, + }, + -- Uncomment out following line to enable platformio menu. + menu_key = '\\', -- replace this menu key to your convenience + menu_name = 'PlatformIO', -- replace this menu name to your convenience + } + local pok, platformio = pcall(require, 'platformio') + if pok then platformio.setup(vim.g.pioConfig) end ``` ### Keybinds + These are the default keybindings, which you can override in your configuration. + ```lua local pok, platformio = pcall(require, 'platformio') if pok then platformio.setup({ - lsp = 'ccls', --default: ccls, other option: clangd - -- If you pick clangd, it also creates compile_commands.json - - -- Uncomment out following line to enable platformio menu. - -- menu_key = '\\', -- replace this menu key to your convenience + lspClangd = { + enabled = false, + attach = { + enabled = false, + keymaps = false, + }, + }, + menu_key = '\\', -- replace this menu key to your convenience menu_name = 'PlatformIO', -- replace this menu name to your convenience + debug = false, - -- Following are the default keybindings, you can overwrite them in the config menu_bindings = { - { node = 'item', desc = '[L]ist terminals', shortcut = 'l', command = 'PioTermList' }, + { node = 'item', desc = '[L]ist terminals', shortcut = 'l', command = 'PioTermList' }, { node = 'item', desc = '[T]erminal Core CLI', shortcut = 't', command = 'Piocmdf' }, { node = 'menu', desc = '[G]eneral', shortcut = 'g', items = { - { node = 'item', desc = '[B]uild', shortcut = 'b', command = 'Piocmdf run' }, - { node = 'item', desc = '[U]pload', shortcut = 'u', command = 'Piocmdf run -t upload' }, - { node = 'item', desc = '[M]onitor', shortcut = 'm', command = 'Piocmdh run -t monitor' }, - { node = 'item', desc = '[C]lean', shortcut = 'c', command = 'Piocmdf run -t clean' }, - { node = 'item', desc = '[F]ull clean', shortcut = 'f', command = 'Piocmdf run -t fullclean' }, + { node = 'item', desc = '[B]uild', shortcut = 'b', command = 'Piocmdf run' }, + { node = 'item', desc = '[U]pload', shortcut = 'u', command = 'Piocmdf run -t upload' }, + { node = 'item', desc = '[M]onitor', shortcut = 'm', command = 'Piocmdh run -t monitor' }, + { node = 'item', desc = '[C]lean', shortcut = 'c', command = 'Piocmdf run -t clean' }, + { node = 'item', desc = '[F]ull clean', shortcut = 'f', command = 'Piocmdf run -t fullclean' }, { node = 'item', desc = '[D]evice list', shortcut = 'd', command = 'Piocmdf device list' }, }, }, @@ -130,10 +150,10 @@ These are the default keybindings, which you can override in your configuration. desc = '[P]latform', shortcut = 'p', items = { - { node = 'item', desc = '[B]uild file system', shortcut = 'b', command = 'Piocmdf run -t buildfs' }, - { node = 'item', desc = 'Program [S]ize', shortcut = 's', command = 'Piocmdf run -t size' }, + { node = 'item', desc = '[B]uild file system', shortcut = 'b', command = 'Piocmdf run -t buildfs' }, + { node = 'item', desc = 'Program [S]ize', shortcut = 's', command = 'Piocmdf run -t size' }, { node = 'item', desc = '[U]pload file system', shortcut = 'u', command = 'Piocmdf run -t uploadfs' }, - { node = 'item', desc = '[E]rase Flash', shortcut = 'e', command = 'Piocmdf run -t erase' }, + { node = 'item', desc = '[E]rase Flash', shortcut = 'e', command = 'Piocmdf run -t erase' }, }, }, { @@ -141,9 +161,9 @@ These are the default keybindings, which you can override in your configuration. desc = '[D]ependencies', shortcut = 'd', items = { - { node = 'item', desc = '[L]ist packages', shortcut = 'l', command = 'Piocmdf pkg list' }, + { node = 'item', desc = '[L]ist packages', shortcut = 'l', command = 'Piocmdf pkg list' }, { node = 'item', desc = '[O]utdated packages', shortcut = 'o', command = 'Piocmdf pkg outdated' }, - { node = 'item', desc = '[U]pdate packages', shortcut = 'u', command = 'Piocmdf pkg update' }, + { node = 'item', desc = '[U]pdate packages', shortcut = 'u', command = 'Piocmdf pkg update' }, }, }, { @@ -151,31 +171,31 @@ These are the default keybindings, which you can override in your configuration. desc = '[A]dvanced', shortcut = 'a', items = { - { node = 'item', desc = '[T]est', shortcut = 't', command = 'Piocmdf test' }, - { node = 'item', desc = '[C]heck', shortcut = 'c', command = 'Piocmdf check' }, - { node = 'item', desc = '[D]ebug', shortcut = 'd', command = 'Piocmdf debug' }, + { node = 'item', desc = '[T]est', shortcut = 't', command = 'Piocmdf test' }, + { node = 'item', desc = '[C]heck', shortcut = 'c', command = 'Piocmdf check' }, + { node = 'item', desc = '[D]ebug', shortcut = 'd', command = 'Piocmdf debug' }, { node = 'item', desc = 'Compilation Data[b]ase', shortcut = 'b', command = 'Piocmdf run -t compiledb' }, { - node = 'menu', - desc = '[V]erbose', - shortcut = 'v', - items = { - { node = 'item', desc = 'Verbose [B]uild', shortcut = 'b', command = 'Piocmdf run -v' }, - { node = 'item', desc = 'Verbose [U]pload', shortcut = 'u', command = 'Piocmdf run -v -t upload' }, - { node = 'item', desc = 'Verbose [T]est', shortcut = 't', command = 'Piocmdf test -v' }, - { node = 'item', desc = 'Verbose [C]heck', shortcut = 'c', command = 'Piocmdf check -v' }, - { node = 'item', desc = 'Verbose [D]ebug', shortcut = 'd', command = 'Piocmdf debug -v' }, - }, + node = 'menu', + desc = '[V]erbose', + shortcut = 'v', + items = { + { node = 'item', desc = 'Verbose [B]uild', shortcut = 'b', command = 'Piocmdf run -v' }, + { node = 'item', desc = 'Verbose [U]pload', shortcut = 'u', command = 'Piocmdf run -v -t upload' }, + { node = 'item', desc = 'Verbose [T]est', shortcut = 't', command = 'Piocmdf test -v' }, + { node = 'item', desc = 'Verbose [C]heck', shortcut = 'c', command = 'Piocmdf check -v' }, + { node = 'item', desc = 'Verbose [D]ebug', shortcut = 'd', command = 'Piocmdf debug -v' }, }, }, + }, }, { node = 'menu', desc = '[R]emote', shortcut = 'r', items = { - { node = 'item', desc = 'Remote [U]pload', shortcut = 'u', command = 'Piocmdf remote run -t upload' }, - { node = 'item', desc = 'Remote [T]est', shortcut = 't', command = 'Piocmdf remote test' }, + { node = 'item', desc = 'Remote [U]pload', shortcut = 'u', command = 'Piocmdf remote run -t upload' }, + { node = 'item', desc = 'Remote [T]est', shortcut = 't', command = 'Piocmdf remote test' }, { node = 'item', desc = 'Remote [M]onitor', shortcut = 'm', command = 'Piocmdh remote run -t monitor' }, { node = 'item', desc = 'Remote [D]evices', shortcut = 'd', command = 'Piocmdf remote device list' }, }, @@ -189,6 +209,7 @@ These are the default keybindings, which you can override in your configuration. }, }, }, + }) end ``` @@ -201,6 +222,6 @@ It's possible to lazy load the plugin using Lazy.nvim, this will load the plugin cmd = { 'Pioinit', 'Piorun', 'Piocmdh', 'Piocmdf', 'Piolib', 'Piomon', 'Piodebug', 'Piodb' }, ``` - ### TODO + - Connect Piodebug with DAP From 4ea1fd9ba55731951985140bb798b0f2417a8b1a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 11:09:24 +0300 Subject: [PATCH 0041/1406] update --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index 1ee27de5..a3ceb1bd 100644 --- a/README.md +++ b/README.md @@ -83,8 +83,6 @@ return { }, }, }, - opts = { - }, } ``` From 01f455e730eb67999d3f5332c942ab0f8ddf9350 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 11:10:09 +0300 Subject: [PATCH 0042/1406] update --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index a3ceb1bd..a06d6538 100644 --- a/README.md +++ b/README.md @@ -70,11 +70,11 @@ return { dependencies = { { 'akinsho/toggleterm.nvim' }, - { 'nvim-telescope/telescope.nvim' }, - { 'nvim-telescope/telescope-ui-select.nvim' }, - { 'nvim-lua/plenary.nvim' }, - { 'folke/which-key.nvim' }, - { + { 'nvim-telescope/telescope.nvim' }, + { 'nvim-telescope/telescope-ui-select.nvim' }, + { 'nvim-lua/plenary.nvim' }, + { 'folke/which-key.nvim' }, + { 'mason-org/mason-lspconfig.nvim', dependencies = { { 'mason-org/mason.nvim' }, From 1cc1f6f102025b523d41d5aa827a7554d8efdce4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 13:40:26 +0300 Subject: [PATCH 0043/1406] update --- lua/platformio/init.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index 1ec15ccc..b88430be 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -156,6 +156,7 @@ end function M.setup(user_config) if next(user_config) ~= nil then + print(vim.inspect(user_config)) if next(user_config.lspClangd) ~= nil then vim.validate('lspClangd', user_config.lspClangd, 'table', true) vim.validate('lspClangdEnabled', user_config.lspClangd.enabled, 'boolean', true) From bd389fd033b2b45acc945f8d6279c9f2ea064da7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 13:43:32 +0300 Subject: [PATCH 0044/1406] update --- lua/platformio/init.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index b88430be..c8a9eaaf 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -157,7 +157,7 @@ end function M.setup(user_config) if next(user_config) ~= nil then print(vim.inspect(user_config)) - if next(user_config.lspClangd) ~= nil then + if user_config.lspClangd then vim.validate('lspClangd', user_config.lspClangd, 'table', true) vim.validate('lspClangdEnabled', user_config.lspClangd.enabled, 'boolean', true) if user_config.lspClangd.attach then From 7937b801a58c7bd14fbbc593f537e9f4ee0cb7ec Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 13:45:33 +0300 Subject: [PATCH 0045/1406] update --- minimal_config.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index a75b928f..89999aae 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -157,7 +157,7 @@ local plugins = { if platformioRootDir and vim.fs.find('.pio', { path = platformioRootDir, type = 'directory' })[1] then -- if platformio.ini file and .pio folder exist in cwd, enable plugin to install plugin (if not istalled) and load it. vim.g.platformioRootDir = platformioRootDir - elseif (vim.uv or vim.loop).fs_stat(vim.fn.stdpath('data') .. '/lazy/nvim-platformio.lua') == nil then + elseif (vim.uv or vim.loop).fs_stat(vim.env.XDG_DATA_HOME .. '/lazy/nvim-platformio.lua') == nil then -- if nvim-platformio not installed, enable plugin to install it first time vim.g.platformioRootDir = vim.fn.getcwd() else -- if nvim-platformio.lua installed but disabled, create Pioinit command From c24a65c5aa24021375b0544175b8c155177957e8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 14:43:48 +0300 Subject: [PATCH 0046/1406] update --- minimal_config.lua | 52 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/minimal_config.lua b/minimal_config.lua index 89999aae..1985d943 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -219,6 +219,58 @@ vim.api.nvim_create_autocmd('User', { end, }) +----------------------------------------------------------------------------------------- +local isWindows = jit.os == 'Windows' +-- +local platformio_core_dir, pynvim_env, pynvim_python, pynvim_lib, pynvim_bin, pynvim_activate +if isWindows then + platformio_core_dir = vim.env.HOME .. '\\.platformio' + pynvim_env = platformio_core_dir .. '\\nenv' + pynvim_bin = pynvim_env .. '\\Scripts' + pynvim_python = pynvim_bin .. '\\python.exe' + pynvim_activate = pynvim_bin .. '\\Activate.ps1' +else + platformio_core_dir = vim.env.HOME .. '/.platformio' + pynvim_env = platformio_core_dir .. '/nenv' + pynvim_bin = pynvim_env .. '/bin' + pynvim_python = pynvim_bin .. '/python' + pynvim_activate = 'source' .. pynvim_bin .. '/activate' +end + +vim.uv.os_setenv('PLATFORMIO_CORE_DIR', platformio_core_dir) +vim.g.python_host_prog = pynvim_python +vim.g.python3_host_prog = pynvim_python +vim.env.PATH = pynvim_bin .. (isWindows and ';' or ':') .. vim.env.PATH +vim.env.VIRTUAL_ENV = pynvim_env + +if vim.fn.isdirectory(platformio_core_dir) == 0 then + vim.fn.mkdir(platformio_core_dir, 'p') + -- vim.fn.system({ + -- "wget", + -- "https://raw.githubusercontent.com/platformio/platformio-core-installer/master/get-platformio.py", + -- }) + -- vim.fn.system({ "python", "get-platformio.py" }) + -- os.execute((isWindows and "del " or "rm -f ") .. "get-platformio.py*") +end + +-- local expand_dir = vim.fn.expand(pynvim_env) +if not vim.uv.fs_stat(pynvim_env) then + vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) + if not isWindows then + os.execute('chmod 755 -R ' .. pynvim_bin) + end + vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'pip' }) + vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'pynvim' }) + vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'neovim' }) + vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'debugpy' }) + vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'isort' }) + vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'scons' }) + vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'yamllint' }) + vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'platformio' }) + -- vim.fn.system({ 'pip', 'install', '-U', 'platformio' }) +end +------------------------ +----------------------------------------------------------------------------------------- -- platformio config local pioConfig = { lspClangd = { From 7fac082a823be7139218ed86515c2d62736f2466 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 14:59:08 +0300 Subject: [PATCH 0047/1406] update --- minimal_config.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/minimal_config.lua b/minimal_config.lua index 1985d943..557b55a5 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -258,6 +258,7 @@ if not vim.uv.fs_stat(pynvim_env) then vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) if not isWindows then os.execute('chmod 755 -R ' .. pynvim_bin) + vim.fn.system({ 'source', pynvim_bin, 'activate' }) end vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'pip' }) vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'pynvim' }) From dacc157488e3fea7f9312b78a6d5e9a8ed81cce8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 15:09:15 +0300 Subject: [PATCH 0048/1406] update --- lua/platformio/init.lua | 1 - minimal_config.lua | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index c8a9eaaf..69686ec3 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -156,7 +156,6 @@ end function M.setup(user_config) if next(user_config) ~= nil then - print(vim.inspect(user_config)) if user_config.lspClangd then vim.validate('lspClangd', user_config.lspClangd, 'table', true) vim.validate('lspClangdEnabled', user_config.lspClangd.enabled, 'boolean', true) diff --git a/minimal_config.lua b/minimal_config.lua index 557b55a5..57b09f55 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -257,6 +257,7 @@ end if not vim.uv.fs_stat(pynvim_env) then vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) if not isWindows then + print('here') os.execute('chmod 755 -R ' .. pynvim_bin) vim.fn.system({ 'source', pynvim_bin, 'activate' }) end From 1367b801fb2a7464ec39606508c04c1158d6b5dc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 15:27:40 +0300 Subject: [PATCH 0049/1406] update --- minimal_config.lua | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index 57b09f55..fc63be64 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -233,7 +233,7 @@ else platformio_core_dir = vim.env.HOME .. '/.platformio' pynvim_env = platformio_core_dir .. '/nenv' pynvim_bin = pynvim_env .. '/bin' - pynvim_python = pynvim_bin .. '/python' + pynvim_python = pynvim_bin .. '/python3' pynvim_activate = 'source' .. pynvim_bin .. '/activate' end @@ -255,11 +255,14 @@ end -- local expand_dir = vim.fn.expand(pynvim_env) if not vim.uv.fs_stat(pynvim_env) then - vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) if not isWindows then - print('here') - os.execute('chmod 755 -R ' .. pynvim_bin) + vim.fn.system({ 'python3', '-m', 'venv', pynvim_env }) + vim.fn.system({ 'chmod', '755', '-R', pynvim_bin }) + -- os.execute('chmod 755 -R ' .. pynvim_bin) vim.fn.system({ 'source', pynvim_bin, 'activate' }) + else + vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) + vim.fn.system({ pynvim_activate }) end vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'pip' }) vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'pynvim' }) From 1af8c00be0261fda23abf3aa14f498f8b8c69511 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 16:15:28 +0300 Subject: [PATCH 0050/1406] update --- minimal_config.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index fc63be64..e3d49d2e 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -234,7 +234,7 @@ else pynvim_env = platformio_core_dir .. '/nenv' pynvim_bin = pynvim_env .. '/bin' pynvim_python = pynvim_bin .. '/python3' - pynvim_activate = 'source' .. pynvim_bin .. '/activate' + pynvim_activate = pynvim_bin .. '/activate' end vim.uv.os_setenv('PLATFORMIO_CORE_DIR', platformio_core_dir) @@ -259,7 +259,7 @@ if not vim.uv.fs_stat(pynvim_env) then vim.fn.system({ 'python3', '-m', 'venv', pynvim_env }) vim.fn.system({ 'chmod', '755', '-R', pynvim_bin }) -- os.execute('chmod 755 -R ' .. pynvim_bin) - vim.fn.system({ 'source', pynvim_bin, 'activate' }) + vim.fn.system({ 'source', pynvim_activate }) else vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) vim.fn.system({ pynvim_activate }) From 895602a5d0251a4ba88efb500545f9aedaa6e8b6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 16:18:45 +0300 Subject: [PATCH 0051/1406] update --- minimal_config.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/minimal_config.lua b/minimal_config.lua index e3d49d2e..512c2262 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -235,6 +235,7 @@ else pynvim_bin = pynvim_env .. '/bin' pynvim_python = pynvim_bin .. '/python3' pynvim_activate = pynvim_bin .. '/activate' + print(pynvim_activate) end vim.uv.os_setenv('PLATFORMIO_CORE_DIR', platformio_core_dir) From c221a64dc65868c19ee74e07203e291d1f9380a5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 16:39:50 +0300 Subject: [PATCH 0052/1406] update --- minimal_config.lua | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/minimal_config.lua b/minimal_config.lua index 512c2262..f463685c 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -25,6 +25,21 @@ vim.g.have_nerd_font = true vim.g.mapleader = ' ' vim.g.maplocalleader = ' ' +local isWindows = jit.os == 'Windows' +if not isWindows then + vim.g.shellcmdflag = '-c' -- Executes the command passed as a string + vim.g.shellpipe = '|' -- Pipes output of external commands + vim.g.shellredir = '> ' -- Redirects output of external commands +else + vim.g.shell = vim.fn.executable('pwsh') and 'pwsh' or 'powershell' + vim.g.shellcmdflag = + '-NoLogo -ExecutionPolicy RemoteSigned -Command [Console]::InputEncoding=[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new();$PSDefaultParameterValues[Out-File:Encoding]=utf8;Remove-Alias -Force -ErrorAction SilentlyContinue tee;' + vim.g.shellredir = '2>&1 | %%{ "$_" } | Out-File %s; exit $LastExitCode' + vim.g.shellpipe = '2>&1 | %%{ "$_" } | tee %s; exit $LastExitCode' + vim.g.shellquote = '' + vim.g.shellxquote = '' +end + -- Toggle virtual_text off when on the line with the error vim.diagnostic.config({ virtual_lines = true, From 20658665f34ba01bd6dcbb8f535b29694efa1052 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 16:43:26 +0300 Subject: [PATCH 0053/1406] update --- minimal_config.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/minimal_config.lua b/minimal_config.lua index f463685c..c7a395f7 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -27,6 +27,7 @@ vim.g.maplocalleader = ' ' local isWindows = jit.os == 'Windows' if not isWindows then + vim.opt.shell = '/bin/bash' -- or '/bin/zsh', '/usr/bin/fish', etc. vim.g.shellcmdflag = '-c' -- Executes the command passed as a string vim.g.shellpipe = '|' -- Pipes output of external commands vim.g.shellredir = '> ' -- Redirects output of external commands From 4f74220bd9b5b1cae466d0efa6a6fe927acbdd0c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 16:47:35 +0300 Subject: [PATCH 0054/1406] update --- minimal_config.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index c7a395f7..b51c015a 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -27,7 +27,7 @@ vim.g.maplocalleader = ' ' local isWindows = jit.os == 'Windows' if not isWindows then - vim.opt.shell = '/bin/bash' -- or '/bin/zsh', '/usr/bin/fish', etc. + vim.g.shell = '/bin/bash' -- or '/bin/zsh', '/usr/bin/fish', etc. vim.g.shellcmdflag = '-c' -- Executes the command passed as a string vim.g.shellpipe = '|' -- Pipes output of external commands vim.g.shellredir = '> ' -- Redirects output of external commands From 0ae3a18c05a30cc482ec7f9116329fcab64e3d16 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 16:53:43 +0300 Subject: [PATCH 0055/1406] update --- minimal_config.lua | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index b51c015a..2d72f81c 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -276,7 +276,18 @@ if not vim.uv.fs_stat(pynvim_env) then vim.fn.system({ 'python3', '-m', 'venv', pynvim_env }) vim.fn.system({ 'chmod', '755', '-R', pynvim_bin }) -- os.execute('chmod 755 -R ' .. pynvim_bin) - vim.fn.system({ 'source', pynvim_activate }) + -- vim.fn.system({ 'source', pynvim_activate }) + + local handle = io.popen('source ' .. pynvim_activate, 'r') + if not handle then + print('failed to run command') + end + + if handle then + local result = handle:read('*a') + handle:close() + print(result) + end else vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) vim.fn.system({ pynvim_activate }) From 02124a986f6671016f7f4faa17b08a47b603433c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 17:01:53 +0300 Subject: [PATCH 0056/1406] update --- minimal_config.lua | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index 2d72f81c..1248bc14 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -277,17 +277,18 @@ if not vim.uv.fs_stat(pynvim_env) then vim.fn.system({ 'chmod', '755', '-R', pynvim_bin }) -- os.execute('chmod 755 -R ' .. pynvim_bin) -- vim.fn.system({ 'source', pynvim_activate }) + os.execute('source ' .. pynvim_activate) - local handle = io.popen('source ' .. pynvim_activate, 'r') - if not handle then - print('failed to run command') - end - - if handle then - local result = handle:read('*a') - handle:close() - print(result) - end + -- local handle = io.popen('source ' .. pynvim_activate, 'r') + -- if not handle then + -- print('failed to run command') + -- end + -- + -- if handle then + -- local result = handle:read('*a') + -- handle:close() + -- print(result) + -- end else vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) vim.fn.system({ pynvim_activate }) From 18768439f5c8439583cf5beb1f3da676b33b2b1d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 17:06:33 +0300 Subject: [PATCH 0057/1406] update --- minimal_config.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index 1248bc14..20c76a07 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -277,7 +277,7 @@ if not vim.uv.fs_stat(pynvim_env) then vim.fn.system({ 'chmod', '755', '-R', pynvim_bin }) -- os.execute('chmod 755 -R ' .. pynvim_bin) -- vim.fn.system({ 'source', pynvim_activate }) - os.execute('source ' .. pynvim_activate) + -- os.execute('source ' .. pynvim_activate) -- local handle = io.popen('source ' .. pynvim_activate, 'r') -- if not handle then From ef3ecc7a507fd129e4d21487b837a336e3b19493 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 17:55:47 +0300 Subject: [PATCH 0058/1406] update --- lua/platformio/lspAttach.lua | 2 +- minimal_config.lua | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 0b38eea4..259cbf4e 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -73,7 +73,7 @@ vim.api.nvim_create_autocmd('LspAttach', { ------------------------------------------------------------------ local config = require('platformio').config if config.lspClangd.attach.keymaps then - local lspkeymaps = require('platformio.lspkeymaps') + local lspkeymaps = require('platformio.lspKeymaps') lspkeymaps.lspKeymaps(client, bufnr) end end diff --git a/minimal_config.lua b/minimal_config.lua index 20c76a07..82d2c570 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -236,7 +236,7 @@ vim.api.nvim_create_autocmd('User', { }) ----------------------------------------------------------------------------------------- -local isWindows = jit.os == 'Windows' +-- local isWindows = jit.os == 'Windows' -- local platformio_core_dir, pynvim_env, pynvim_python, pynvim_lib, pynvim_bin, pynvim_activate if isWindows then @@ -283,7 +283,6 @@ if not vim.uv.fs_stat(pynvim_env) then -- if not handle then -- print('failed to run command') -- end - -- -- if handle then -- local result = handle:read('*a') -- handle:close() @@ -291,8 +290,9 @@ if not vim.uv.fs_stat(pynvim_env) then -- end else vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) - vim.fn.system({ pynvim_activate }) + -- vim.fn.system({ pynvim_activate }) end + vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'pip' }) vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'pynvim' }) vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'neovim' }) From b72bf98e05c8553900a9ba4793c8b64c46408943 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 18:05:21 +0300 Subject: [PATCH 0059/1406] update --- plugin/platformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 5cf86b59..63bdd48a 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -33,7 +33,7 @@ end, { }) -- Piomon -piolsserial.sync_ttylist() +-- piolsserial.sync_ttylist() vim.api.nvim_create_user_command('Piomon', function(opts) local args = opts.fargs require('platformio.piomon').piomon(args) From c2bfc6d3393abfcdd22193c6a61756b7d65e58aa Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 18:06:56 +0300 Subject: [PATCH 0060/1406] update --- minimal_config.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index 82d2c570..8c799034 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -251,7 +251,6 @@ else pynvim_bin = pynvim_env .. '/bin' pynvim_python = pynvim_bin .. '/python3' pynvim_activate = pynvim_bin .. '/activate' - print(pynvim_activate) end vim.uv.os_setenv('PLATFORMIO_CORE_DIR', platformio_core_dir) From db71b7864fe11ac1295eec497ec12e212c26dcd8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 19:21:34 +0300 Subject: [PATCH 0061/1406] update --- lua/platformio/lspClangd.lua | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index cb91a194..094cd077 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -77,13 +77,14 @@ boilerplate_gen([[.clang_format]]) local cmd = { 'clangd' } -local path = vim.fn.getcwd() -local fname = string.format('%s\\.clangd_cmd', path) +-- local path = vim.fn.getcwd() +-- local fname = string.format('%s\\.clangd_cmd', path) +local fname = string.format('%s\\.clangd_cmd', vim.g.platformioRootDir) if vim.fn.filereadable(fname) == 1 then ok, result = pcall(vim.fn.readfile, fname) if ok then cmd = result - -- print(vim.inspect(cmd)) + print(vim.inspect(cmd)) end end From 9ff216a98b0bbd7bf68ea654c514020ef45f21af Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 19:29:21 +0300 Subject: [PATCH 0062/1406] update --- lua/platformio/lspClangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 094cd077..b415e72b 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -79,7 +79,7 @@ local cmd = { 'clangd' } -- local path = vim.fn.getcwd() -- local fname = string.format('%s\\.clangd_cmd', path) -local fname = string.format('%s\\.clangd_cmd', vim.g.platformioRootDir) +local fname = string.format('%s/.clangd_cmd', vim.g.platformioRootDir) if vim.fn.filereadable(fname) == 1 then ok, result = pcall(vim.fn.readfile, fname) if ok then From 14b016523140fc832431e1d6eebd4358aa2326c6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 19:38:25 +0300 Subject: [PATCH 0063/1406] update --- lua/platformio/lspClangd.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index b415e72b..ed86f581 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -66,7 +66,7 @@ end) require('mason-lspconfig').setup({ ensure_installed = { 'clangd' }, - -- automatic_enable = true, -- this will automatically enable LSP servers after install + automatic_enable = true, -- this will automatically enable LSP servers after install }) ----------------------------------------------------------------------------------------- @@ -78,8 +78,8 @@ boilerplate_gen([[.clang_format]]) local cmd = { 'clangd' } -- local path = vim.fn.getcwd() --- local fname = string.format('%s\\.clangd_cmd', path) -local fname = string.format('%s/.clangd_cmd', vim.g.platformioRootDir) +local fname = string.format('%s/.clangd_cmd', vim.fn.getcw()) +-- local fname = string.format('%s/.clangd_cmd', vim.g.platformioRootDir) if vim.fn.filereadable(fname) == 1 then ok, result = pcall(vim.fn.readfile, fname) if ok then From f708778c2070513d2f7309fb0499be7a5fa45936 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 19:44:24 +0300 Subject: [PATCH 0064/1406] update --- lua/platformio/lspClangd.lua | 1 + minimal_config.lua | 14 -------------- 2 files changed, 1 insertion(+), 14 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index ed86f581..93f4e796 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -127,6 +127,7 @@ if mok then mason_lspconfig.setup({}) end +require('platformio.piolsp').piolsp() local config = require('platformio').config if config.lspClangd.attach.enabled then require('platformio.lspAttach') diff --git a/minimal_config.lua b/minimal_config.lua index 8c799034..6ef2d1ad 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -274,22 +274,8 @@ if not vim.uv.fs_stat(pynvim_env) then if not isWindows then vim.fn.system({ 'python3', '-m', 'venv', pynvim_env }) vim.fn.system({ 'chmod', '755', '-R', pynvim_bin }) - -- os.execute('chmod 755 -R ' .. pynvim_bin) - -- vim.fn.system({ 'source', pynvim_activate }) - -- os.execute('source ' .. pynvim_activate) - - -- local handle = io.popen('source ' .. pynvim_activate, 'r') - -- if not handle then - -- print('failed to run command') - -- end - -- if handle then - -- local result = handle:read('*a') - -- handle:close() - -- print(result) - -- end else vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) - -- vim.fn.system({ pynvim_activate }) end vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'pip' }) From 23e3bd2188802ee8f1cba8f5ae4c6b2a0f2a1f1e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 20:08:07 +0300 Subject: [PATCH 0065/1406] update --- lua/platformio/lspClangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 93f4e796..db4e371d 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -78,7 +78,7 @@ boilerplate_gen([[.clang_format]]) local cmd = { 'clangd' } -- local path = vim.fn.getcwd() -local fname = string.format('%s/.clangd_cmd', vim.fn.getcw()) +local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) -- local fname = string.format('%s/.clangd_cmd', vim.g.platformioRootDir) if vim.fn.filereadable(fname) == 1 then ok, result = pcall(vim.fn.readfile, fname) From 17e879afceddfe05e62e4e2bc3a5d7a459c05852 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 20:11:32 +0300 Subject: [PATCH 0066/1406] update --- lua/platformio/lspClangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index db4e371d..f1bfefcc 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -84,7 +84,7 @@ if vim.fn.filereadable(fname) == 1 then ok, result = pcall(vim.fn.readfile, fname) if ok then cmd = result - print(vim.inspect(cmd)) + -- print(vim.inspect(cmd)) end end From e667c141e553ca2b00b081651063262f3cde4913 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 20:21:48 +0300 Subject: [PATCH 0067/1406] update --- minimal_config.lua | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index 6ef2d1ad..47021006 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -145,9 +145,11 @@ local plugins = { }, keymap = { preset = 'super-tab', - [''] = { 'insert_next' }, - [''] = { 'insert_prev' }, - [''] = { 'select_and_accept' }, + -- [''] = { 'insert_next' }, + -- [''] = { 'insert_prev' }, + -- [''] = { 'insert_next' }, + -- [''] = { 'insert_prev' }, + [''] = { 'select_and_accept' }, [''] = { 'hide', 'show' }, }, }, From 4d5a0a9487a07e0d3c24391c836fc8d8e5a4b8bf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 20:43:25 +0300 Subject: [PATCH 0068/1406] update --- minimal_config.lua | 66 ++++++++++++++++++++++++++++------------------ 1 file changed, 40 insertions(+), 26 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index 47021006..da2dc491 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -102,25 +102,25 @@ local plugins = { use_nvim_cmp_as_default = false, nerd_font_variant = 'mono', }, - completion = { - accept = { - auto_brackets = { - enabled = true, - }, - }, - menu = { - draw = { - treesitter = { 'lsp' }, - }, - }, - documentation = { - auto_show = true, - auto_show_delay_ms = 200, - }, - ghost_text = { - enabled = vim.g.ai_cmp, - }, - }, + -- completion = { + -- accept = { + -- auto_brackets = { + -- enabled = true, + -- }, + -- }, + -- menu = { + -- draw = { + -- treesitter = { 'lsp' }, + -- }, + -- }, + -- documentation = { + -- auto_show = true, + -- auto_show_delay_ms = 200, + -- }, + -- ghost_text = { + -- enabled = vim.g.ai_cmp, + -- }, + -- }, sources = { default = { 'lsp', 'path', 'snippets', 'buffer' }, }, @@ -143,15 +143,29 @@ local plugins = { }, }, }, + keymap = { - preset = 'super-tab', - -- [''] = { 'insert_next' }, - -- [''] = { 'insert_prev' }, - -- [''] = { 'insert_next' }, - -- [''] = { 'insert_prev' }, - [''] = { 'select_and_accept' }, - [''] = { 'hide', 'show' }, + preset = 'default', + + [''] = { 'select_prev', 'snippet_backward', 'fallback' }, + [''] = { 'select_next', 'snippet_forward', 'fallback' }, + -- [''] = { 'select_prev', 'snippet_backward', 'fallback' }, + -- [''] = { 'select_next', 'snippet_forward', 'fallback' }, + [''] = { 'accept', 'fallback' }, + [''] = { 'hide', 'fallback' }, + [''] = { 'scroll_documentation_up', 'fallback' }, + [''] = { 'scroll_documentation_down', 'fallback' }, }, + completion = { list = { selection = 'manual' } }, + -- keymap = { + -- preset = 'super-tab', + -- -- [''] = { 'insert_next' }, + -- -- [''] = { 'insert_prev' }, + -- -- [''] = { 'insert_next' }, + -- -- [''] = { 'insert_prev' }, + -- [''] = { 'select_and_accept' }, + -- [''] = { 'hide', 'show' }, + -- }, }, }, -- From 49ee446f169dd90850e980539c4cc8f6f82b6060 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 20:47:33 +0300 Subject: [PATCH 0069/1406] update --- minimal_config.lua | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index da2dc491..f56e4b98 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -102,25 +102,25 @@ local plugins = { use_nvim_cmp_as_default = false, nerd_font_variant = 'mono', }, - -- completion = { - -- accept = { - -- auto_brackets = { - -- enabled = true, - -- }, - -- }, - -- menu = { - -- draw = { - -- treesitter = { 'lsp' }, - -- }, - -- }, - -- documentation = { - -- auto_show = true, - -- auto_show_delay_ms = 200, - -- }, - -- ghost_text = { - -- enabled = vim.g.ai_cmp, - -- }, - -- }, + completion = { + accept = { + auto_brackets = { + enabled = true, + }, + }, + menu = { + draw = { + treesitter = { 'lsp' }, + }, + }, + documentation = { + auto_show = true, + auto_show_delay_ms = 200, + }, + ghost_text = { + enabled = vim.g.ai_cmp, + }, + }, sources = { default = { 'lsp', 'path', 'snippets', 'buffer' }, }, @@ -156,7 +156,7 @@ local plugins = { [''] = { 'scroll_documentation_up', 'fallback' }, [''] = { 'scroll_documentation_down', 'fallback' }, }, - completion = { list = { selection = 'manual' } }, + -- completion = { list = { selection = 'manual' } }, -- keymap = { -- preset = 'super-tab', -- -- [''] = { 'insert_next' }, From 429b50bde0edab783fb4e498c21f7aacda803e8a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 21:01:13 +0300 Subject: [PATCH 0070/1406] update --- minimal_config.lua | 175 +++++++++++++++++++++++++++++---------------- 1 file changed, 114 insertions(+), 61 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index f56e4b98..ff19e9a7 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -95,79 +95,132 @@ vim.opt.rtp:prepend(lazypath) local plugins = { { 'saghen/blink.cmp', + -- optional: provides snippets for the snippet source dependencies = { 'rafamadriz/friendly-snippets' }, + + -- use a release tag to download pre-built binaries version = '1.*', + -- AND/OR build from source + -- build = 'cargo build --release', + -- If you use nix, you can build from source with: + -- build = 'nix run .#build-plugin', + + ---@module 'blink.cmp' + ---@type blink.cmp.Config opts = { + -- 'default' (recommended) for mappings similar to built-in completions (C-y to accept) + -- 'super-tab' for mappings similar to vscode (tab to accept) + -- 'enter' for enter to accept + -- 'none' for no mappings + -- + -- All presets have the following mappings: + -- C-space: Open menu or open docs if already open + -- C-n/C-p or Up/Down: Select next/previous item + -- C-e: Hide menu + -- C-k: Toggle signature help (if signature.enabled = true) + -- + -- See :h blink-cmp-config-keymap for defining your own keymap + keymap = { preset = 'default' }, + appearance = { - use_nvim_cmp_as_default = false, + -- 'mono' (default) for 'Nerd Font Mono' or 'normal' for 'Nerd Font' + -- Adjusts spacing to ensure icons are aligned nerd_font_variant = 'mono', }, - completion = { - accept = { - auto_brackets = { - enabled = true, - }, - }, - menu = { - draw = { - treesitter = { 'lsp' }, - }, - }, - documentation = { - auto_show = true, - auto_show_delay_ms = 200, - }, - ghost_text = { - enabled = vim.g.ai_cmp, - }, - }, + + -- (Default) Only show the documentation popup when manually triggered + completion = { documentation = { auto_show = false } }, + + -- Default list of enabled providers defined so that you can extend it + -- elsewhere in your config, without redefining it, due to `opts_extend` sources = { default = { 'lsp', 'path', 'snippets', 'buffer' }, }, - cmdline = { - enabled = false, - keymap = { - preset = 'cmdline', - [''] = false, - [''] = false, - }, - sources = { - default = { 'lsp', 'path', 'snippets', 'buffer' }, - }, - completion = { - menu = { - auto_show = true, - }, - ghost_text = { - enabled = true, - }, - }, - }, - keymap = { - preset = 'default', - - [''] = { 'select_prev', 'snippet_backward', 'fallback' }, - [''] = { 'select_next', 'snippet_forward', 'fallback' }, - -- [''] = { 'select_prev', 'snippet_backward', 'fallback' }, - -- [''] = { 'select_next', 'snippet_forward', 'fallback' }, - [''] = { 'accept', 'fallback' }, - [''] = { 'hide', 'fallback' }, - [''] = { 'scroll_documentation_up', 'fallback' }, - [''] = { 'scroll_documentation_down', 'fallback' }, - }, - -- completion = { list = { selection = 'manual' } }, - -- keymap = { - -- preset = 'super-tab', - -- -- [''] = { 'insert_next' }, - -- -- [''] = { 'insert_prev' }, - -- -- [''] = { 'insert_next' }, - -- -- [''] = { 'insert_prev' }, - -- [''] = { 'select_and_accept' }, - -- [''] = { 'hide', 'show' }, - -- }, + -- (Default) Rust fuzzy matcher for typo resistance and significantly better performance + -- You may use a lua implementation instead by using `implementation = "lua"` or fallback to the lua implementation, + -- when the Rust fuzzy matcher is not available, by using `implementation = "prefer_rust"` + -- + -- See the fuzzy documentation for more information + fuzzy = { implementation = 'prefer_rust_with_warning' }, }, + opts_extend = { 'sources.default' }, }, + -- { + -- 'saghen/blink.cmp', + -- dependencies = { 'rafamadriz/friendly-snippets' }, + -- version = '1.*', + -- opts = { + -- appearance = { + -- use_nvim_cmp_as_default = false, + -- nerd_font_variant = 'mono', + -- }, + -- completion = { + -- accept = { + -- auto_brackets = { + -- enabled = true, + -- }, + -- }, + -- menu = { + -- draw = { + -- treesitter = { 'lsp' }, + -- }, + -- }, + -- documentation = { + -- auto_show = true, + -- auto_show_delay_ms = 200, + -- }, + -- ghost_text = { + -- enabled = vim.g.ai_cmp, + -- }, + -- }, + -- sources = { + -- default = { 'lsp', 'path', 'snippets', 'buffer' }, + -- }, + -- cmdline = { + -- enabled = false, + -- keymap = { + -- preset = 'cmdline', + -- [''] = false, + -- [''] = false, + -- }, + -- sources = { + -- default = { 'lsp', 'path', 'snippets', 'buffer' }, + -- }, + -- completion = { + -- menu = { + -- auto_show = true, + -- }, + -- ghost_text = { + -- enabled = true, + -- }, + -- }, + -- }, + -- + -- keymap = { + -- preset = 'default', + -- + -- [''] = { 'select_prev', 'snippet_backward', 'fallback' }, + -- [''] = { 'select_next', 'snippet_forward', 'fallback' }, + -- -- [''] = { 'select_prev', 'snippet_backward', 'fallback' }, + -- -- [''] = { 'select_next', 'snippet_forward', 'fallback' }, + -- [''] = { 'accept', 'fallback' }, + -- [''] = { 'hide', 'fallback' }, + -- [''] = { 'scroll_documentation_up', 'fallback' }, + -- [''] = { 'scroll_documentation_down', 'fallback' }, + -- }, + -- -- completion = { list = { selection = 'manual' } }, + -- -- keymap = { + -- -- preset = 'super-tab', + -- -- -- [''] = { 'insert_next' }, + -- -- -- [''] = { 'insert_prev' }, + -- -- -- [''] = { 'insert_next' }, + -- -- -- [''] = { 'insert_prev' }, + -- -- [''] = { 'select_and_accept' }, + -- -- [''] = { 'hide', 'show' }, + -- -- }, + -- }, + -- }, -- { 'nvim-tree/nvim-tree.lua', From a48b21ec329b4ed2b3ac66bf0d859e35847bb60b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 21:16:40 +0300 Subject: [PATCH 0071/1406] update --- lua/platformio/lspClangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index f1bfefcc..f5443082 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -32,7 +32,7 @@ end -- List of packages you want Mason to ensure are installed local ensure_installed = { 'clang-format', - 'biome', + -- 'biome', } -- call mason-registry function to install or ensure formatters/linters are installed From 3a7c94357fc7cd7d0be7b72a97dcaa47538a3b2b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 1 Apr 2026 21:21:17 +0300 Subject: [PATCH 0072/1406] update --- lua/platformio/boilerplate.lua | 4 ++-- lua/platformio/lspClangd.lua | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index d4fd878d..60d69fce 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -46,9 +46,9 @@ clangd ]], } -boilerplate['.clang_format'] = { +boilerplate['.clang-format'] = { src_path = vim.fn.getcwd(), - filename = '.clang_format', + filename = '.clang-format', content = [[ --- Language: Cpp diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index f5443082..1f347d0b 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -73,7 +73,7 @@ require('mason-lspconfig').setup({ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]]) boilerplate_gen([[.clangd_cmd]]) -boilerplate_gen([[.clang_format]]) +boilerplate_gen([[.clang-format]]) local cmd = { 'clangd' } From 6c694561ede9de7282473d1598d7646813bb4250 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 05:05:54 +0300 Subject: [PATCH 0073/1406] update --- README.md | 2 +- minimal_config.lua | 153 ++++++++++++--------------------------------- 2 files changed, 40 insertions(+), 115 deletions(-) diff --git a/README.md b/README.md index a06d6538..40a6329d 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ https://github.com/user-attachments/assets/fdbb6655-4b2d-4a2b-81d1-fd8af6e7d9f1 Try the plugin with this minimal standalone config without modifying your existing nvim setup. **This is especially useful if you're encountering errors during installation or usage**. ```sh -wget https://raw.githubusercontent.com/batoaqaa/nvim-platformio.lua/main/minimal_config.lua +wget https://raw.githubusercontent.com/batoaqaa/nvim-platformio.lua/refs/heads/main/minimal_config.lua nvim -u minimal_config.lua # Now run :Pioinit diff --git a/minimal_config.lua b/minimal_config.lua index ff19e9a7..1d9ecc1b 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -93,133 +93,58 @@ vim.opt.rtp:prepend(lazypath) ---------------------------------------------------------------------------------------- local plugins = { - { - 'saghen/blink.cmp', - -- optional: provides snippets for the snippet source - dependencies = { 'rafamadriz/friendly-snippets' }, - - -- use a release tag to download pre-built binaries - version = '1.*', - -- AND/OR build from source - -- build = 'cargo build --release', - -- If you use nix, you can build from source with: - -- build = 'nix run .#build-plugin', - - ---@module 'blink.cmp' - ---@type blink.cmp.Config - opts = { - -- 'default' (recommended) for mappings similar to built-in completions (C-y to accept) - -- 'super-tab' for mappings similar to vscode (tab to accept) - -- 'enter' for enter to accept - -- 'none' for no mappings - -- - -- All presets have the following mappings: - -- C-space: Open menu or open docs if already open - -- C-n/C-p or Up/Down: Select next/previous item - -- C-e: Hide menu - -- C-k: Toggle signature help (if signature.enabled = true) - -- - -- See :h blink-cmp-config-keymap for defining your own keymap - keymap = { preset = 'default' }, - - appearance = { - -- 'mono' (default) for 'Nerd Font Mono' or 'normal' for 'Nerd Font' - -- Adjusts spacing to ensure icons are aligned - nerd_font_variant = 'mono', - }, - - -- (Default) Only show the documentation popup when manually triggered - completion = { documentation = { auto_show = false } }, - - -- Default list of enabled providers defined so that you can extend it - -- elsewhere in your config, without redefining it, due to `opts_extend` - sources = { - default = { 'lsp', 'path', 'snippets', 'buffer' }, - }, - - -- (Default) Rust fuzzy matcher for typo resistance and significantly better performance - -- You may use a lua implementation instead by using `implementation = "lua"` or fallback to the lua implementation, - -- when the Rust fuzzy matcher is not available, by using `implementation = "prefer_rust"` - -- - -- See the fuzzy documentation for more information - fuzzy = { implementation = 'prefer_rust_with_warning' }, - }, - opts_extend = { 'sources.default' }, - }, -- { -- 'saghen/blink.cmp', + -- -- optional: provides snippets for the snippet source -- dependencies = { 'rafamadriz/friendly-snippets' }, + -- + -- -- use a release tag to download pre-built binaries -- version = '1.*', + -- -- AND/OR build from source + -- -- build = 'cargo build --release', + -- -- If you use nix, you can build from source with: + -- -- build = 'nix run .#build-plugin', + -- + -- ---@module 'blink.cmp' + -- ---@type blink.cmp.Config -- opts = { + -- -- 'default' (recommended) for mappings similar to built-in completions (C-y to accept) + -- -- 'super-tab' for mappings similar to vscode (tab to accept) + -- -- 'enter' for enter to accept + -- -- 'none' for no mappings + -- -- + -- -- All presets have the following mappings: + -- -- C-space: Open menu or open docs if already open + -- -- C-n/C-p or Up/Down: Select next/previous item + -- -- C-e: Hide menu + -- -- C-k: Toggle signature help (if signature.enabled = true) + -- -- + -- -- See :h blink-cmp-config-keymap for defining your own keymap + -- keymap = { preset = 'default' }, + -- -- appearance = { - -- use_nvim_cmp_as_default = false, + -- -- 'mono' (default) for 'Nerd Font Mono' or 'normal' for 'Nerd Font' + -- -- Adjusts spacing to ensure icons are aligned -- nerd_font_variant = 'mono', -- }, - -- completion = { - -- accept = { - -- auto_brackets = { - -- enabled = true, - -- }, - -- }, - -- menu = { - -- draw = { - -- treesitter = { 'lsp' }, - -- }, - -- }, - -- documentation = { - -- auto_show = true, - -- auto_show_delay_ms = 200, - -- }, - -- ghost_text = { - -- enabled = vim.g.ai_cmp, - -- }, - -- }, + -- + -- -- (Default) Only show the documentation popup when manually triggered + -- completion = { documentation = { auto_show = false } }, + -- + -- -- Default list of enabled providers defined so that you can extend it + -- -- elsewhere in your config, without redefining it, due to `opts_extend` -- sources = { -- default = { 'lsp', 'path', 'snippets', 'buffer' }, -- }, - -- cmdline = { - -- enabled = false, - -- keymap = { - -- preset = 'cmdline', - -- [''] = false, - -- [''] = false, - -- }, - -- sources = { - -- default = { 'lsp', 'path', 'snippets', 'buffer' }, - -- }, - -- completion = { - -- menu = { - -- auto_show = true, - -- }, - -- ghost_text = { - -- enabled = true, - -- }, - -- }, - -- }, -- - -- keymap = { - -- preset = 'default', - -- - -- [''] = { 'select_prev', 'snippet_backward', 'fallback' }, - -- [''] = { 'select_next', 'snippet_forward', 'fallback' }, - -- -- [''] = { 'select_prev', 'snippet_backward', 'fallback' }, - -- -- [''] = { 'select_next', 'snippet_forward', 'fallback' }, - -- [''] = { 'accept', 'fallback' }, - -- [''] = { 'hide', 'fallback' }, - -- [''] = { 'scroll_documentation_up', 'fallback' }, - -- [''] = { 'scroll_documentation_down', 'fallback' }, - -- }, - -- -- completion = { list = { selection = 'manual' } }, - -- -- keymap = { - -- -- preset = 'super-tab', - -- -- -- [''] = { 'insert_next' }, - -- -- -- [''] = { 'insert_prev' }, - -- -- -- [''] = { 'insert_next' }, - -- -- -- [''] = { 'insert_prev' }, - -- -- [''] = { 'select_and_accept' }, - -- -- [''] = { 'hide', 'show' }, - -- -- }, + -- -- (Default) Rust fuzzy matcher for typo resistance and significantly better performance + -- -- You may use a lua implementation instead by using `implementation = "lua"` or fallback to the lua implementation, + -- -- when the Rust fuzzy matcher is not available, by using `implementation = "prefer_rust"` + -- -- + -- -- See the fuzzy documentation for more information + -- fuzzy = { implementation = 'prefer_rust_with_warning' }, -- }, + -- opts_extend = { 'sources.default' }, -- }, -- { From 997317b8e20295c6787b9823bd8d35ccb5fe0730 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 05:24:46 +0300 Subject: [PATCH 0074/1406] update --- lua/platformio/lspKeymaps.lua | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/lua/platformio/lspKeymaps.lua b/lua/platformio/lspKeymaps.lua index f983781c..555805e8 100644 --- a/lua/platformio/lspKeymaps.lua +++ b/lua/platformio/lspKeymaps.lua @@ -102,23 +102,23 @@ function K.lspKeymaps(client, bufnr) -- }) -- -- -- LSP format the current buffer on save - --local fmt_group = vim.api.nvim_create_augroup('autoformat_cmds', { clear = true }) - -- vim.api.nvim_create_autocmd('BufWritePre', { - -- buffer = buf_number, - -- group = get_augroup(client), - -- desc = 'Fromat current buffer', - -- callback = function() - -- vim.lsp.buf.format { - -- bufnr = buf_number, - -- async = false, - -- timeout_ms = 10000, - -- id = client.id, - -- filter = function(c) - -- return c.id == client.id - -- end, - -- } - -- end, - -- }) + local fmt_group = vim.api.nvim_create_augroup('autoformat_cmds', { clear = true }) + vim.api.nvim_create_autocmd('BufWritePre', { + buffer = bufnr, + group = fmt_group, + desc = 'Fromat current buffer', + callback = function() + vim.lsp.buf.format({ + bufnr = bufnr, + async = false, + timeout_ms = 10000, + id = client.id, + filter = function(c) + return c.id == client.id + end, + }) + end, + }) end -- if client.server_capabilities.inlayHintProvider and vim.lsp.inlay_hint then From 46c02a2b146734cd12271617a28e57e6e9dbe277 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 05:28:38 +0300 Subject: [PATCH 0075/1406] update --- lua/platformio/lspAttach.lua | 2 +- lua/platformio/lspKeymaps.lua | 34 +++++++++++++++++----------------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 259cbf4e..93f47667 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -42,7 +42,7 @@ vim.api.nvim_create_autocmd('LspAttach', { current_line = true, }, }) - vim.cmd([[set completeopt+=noselect]]) + -- vim.cmd([[set completeopt+=noselect]]) end ------------------------------------------------------------------ diff --git a/lua/platformio/lspKeymaps.lua b/lua/platformio/lspKeymaps.lua index 555805e8..3ba996f2 100644 --- a/lua/platformio/lspKeymaps.lua +++ b/lua/platformio/lspKeymaps.lua @@ -102,23 +102,23 @@ function K.lspKeymaps(client, bufnr) -- }) -- -- -- LSP format the current buffer on save - local fmt_group = vim.api.nvim_create_augroup('autoformat_cmds', { clear = true }) - vim.api.nvim_create_autocmd('BufWritePre', { - buffer = bufnr, - group = fmt_group, - desc = 'Fromat current buffer', - callback = function() - vim.lsp.buf.format({ - bufnr = bufnr, - async = false, - timeout_ms = 10000, - id = client.id, - filter = function(c) - return c.id == client.id - end, - }) - end, - }) + -- local fmt_group = vim.api.nvim_create_augroup('autoformat_cmds', { clear = true }) + -- vim.api.nvim_create_autocmd('BufWritePre', { + -- buffer = bufnr, + -- group = fmt_group, + -- desc = 'Fromat current buffer', + -- callback = function() + -- vim.lsp.buf.format({ + -- bufnr = bufnr, + -- async = false, + -- timeout_ms = 10000, + -- id = client.id, + -- filter = function(c) + -- return c.id == client.id + -- end, + -- }) + -- end, + -- }) end -- if client.server_capabilities.inlayHintProvider and vim.lsp.inlay_hint then From aef86a945e548abb926448e4f6e1b629a3efd56a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 05:32:21 +0300 Subject: [PATCH 0076/1406] update --- lua/platformio/lspKeymaps.lua | 41 +++++++++++++++-------------------- 1 file changed, 18 insertions(+), 23 deletions(-) diff --git a/lua/platformio/lspKeymaps.lua b/lua/platformio/lspKeymaps.lua index 3ba996f2..f4606acf 100644 --- a/lua/platformio/lspKeymaps.lua +++ b/lua/platformio/lspKeymaps.lua @@ -95,30 +95,25 @@ function K.lspKeymaps(client, bufnr) vim.lsp.buf.format({ bufnr = bufnr, async = true }) -- require('conform').format({ bufnr = bufnr, async = true }) end, '[f]ormat buffer') - -- -- - -- vim.api.nvim_clear_autocmds({ - -- group = get_augroup(client), - -- buffer = buf_number, - -- }) - -- -- + -- LSP format the current buffer on save - -- local fmt_group = vim.api.nvim_create_augroup('autoformat_cmds', { clear = true }) - -- vim.api.nvim_create_autocmd('BufWritePre', { - -- buffer = bufnr, - -- group = fmt_group, - -- desc = 'Fromat current buffer', - -- callback = function() - -- vim.lsp.buf.format({ - -- bufnr = bufnr, - -- async = false, - -- timeout_ms = 10000, - -- id = client.id, - -- filter = function(c) - -- return c.id == client.id - -- end, - -- }) - -- end, - -- }) + local fmt_group = vim.api.nvim_create_augroup('autoformat_cmds', { clear = true }) + vim.api.nvim_create_autocmd('BufWritePre', { + buffer = bufnr, + group = fmt_group, + desc = 'Fromat current buffer', + callback = function() + vim.lsp.buf.format({ + bufnr = bufnr, + async = false, + timeout_ms = 10000, + id = client.id, + filter = function(c) + return c.id == client.id + end, + }) + end, + }) end -- if client.server_capabilities.inlayHintProvider and vim.lsp.inlay_hint then From 8f0e766af485df65cdd98b0511d11b9f349854ce Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 05:37:06 +0300 Subject: [PATCH 0077/1406] update --- lua/platformio/lspAttach.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 93f47667..259cbf4e 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -42,7 +42,7 @@ vim.api.nvim_create_autocmd('LspAttach', { current_line = true, }, }) - -- vim.cmd([[set completeopt+=noselect]]) + vim.cmd([[set completeopt+=noselect]]) end ------------------------------------------------------------------ From 6efacdeb5e1a82fd70db64c131bf5966aafe4464 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 05:47:57 +0300 Subject: [PATCH 0078/1406] update --- lua/platformio/boilerplate.lua | 10 ++++------ lua/platformio/lspClangd.lua | 7 ++++--- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 60d69fce..1e60b2e1 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -6,7 +6,6 @@ local boilerplate = {} boilerplate['arduino'] = { -- local platformioRootDir = vim.fs.root(vim.fn.getcwd(), { 'platformio.ini' }) -- cwd and parents - src_path = vim.fn.getcwd() .. '/src', filename = 'main.cpp', content = [[ #include @@ -22,7 +21,6 @@ void loop() { } boilerplate['.clangd_cmd'] = { - src_path = vim.fn.getcwd(), filename = '.clangd_cmd', content = [[ clangd @@ -47,7 +45,6 @@ clangd } boilerplate['.clang-format'] = { - src_path = vim.fn.getcwd(), filename = '.clang-format', content = [[ --- @@ -299,8 +296,9 @@ WhitespaceSensitiveMacros: ]], } +-- local home = vim.env.HOME +-- print(home) boilerplate['.clangd'] = { - src_path = vim.fn.getcwd(), filename = '.clangd', content = [[ CompileFlags: @@ -342,13 +340,13 @@ Diagnostics: ]], } -function M.boilerplate_gen(framework) +function M.boilerplate_gen(framework, src_path) local entry = boilerplate[framework] if not entry then return end -- - local file_path = entry.src_path .. '/' .. entry.filename + local file_path = src_path .. '/' .. entry.filename if vim.uv.fs_stat(file_path) then return end diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 1f347d0b..71e93dfd 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -71,9 +71,10 @@ require('mason-lspconfig').setup({ ----------------------------------------------------------------------------------------- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -boilerplate_gen([[.clangd]]) -boilerplate_gen([[.clangd_cmd]]) -boilerplate_gen([[.clang-format]]) +boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) +boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) +boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) local cmd = { 'clangd' } From 13a839834f9c272f862c510df2fcd7b7a3df43aa Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 05:53:52 +0300 Subject: [PATCH 0079/1406] update --- lua/platformio/lspClangd.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 71e93dfd..09db7366 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -72,6 +72,7 @@ require('mason-lspconfig').setup({ ----------------------------------------------------------------------------------------- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +print(vim.env.PLATFORMIO_CORE_DIR) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) From 4257283c98e8df07617a6fdccec4d554a2a5d198 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 06:03:40 +0300 Subject: [PATCH 0080/1406] update --- lua/platformio/lspClangd.lua | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 09db7366..f3fae3a0 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -72,7 +72,6 @@ require('mason-lspconfig').setup({ ----------------------------------------------------------------------------------------- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -print(vim.env.PLATFORMIO_CORE_DIR) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) @@ -129,7 +128,7 @@ if mok then mason_lspconfig.setup({}) end -require('platformio.piolsp').piolsp() +-- require('platformio.piolsp').piolsp() local config = require('platformio').config if config.lspClangd.attach.enabled then require('platformio.lspAttach') From 01529c8e53faee6fb1dddf9065169d136fc5ceb6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 06:28:05 +0300 Subject: [PATCH 0081/1406] update --- lua/platformio/lspClangd.lua | 66 ++++++++++++++++++------------------ 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index f3fae3a0..b1798cab 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -30,39 +30,39 @@ if ok then end -- List of packages you want Mason to ensure are installed -local ensure_installed = { - 'clang-format', - -- 'biome', -} - --- call mason-registry function to install or ensure formatters/linters are installed -local mr = require('mason-registry') -mr.refresh(function() - for _, tool in ipairs(ensure_installed) do - ok, result = pcall(mr.get_package, tool) - if ok and result then - if not result:is_installed() then - if not result:is_installing() then - result:install({}, function(success, _) - if not success then - vim.defer_fn(function() - vim.notify(tool .. ' failed to install', vim.log.levels.ERROR) - end, 0) - end - end) - else - vim.defer_fn(function() - vim.notify(tool .. ' already installed', vim.log.levels.WARN) - end, 0) - end - end - else - vim.defer_fn(function() - vim.notify('Failed to get package: ' .. tool, vim.log.levels.WARN) - end, 0) - end - end -end) +-- local ensure_installed = { +-- 'clang-format', +-- -- 'biome', +-- } +-- +-- -- call mason-registry function to install or ensure formatters/linters are installed +-- local mr = require('mason-registry') +-- mr.refresh(function() +-- for _, tool in ipairs(ensure_installed) do +-- ok, result = pcall(mr.get_package, tool) +-- if ok and result then +-- if not result:is_installed() then +-- if not result:is_installing() then +-- result:install({}, function(success, _) +-- if not success then +-- vim.defer_fn(function() +-- vim.notify(tool .. ' failed to install', vim.log.levels.ERROR) +-- end, 0) +-- end +-- end) +-- else +-- vim.defer_fn(function() +-- vim.notify(tool .. ' already installed', vim.log.levels.WARN) +-- end, 0) +-- end +-- end +-- else +-- vim.defer_fn(function() +-- vim.notify('Failed to get package: ' .. tool, vim.log.levels.WARN) +-- end, 0) +-- end +-- end +-- end) require('mason-lspconfig').setup({ ensure_installed = { 'clangd' }, From 489c10fb1fc868d610a391a02f22c1cfdb576957 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 06:40:42 +0300 Subject: [PATCH 0082/1406] update --- lua/platformio/lspClangd.lua | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index b1798cab..c63283bd 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -129,6 +129,14 @@ if mok then end -- require('platformio.piolsp').piolsp() +if vim.fn.has('nvim-0.12') then + if #vim.lsp.get_clients() > 0 then + vim.cmd('lsp restart') + end +else + vim.cmd('LspRestart') +end + local config = require('platformio').config if config.lspClangd.attach.enabled then require('platformio.lspAttach') From 97afe947bbbda80ab12474eb549450cf8d253ee7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 08:02:51 +0300 Subject: [PATCH 0083/1406] update --- lua/platformio/lspKeymaps.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspKeymaps.lua b/lua/platformio/lspKeymaps.lua index f4606acf..04280519 100644 --- a/lua/platformio/lspKeymaps.lua +++ b/lua/platformio/lspKeymaps.lua @@ -85,11 +85,11 @@ function K.lspKeymaps(client, bufnr) end, '[W]orkspace [L]ist folders') end -- - if client.supports_method('textDocument/switchSourceHeader') then + if client:supports_method('textDocument/switchSourceHeader') then bufkeymap('n', 'glws', 'LspClangdSwitchSourceHeader', '[S]witch Source/Header (C/C++)') end - if client.supports_method('textDocument/formatting') then + if client:supports_method('textDocument/formatting') then -- if client.server_capabilities.documentFormattingProvider then bufkeymap({ 'n', 'x' }, 'glf', function() vim.lsp.buf.format({ bufnr = bufnr, async = true }) From d0f247256a22c30e215bd17392efb1294fa52b52 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 08:38:02 +0300 Subject: [PATCH 0084/1406] update --- lua/platformio/lspAttach.lua | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 259cbf4e..9c8b753b 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -79,15 +79,15 @@ vim.api.nvim_create_autocmd('LspAttach', { end ------------------------------------------------------------------ - vim.lsp.handlers['textDocument/publishDiagnostics'] = vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { - signs = true, - underline = true, - virtual_text = { - spacing = 5, - min = vim.diagnostic.severity.HINT, - }, - update_in_insert = true, - }) + -- vim.lsp.handlers['textDocument/publishDiagnostics'] = vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { + -- signs = true, + -- underline = true, + -- virtual_text = { + -- spacing = 5, + -- min = vim.diagnostic.severity.HINT, + -- }, + -- update_in_insert = true, + -- }) ------------------------------------------------------------------ vim.cmd([[autocmd FileType * set formatoptions-=ro]]) From a7f2d103925d1fab2264e8c905e1b83e77f16cee Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 09:02:00 +0300 Subject: [PATCH 0085/1406] update --- lua/platformio/lspAttach.lua | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 9c8b753b..c9023386 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -78,17 +78,6 @@ vim.api.nvim_create_autocmd('LspAttach', { end end - ------------------------------------------------------------------ - -- vim.lsp.handlers['textDocument/publishDiagnostics'] = vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { - -- signs = true, - -- underline = true, - -- virtual_text = { - -- spacing = 5, - -- min = vim.diagnostic.severity.HINT, - -- }, - -- update_in_insert = true, - -- }) - ------------------------------------------------------------------ vim.cmd([[autocmd FileType * set formatoptions-=ro]]) -- From d7c61f736c4f32ddc2dfd675eac2838a57cef280 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 09:17:22 +0300 Subject: [PATCH 0086/1406] update --- lua/platformio/lspAttach.lua | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index c9023386..59aa83d2 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -36,12 +36,12 @@ vim.api.nvim_create_autocmd('LspAttach', { if client:supports_method('textDocument/completion', { bufnr = bufnr }) then vim.lsp.completion.enable(true, client.id, args.buf, { autotrigger = true }) end - vim.diagnostic.config({ - current_line = true, - virtual_lines = { - current_line = true, - }, - }) + -- vim.diagnostic.config({ + -- current_line = true, + -- virtual_lines = { + -- current_line = true, + -- }, + -- }) vim.cmd([[set completeopt+=noselect]]) end From 41be83f52bc31f14ea7f9e9f848223cfd1279b17 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 09:24:25 +0300 Subject: [PATCH 0087/1406] update --- lua/platformio/lspAttach.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 59aa83d2..256e3ee6 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -34,15 +34,16 @@ vim.api.nvim_create_autocmd('LspAttach', { local bok, _ = pcall(require, 'blink') if not bok then if client:supports_method('textDocument/completion', { bufnr = bufnr }) then - vim.lsp.completion.enable(true, client.id, args.buf, { autotrigger = true }) + vim.lsp.completion.enable(true, client.id, bufnr, { autotrigger = true }) end + -- vim.diagnostic.config({ -- current_line = true, -- virtual_lines = { -- current_line = true, -- }, -- }) - vim.cmd([[set completeopt+=noselect]]) + -- vim.cmd([[set completeopt+=noselect]]) end ------------------------------------------------------------------ From e5489d4df0dccc81683adcb61a897ebb8deffdeb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 09:41:59 +0300 Subject: [PATCH 0088/1406] update --- minimal_config.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/minimal_config.lua b/minimal_config.lua index 1d9ecc1b..c93ff938 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -268,6 +268,7 @@ if not vim.uv.fs_stat(pynvim_env) then if not isWindows then vim.fn.system({ 'python3', '-m', 'venv', pynvim_env }) vim.fn.system({ 'chmod', '755', '-R', pynvim_bin }) + vim.cmd.source(pynvim_activate) else vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) end From 3c4cc2d275f969a5856f866cdabac6f757527a5b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 10:02:08 +0300 Subject: [PATCH 0089/1406] update --- minimal_config.lua | 3 +++ 1 file changed, 3 insertions(+) diff --git a/minimal_config.lua b/minimal_config.lua index c93ff938..35c39c08 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -271,6 +271,7 @@ if not vim.uv.fs_stat(pynvim_env) then vim.cmd.source(pynvim_activate) else vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) + print('create venv') end vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'pip' }) @@ -280,7 +281,9 @@ if not vim.uv.fs_stat(pynvim_env) then vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'isort' }) vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'scons' }) vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'yamllint' }) + print('before') vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'platformio' }) + print('after') -- vim.fn.system({ 'pip', 'install', '-U', 'platformio' }) end ------------------------ From 617ab0f1d2d8677c390f0a8af3261af0da0a3c51 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 10:08:32 +0300 Subject: [PATCH 0090/1406] update --- minimal_config.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index 35c39c08..b4f101ea 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -268,10 +268,10 @@ if not vim.uv.fs_stat(pynvim_env) then if not isWindows then vim.fn.system({ 'python3', '-m', 'venv', pynvim_env }) vim.fn.system({ 'chmod', '755', '-R', pynvim_bin }) - vim.cmd.source(pynvim_activate) + print('create venv') + vim.cmd('source ' .. pynvim_activate) else vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) - print('create venv') end vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'pip' }) From 31b2a2e4bc72cd2730c0479b02da6dc24e98c003 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 10:16:36 +0300 Subject: [PATCH 0091/1406] update --- minimal_config.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index b4f101ea..abe390a5 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -269,7 +269,8 @@ if not vim.uv.fs_stat(pynvim_env) then vim.fn.system({ 'python3', '-m', 'venv', pynvim_env }) vim.fn.system({ 'chmod', '755', '-R', pynvim_bin }) print('create venv') - vim.cmd('source ' .. pynvim_activate) + -- vim.cmd('source ' .. pynvim_activate) + vim.fn.system('source ' .. pynvim_activate) else vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) end From ff134a1802050889a44487eb82b6be2b7ce224ef Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 10:24:02 +0300 Subject: [PATCH 0092/1406] update --- minimal_config.lua | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index abe390a5..9b09c731 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -275,16 +275,22 @@ if not vim.uv.fs_stat(pynvim_env) then vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) end - vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'pip' }) - vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'pynvim' }) - vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'neovim' }) - vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'debugpy' }) - vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'isort' }) - vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'scons' }) - vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'yamllint' }) - print('before') - vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'platformio' }) - print('after') + local output = vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'pip' }) + print('pip: ' .. output) + output = vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'pynvim' }) + print('pynvim: ' .. output) + output = vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'neovim' }) + print('neovim: ' .. output) + output = vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'debugpy' }) + print('debugpy: ' .. output) + output = vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'isort' }) + print('isort: ' .. output) + output = vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'scons' }) + print('scons: ' .. output) + output = vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'yamllint' }) + print('yamllint: ' .. output) + output = vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'platformio' }) + print('platformio: ' .. output) -- vim.fn.system({ 'pip', 'install', '-U', 'platformio' }) end ------------------------ From ce95b91e2f6d735aa8f12c8e68e6a92b07ee0d8b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 11:35:03 +0300 Subject: [PATCH 0093/1406] update --- minimal_config.lua | 25 +++++++++---------------- 1 file changed, 9 insertions(+), 16 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index 9b09c731..b3b931e8 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -273,24 +273,17 @@ if not vim.uv.fs_stat(pynvim_env) then vim.fn.system('source ' .. pynvim_activate) else vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) + vim.fn.system(pynvim_activate) end - local output = vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'pip' }) - print('pip: ' .. output) - output = vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'pynvim' }) - print('pynvim: ' .. output) - output = vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'neovim' }) - print('neovim: ' .. output) - output = vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'debugpy' }) - print('debugpy: ' .. output) - output = vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'isort' }) - print('isort: ' .. output) - output = vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'scons' }) - print('scons: ' .. output) - output = vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'yamllint' }) - print('yamllint: ' .. output) - output = vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'platformio' }) - print('platformio: ' .. output) + vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'pip' }) + vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'pynvim' }) + vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'neovim' }) + vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'debugpy' }) + vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'isort' }) + vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'scons' }) + vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'yamllint' }) + vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'platformio' }) -- vim.fn.system({ 'pip', 'install', '-U', 'platformio' }) end ------------------------ From 882fafac848b76bd34d99f7a3047ebdcc204f831 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 11:49:20 +0300 Subject: [PATCH 0094/1406] update --- lua/platformio/pioinit.lua | 2 +- minimal_config.lua | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index a9843aab..2a5561da 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -62,7 +62,7 @@ local function pick_framework(board_details) -- .. utils.extra utils.ToggleTerminal(command, 'float', function() vim.cmd(':PioLSP') - boilerplate_gen(selected_framework) + boilerplate_gen(selected_framework, vim.g.platformioRootDir) end) end) return true diff --git a/minimal_config.lua b/minimal_config.lua index b3b931e8..e9769f1c 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -268,7 +268,6 @@ if not vim.uv.fs_stat(pynvim_env) then if not isWindows then vim.fn.system({ 'python3', '-m', 'venv', pynvim_env }) vim.fn.system({ 'chmod', '755', '-R', pynvim_bin }) - print('create venv') -- vim.cmd('source ' .. pynvim_activate) vim.fn.system('source ' .. pynvim_activate) else From ace0dca694639657879ff32818b9b6d68b9fad35 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 11:53:59 +0300 Subject: [PATCH 0095/1406] update --- lua/platformio/pioinit.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 2a5561da..e9d1b2f0 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -61,8 +61,8 @@ local function pick_framework(board_details) local command = 'pio project init --board ' .. board_details['id'] .. ' --project-option "framework=' .. selected_framework .. '"' -- .. utils.extra utils.ToggleTerminal(command, 'float', function() - vim.cmd(':PioLSP') boilerplate_gen(selected_framework, vim.g.platformioRootDir) + vim.cmd(':PioLSP') end) end) return true From 2d911bf8592173df553ae4d9e785776cf764af90 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 11:57:34 +0300 Subject: [PATCH 0096/1406] update --- lua/platformio/pioinit.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index e9d1b2f0..bb6fa29b 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -61,7 +61,7 @@ local function pick_framework(board_details) local command = 'pio project init --board ' .. board_details['id'] .. ' --project-option "framework=' .. selected_framework .. '"' -- .. utils.extra utils.ToggleTerminal(command, 'float', function() - boilerplate_gen(selected_framework, vim.g.platformioRootDir) + boilerplate_gen(selected_framework, vim.g.platformioRootDir .. '/src') vim.cmd(':PioLSP') end) end) From e157727e6d5ea157c72781114b7001983a5f51a4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 12:44:00 +0300 Subject: [PATCH 0097/1406] update --- lua/platformio/boilerplate.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 1e60b2e1..a9180f9b 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -346,6 +346,7 @@ function M.boilerplate_gen(framework, src_path) return end -- + print(src_path) local file_path = src_path .. '/' .. entry.filename if vim.uv.fs_stat(file_path) then return From daa0c6e2f7a139cf592ff614ac4ee9ee86d4fded Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 12:51:26 +0300 Subject: [PATCH 0098/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index a9180f9b..871a687d 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -341,12 +341,12 @@ Diagnostics: } function M.boilerplate_gen(framework, src_path) + print(src_path) local entry = boilerplate[framework] if not entry then return end -- - print(src_path) local file_path = src_path .. '/' .. entry.filename if vim.uv.fs_stat(file_path) then return From 4be41279b7c097d9dc1fa6deaf42b3bcea429074 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 13:04:03 +0300 Subject: [PATCH 0099/1406] update --- lua/platformio/lspClangd.lua | 1 - lua/platformio/pioinit.lua | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index c63283bd..19dff981 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -80,7 +80,6 @@ local cmd = { 'clangd' } -- local path = vim.fn.getcwd() local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) --- local fname = string.format('%s/.clangd_cmd', vim.g.platformioRootDir) if vim.fn.filereadable(fname) == 1 then ok, result = pcall(vim.fn.readfile, fname) if ok then diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index bb6fa29b..53fac35f 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -61,7 +61,7 @@ local function pick_framework(board_details) local command = 'pio project init --board ' .. board_details['id'] .. ' --project-option "framework=' .. selected_framework .. '"' -- .. utils.extra utils.ToggleTerminal(command, 'float', function() - boilerplate_gen(selected_framework, vim.g.platformioRootDir .. '/src') + boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') vim.cmd(':PioLSP') end) end) From 65572519c3d65cddfb8ca0a5c0d04a0605601421 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 13:16:48 +0300 Subject: [PATCH 0100/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/utils.lua | 24 +++++++++++++----------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 871a687d..67da4c2a 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -341,7 +341,7 @@ Diagnostics: } function M.boilerplate_gen(framework, src_path) - print(src_path) + print(src_path .. '/' .. framework) local entry = boilerplate[framework] if not entry then return diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index e0849e20..6374aeb3 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -44,9 +44,9 @@ end local function getPreviousWindow(orig_window) local prev = { orig_window = orig_window, - term = nil, --active terminal - cli = nil, --cli terminal - mon = nil, --mon terminal + term = nil, --active terminal + cli = nil, --cli terminal + mon = nil, --mon terminal float = false, --is active terminal direction float } local terms = require('toggleterm.terminal').get_all(true) @@ -87,7 +87,7 @@ local function send(term, cmd) vim.fn.chansend(term.job_id, cmd .. M.enter()) if vim.api.nvim_buf_is_loaded(term.bufnr) and vim.api.nvim_buf_is_valid(term.bufnr) then if term.window and vim.api.nvim_win_is_valid(term.window) then --vim.ui.term_has_open_win(term) then - vim.api.nvim_set_current_win(term.window) -- terminal focus + vim.api.nvim_set_current_win(term.window) -- terminal focus vim.api.nvim_buf_call(term.bufnr, function() local mode = vim.api.nvim_get_mode().mode if mode == 'n' or mode == 'nt' then @@ -217,13 +217,13 @@ function M.ToggleTerminal(command, direction, exit_callback) if config.debug then local name_splt = M.strsplit(t.display_name, ':') vim.api.nvim_echo({ - { 'ToggleTerm ', 'MoreMsg' }, - { '(Term name: ' .. name_splt[1] .. ')', 'MoreMsg' }, + { 'ToggleTerm ', 'MoreMsg' }, + { '(Term name: ' .. name_splt[1] .. ')', 'MoreMsg' }, { '(Prev win ID: ' .. name_splt[2] .. ')', 'MoreMsg' }, - { '(Term Win ID: ' .. t.window .. ')', 'MoreMsg' }, - { '(Term Buffer#: ' .. t.bufnr .. ')', 'MoreMsg' }, - { '(Term id: ' .. t.id .. ')', 'MoreMsg' }, - { '(Job ID: ' .. t.job_id .. ')', 'MoreMsg' }, + { '(Term Win ID: ' .. t.window .. ')', 'MoreMsg' }, + { '(Term Buffer#: ' .. t.bufnr .. ')', 'MoreMsg' }, + { '(Term id: ' .. t.id .. ')', 'MoreMsg' }, + { '(Job ID: ' .. t.job_id .. ')', 'MoreMsg' }, }, true, {}) end end, @@ -237,6 +237,7 @@ function M.ToggleTerminal(command, direction, exit_callback) else vim.api.nvim_set_current_win(0) end + print('exit:') exit_callback() end, @@ -343,7 +344,8 @@ function M.cd_pioini() end function M.pio_install_check() - local handel = (jit.os == 'Windows') and assert(io.popen('where.exe pio 2>./nul')) or assert(io.popen('which pio 2>/dev/null')) + local handel = (jit.os == 'Windows') and assert(io.popen('where.exe pio 2>./nul')) or + assert(io.popen('which pio 2>/dev/null')) local pio_path = assert(handel:read('*a')) handel:close() From 6011559f754987cdfdfaf2855e8b3b801b5d5abd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 13:45:36 +0300 Subject: [PATCH 0101/1406] update --- lua/platformio/boilerplate.lua | 4 +--- lua/platformio/utils.lua | 6 ++++++ 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 67da4c2a..7580009c 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -3,9 +3,7 @@ local uv = vim.loop local boilerplate = {} -boilerplate['arduino'] = { - - -- local platformioRootDir = vim.fs.root(vim.fn.getcwd(), { 'platformio.ini' }) -- cwd and parents +boilerplate['Arduino'] = { filename = 'main.cpp', content = [[ #include diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 6374aeb3..4dcd6a43 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -237,6 +237,12 @@ function M.ToggleTerminal(command, direction, exit_callback) else vim.api.nvim_set_current_win(0) end + -- print('exit:') + -- exit_callback() + end, + + -- INFO: on_exit() + on_exit = function(t) print('exit:') exit_callback() end, From ee4fca61e550d4fafa3e43bd308e3519e66bdda6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 14:10:51 +0300 Subject: [PATCH 0102/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 7580009c..b6d5ce4e 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -3,7 +3,7 @@ local uv = vim.loop local boilerplate = {} -boilerplate['Arduino'] = { +boilerplate['arduino'] = { filename = 'main.cpp', content = [[ #include From 7e7913c221a70679329f8f4554616dfc7ed1c7ed Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 15:07:20 +0300 Subject: [PATCH 0103/1406] update --- lua/platformio/utils.lua | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 4dcd6a43..c2533e18 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -44,9 +44,9 @@ end local function getPreviousWindow(orig_window) local prev = { orig_window = orig_window, - term = nil, --active terminal - cli = nil, --cli terminal - mon = nil, --mon terminal + term = nil, --active terminal + cli = nil, --cli terminal + mon = nil, --mon terminal float = false, --is active terminal direction float } local terms = require('toggleterm.terminal').get_all(true) @@ -87,7 +87,7 @@ local function send(term, cmd) vim.fn.chansend(term.job_id, cmd .. M.enter()) if vim.api.nvim_buf_is_loaded(term.bufnr) and vim.api.nvim_buf_is_valid(term.bufnr) then if term.window and vim.api.nvim_win_is_valid(term.window) then --vim.ui.term_has_open_win(term) then - vim.api.nvim_set_current_win(term.window) -- terminal focus + vim.api.nvim_set_current_win(term.window) -- terminal focus vim.api.nvim_buf_call(term.bufnr, function() local mode = vim.api.nvim_get_mode().mode if mode == 'n' or mode == 'nt' then @@ -217,13 +217,13 @@ function M.ToggleTerminal(command, direction, exit_callback) if config.debug then local name_splt = M.strsplit(t.display_name, ':') vim.api.nvim_echo({ - { 'ToggleTerm ', 'MoreMsg' }, - { '(Term name: ' .. name_splt[1] .. ')', 'MoreMsg' }, + { 'ToggleTerm ', 'MoreMsg' }, + { '(Term name: ' .. name_splt[1] .. ')', 'MoreMsg' }, { '(Prev win ID: ' .. name_splt[2] .. ')', 'MoreMsg' }, - { '(Term Win ID: ' .. t.window .. ')', 'MoreMsg' }, - { '(Term Buffer#: ' .. t.bufnr .. ')', 'MoreMsg' }, - { '(Term id: ' .. t.id .. ')', 'MoreMsg' }, - { '(Job ID: ' .. t.job_id .. ')', 'MoreMsg' }, + { '(Term Win ID: ' .. t.window .. ')', 'MoreMsg' }, + { '(Term Buffer#: ' .. t.bufnr .. ')', 'MoreMsg' }, + { '(Term id: ' .. t.id .. ')', 'MoreMsg' }, + { '(Job ID: ' .. t.job_id .. ')', 'MoreMsg' }, }, true, {}) end end, @@ -237,12 +237,12 @@ function M.ToggleTerminal(command, direction, exit_callback) else vim.api.nvim_set_current_win(0) end - -- print('exit:') + print('close:') -- exit_callback() end, -- INFO: on_exit() - on_exit = function(t) + on_exit = function(_) print('exit:') exit_callback() end, @@ -350,8 +350,7 @@ function M.cd_pioini() end function M.pio_install_check() - local handel = (jit.os == 'Windows') and assert(io.popen('where.exe pio 2>./nul')) or - assert(io.popen('which pio 2>/dev/null')) + local handel = (jit.os == 'Windows') and assert(io.popen('where.exe pio 2>./nul')) or assert(io.popen('which pio 2>/dev/null')) local pio_path = assert(handel:read('*a')) handel:close() From 734640cc168c2e25ce78b9c003b240b46e63d331 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 15:57:00 +0300 Subject: [PATCH 0104/1406] update --- lua/platformio/utils.lua | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index c2533e18..bc292d5d 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -44,9 +44,9 @@ end local function getPreviousWindow(orig_window) local prev = { orig_window = orig_window, - term = nil, --active terminal - cli = nil, --cli terminal - mon = nil, --mon terminal + term = nil, --active terminal + cli = nil, --cli terminal + mon = nil, --mon terminal float = false, --is active terminal direction float } local terms = require('toggleterm.terminal').get_all(true) @@ -87,7 +87,7 @@ local function send(term, cmd) vim.fn.chansend(term.job_id, cmd .. M.enter()) if vim.api.nvim_buf_is_loaded(term.bufnr) and vim.api.nvim_buf_is_valid(term.bufnr) then if term.window and vim.api.nvim_win_is_valid(term.window) then --vim.ui.term_has_open_win(term) then - vim.api.nvim_set_current_win(term.window) -- terminal focus + vim.api.nvim_set_current_win(term.window) -- terminal focus vim.api.nvim_buf_call(term.bufnr, function() local mode = vim.api.nvim_get_mode().mode if mode == 'n' or mode == 'nt' then @@ -116,7 +116,10 @@ end ------------------------------------------------------ -- INFO: ToggleTerminal function M.ToggleTerminal(command, direction, exit_callback) - if type(exit_callback) ~= 'function' then + local closeOnexit = false + if type(exit_callback) == 'function' then + closeOnexit = true + else exit_callback = function() end end @@ -187,7 +190,7 @@ function M.ToggleTerminal(command, direction, exit_callback) background = 'NormalFloat', }, }, - close_on_exit = false, + close_on_exit = closeOnexit, -- INFO: on_open() on_open = function(t) @@ -217,13 +220,13 @@ function M.ToggleTerminal(command, direction, exit_callback) if config.debug then local name_splt = M.strsplit(t.display_name, ':') vim.api.nvim_echo({ - { 'ToggleTerm ', 'MoreMsg' }, - { '(Term name: ' .. name_splt[1] .. ')', 'MoreMsg' }, + { 'ToggleTerm ', 'MoreMsg' }, + { '(Term name: ' .. name_splt[1] .. ')', 'MoreMsg' }, { '(Prev win ID: ' .. name_splt[2] .. ')', 'MoreMsg' }, - { '(Term Win ID: ' .. t.window .. ')', 'MoreMsg' }, - { '(Term Buffer#: ' .. t.bufnr .. ')', 'MoreMsg' }, - { '(Term id: ' .. t.id .. ')', 'MoreMsg' }, - { '(Job ID: ' .. t.job_id .. ')', 'MoreMsg' }, + { '(Term Win ID: ' .. t.window .. ')', 'MoreMsg' }, + { '(Term Buffer#: ' .. t.bufnr .. ')', 'MoreMsg' }, + { '(Term id: ' .. t.id .. ')', 'MoreMsg' }, + { '(Job ID: ' .. t.job_id .. ')', 'MoreMsg' }, }, true, {}) end end, @@ -350,7 +353,8 @@ function M.cd_pioini() end function M.pio_install_check() - local handel = (jit.os == 'Windows') and assert(io.popen('where.exe pio 2>./nul')) or assert(io.popen('which pio 2>/dev/null')) + local handel = (jit.os == 'Windows') and assert(io.popen('where.exe pio 2>./nul')) or + assert(io.popen('which pio 2>/dev/null')) local pio_path = assert(handel:read('*a')) handel:close() From f064f7b48cf2d6529801f6cc2c63cd2221258ba5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 16:27:25 +0300 Subject: [PATCH 0105/1406] update --- lua/platformio/utils.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index bc292d5d..0172bf33 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -119,6 +119,7 @@ function M.ToggleTerminal(command, direction, exit_callback) local closeOnexit = false if type(exit_callback) == 'function' then closeOnexit = true + print('closeOnexit') else exit_callback = function() end end @@ -190,7 +191,7 @@ function M.ToggleTerminal(command, direction, exit_callback) background = 'NormalFloat', }, }, - close_on_exit = closeOnexit, + close_on_exit = true, --closeOnexit, -- INFO: on_open() on_open = function(t) From 0c8a27c73069c4b4050e97cc16f322cadd7ffa39 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 16:48:16 +0300 Subject: [PATCH 0106/1406] update --- lua/platformio/pioinit.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 53fac35f..9b9d2535 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -58,7 +58,7 @@ local function pick_framework(board_details) actions.close(prompt_bufnr) local selection = action_state.get_selected_entry() local selected_framework = selection[1] - local command = 'pio project init --board ' .. board_details['id'] .. ' --project-option "framework=' .. selected_framework .. '"' + local command = 'pio project init --board ' .. board_details['id'] .. ' --project-option "framework=' .. selected_framework .. ' && exit"' -- .. utils.extra utils.ToggleTerminal(command, 'float', function() boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') From ca8965b30f3263c69f696d3e631b41c10d156996 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 16:48:57 +0300 Subject: [PATCH 0107/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index b6d5ce4e..fead9f0e 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -339,7 +339,7 @@ Diagnostics: } function M.boilerplate_gen(framework, src_path) - print(src_path .. '/' .. framework) + -- print(src_path .. '/' .. framework) local entry = boilerplate[framework] if not entry then return From f54a49961154bd1af659c3576405e3997363c632 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 17:01:14 +0300 Subject: [PATCH 0108/1406] update --- lua/platformio/pioinit.lua | 108 +++++++++++++++++++------------------ lua/platformio/utils.lua | 1 - 2 files changed, 56 insertions(+), 53 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 9b9d2535..260e16a1 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -48,65 +48,69 @@ end local function pick_framework(board_details) local opts = {} pickers - .new(opts, { - prompt_title = 'frameworks', - finder = finders.new_table({ - results = board_details['frameworks'], - }), - attach_mappings = function(prompt_bufnr, _) - actions.select_default:replace(function() - actions.close(prompt_bufnr) - local selection = action_state.get_selected_entry() - local selected_framework = selection[1] - local command = 'pio project init --board ' .. board_details['id'] .. ' --project-option "framework=' .. selected_framework .. ' && exit"' - -- .. utils.extra - utils.ToggleTerminal(command, 'float', function() - boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') - vim.cmd(':PioLSP') + .new(opts, { + prompt_title = 'frameworks', + finder = finders.new_table({ + results = board_details['frameworks'], + }), + attach_mappings = function(prompt_bufnr, _) + actions.select_default:replace(function() + actions.close(prompt_bufnr) + local selection = action_state.get_selected_entry() + local selected_framework = selection[1] + local command = 'pio project init --board ' + .. board_details['id'] + .. ' --project-option "framework=' + .. selected_framework + .. '" && exit && echo "done"' + -- .. utils.extra + utils.ToggleTerminal(command, 'float', function() + boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') + vim.cmd(':PioLSP') + end) end) - end) - return true - end, - sorter = telescope_conf.generic_sorter(opts), - }) - :find() + return true + end, + sorter = telescope_conf.generic_sorter(opts), + }) + :find() end local function pick_board(json_data) local opts = {} pickers - .new(opts, { - prompt_title = 'Boards', - finder = finders.new_table({ - results = json_data, - entry_maker = opts.entry_maker or boardentry_maker(opts), - }), - attach_mappings = function(prompt_bufnr, _) - actions.select_default:replace(function() - actions.close(prompt_bufnr) - local selection = action_state.get_selected_entry() - pick_framework(selection['value']['data']) - end) - return true - end, - previewer = previewers.new_buffer_previewer({ - title = 'Board Info', - define_preview = function(self, entry, _) - local json = utils.strsplit(vim.inspect(entry['value']['data']), '\n') - local bufnr = self.state.bufnr - vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) - vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function - vim.defer_fn(function() - local win = self.state.winid - vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) - vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) - vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) - end, 0) + .new(opts, { + prompt_title = 'Boards', + finder = finders.new_table({ + results = json_data, + entry_maker = opts.entry_maker or boardentry_maker(opts), + }), + attach_mappings = function(prompt_bufnr, _) + actions.select_default:replace(function() + actions.close(prompt_bufnr) + local selection = action_state.get_selected_entry() + pick_framework(selection['value']['data']) + end) + return true end, - }), - sorter = telescope_conf.generic_sorter(opts), - }) - :find() + previewer = previewers.new_buffer_previewer({ + title = 'Board Info', + define_preview = function(self, entry, _) + local json = utils.strsplit(vim.inspect(entry['value']['data']), '\n') + local bufnr = self.state.bufnr + vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) + vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function + vim.defer_fn(function() + local win = self.state.winid + vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) + vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) + vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) + end, 0) + end, + }), + sorter = telescope_conf.generic_sorter(opts), + }) + :find() end function M.pioinit() diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 0172bf33..3dcc148f 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -119,7 +119,6 @@ function M.ToggleTerminal(command, direction, exit_callback) local closeOnexit = false if type(exit_callback) == 'function' then closeOnexit = true - print('closeOnexit') else exit_callback = function() end end From 78c92306db74c98a2f9244971fdd3244f1acaf72 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 17:43:41 +0300 Subject: [PATCH 0109/1406] update --- lua/platformio/piolib.lua | 73 ++++++++++++++++++++------------------- 1 file changed, 37 insertions(+), 36 deletions(-) diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 98b7e517..c7b3b7e8 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -48,43 +48,43 @@ end local function pick_library(json_data) local opts = {} pickers - .new(opts, { - prompt_title = 'Libraries', - finder = finders.new_table({ - results = json_data['items'], - entry_maker = opts.entry_maker or libentry_maker(opts), - }), - attach_mappings = function(prompt_bufnr, _) - actions.select_default:replace(function() - actions.close(prompt_bufnr) - local selection = action_state.get_selected_entry() - local pkg_name = selection['value']['owner'] .. '/' .. selection['value']['name'] - local command = 'pio pkg install --library "' .. pkg_name .. '"' - utils.ToggleTerminal(command, 'float', function() - vim.cmd(':PioLSP') + .new(opts, { + prompt_title = 'Libraries', + finder = finders.new_table({ + results = json_data['items'], + entry_maker = opts.entry_maker or libentry_maker(opts), + }), + attach_mappings = function(prompt_bufnr, _) + actions.select_default:replace(function() + actions.close(prompt_bufnr) + local selection = action_state.get_selected_entry() + local pkg_name = selection['value']['owner'] .. '/' .. selection['value']['name'] + local command = 'pio pkg install --library "' .. pkg_name .. '" && exit && echo "done"' + utils.ToggleTerminal(command, 'float', function() + vim.cmd(':PioLSP') + end) end) - end) - return true - end, - - previewer = previewers.new_buffer_previewer({ - title = 'Package Info', - define_preview = function(self, entry, _) - local json = utils.strsplit(vim.inspect(entry['value']['data']), '\n') - local bufnr = self.state.bufnr - vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) - vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function - vim.defer_fn(function() - local win = self.state.winid - vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) - vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) - vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) - end, 0) + return true end, - }), - sorter = conf.generic_sorter(opts), - }) - :find() + + previewer = previewers.new_buffer_previewer({ + title = 'Package Info', + define_preview = function(self, entry, _) + local json = utils.strsplit(vim.inspect(entry['value']['data']), '\n') + local bufnr = self.state.bufnr + vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) + vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function + vim.defer_fn(function() + local win = self.state.winid + vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) + vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) + vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) + end, 0) + end, + }), + sorter = conf.generic_sorter(opts), + }) + :find() end function M.piolib(lib_arg_list) @@ -118,7 +118,8 @@ function M.piolib(lib_arg_list) pick_library(json_data) else vim.notify( - 'API Request to platformio return HTTP code: ' .. res['status'] .. '\nplease run `curl -LI ' .. url .. '` for complete information', + 'API Request to platformio return HTTP code: ' .. + res['status'] .. '\nplease run `curl -LI ' .. url .. '` for complete information', vim.log.levels.ERROR ) end From 5f05bc1e90bd8294ebda6667c0033d0a8782f933 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 20:37:09 +0300 Subject: [PATCH 0110/1406] update --- lua/platformio/pioinit.lua | 111 ++++++++++++++++++------------------- minimal_config.lua | 5 ++ 2 files changed, 60 insertions(+), 56 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 260e16a1..9aa1d0f6 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -48,69 +48,68 @@ end local function pick_framework(board_details) local opts = {} pickers - .new(opts, { - prompt_title = 'frameworks', - finder = finders.new_table({ - results = board_details['frameworks'], - }), - attach_mappings = function(prompt_bufnr, _) - actions.select_default:replace(function() - actions.close(prompt_bufnr) - local selection = action_state.get_selected_entry() - local selected_framework = selection[1] - local command = 'pio project init --board ' - .. board_details['id'] - .. ' --project-option "framework=' - .. selected_framework - .. '" && exit && echo "done"' - -- .. utils.extra - utils.ToggleTerminal(command, 'float', function() - boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') - vim.cmd(':PioLSP') - end) + .new(opts, { + prompt_title = 'frameworks', + finder = finders.new_table({ + results = board_details['frameworks'], + }), + attach_mappings = function(prompt_bufnr, _) + actions.select_default:replace(function() + actions.close(prompt_bufnr) + local selection = action_state.get_selected_entry() + local selected_framework = selection[1] + local command = 'pio project init --board ' + .. board_details['id'] + .. ' --project-option "framework=' + .. selected_framework + .. '" && exit && echo "done"' + utils.ToggleTerminal(command, 'float', function() + boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') + vim.cmd(':PioLSP') end) - return true - end, - sorter = telescope_conf.generic_sorter(opts), - }) - :find() + end) + return true + end, + sorter = telescope_conf.generic_sorter(opts), + }) + :find() end local function pick_board(json_data) local opts = {} pickers - .new(opts, { - prompt_title = 'Boards', - finder = finders.new_table({ - results = json_data, - entry_maker = opts.entry_maker or boardentry_maker(opts), - }), - attach_mappings = function(prompt_bufnr, _) - actions.select_default:replace(function() - actions.close(prompt_bufnr) - local selection = action_state.get_selected_entry() - pick_framework(selection['value']['data']) - end) - return true + .new(opts, { + prompt_title = 'Boards', + finder = finders.new_table({ + results = json_data, + entry_maker = opts.entry_maker or boardentry_maker(opts), + }), + attach_mappings = function(prompt_bufnr, _) + actions.select_default:replace(function() + actions.close(prompt_bufnr) + local selection = action_state.get_selected_entry() + pick_framework(selection['value']['data']) + end) + return true + end, + previewer = previewers.new_buffer_previewer({ + title = 'Board Info', + define_preview = function(self, entry, _) + local json = utils.strsplit(vim.inspect(entry['value']['data']), '\n') + local bufnr = self.state.bufnr + vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) + vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function + vim.defer_fn(function() + local win = self.state.winid + vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) + vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) + vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) + end, 0) end, - previewer = previewers.new_buffer_previewer({ - title = 'Board Info', - define_preview = function(self, entry, _) - local json = utils.strsplit(vim.inspect(entry['value']['data']), '\n') - local bufnr = self.state.bufnr - vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) - vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function - vim.defer_fn(function() - local win = self.state.winid - vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) - vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) - vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) - end, 0) - end, - }), - sorter = telescope_conf.generic_sorter(opts), - }) - :find() + }), + sorter = telescope_conf.generic_sorter(opts), + }) + :find() end function M.pioinit() diff --git a/minimal_config.lua b/minimal_config.lua index e9769f1c..81bf4c22 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -13,6 +13,11 @@ vim.g.loaded_netrwPlugin = 1 vim.opt.termguicolors = true vim.opt['number'] = true +vim.opt.autowrite = true -- Enable auto write +-- only set clipboard if not in ssh, to make sure the OSC 52 +-- integration works automatically. Requires Neovim >= 0.10.0 +vim.opt.clipboard = vim.env.SSH_TTY and '' or 'unnamedplus' -- Sync with system clipboard +vim.opt.completeopt = 'menu,menuone,noselect' vim.opt.tabstop = 2 -- Number of spaces tabs count for vim.opt.softtabstop = 2 vim.opt.shiftround = true -- Round indent From fe1bcd001a19ec36ca1b1112ebcba1a0a18fe69a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 21:06:44 +0300 Subject: [PATCH 0111/1406] update --- minimal_config.lua | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/minimal_config.lua b/minimal_config.lua index 81bf4c22..0e7c8806 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -152,6 +152,14 @@ local plugins = { -- opts_extend = { 'sources.default' }, -- }, -- + { + 'akinsho/bufferline.nvim', + version = '*', + dependencies = 'nvim-tree/nvim-web-devicons', + config = function() + require('bufferline').setup({}) + end, + }, { 'nvim-tree/nvim-tree.lua', version = '*', From 7bdbb70e5a85b53f4d84b1fae4dd99939f56a7bf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 22:21:39 +0300 Subject: [PATCH 0112/1406] update --- minimal_config.lua | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index 0e7c8806..5aaa631a 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -157,7 +157,19 @@ local plugins = { version = '*', dependencies = 'nvim-tree/nvim-web-devicons', config = function() - require('bufferline').setup({}) + require('bufferline').setup({ + options = { + mode = 'buffers', -- set to "tabs" to only show tabpages instead + offsets = { + { + filetype = 'nvim-tree', + text = 'File Explorer', -- | function , + text_align = 'left', -- | "center" | "right" + separator = true, + }, + }, + }, + }) end, }, { From ba84206929cafa1335cf036d16a3eb65173ad1d4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 22:46:00 +0300 Subject: [PATCH 0113/1406] update --- minimal_config.lua | 67 +++++++++++++++++++++++++++++++--------------- 1 file changed, 46 insertions(+), 21 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index 5aaa631a..ebec5d6c 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -70,15 +70,53 @@ vim.diagnostic.config({ }, }) -vim.keymap.set('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) -vim.keymap.set('n', '\\', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) +local keymap = function(mode, lhs, rhs, opts) + local options = { silent = true } --noremap = true by default in vim.keymap.set + if opts then + options = vim.tbl_extend('force', options, opts or {}) + end + vim.keymap.set(mode, lhs, rhs, options) +end -- Keybinds to make split navigation easier. -- Use CTRL+ to switch between windows -vim.keymap.set('n', '', '', { desc = 'Move focus to the left window' }) -vim.keymap.set('n', '', '', { desc = 'Move focus to the right window' }) -vim.keymap.set('n', '', '', { desc = 'Move focus to the lower window' }) -vim.keymap.set('n', '', '', { desc = 'Move focus to the upper window' }) +-- See `:help wincmd` for a list of all window commands +keymap('n', '', '', { desc = 'Move focus to the left window' }) +keymap('n', '', '', { desc = 'Move focus to the right window' }) +keymap('n', '', '', { desc = 'Move focus to the lower window' }) +keymap('n', '', '', { desc = 'Move focus to the upper window' }) + +-- Resize with arrows +keymap('n', '', ':resize -2') +keymap('n', '', ':resize +2') +keymap('n', '', ':vertical resize -2') +keymap('n', '', ':vertical resize +2') + +keymap('n', 'bb', ':bprevious', { desc = '[B]efore Buffer' }) +keymap('n', 'ba', ':bnext', { desc = '[A]fter Buffer' }) +keymap('n', 'bs', ':ball', { desc = '[S]how AllOpened Buffers' }) +keymap('n', 'bp', 'BufferLineTogglePin', { desc = 'Toggle Pin' }) +keymap('n', 'bd', 'bdelete', { desc = '[D]elete Buffer' }) +keymap('n', 'bP', 'BufferLineGroupClose ungrouped', { desc = 'Delete Non-Pinned Buffers' }) +keymap('n', 'bo', 'BufferLineCloseOthers', { desc = 'Delete Other Buffers' }) +keymap('n', 'br', 'BufferLineCloseRight', { desc = 'Delete Buffers to the Right' }) +keymap('n', 'bl', 'BufferLineCloseLeft', { desc = 'Delete Buffers to the Left' }) +keymap('n', '', 'BufferLineCyclePrev', { desc = 'Prev Buffer' }) +keymap('n', '', 'BufferLineCycleNext', { desc = 'Next Buffer' }) +keymap('n', '[b', 'BufferLineCyclePrev', { desc = 'Prev Buffer' }) +keymap('n', ']b', 'BufferLineCycleNext', { desc = 'Next Buffer' }) +keymap('n', '[B', 'BufferLineMovePrev', { desc = 'Move buffer prev' }) +keymap('n', ']B', 'BufferLineMoveNext', { desc = 'Move buffer next' }) + +keymap('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) +keymap('n', '\\', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) + +-- Keybinds to make split navigation easier. +-- Use CTRL+ to switch between windows +keymap('n', '', '', { desc = 'Move focus to the left window' }) +keymap('n', '', '', { desc = 'Move focus to the right window' }) +keymap('n', '', '', { desc = 'Move focus to the lower window' }) +keymap('n', '', '', { desc = 'Move focus to the upper window' }) ---------------------------------------------------------------------------------------- local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' @@ -156,21 +194,8 @@ local plugins = { 'akinsho/bufferline.nvim', version = '*', dependencies = 'nvim-tree/nvim-web-devicons', - config = function() - require('bufferline').setup({ - options = { - mode = 'buffers', -- set to "tabs" to only show tabpages instead - offsets = { - { - filetype = 'nvim-tree', - text = 'File Explorer', -- | function , - text_align = 'left', -- | "center" | "right" - separator = true, - }, - }, - }, - }) - end, + config = true, + -- config = true is shorthand for config = function() require('bufferline').setup() end }, { 'nvim-tree/nvim-tree.lua', From 30d39200c4a0e0dc928f15bc23ffd0bf4f51de33 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 22:48:57 +0300 Subject: [PATCH 0114/1406] update --- minimal_config.lua | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/minimal_config.lua b/minimal_config.lua index ebec5d6c..3f4c33a0 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -190,6 +190,18 @@ local plugins = { -- opts_extend = { 'sources.default' }, -- }, -- + { + 'famiu/bufdelete.nvim', + keys = { + { + 'bd', + function() + require('bufdelete').bufdelete(0, true) + end, + desc = 'Delete buffer', + }, + }, + }, { 'akinsho/bufferline.nvim', version = '*', From ef61a2920c790d108df8bdddb65ce97a42c39b9c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 22:54:33 +0300 Subject: [PATCH 0115/1406] update --- minimal_config.lua | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index 3f4c33a0..0efe1a4a 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -190,6 +190,18 @@ local plugins = { -- opts_extend = { 'sources.default' }, -- }, -- + -- + + { + 'akinsho/bufferline.nvim', + config = function() + require('bufferline').setup({ + options = { + mode = 'tabs', + }, + }) + end, + }, { 'famiu/bufdelete.nvim', keys = { @@ -202,13 +214,6 @@ local plugins = { }, }, }, - { - 'akinsho/bufferline.nvim', - version = '*', - dependencies = 'nvim-tree/nvim-web-devicons', - config = true, - -- config = true is shorthand for config = function() require('bufferline').setup() end - }, { 'nvim-tree/nvim-tree.lua', version = '*', From e2063356d744bfbc76c4169c250755061ec2f9cc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 22:58:59 +0300 Subject: [PATCH 0116/1406] update --- minimal_config.lua | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index 0efe1a4a..d5d37180 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -192,16 +192,16 @@ local plugins = { -- -- - { - 'akinsho/bufferline.nvim', - config = function() - require('bufferline').setup({ - options = { - mode = 'tabs', - }, - }) - end, - }, + -- { + -- 'akinsho/bufferline.nvim', + -- config = function() + -- require('bufferline').setup({ + -- options = { + -- mode = "tabs", + -- }, + -- }) + -- end + -- }, { 'famiu/bufdelete.nvim', keys = { @@ -214,6 +214,13 @@ local plugins = { }, }, }, + { + 'akinsho/bufferline.nvim', + version = '*', + dependencies = 'nvim-tree/nvim-web-devicons', + config = true, + -- config = true is shorthand for config = function() require('bufferline').setup() end + }, { 'nvim-tree/nvim-tree.lua', version = '*', From 1abbe882ad4ba04215a1a5b6bd9fb86ba40cafbe Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 23:05:48 +0300 Subject: [PATCH 0117/1406] update --- minimal_config.lua | 40 +++++++++++++++++----------------------- 1 file changed, 17 insertions(+), 23 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index d5d37180..c9892fdf 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -190,35 +190,29 @@ local plugins = { -- opts_extend = { 'sources.default' }, -- }, -- - -- - -- { - -- 'akinsho/bufferline.nvim', - -- config = function() - -- require('bufferline').setup({ - -- options = { - -- mode = "tabs", - -- }, - -- }) - -- end + -- 'famiu/bufdelete.nvim', + -- keys = { + -- { + -- 'bd', + -- function() + -- require('bufdelete').bufdelete(0, true) + -- end, + -- desc = 'Delete buffer', + -- }, + -- }, -- }, - { - 'famiu/bufdelete.nvim', - keys = { - { - 'bd', - function() - require('bufdelete').bufdelete(0, true) - end, - desc = 'Delete buffer', - }, - }, - }, { 'akinsho/bufferline.nvim', version = '*', dependencies = 'nvim-tree/nvim-web-devicons', - config = true, + config = function() + require('bufferline').setup({}) + end, + options = { + mode = 'buffers', -- set to "tabs" to only show tabpages instead + }, + -- config = true, -- config = true is shorthand for config = function() require('bufferline').setup() end }, { From 7e7ae3d44d87c526b5665800062449d6e61fa08e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 23:09:28 +0300 Subject: [PATCH 0118/1406] update --- minimal_config.lua | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index c9892fdf..e672caba 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -210,7 +210,15 @@ local plugins = { require('bufferline').setup({}) end, options = { - mode = 'buffers', -- set to "tabs" to only show tabpages instead + -- mode = 'buffers', -- set to "tabs" to only show tabpages instead + offsets = { + { + filetype = 'NvimTree', + text = 'File Explorer', + text_align = 'left', -- options: "left", "center", "right" + separator = true, + }, + }, }, -- config = true, -- config = true is shorthand for config = function() require('bufferline').setup() end From df7701fd7627dce5dda9a7107784b651f7571ae1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 23:14:04 +0300 Subject: [PATCH 0119/1406] update --- minimal_config.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index e672caba..726b7451 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -96,7 +96,7 @@ keymap('n', 'bb', ':bprevious', { desc = '[B]efore Buffer' }) keymap('n', 'ba', ':bnext', { desc = '[A]fter Buffer' }) keymap('n', 'bs', ':ball', { desc = '[S]how AllOpened Buffers' }) keymap('n', 'bp', 'BufferLineTogglePin', { desc = 'Toggle Pin' }) -keymap('n', 'bd', 'bdelete', { desc = '[D]elete Buffer' }) +keymap('n', 'bd', 'Bdelete', { desc = '[D]elete Buffer' }) keymap('n', 'bP', 'BufferLineGroupClose ungrouped', { desc = 'Delete Non-Pinned Buffers' }) keymap('n', 'bo', 'BufferLineCloseOthers', { desc = 'Delete Other Buffers' }) keymap('n', 'br', 'BufferLineCloseRight', { desc = 'Delete Buffers to the Right' }) From 2bfac14d74828306cb083f776fd52e1f14141e92 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 23:24:40 +0300 Subject: [PATCH 0120/1406] update --- minimal_config.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index 726b7451..89e48cc1 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -96,7 +96,7 @@ keymap('n', 'bb', ':bprevious', { desc = '[B]efore Buffer' }) keymap('n', 'ba', ':bnext', { desc = '[A]fter Buffer' }) keymap('n', 'bs', ':ball', { desc = '[S]how AllOpened Buffers' }) keymap('n', 'bp', 'BufferLineTogglePin', { desc = 'Toggle Pin' }) -keymap('n', 'bd', 'Bdelete', { desc = '[D]elete Buffer' }) +keymap('n', 'bd', 'BDelete', { desc = '[D]elete Buffer' }) keymap('n', 'bP', 'BufferLineGroupClose ungrouped', { desc = 'Delete Non-Pinned Buffers' }) keymap('n', 'bo', 'BufferLineCloseOthers', { desc = 'Delete Other Buffers' }) keymap('n', 'br', 'BufferLineCloseRight', { desc = 'Delete Buffers to the Right' }) @@ -223,6 +223,7 @@ local plugins = { -- config = true, -- config = true is shorthand for config = function() require('bufferline').setup() end }, + { 'famiu/bufdelete.nvim', config = true }, { 'nvim-tree/nvim-tree.lua', version = '*', From 25feea28f1afe2166d2de1029c97559d177ff020 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 23:25:09 +0300 Subject: [PATCH 0121/1406] update --- minimal_config.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index 89e48cc1..d8ed10a1 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -96,7 +96,7 @@ keymap('n', 'bb', ':bprevious', { desc = '[B]efore Buffer' }) keymap('n', 'ba', ':bnext', { desc = '[A]fter Buffer' }) keymap('n', 'bs', ':ball', { desc = '[S]how AllOpened Buffers' }) keymap('n', 'bp', 'BufferLineTogglePin', { desc = 'Toggle Pin' }) -keymap('n', 'bd', 'BDelete', { desc = '[D]elete Buffer' }) +keymap('n', 'bd', 'Bdelete', { desc = '[D]elete Buffer' }) keymap('n', 'bP', 'BufferLineGroupClose ungrouped', { desc = 'Delete Non-Pinned Buffers' }) keymap('n', 'bo', 'BufferLineCloseOthers', { desc = 'Delete Other Buffers' }) keymap('n', 'br', 'BufferLineCloseRight', { desc = 'Delete Buffers to the Right' }) From b28d7428783cc111c7a7bf87a849e1b39a66277f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 2 Apr 2026 23:27:32 +0300 Subject: [PATCH 0122/1406] update --- minimal_config.lua | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index d8ed10a1..1ee6ec39 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -223,7 +223,10 @@ local plugins = { -- config = true, -- config = true is shorthand for config = function() require('bufferline').setup() end }, - { 'famiu/bufdelete.nvim', config = true }, + { 'famiu/bufdelete.nvim', + config = function() + require('bufdelete ').setup({}) + end, { 'nvim-tree/nvim-tree.lua', version = '*', From 115fd269ee4e269f409bc0cb2dcbeceab1040e42 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 06:15:59 +0300 Subject: [PATCH 0123/1406] update --- minimal_config.lua | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/minimal_config.lua b/minimal_config.lua index 1ee6ec39..0e4865a0 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -97,6 +97,11 @@ keymap('n', 'ba', ':bnext', { desc = '[A]fter Buffer' }) keymap('n', 'bs', ':ball', { desc = '[S]how AllOpened Buffers' }) keymap('n', 'bp', 'BufferLineTogglePin', { desc = 'Toggle Pin' }) keymap('n', 'bd', 'Bdelete', { desc = '[D]elete Buffer' }) + +-- Native way to avoid jumping to nvim-tree +vim.keymap.set('n', 'bd', ':bp | bd #', { desc = '[D]elete Buffer' }) +-- keymap('n', 'bd', 'Bdelete', { desc = '[D]elete Buffer' }) +-- map({ mode = "n", key = "c", desc = "Close buffer", cmd = ":let n=bufnr() | bnext | exec 'sil bd' .. n" }) keymap('n', 'bP', 'BufferLineGroupClose ungrouped', { desc = 'Delete Non-Pinned Buffers' }) keymap('n', 'bo', 'BufferLineCloseOthers', { desc = 'Delete Other Buffers' }) keymap('n', 'br', 'BufferLineCloseRight', { desc = 'Delete Buffers to the Right' }) From 439c427bf23e87b88c6cfde6e3bac6e8f36a9bae Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 06:17:42 +0300 Subject: [PATCH 0124/1406] update --- minimal_config.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index 0e4865a0..d14bcbc2 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -96,10 +96,10 @@ keymap('n', 'bb', ':bprevious', { desc = '[B]efore Buffer' }) keymap('n', 'ba', ':bnext', { desc = '[A]fter Buffer' }) keymap('n', 'bs', ':ball', { desc = '[S]how AllOpened Buffers' }) keymap('n', 'bp', 'BufferLineTogglePin', { desc = 'Toggle Pin' }) -keymap('n', 'bd', 'Bdelete', { desc = '[D]elete Buffer' }) +-- keymap('n', 'bd', 'Bdelete', { desc = '[D]elete Buffer' }) -- Native way to avoid jumping to nvim-tree -vim.keymap.set('n', 'bd', ':bp | bd #', { desc = '[D]elete Buffer' }) +keymap('n', 'bd', ':bp | bd #', { desc = '[D]elete Buffer' }) -- keymap('n', 'bd', 'Bdelete', { desc = '[D]elete Buffer' }) -- map({ mode = "n", key = "c", desc = "Close buffer", cmd = ":let n=bufnr() | bnext | exec 'sil bd' .. n" }) keymap('n', 'bP', 'BufferLineGroupClose ungrouped', { desc = 'Delete Non-Pinned Buffers' }) From d7ecb3eeeb6718bcebbf2e14ee4cb7f779899fc5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 06:22:33 +0300 Subject: [PATCH 0125/1406] update --- minimal_config.lua | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index d14bcbc2..5394d8a8 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -96,12 +96,9 @@ keymap('n', 'bb', ':bprevious', { desc = '[B]efore Buffer' }) keymap('n', 'ba', ':bnext', { desc = '[A]fter Buffer' }) keymap('n', 'bs', ':ball', { desc = '[S]how AllOpened Buffers' }) keymap('n', 'bp', 'BufferLineTogglePin', { desc = 'Toggle Pin' }) --- keymap('n', 'bd', 'Bdelete', { desc = '[D]elete Buffer' }) - --- Native way to avoid jumping to nvim-tree -keymap('n', 'bd', ':bp | bd #', { desc = '[D]elete Buffer' }) --- keymap('n', 'bd', 'Bdelete', { desc = '[D]elete Buffer' }) --- map({ mode = "n", key = "c", desc = "Close buffer", cmd = ":let n=bufnr() | bnext | exec 'sil bd' .. n" }) +-- keymap('n', 'bd', 'BDelete', { desc = '[D]elete Buffer' }) +keymap('n', 'q', ':bp | bd #', { desc = '[D]elete Buffer' }) +keymap('n', 'bd', 'BDelete', { desc = '[D]elete Buffer' }) keymap('n', 'bP', 'BufferLineGroupClose ungrouped', { desc = 'Delete Non-Pinned Buffers' }) keymap('n', 'bo', 'BufferLineCloseOthers', { desc = 'Delete Other Buffers' }) keymap('n', 'br', 'BufferLineCloseRight', { desc = 'Delete Buffers to the Right' }) @@ -228,10 +225,7 @@ local plugins = { -- config = true, -- config = true is shorthand for config = function() require('bufferline').setup() end }, - { 'famiu/bufdelete.nvim', - config = function() - require('bufdelete ').setup({}) - end, + { 'famiu/bufdelete.nvim', config = true }, { 'nvim-tree/nvim-tree.lua', version = '*', From 8ebbd9d4b081531df17cfa5365fe650a5b493b05 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 06:24:37 +0300 Subject: [PATCH 0126/1406] update --- minimal_config.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index 5394d8a8..ba416aa3 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -97,8 +97,8 @@ keymap('n', 'ba', ':bnext', { desc = '[A]fter Buffer' }) keymap('n', 'bs', ':ball', { desc = '[S]how AllOpened Buffers' }) keymap('n', 'bp', 'BufferLineTogglePin', { desc = 'Toggle Pin' }) -- keymap('n', 'bd', 'BDelete', { desc = '[D]elete Buffer' }) -keymap('n', 'q', ':bp | bd #', { desc = '[D]elete Buffer' }) -keymap('n', 'bd', 'BDelete', { desc = '[D]elete Buffer' }) +-- keymap('n', 'bd', 'BDelete', { desc = '[D]elete Buffer' }) +keymap('n', 'bd', ':bp | bd #', { desc = '[D]elete Buffer' }) keymap('n', 'bP', 'BufferLineGroupClose ungrouped', { desc = 'Delete Non-Pinned Buffers' }) keymap('n', 'bo', 'BufferLineCloseOthers', { desc = 'Delete Other Buffers' }) keymap('n', 'br', 'BufferLineCloseRight', { desc = 'Delete Buffers to the Right' }) From dcd40886940d8be9522db1bdcd1f33b76fe312ac Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 06:26:03 +0300 Subject: [PATCH 0127/1406] update --- minimal_config.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index ba416aa3..296bae33 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -225,7 +225,6 @@ local plugins = { -- config = true, -- config = true is shorthand for config = function() require('bufferline').setup() end }, - { 'famiu/bufdelete.nvim', config = true }, { 'nvim-tree/nvim-tree.lua', version = '*', From d534d2d7431a70593f43205913b021a9f3f6fb4f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 06:39:08 +0300 Subject: [PATCH 0128/1406] update --- minimal_config.lua | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index 296bae33..3ad4267c 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -96,9 +96,22 @@ keymap('n', 'bb', ':bprevious', { desc = '[B]efore Buffer' }) keymap('n', 'ba', ':bnext', { desc = '[A]fter Buffer' }) keymap('n', 'bs', ':ball', { desc = '[S]how AllOpened Buffers' }) keymap('n', 'bp', 'BufferLineTogglePin', { desc = 'Toggle Pin' }) --- keymap('n', 'bd', 'BDelete', { desc = '[D]elete Buffer' }) --- keymap('n', 'bd', 'BDelete', { desc = '[D]elete Buffer' }) -keymap('n', 'bd', ':bp | bd #', { desc = '[D]elete Buffer' }) +-- keymap('n', 'bd', 'bdelete', { desc = '[D]elete Buffer' }) +-- keymap('n', 'bd', ':bp | bd #', { desc = '[D]elete Buffer' }) +keymap('n', 'bd', function() + -- local bufnr = vim.api.nvim_get_current_buf() + local bufs = vim.fn.getbufinfo({ buflisted = 1 }) + + if #bufs <= 1 then + -- If it's the last buffer, create a new empty one first + -- This prevents focus from jumping to NvimTree + vim.cmd('enew | bd #') + else + -- Otherwise, go to the previous buffer and delete the old one + vim.cmd('bp | bd #') + end +end, { desc = '[D]elete Buffer' }) + keymap('n', 'bP', 'BufferLineGroupClose ungrouped', { desc = 'Delete Non-Pinned Buffers' }) keymap('n', 'bo', 'BufferLineCloseOthers', { desc = 'Delete Other Buffers' }) keymap('n', 'br', 'BufferLineCloseRight', { desc = 'Delete Buffers to the Right' }) From c0a33b0f2bd0f594497b81c2c635ba5a590741ed Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 06:42:58 +0300 Subject: [PATCH 0129/1406] update --- minimal_config.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index 3ad4267c..184748fa 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -96,12 +96,12 @@ keymap('n', 'bb', ':bprevious', { desc = '[B]efore Buffer' }) keymap('n', 'ba', ':bnext', { desc = '[A]fter Buffer' }) keymap('n', 'bs', ':ball', { desc = '[S]how AllOpened Buffers' }) keymap('n', 'bp', 'BufferLineTogglePin', { desc = 'Toggle Pin' }) + -- keymap('n', 'bd', 'bdelete', { desc = '[D]elete Buffer' }) -- keymap('n', 'bd', ':bp | bd #', { desc = '[D]elete Buffer' }) keymap('n', 'bd', function() -- local bufnr = vim.api.nvim_get_current_buf() local bufs = vim.fn.getbufinfo({ buflisted = 1 }) - if #bufs <= 1 then -- If it's the last buffer, create a new empty one first -- This prevents focus from jumping to NvimTree From 73fbc9e8b418ff3dd129abfde9c85d7d7cfa28a9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 06:46:32 +0300 Subject: [PATCH 0130/1406] update --- minimal_config.lua | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/minimal_config.lua b/minimal_config.lua index 184748fa..6bbb234d 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -17,7 +17,11 @@ vim.opt.autowrite = true -- Enable auto write -- only set clipboard if not in ssh, to make sure the OSC 52 -- integration works automatically. Requires Neovim >= 0.10.0 vim.opt.clipboard = vim.env.SSH_TTY and '' or 'unnamedplus' -- Sync with system clipboard + vim.opt.completeopt = 'menu,menuone,noselect' +-- This enables automatic triggers and snippet support +vim.lsp.completion.enable(true) + vim.opt.tabstop = 2 -- Number of spaces tabs count for vim.opt.softtabstop = 2 vim.opt.shiftround = true -- Round indent From b51a13111007abc7aa2fe5ce80cf1954706ef6fb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 06:56:21 +0300 Subject: [PATCH 0131/1406] update --- lua/platformio/lspAttach.lua | 9 +++++---- minimal_config.lua | 2 -- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 256e3ee6..20d43c02 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -35,6 +35,7 @@ vim.api.nvim_create_autocmd('LspAttach', { if not bok then if client:supports_method('textDocument/completion', { bufnr = bufnr }) then vim.lsp.completion.enable(true, client.id, bufnr, { autotrigger = true }) + print('completion enabled') end -- vim.diagnostic.config({ @@ -43,12 +44,12 @@ vim.api.nvim_create_autocmd('LspAttach', { -- current_line = true, -- }, -- }) - -- vim.cmd([[set completeopt+=noselect]]) + vim.cmd([[set completeopt+=noselect]]) end ------------------------------------------------------------------ if client.server_capabilities.documentHighlightProvider then - local highlight_augroup = vim.api.nvim_create_augroup('kickstart-lsp-highlight', { clear = false }) + local highlight_augroup = vim.api.nvim_create_augroup('platformio-lsp-highlight', { clear = false }) vim.api.nvim_create_autocmd({ 'CursorHold', 'CursorHoldI' }, { buffer = bufnr, group = highlight_augroup, @@ -62,10 +63,10 @@ vim.api.nvim_create_autocmd('LspAttach', { }) -- vim.api.nvim_create_autocmd('LspDetach', { - group = vim.api.nvim_create_augroup('kickstart-lsp-detach', { clear = true }), + group = vim.api.nvim_create_augroup('platformio-lsp-detach', { clear = true }), callback = function(event) vim.lsp.buf.clear_references() - vim.api.nvim_clear_autocmds({ group = 'kickstart-lsp-highlight', buffer = event.buf }) + vim.api.nvim_clear_autocmds({ group = 'platformio-lsp-highlight', buffer = event.buf }) end, }) -- diff --git a/minimal_config.lua b/minimal_config.lua index 6bbb234d..8f6def14 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -19,8 +19,6 @@ vim.opt.autowrite = true -- Enable auto write vim.opt.clipboard = vim.env.SSH_TTY and '' or 'unnamedplus' -- Sync with system clipboard vim.opt.completeopt = 'menu,menuone,noselect' --- This enables automatic triggers and snippet support -vim.lsp.completion.enable(true) vim.opt.tabstop = 2 -- Number of spaces tabs count for vim.opt.softtabstop = 2 From 21bdd805b594eb80f885425a8d6c6eaf17cba554 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 06:59:50 +0300 Subject: [PATCH 0132/1406] update --- lua/platformio/lspAttach.lua | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 20d43c02..273f74e2 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -29,23 +29,28 @@ vim.api.nvim_create_autocmd('LspAttach', { end, { desc = 'Switch between source/header' }) end + if client and client.server_capabilities.completionProvider then + -- Enable native completion for this specific client and buffer + vim.lsp.completion.enable(true, client.id, args.buf, { autotrigger = true }) + print('completion enabled') + end ------------------------------------------------------------------ --- Skip this if you are using blink - local bok, _ = pcall(require, 'blink') - if not bok then - if client:supports_method('textDocument/completion', { bufnr = bufnr }) then - vim.lsp.completion.enable(true, client.id, bufnr, { autotrigger = true }) - print('completion enabled') - end - - -- vim.diagnostic.config({ - -- current_line = true, - -- virtual_lines = { - -- current_line = true, - -- }, - -- }) - vim.cmd([[set completeopt+=noselect]]) - end + -- local bok, _ = pcall(require, 'blink') + -- if not bok then + -- if client:supports_method('textDocument/completion', { bufnr = bufnr }) then + -- vim.lsp.completion.enable(true, client.id, bufnr, { autotrigger = true }) + -- print('completion enabled') + -- end + -- + -- -- vim.diagnostic.config({ + -- -- current_line = true, + -- -- virtual_lines = { + -- -- current_line = true, + -- -- }, + -- -- }) + -- -- vim.cmd([[set completeopt+=noselect]]) + -- end ------------------------------------------------------------------ if client.server_capabilities.documentHighlightProvider then From 1065959eabbc0607508a39d8a0933295f62048fd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 07:05:50 +0300 Subject: [PATCH 0133/1406] update --- lua/platformio/lspAttach.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 273f74e2..e1dd2bcf 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -29,9 +29,10 @@ vim.api.nvim_create_autocmd('LspAttach', { end, { desc = 'Switch between source/header' }) end - if client and client.server_capabilities.completionProvider then + -- if client and client.server_capabilities.completionProvider then + if client:supports_method('textDocument/completion', { bufnr = bufnr }) then -- Enable native completion for this specific client and buffer - vim.lsp.completion.enable(true, client.id, args.buf, { autotrigger = true }) + vim.lsp.completion.enable(true, client.id, bufnr, { autotrigger = true }) print('completion enabled') end ------------------------------------------------------------------ From 4864dce30636b86e6751aff16d7372a6981ea28e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 07:08:17 +0300 Subject: [PATCH 0134/1406] update --- lua/platformio/lspAttach.lua | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index e1dd2bcf..0526677a 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -33,6 +33,14 @@ vim.api.nvim_create_autocmd('LspAttach', { if client:supports_method('textDocument/completion', { bufnr = bufnr }) then -- Enable native completion for this specific client and buffer vim.lsp.completion.enable(true, client.id, bufnr, { autotrigger = true }) + + vim.diagnostic.config({ + current_line = true, + virtual_lines = { + current_line = true, + }, + }) + vim.cmd([[set completeopt+=noselect]]) print('completion enabled') end ------------------------------------------------------------------ From befa64e8a03ec179590c7daf179a218d3aa1aaee Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 07:18:38 +0300 Subject: [PATCH 0135/1406] update --- minimal_config.lua | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index 8f6def14..3412ecb0 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -18,8 +18,10 @@ vim.opt.autowrite = true -- Enable auto write -- integration works automatically. Requires Neovim >= 0.10.0 vim.opt.clipboard = vim.env.SSH_TTY and '' or 'unnamedplus' -- Sync with system clipboard -vim.opt.completeopt = 'menu,menuone,noselect' +-- vim.opt.completeopt = 'menu,menuone,noselect' +vim.opt.completeopt = { 'menuone', 'noselect', 'fuzzy' } +vim.opt.completeopt:append('fuzzy') vim.opt.tabstop = 2 -- Number of spaces tabs count for vim.opt.softtabstop = 2 vim.opt.shiftround = true -- Round indent From 7bba8194f8fcb652a98be814423589199292aa05 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 07:20:54 +0300 Subject: [PATCH 0136/1406] update --- lua/platformio/lspAttach.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 0526677a..a9e2032f 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -31,9 +31,6 @@ vim.api.nvim_create_autocmd('LspAttach', { -- if client and client.server_capabilities.completionProvider then if client:supports_method('textDocument/completion', { bufnr = bufnr }) then - -- Enable native completion for this specific client and buffer - vim.lsp.completion.enable(true, client.id, bufnr, { autotrigger = true }) - vim.diagnostic.config({ current_line = true, virtual_lines = { @@ -42,6 +39,9 @@ vim.api.nvim_create_autocmd('LspAttach', { }) vim.cmd([[set completeopt+=noselect]]) print('completion enabled') + + -- Enable native completion for this specific client and buffer + vim.lsp.completion.enable(true, client.id, bufnr, { autotrigger = true }) end ------------------------------------------------------------------ --- Skip this if you are using blink From 00e6d2dee0b7e1ac6a14a5432da4d1445e896bf9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 07:30:43 +0300 Subject: [PATCH 0137/1406] update --- lua/platformio/lspAttach.lua | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index a9e2032f..1a756d2a 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -41,7 +41,18 @@ vim.api.nvim_create_autocmd('LspAttach', { print('completion enabled') -- Enable native completion for this specific client and buffer - vim.lsp.completion.enable(true, client.id, bufnr, { autotrigger = true }) + vim.lsp.completion.enable(true, client.id, args.buf, { autotrigger = true }) + end + + -- Inlay hints + if client:supports_method('textDocument/inlayHints') then + vim.lsp.inlay_hint.enable(true, { bufnr = args.buf }) + end + + if client:supports_method('textDocument/documentColor') then + vim.lsp.document_color.enable(true, args.buf, { + style = 'background', -- 'background', 'foreground', or 'virtual' + }) end ------------------------------------------------------------------ --- Skip this if you are using blink From 5cd4419d2b833ee6e649047ad170fd64dea0e45d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 07:41:20 +0300 Subject: [PATCH 0138/1406] update --- lua/platformio/lspAttach.lua | 9 ++------- minimal_config.lua | 4 ---- 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 1a756d2a..7be2dd8b 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -31,13 +31,8 @@ vim.api.nvim_create_autocmd('LspAttach', { -- if client and client.server_capabilities.completionProvider then if client:supports_method('textDocument/completion', { bufnr = bufnr }) then - vim.diagnostic.config({ - current_line = true, - virtual_lines = { - current_line = true, - }, - }) - vim.cmd([[set completeopt+=noselect]]) + vim.opt.completeopt = { 'menu', 'menuone', 'noinsert', 'fuzzy' } + print('completion enabled') -- Enable native completion for this specific client and buffer diff --git a/minimal_config.lua b/minimal_config.lua index 3412ecb0..70f9a757 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -18,10 +18,6 @@ vim.opt.autowrite = true -- Enable auto write -- integration works automatically. Requires Neovim >= 0.10.0 vim.opt.clipboard = vim.env.SSH_TTY and '' or 'unnamedplus' -- Sync with system clipboard --- vim.opt.completeopt = 'menu,menuone,noselect' -vim.opt.completeopt = { 'menuone', 'noselect', 'fuzzy' } - -vim.opt.completeopt:append('fuzzy') vim.opt.tabstop = 2 -- Number of spaces tabs count for vim.opt.softtabstop = 2 vim.opt.shiftround = true -- Round indent From 0ac74120458bf744c9373c6fe18bba63d8588df0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 07:43:35 +0300 Subject: [PATCH 0139/1406] update --- lua/platformio/lspAttach.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 7be2dd8b..a8be95a5 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -30,7 +30,8 @@ vim.api.nvim_create_autocmd('LspAttach', { end -- if client and client.server_capabilities.completionProvider then - if client:supports_method('textDocument/completion', { bufnr = bufnr }) then + -- if client:supports_method('textDocument/completion', { bufnr = bufnr }) then + if client:supports_method('textDocument/completion') then vim.opt.completeopt = { 'menu', 'menuone', 'noinsert', 'fuzzy' } print('completion enabled') From 26ba92cec9220906ac353e8f047ce9ec4ff9035b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 07:58:44 +0300 Subject: [PATCH 0140/1406] update --- lua/platformio/lspAttach.lua | 24 +++++------------------- 1 file changed, 5 insertions(+), 19 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index a8be95a5..b831e0d0 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -32,12 +32,15 @@ vim.api.nvim_create_autocmd('LspAttach', { -- if client and client.server_capabilities.completionProvider then -- if client:supports_method('textDocument/completion', { bufnr = bufnr }) then if client:supports_method('textDocument/completion') then - vim.opt.completeopt = { 'menu', 'menuone', 'noinsert', 'fuzzy' } + vim.opt.completeopt = { 'menu', 'menuone', 'noinsert', 'fuzzy', 'popup' } print('completion enabled') -- Enable native completion for this specific client and buffer vim.lsp.completion.enable(true, client.id, args.buf, { autotrigger = true }) + vim.keymap.set('i', ' Date: Fri, 3 Apr 2026 08:22:32 +0300 Subject: [PATCH 0141/1406] update --- lua/platformio/lspAttach.lua | 20 ++++++++++++-------- minimal_config.lua | 11 +++++++++++ 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index b831e0d0..95a9843c 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -31,16 +31,20 @@ vim.api.nvim_create_autocmd('LspAttach', { -- if client and client.server_capabilities.completionProvider then -- if client:supports_method('textDocument/completion', { bufnr = bufnr }) then - if client:supports_method('textDocument/completion') then - vim.opt.completeopt = { 'menu', 'menuone', 'noinsert', 'fuzzy', 'popup' } - print('completion enabled') + local ok, _ = pcall(require, 'blink') + if not ok then + if client:supports_method('textDocument/completion') then + vim.opt.completeopt = { 'menu', 'menuone', 'noselect', 'noinsert', 'fuzzy', 'popup' } - -- Enable native completion for this specific client and buffer - vim.lsp.completion.enable(true, client.id, args.buf, { autotrigger = true }) - vim.keymap.set('i', ' Date: Fri, 3 Apr 2026 08:24:33 +0300 Subject: [PATCH 0142/1406] update --- minimal_config.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index e29ecda5..7f46751f 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -154,7 +154,7 @@ local plugins = { { 'Saghen/blink.nvim', - version = '*', -- Download pre-built binaries + version = '1.*', -- Download pre-built binaries opts = { keymap = { preset = 'default' }, -- 'default', 'super-tab', or 'enter' sources = { From dee3901a5c7820c55fa54169e101c84f09d09e64 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 08:26:05 +0300 Subject: [PATCH 0143/1406] update --- minimal_config.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index 7f46751f..8bdec654 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -153,7 +153,7 @@ vim.opt.rtp:prepend(lazypath) local plugins = { { - 'Saghen/blink.nvim', + 'Saghen/blink.cmp', version = '1.*', -- Download pre-built binaries opts = { keymap = { preset = 'default' }, -- 'default', 'super-tab', or 'enter' From df51ba4a688b537434cd03f8f2b187a71ce860e7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 08:29:26 +0300 Subject: [PATCH 0144/1406] update --- lua/platformio/lspClangd.lua | 2 +- minimal_config.lua | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 19dff981..8645c7e7 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -91,7 +91,7 @@ end local capabilities = vim.lsp.protocol.make_client_capabilities() ok, _ = pcall(require, 'blink') if ok then - capabilities = vim.tbl_deep_extend('force', capabilities, require('blink.cmp').get_lsp_capabilities({}, false)) + capabilities = vim.tbl_deep_extend('force', capabilities, require('blink.nvim').get_lsp_capabilities({}, false)) end local clangd = { diff --git a/minimal_config.lua b/minimal_config.lua index 8bdec654..7f46751f 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -153,7 +153,7 @@ vim.opt.rtp:prepend(lazypath) local plugins = { { - 'Saghen/blink.cmp', + 'Saghen/blink.nvim', version = '1.*', -- Download pre-built binaries opts = { keymap = { preset = 'default' }, -- 'default', 'super-tab', or 'enter' From ca4e50cbcd2e8311541330a9c2ba33016b6e6535 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 08:31:49 +0300 Subject: [PATCH 0145/1406] update --- lua/platformio/lspClangd.lua | 2 +- minimal_config.lua | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 8645c7e7..19dff981 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -91,7 +91,7 @@ end local capabilities = vim.lsp.protocol.make_client_capabilities() ok, _ = pcall(require, 'blink') if ok then - capabilities = vim.tbl_deep_extend('force', capabilities, require('blink.nvim').get_lsp_capabilities({}, false)) + capabilities = vim.tbl_deep_extend('force', capabilities, require('blink.cmp').get_lsp_capabilities({}, false)) end local clangd = { diff --git a/minimal_config.lua b/minimal_config.lua index 7f46751f..8bdec654 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -153,7 +153,7 @@ vim.opt.rtp:prepend(lazypath) local plugins = { { - 'Saghen/blink.nvim', + 'Saghen/blink.cmp', version = '1.*', -- Download pre-built binaries opts = { keymap = { preset = 'default' }, -- 'default', 'super-tab', or 'enter' From d5995491cdc37f47650cc4f98cdde195ed9677e6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 08:38:03 +0300 Subject: [PATCH 0146/1406] update --- lua/platformio/lspAttach.lua | 2 +- lua/platformio/lspClangd.lua | 4 ++-- minimal_config.lua | 1 + 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 95a9843c..48ad3034 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -32,7 +32,7 @@ vim.api.nvim_create_autocmd('LspAttach', { -- if client and client.server_capabilities.completionProvider then -- if client:supports_method('textDocument/completion', { bufnr = bufnr }) then - local ok, _ = pcall(require, 'blink') + local ok, _ = pcall(require, 'blink.cmp') if not ok then if client:supports_method('textDocument/completion') then vim.opt.completeopt = { 'menu', 'menuone', 'noselect', 'noinsert', 'fuzzy', 'popup' } diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 19dff981..18192a40 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -89,9 +89,9 @@ if vim.fn.filereadable(fname) == 1 then end local capabilities = vim.lsp.protocol.make_client_capabilities() -ok, _ = pcall(require, 'blink') +ok, result = pcall(require, 'blink.cmp') if ok then - capabilities = vim.tbl_deep_extend('force', capabilities, require('blink.cmp').get_lsp_capabilities({}, false)) + capabilities = vim.tbl_deep_extend('force', capabilities, result().get_lsp_capabilities({}, false)) end local clangd = { diff --git a/minimal_config.lua b/minimal_config.lua index 8bdec654..9daac3fb 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -154,6 +154,7 @@ local plugins = { { 'Saghen/blink.cmp', + dependencies = { 'rafamadriz/friendly-snippets' }, version = '1.*', -- Download pre-built binaries opts = { keymap = { preset = 'default' }, -- 'default', 'super-tab', or 'enter' From 372b097b4e087e401e0b29b4550877c7c5b1ddc8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 08:42:59 +0300 Subject: [PATCH 0147/1406] update --- lua/platformio/lspAttach.lua | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 48ad3034..63dba100 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -32,20 +32,20 @@ vim.api.nvim_create_autocmd('LspAttach', { -- if client and client.server_capabilities.completionProvider then -- if client:supports_method('textDocument/completion', { bufnr = bufnr }) then - local ok, _ = pcall(require, 'blink.cmp') - if not ok then - if client:supports_method('textDocument/completion') then - vim.opt.completeopt = { 'menu', 'menuone', 'noselect', 'noinsert', 'fuzzy', 'popup' } - - print('completion enabled') - - -- Enable native completion for this specific client and buffer - vim.lsp.completion.enable(true, client.id, args.buf, { autotrigger = true }) - vim.keymap.set('i', ' Date: Fri, 3 Apr 2026 08:44:39 +0300 Subject: [PATCH 0148/1406] update --- lua/platformio/lspAttach.lua | 28 ++++++++++++++-------------- lua/platformio/lspClangd.lua | 2 +- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 63dba100..48ad3034 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -32,20 +32,20 @@ vim.api.nvim_create_autocmd('LspAttach', { -- if client and client.server_capabilities.completionProvider then -- if client:supports_method('textDocument/completion', { bufnr = bufnr }) then - -- local ok, _ = pcall(require, 'blink.cmp') - -- if not ok then - -- if client:supports_method('textDocument/completion') then - -- vim.opt.completeopt = { 'menu', 'menuone', 'noselect', 'noinsert', 'fuzzy', 'popup' } - -- - -- print('completion enabled') - -- - -- -- Enable native completion for this specific client and buffer - -- vim.lsp.completion.enable(true, client.id, args.buf, { autotrigger = true }) - -- vim.keymap.set('i', ' Date: Fri, 3 Apr 2026 08:51:44 +0300 Subject: [PATCH 0149/1406] update --- lua/platformio/lspClangd.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index de275a0b..65472d79 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -89,9 +89,9 @@ if vim.fn.filereadable(fname) == 1 then end local capabilities = vim.lsp.protocol.make_client_capabilities() -ok, result = pcall(require, 'blink.cmp') -if ok then - capabilities = vim.tbl_deep_extend('force', capabilities, result.get_lsp_capabilities({}, false)) +local bok, blink = pcall(require, 'blink.cmp') +if bok then + capabilities = vim.tbl_deep_extend('force', capabilities, blink.get_lsp_capabilities({}, false)) end local clangd = { From d5eee2e7f5969d2c1ec3a8b16f66a2e301b72e32 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 09:17:14 +0300 Subject: [PATCH 0150/1406] update --- minimal_config.lua | 107 ++++++++++++--------------------------------- 1 file changed, 27 insertions(+), 80 deletions(-) diff --git a/minimal_config.lua b/minimal_config.lua index 9daac3fb..a0c1a893 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -1,10 +1,7 @@ --- pick a temp root -local tmp = vim.loop.os_tmpdir() .. '/nvim-temp' - -vim.env.XDG_DATA_HOME = tmp .. '/data' -vim.env.XDG_CACHE_HOME = tmp .. '/cache' -vim.env.XDG_STATE_HOME = tmp .. '/state' +local isWindows = jit.os == 'Windows' +---------------------------------------------------------------------------------------- +-- INFO: Set options -- disable netrw at the very start of your init.lua vim.g.loaded_netrw = 1 vim.g.loaded_netrwPlugin = 1 @@ -30,7 +27,6 @@ vim.g.have_nerd_font = true vim.g.mapleader = ' ' vim.g.maplocalleader = ' ' -local isWindows = jit.os == 'Windows' if not isWindows then vim.g.shell = '/bin/bash' -- or '/bin/zsh', '/usr/bin/fish', etc. vim.g.shellcmdflag = '-c' -- Executes the command passed as a string @@ -46,7 +42,8 @@ else vim.g.shellxquote = '' end --- Toggle virtual_text off when on the line with the error +---------------------------------------------------------------------------------------- +-- INFO: Set diagnostic config vim.diagnostic.config({ virtual_lines = true, update_in_insert = true, @@ -70,6 +67,8 @@ vim.diagnostic.config({ }, }) +---------------------------------------------------------------------------------------- +-- INFO: Set nvim keymaps local keymap = function(mode, lhs, rhs, opts) local options = { silent = true } --noremap = true by default in vim.keymap.set if opts then @@ -132,7 +131,15 @@ keymap('n', '', '', { desc = 'Move focus to the left window' }) keymap('n', '', '', { desc = 'Move focus to the right window' }) keymap('n', '', '', { desc = 'Move focus to the lower window' }) keymap('n', '', '', { desc = 'Move focus to the upper window' }) + ---------------------------------------------------------------------------------------- +-- INFO: Set mini lazy config +-- pick a temp root +local tmp = vim.loop.os_tmpdir() .. '/nvim-temp' + +vim.env.XDG_DATA_HOME = tmp .. '/data' +vim.env.XDG_CACHE_HOME = tmp .. '/cache' +vim.env.XDG_STATE_HOME = tmp .. '/state' local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' @@ -150,6 +157,7 @@ end vim.opt.rtp:prepend(lazypath) ---------------------------------------------------------------------------------------- +-- INFO: define plugins table local plugins = { { @@ -163,72 +171,6 @@ local plugins = { }, }, }, - -- { - -- 'saghen/blink.cmp', - -- -- optional: provides snippets for the snippet source - -- dependencies = { 'rafamadriz/friendly-snippets' }, - -- - -- -- use a release tag to download pre-built binaries - -- version = '1.*', - -- -- AND/OR build from source - -- -- build = 'cargo build --release', - -- -- If you use nix, you can build from source with: - -- -- build = 'nix run .#build-plugin', - -- - -- ---@module 'blink.cmp' - -- ---@type blink.cmp.Config - -- opts = { - -- -- 'default' (recommended) for mappings similar to built-in completions (C-y to accept) - -- -- 'super-tab' for mappings similar to vscode (tab to accept) - -- -- 'enter' for enter to accept - -- -- 'none' for no mappings - -- -- - -- -- All presets have the following mappings: - -- -- C-space: Open menu or open docs if already open - -- -- C-n/C-p or Up/Down: Select next/previous item - -- -- C-e: Hide menu - -- -- C-k: Toggle signature help (if signature.enabled = true) - -- -- - -- -- See :h blink-cmp-config-keymap for defining your own keymap - -- keymap = { preset = 'default' }, - -- - -- appearance = { - -- -- 'mono' (default) for 'Nerd Font Mono' or 'normal' for 'Nerd Font' - -- -- Adjusts spacing to ensure icons are aligned - -- nerd_font_variant = 'mono', - -- }, - -- - -- -- (Default) Only show the documentation popup when manually triggered - -- completion = { documentation = { auto_show = false } }, - -- - -- -- Default list of enabled providers defined so that you can extend it - -- -- elsewhere in your config, without redefining it, due to `opts_extend` - -- sources = { - -- default = { 'lsp', 'path', 'snippets', 'buffer' }, - -- }, - -- - -- -- (Default) Rust fuzzy matcher for typo resistance and significantly better performance - -- -- You may use a lua implementation instead by using `implementation = "lua"` or fallback to the lua implementation, - -- -- when the Rust fuzzy matcher is not available, by using `implementation = "prefer_rust"` - -- -- - -- -- See the fuzzy documentation for more information - -- fuzzy = { implementation = 'prefer_rust_with_warning' }, - -- }, - -- opts_extend = { 'sources.default' }, - -- }, - -- - -- { - -- 'famiu/bufdelete.nvim', - -- keys = { - -- { - -- 'bd', - -- function() - -- require('bufdelete').bufdelete(0, true) - -- end, - -- desc = 'Delete buffer', - -- }, - -- }, - -- }, { 'akinsho/bufferline.nvim', version = '*', @@ -312,6 +254,8 @@ local plugins = { } ---------------------------------------------------------------------------------------- +---------------------------------------------------------------------------------------- +-- INFO: Install/config plugins require('lazy').setup(plugins, { install = { missing = true, @@ -319,6 +263,8 @@ require('lazy').setup(plugins, { }) ---------------------------------------------------------------------------------------- +---------------------------------------------------------------------------------------- +-- INFO: autocommand to Update lazy.nvim plugins in the background vim.api.nvim_create_autocmd('User', { pattern = 'LazyVimStarted', -- Triggers after the UI enters and startup time is calculated desc = 'Update lazy.nvim plugins in the background', @@ -332,9 +278,8 @@ vim.api.nvim_create_autocmd('User', { end, }) ------------------------------------------------------------------------------------------ --- local isWindows = jit.os == 'Windows' --- +---------------------------------------------------------------------------------------- +-- INFO: set up python nvim venv (virtual environment 'nenv'), activaten. local platformio_core_dir, pynvim_env, pynvim_python, pynvim_lib, pynvim_bin, pynvim_activate if isWindows then platformio_core_dir = vim.env.HOME .. '\\.platformio' @@ -371,13 +316,14 @@ if not vim.uv.fs_stat(pynvim_env) then if not isWindows then vim.fn.system({ 'python3', '-m', 'venv', pynvim_env }) vim.fn.system({ 'chmod', '755', '-R', pynvim_bin }) - -- vim.cmd('source ' .. pynvim_activate) vim.fn.system('source ' .. pynvim_activate) else vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) vim.fn.system(pynvim_activate) end + -------------------------------------------------------------------------------------- + -- INFO: install platformio and nvim required packages. vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'pip' }) vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'pynvim' }) vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'neovim' }) @@ -388,9 +334,10 @@ if not vim.uv.fs_stat(pynvim_env) then vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'platformio' }) -- vim.fn.system({ 'pip', 'install', '-U', 'platformio' }) end ------------------------- + +---------------------------------------------------------------------------------------- +-- INFO: configure nvim-platformio and load ----------------------------------------------------------------------------------------- --- platformio config local pioConfig = { lspClangd = { enabled = true, From 13ed6eeaf692f328e85598c52d72fdbba9cb8229 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 09:21:11 +0300 Subject: [PATCH 0151/1406] update --- minimal_config.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/minimal_config.lua b/minimal_config.lua index a0c1a893..edcc5f24 100644 --- a/minimal_config.lua +++ b/minimal_config.lua @@ -159,7 +159,7 @@ vim.opt.rtp:prepend(lazypath) ---------------------------------------------------------------------------------------- -- INFO: define plugins table local plugins = { - + { 'windwp/nvim-autopairs', event = 'InsertEnter', config = true }, { 'Saghen/blink.cmp', dependencies = { 'rafamadriz/friendly-snippets' }, From d861ab5a55775267dfb0acc3179a7e011defae51 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 09:26:35 +0300 Subject: [PATCH 0152/1406] update --- README.md | 2 +- minimal_config.lua => mini_nvimPlatformio.lua | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename minimal_config.lua => mini_nvimPlatformio.lua (100%) diff --git a/README.md b/README.md index 40a6329d..85154975 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Try the plugin with this minimal standalone config without modifying your existi ```sh wget https://raw.githubusercontent.com/batoaqaa/nvim-platformio.lua/refs/heads/main/minimal_config.lua -nvim -u minimal_config.lua +nvim -u mini_nvimPlatformio.lua # Now run :Pioinit ``` diff --git a/minimal_config.lua b/mini_nvimPlatformio.lua similarity index 100% rename from minimal_config.lua rename to mini_nvimPlatformio.lua From 3e556c8bac80a8e9699b7b04d9cce6d0cda81d4f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 09:31:19 +0300 Subject: [PATCH 0153/1406] update --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 85154975..d255f8e4 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ https://github.com/user-attachments/assets/fdbb6655-4b2d-4a2b-81d1-fd8af6e7d9f1 Try the plugin with this minimal standalone config without modifying your existing nvim setup. **This is especially useful if you're encountering errors during installation or usage**. ```sh -wget https://raw.githubusercontent.com/batoaqaa/nvim-platformio.lua/refs/heads/main/minimal_config.lua +wget https://raw.githubusercontent.com/batoaqaa/nvim-platformio.lua/refs/heads/main/mini_nvimPlatformio.lua nvim -u mini_nvimPlatformio.lua # Now run :Pioinit From ac87b0b5a87551d7141a5f8b14399e50ea5f6ea2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 09:33:17 +0300 Subject: [PATCH 0154/1406] update --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index d255f8e4..b69d0a70 100644 --- a/README.md +++ b/README.md @@ -100,7 +100,6 @@ return { keymaps = true, }, }, - -- Uncomment out following line to enable platformio menu. menu_key = '\\', -- replace this menu key to your convenience menu_name = 'PlatformIO', -- replace this menu name to your convenience } From e8d7b8ff093030ff17d3ef8529baf1c8ace34f68 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 18:33:18 +0300 Subject: [PATCH 0155/1406] update --- lua/platformio/pioinit.lua | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 9aa1d0f6..e8db0638 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -58,15 +58,18 @@ local function pick_framework(board_details) actions.close(prompt_bufnr) local selection = action_state.get_selected_entry() local selected_framework = selection[1] + local piolsp = require('platformio.piolsp').piolsp() local command = 'pio project init --board ' .. board_details['id'] .. ' --project-option "framework=' .. selected_framework .. '" && exit && echo "done"' - utils.ToggleTerminal(command, 'float', function() - boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') - vim.cmd(':PioLSP') - end) + utils.ToggleTerminal(command, 'float', piolsp) + boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') + -- utils.ToggleTerminal(command, 'float', function() + -- boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') + -- vim.cmd(':PioLSP') + -- end) end) return true end, From 232d6bd7290360f153d577f53f683a52818995dc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 18:55:55 +0300 Subject: [PATCH 0156/1406] update --- mini_nvimPlatformio.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index edcc5f24..71af9b3a 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -316,7 +316,8 @@ if not vim.uv.fs_stat(pynvim_env) then if not isWindows then vim.fn.system({ 'python3', '-m', 'venv', pynvim_env }) vim.fn.system({ 'chmod', '755', '-R', pynvim_bin }) - vim.fn.system('source ' .. pynvim_activate) + local out = vim.fn.system('source ' .. pynvim_activate) + print(out) else vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) vim.fn.system(pynvim_activate) From bb1ef7457df322b5504ce8e5db536622c2fc22ea Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 19:00:01 +0300 Subject: [PATCH 0157/1406] update --- lua/platformio/pioinit.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index e8db0638..98d06eea 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -64,8 +64,8 @@ local function pick_framework(board_details) .. ' --project-option "framework=' .. selected_framework .. '" && exit && echo "done"' - utils.ToggleTerminal(command, 'float', piolsp) boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') + utils.ToggleTerminal(command, 'float', piolsp) -- utils.ToggleTerminal(command, 'float', function() -- boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') -- vim.cmd(':PioLSP') From 0e49feb10b4e88c78330ddbf4a470b38a6faa929 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 19:08:39 +0300 Subject: [PATCH 0158/1406] update --- mini_nvimPlatformio.lua | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 71af9b3a..79c3dd83 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -314,10 +314,11 @@ end -- local expand_dir = vim.fn.expand(pynvim_env) if not vim.uv.fs_stat(pynvim_env) then if not isWindows then - vim.fn.system({ 'python3', '-m', 'venv', pynvim_env }) - vim.fn.system({ 'chmod', '755', '-R', pynvim_bin }) - local out = vim.fn.system('source ' .. pynvim_activate) + print('linux:') + local out = vim.fn.system({ 'python3', '-m', 'venv', pynvim_env }) print(out) + out = vim.fn.system({ 'chmod', '755', '-R', pynvim_bin }) + out = vim.fn.system('source ' .. pynvim_activate) else vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) vim.fn.system(pynvim_activate) From 4faa47516178c4764831d5114d113d4e21c846c3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 19:12:29 +0300 Subject: [PATCH 0159/1406] update --- mini_nvimPlatformio.lua | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 79c3dd83..18528e68 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -311,14 +311,15 @@ if vim.fn.isdirectory(platformio_core_dir) == 0 then -- os.execute((isWindows and "del " or "rm -f ") .. "get-platformio.py*") end +local output -- local expand_dir = vim.fn.expand(pynvim_env) if not vim.uv.fs_stat(pynvim_env) then if not isWindows then print('linux:') - local out = vim.fn.system({ 'python3', '-m', 'venv', pynvim_env }) - print(out) - out = vim.fn.system({ 'chmod', '755', '-R', pynvim_bin }) - out = vim.fn.system('source ' .. pynvim_activate) + output = vim.fn.system({ 'python3', '-m', 'venv', pynvim_env }) + print(output) + vim.fn.system({ 'chmod', '755', '-R', pynvim_bin }) + vim.fn.system('source ' .. pynvim_activate) else vim.fn.system({ 'python', '-m', 'venv', pynvim_env }) vim.fn.system(pynvim_activate) @@ -326,8 +327,10 @@ if not vim.uv.fs_stat(pynvim_env) then -------------------------------------------------------------------------------------- -- INFO: install platformio and nvim required packages. - vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'pip' }) - vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'pynvim' }) + output = vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'pip' }) + print(output) + output = vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'pynvim' }) + print(output) vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'neovim' }) vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'debugpy' }) vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'isort' }) From cea438157628269b8b2e8082feb3f74fe3dd8634 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 19:42:45 +0300 Subject: [PATCH 0160/1406] update --- lua/platformio/pioinit.lua | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 98d06eea..da6a3842 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -64,12 +64,12 @@ local function pick_framework(board_details) .. ' --project-option "framework=' .. selected_framework .. '" && exit && echo "done"' - boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') - utils.ToggleTerminal(command, 'float', piolsp) - -- utils.ToggleTerminal(command, 'float', function() - -- boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') - -- vim.cmd(':PioLSP') - -- end) + -- boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') + -- utils.ToggleTerminal(command, 'float', piolsp) + utils.ToggleTerminal(command, 'float', function() + boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') + vim.cmd(':PioLSP') + end) end) return true end, From 7b6ee951d423103150e0b0363e6e55db6b0e0311 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 21:52:13 +0300 Subject: [PATCH 0161/1406] update --- lua/platformio/pioinit.lua | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index da6a3842..644ef103 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -58,18 +58,18 @@ local function pick_framework(board_details) actions.close(prompt_bufnr) local selection = action_state.get_selected_entry() local selected_framework = selection[1] - local piolsp = require('platformio.piolsp').piolsp() local command = 'pio project init --board ' .. board_details['id'] .. ' --project-option "framework=' .. selected_framework .. '" && exit && echo "done"' - -- boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') - -- utils.ToggleTerminal(command, 'float', piolsp) - utils.ToggleTerminal(command, 'float', function() - boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') - vim.cmd(':PioLSP') - end) + boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') + local piolsp = require('platformio.piolsp').piolsp + utils.ToggleTerminal(command, 'float', piolsp) + -- utils.ToggleTerminal(command, 'float', function() + -- boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') + -- vim.cmd(':PioLSP') + -- end) end) return true end, From 32c273b5c8c93893a938cc7fabd0e62e42791cc0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 22:21:22 +0300 Subject: [PATCH 0162/1406] update --- lua/platformio/pioinit.lua | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 644ef103..f5d599c6 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -64,8 +64,13 @@ local function pick_framework(board_details) .. selected_framework .. '" && exit && echo "done"' boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') - local piolsp = require('platformio.piolsp').piolsp - utils.ToggleTerminal(command, 'float', piolsp) + -- local piolsp = require('platformio.piolsp').piolsp + -- utils.ToggleTerminal(command, 'float', piolsp) + -- + utils.ToggleTerminal(command, 'float', function() + require('platformio.piolsp').piolsp() + end) + -- -- utils.ToggleTerminal(command, 'float', function() -- boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') -- vim.cmd(':PioLSP') From 1bb028960a008d2dbceba5897887b9fa1a25bd1e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 22:27:06 +0300 Subject: [PATCH 0163/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index fead9f0e..b6d5ce4e 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -339,7 +339,7 @@ Diagnostics: } function M.boilerplate_gen(framework, src_path) - -- print(src_path .. '/' .. framework) + print(src_path .. '/' .. framework) local entry = boilerplate[framework] if not entry then return From 54fb2ce2bc161f193873457a57fa816766dddd12 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 22:31:19 +0300 Subject: [PATCH 0164/1406] update --- lua/platformio/pioinit.lua | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index f5d599c6..ba9be8a3 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -10,7 +10,8 @@ local make_entry = require('telescope.make_entry') local utils = require('platformio.utils') local previewers = require('telescope.previewers') local config = require('platformio').config -local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +-- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +local boilerplate = require('platformio.boilerplate') local boardentry_maker = function(opts) local displayer = entry_display.create({ @@ -63,13 +64,13 @@ local function pick_framework(board_details) .. ' --project-option "framework=' .. selected_framework .. '" && exit && echo "done"' - boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') - -- local piolsp = require('platformio.piolsp').piolsp - -- utils.ToggleTerminal(command, 'float', piolsp) + boilerplate.boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') + local piolsp = require('platformio.piolsp').piolsp + utils.ToggleTerminal(command, 'float', piolsp) -- - utils.ToggleTerminal(command, 'float', function() - require('platformio.piolsp').piolsp() - end) + -- utils.ToggleTerminal(command, 'float', function() + -- require('platformio.piolsp').piolsp() + -- end) -- -- utils.ToggleTerminal(command, 'float', function() -- boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') From 5df0fd0d238f38402747a85f912ab3f1e1d8a818 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 22:37:33 +0300 Subject: [PATCH 0165/1406] update --- lua/platformio/boilerplate.lua | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index b6d5ce4e..e90cbe25 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -339,11 +339,13 @@ Diagnostics: } function M.boilerplate_gen(framework, src_path) - print(src_path .. '/' .. framework) + print(src_path .. '/0' .. framework) local entry = boilerplate[framework] if not entry then + print(src_path .. '/1' .. framework) return end + print(src_path .. '/2' .. framework) -- local file_path = src_path .. '/' .. entry.filename if vim.uv.fs_stat(file_path) then From 88789e76cd2bb850c687283cd278ef1e4a7848fa Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 22:44:15 +0300 Subject: [PATCH 0166/1406] update --- lua/platformio/boilerplate.lua | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index e90cbe25..73012c05 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -345,17 +345,19 @@ function M.boilerplate_gen(framework, src_path) print(src_path .. '/1' .. framework) return end - print(src_path .. '/2' .. framework) + print(src_path .. '/2' .. entry.filename) -- local file_path = src_path .. '/' .. entry.filename if vim.uv.fs_stat(file_path) then return end -- + print(src_path .. '/3' .. entry.filename) local fd = uv.fs_open(file_path, 'w', 420) if not fd then return end + print(src_path .. '/4' .. entry.filename) uv.fs_write(fd, entry.content) uv.fs_close(fd) end From d8c98f24a744acdeff832fdc7ea8fb2f24d66f76 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 23:29:14 +0300 Subject: [PATCH 0167/1406] update --- lua/platformio/boilerplate.lua | 37 +++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 73012c05..f46cbfff 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -353,13 +353,36 @@ function M.boilerplate_gen(framework, src_path) end -- print(src_path .. '/3' .. entry.filename) - local fd = uv.fs_open(file_path, 'w', 420) - if not fd then - return - end + + -- local fd = uv.fs_open(file_path, 'w', 420) + -- if not fd then + -- return + -- end + + -- + uv.fs_open(file_path, 'r', 438, function(err, fd) + if err then + return + end + uv.fs_fstat(fd, function(serr, _) + if serr then + return + end + uv.fs_write(fd, entry.content, 0, function(werr, _) + if werr then + return + end + uv.fs_close(fd, function(cerr) + if cerr then + return + end + end) + end) + end) + end) + -- print(src_path .. '/4' .. entry.filename) - uv.fs_write(fd, entry.content) - uv.fs_close(fd) + -- uv.fs_write(fd, entry.content) + -- uv.fs_close(fd) end - return M From d1fa4a9e8d35fcd41de2e57ab9e0580ee57cbdbe Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 23:32:27 +0300 Subject: [PATCH 0168/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index f46cbfff..e79f2b87 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -360,7 +360,7 @@ function M.boilerplate_gen(framework, src_path) -- end -- - uv.fs_open(file_path, 'r', 438, function(err, fd) + uv.fs_open(file_path, 'w', 420, function(err, fd) if err then return end From 1d78577e3f987ad0d553ff859b48b9310094f42d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 3 Apr 2026 23:35:46 +0300 Subject: [PATCH 0169/1406] update --- lua/platformio/boilerplate.lua | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index e79f2b87..e5794302 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -362,18 +362,22 @@ function M.boilerplate_gen(framework, src_path) -- uv.fs_open(file_path, 'w', 420, function(err, fd) if err then + print(src_path .. '/30' .. entry.filename) return end uv.fs_fstat(fd, function(serr, _) if serr then + print(src_path .. '/31' .. entry.filename) return end uv.fs_write(fd, entry.content, 0, function(werr, _) if werr then + print(src_path .. '/32' .. entry.filename) return end uv.fs_close(fd, function(cerr) if cerr then + print(src_path .. '/33' .. entry.filename) return end end) From f32abce1fb2b735a20ae5dc80b8bfc0b491261bc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 00:26:53 +0300 Subject: [PATCH 0170/1406] update --- lua/platformio/pioinit.lua | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index ba9be8a3..0c124c22 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -10,8 +10,8 @@ local make_entry = require('telescope.make_entry') local utils = require('platformio.utils') local previewers = require('telescope.previewers') local config = require('platformio').config --- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -local boilerplate = require('platformio.boilerplate') +local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +-- local boilerplate = require('platformio.boilerplate') local boardentry_maker = function(opts) local displayer = entry_display.create({ @@ -64,7 +64,8 @@ local function pick_framework(board_details) .. ' --project-option "framework=' .. selected_framework .. '" && exit && echo "done"' - boilerplate.boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') + boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') + -- boilerplate.boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') local piolsp = require('platformio.piolsp').piolsp utils.ToggleTerminal(command, 'float', piolsp) -- From eb09e13a0568a1f3ff75966d36fb84873f35ea0f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 00:40:10 +0300 Subject: [PATCH 0171/1406] update --- lua/platformio/boilerplate.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index e5794302..e2c0e5e5 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -362,22 +362,22 @@ function M.boilerplate_gen(framework, src_path) -- uv.fs_open(file_path, 'w', 420, function(err, fd) if err then - print(src_path .. '/30' .. entry.filename) + print(file_path .. '/30' .. entry.filename) return end uv.fs_fstat(fd, function(serr, _) if serr then - print(src_path .. '/31' .. entry.filename) + print(file_path .. '/31' .. entry.filename) return end uv.fs_write(fd, entry.content, 0, function(werr, _) if werr then - print(src_path .. '/32' .. entry.filename) + print(file_path .. '/32' .. entry.filename) return end uv.fs_close(fd, function(cerr) if cerr then - print(src_path .. '/33' .. entry.filename) + print(file_path .. '/33' .. entry.filename) return end end) From 26efdfa51176666570a825818ea0a7319e9cba9f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 00:47:41 +0300 Subject: [PATCH 0172/1406] update --- lua/platformio/boilerplate.lua | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index e2c0e5e5..c72f4034 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -360,29 +360,29 @@ function M.boilerplate_gen(framework, src_path) -- end -- - uv.fs_open(file_path, 'w', 420, function(err, fd) - if err then + uv.fs_open(file_path, 'w', 420, function(_, fd) + if not fd then print(file_path .. '/30' .. entry.filename) return end - uv.fs_fstat(fd, function(serr, _) - if serr then - print(file_path .. '/31' .. entry.filename) + -- uv.fs_fstat(fd, function(serr, _) + -- if serr then + -- print(file_path .. '/31' .. entry.filename) + -- return + -- end + uv.fs_write(fd, entry.content, 0, function(werr, _) + if werr then + print(file_path .. '/32' .. entry.filename) return end - uv.fs_write(fd, entry.content, 0, function(werr, _) - if werr then - print(file_path .. '/32' .. entry.filename) + uv.fs_close(fd, function(cerr) + if cerr then + print(file_path .. '/33' .. entry.filename) return end - uv.fs_close(fd, function(cerr) - if cerr then - print(file_path .. '/33' .. entry.filename) - return - end - end) end) end) + -- end) end) -- print(src_path .. '/4' .. entry.filename) From 66b995fe06d31e517dde85cb0bd81591a4b387ce Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 01:02:25 +0300 Subject: [PATCH 0173/1406] update --- lua/platformio/pioinit.lua | 20 ++++++-------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 0c124c22..2618a073 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -9,9 +9,8 @@ local entry_display = require('telescope.pickers.entry_display') local make_entry = require('telescope.make_entry') local utils = require('platformio.utils') local previewers = require('telescope.previewers') -local config = require('platformio').config local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen --- local boilerplate = require('platformio.boilerplate') +local piolsp = require('platformio.piolsp').piolsp local boardentry_maker = function(opts) local displayer = entry_display.create({ @@ -64,19 +63,12 @@ local function pick_framework(board_details) .. ' --project-option "framework=' .. selected_framework .. '" && exit && echo "done"' - boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') - -- boilerplate.boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') - local piolsp = require('platformio.piolsp').piolsp + utils.ToggleTerminal(command, 'float', piolsp) - -- - -- utils.ToggleTerminal(command, 'float', function() - -- require('platformio.piolsp').piolsp() - -- end) - -- - -- utils.ToggleTerminal(command, 'float', function() - -- boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') - -- vim.cmd(':PioLSP') - -- end) + + -- it fails creating the file if src directory not exist + -- src directory should be created by piolsp callback function in the previous command + boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') end) return true end, From 5defec1eab5e9915b97d259ea658505c0b3dbad0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 01:09:58 +0300 Subject: [PATCH 0174/1406] update --- lua/platformio/boilerplate.lua | 29 +++++------------------------ 1 file changed, 5 insertions(+), 24 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index c72f4034..b1a58a44 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -339,54 +339,35 @@ Diagnostics: } function M.boilerplate_gen(framework, src_path) - print(src_path .. '/0' .. framework) + -- print(src_path .. '/0' .. framework) local entry = boilerplate[framework] if not entry then - print(src_path .. '/1' .. framework) return end - print(src_path .. '/2' .. entry.filename) -- local file_path = src_path .. '/' .. entry.filename if vim.uv.fs_stat(file_path) then return end -- - print(src_path .. '/3' .. entry.filename) - - -- local fd = uv.fs_open(file_path, 'w', 420) - -- if not fd then - -- return - -- end - - -- - uv.fs_open(file_path, 'w', 420, function(_, fd) + uv.fs_open(file_path, 'w', 420, function(_, fd) -- crtete file if directory of the path exists if not fd then - print(file_path .. '/30' .. entry.filename) + print('failed to create file: ' .. file_path .. '/' .. entry.filename) return end - -- uv.fs_fstat(fd, function(serr, _) - -- if serr then - -- print(file_path .. '/31' .. entry.filename) - -- return - -- end uv.fs_write(fd, entry.content, 0, function(werr, _) if werr then - print(file_path .. '/32' .. entry.filename) + print('failed to write to file: ' .. file_path .. '/' .. entry.filename) return end uv.fs_close(fd, function(cerr) if cerr then - print(file_path .. '/33' .. entry.filename) + print('failed to close file: ' .. file_path .. '/' .. entry.filename) return end end) end) -- end) end) - -- - print(src_path .. '/4' .. entry.filename) - -- uv.fs_write(fd, entry.content) - -- uv.fs_close(fd) end return M From 8f9f7727b76b2af493351b5525d72f9a018ad25a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 01:16:31 +0300 Subject: [PATCH 0175/1406] update --- lua/platformio/pioinit.lua | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 2618a073..36b10b57 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -64,11 +64,15 @@ local function pick_framework(board_details) .. selected_framework .. '" && exit && echo "done"' - utils.ToggleTerminal(command, 'float', piolsp) + -- utils.ToggleTerminal(command, 'float', piolsp) + utils.ToggleTerminal(command, 'float', function() + -- require('platformio.piolsp').piolsp() + piolsp() + boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') + end) -- it fails creating the file if src directory not exist -- src directory should be created by piolsp callback function in the previous command - boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') end) return true end, From fc22e2c8cf64809d54c8d5a8a293305e5760f191 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 01:42:20 +0300 Subject: [PATCH 0176/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/pioinit.lua | 11 +---- lua/platformio/piolib.lua | 82 +++++++++++++++++----------------- lua/platformio/utils.lua | 39 ++++++++-------- 4 files changed, 63 insertions(+), 71 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index b1a58a44..f660571a 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -347,7 +347,7 @@ function M.boilerplate_gen(framework, src_path) -- local file_path = src_path .. '/' .. entry.filename if vim.uv.fs_stat(file_path) then - return + return -- return if file exists end -- uv.fs_open(file_path, 'w', 420, function(_, fd) -- crtete file if directory of the path exists diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 36b10b57..ddf6f661 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -58,21 +58,14 @@ local function pick_framework(board_details) actions.close(prompt_bufnr) local selection = action_state.get_selected_entry() local selected_framework = selection[1] - local command = 'pio project init --board ' - .. board_details['id'] - .. ' --project-option "framework=' - .. selected_framework - .. '" && exit && echo "done"' + local command = 'pio project init --board ' .. board_details['id'] .. ' --project-option "framework=' .. selected_framework .. '"' + -- .. '" && exit && echo "done"' - -- utils.ToggleTerminal(command, 'float', piolsp) utils.ToggleTerminal(command, 'float', function() -- require('platformio.piolsp').piolsp() piolsp() boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') end) - - -- it fails creating the file if src directory not exist - -- src directory should be created by piolsp callback function in the previous command end) return true end, diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index c7b3b7e8..0211b9cf 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -1,8 +1,6 @@ local M = {} -local config = require('platformio').config local curl = require('plenary.curl') - local pickers = require('telescope.pickers') local finders = require('telescope.finders') local entry_display = require('telescope.pickers.entry_display') @@ -12,6 +10,7 @@ local actions = require('telescope.actions') local action_state = require('telescope.actions.state') local utils = require('platformio.utils') local previewers = require('telescope.previewers') +local piolsp = require('platformio.piolsp').piolsp local libentry_maker = function(opts) local displayer = entry_display.create({ @@ -48,43 +47,47 @@ end local function pick_library(json_data) local opts = {} pickers - .new(opts, { - prompt_title = 'Libraries', - finder = finders.new_table({ - results = json_data['items'], - entry_maker = opts.entry_maker or libentry_maker(opts), - }), - attach_mappings = function(prompt_bufnr, _) - actions.select_default:replace(function() - actions.close(prompt_bufnr) - local selection = action_state.get_selected_entry() - local pkg_name = selection['value']['owner'] .. '/' .. selection['value']['name'] - local command = 'pio pkg install --library "' .. pkg_name .. '" && exit && echo "done"' - utils.ToggleTerminal(command, 'float', function() - vim.cmd(':PioLSP') - end) - end) - return true - end, + .new(opts, { + prompt_title = 'Libraries', + finder = finders.new_table({ + results = json_data['items'], + entry_maker = opts.entry_maker or libentry_maker(opts), + }), + attach_mappings = function(prompt_bufnr, _) + actions.select_default:replace(function() + actions.close(prompt_bufnr) + local selection = action_state.get_selected_entry() + local pkg_name = selection['value']['owner'] .. '/' .. selection['value']['name'] + local command = 'pio pkg install --library "' .. pkg_name .. '"' + -- local command = 'pio pkg install --library "' .. pkg_name .. '" && exit && echo "done"' + + -- utils.ToggleTerminal(command, 'float', function() + -- -- require('platformio.piolsp').piolsp() + -- piolsp() + -- end) + utils.ToggleTerminal(command, 'float', piolsp) + end) + return true + end, - previewer = previewers.new_buffer_previewer({ - title = 'Package Info', - define_preview = function(self, entry, _) - local json = utils.strsplit(vim.inspect(entry['value']['data']), '\n') - local bufnr = self.state.bufnr - vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) - vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function - vim.defer_fn(function() - local win = self.state.winid - vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) - vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) - vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) - end, 0) - end, - }), - sorter = conf.generic_sorter(opts), - }) - :find() + previewer = previewers.new_buffer_previewer({ + title = 'Package Info', + define_preview = function(self, entry, _) + local json = utils.strsplit(vim.inspect(entry['value']['data']), '\n') + local bufnr = self.state.bufnr + vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) + vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function + vim.defer_fn(function() + local win = self.state.winid + vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) + vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) + vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) + end, 0) + end, + }), + sorter = conf.generic_sorter(opts), + }) + :find() end function M.piolib(lib_arg_list) @@ -118,8 +121,7 @@ function M.piolib(lib_arg_list) pick_library(json_data) else vim.notify( - 'API Request to platformio return HTTP code: ' .. - res['status'] .. '\nplease run `curl -LI ' .. url .. '` for complete information', + 'API Request to platformio return HTTP code: ' .. res['status'] .. '\nplease run `curl -LI ' .. url .. '` for complete information', vim.log.levels.ERROR ) end diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 3dcc148f..c2b26316 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -44,9 +44,9 @@ end local function getPreviousWindow(orig_window) local prev = { orig_window = orig_window, - term = nil, --active terminal - cli = nil, --cli terminal - mon = nil, --mon terminal + term = nil, --active terminal + cli = nil, --cli terminal + mon = nil, --mon terminal float = false, --is active terminal direction float } local terms = require('toggleterm.terminal').get_all(true) @@ -87,7 +87,7 @@ local function send(term, cmd) vim.fn.chansend(term.job_id, cmd .. M.enter()) if vim.api.nvim_buf_is_loaded(term.bufnr) and vim.api.nvim_buf_is_valid(term.bufnr) then if term.window and vim.api.nvim_win_is_valid(term.window) then --vim.ui.term_has_open_win(term) then - vim.api.nvim_set_current_win(term.window) -- terminal focus + vim.api.nvim_set_current_win(term.window) -- terminal focus vim.api.nvim_buf_call(term.bufnr, function() local mode = vim.api.nvim_get_mode().mode if mode == 'n' or mode == 'nt' then @@ -116,11 +116,10 @@ end ------------------------------------------------------ -- INFO: ToggleTerminal function M.ToggleTerminal(command, direction, exit_callback) - local closeOnexit = false if type(exit_callback) == 'function' then - closeOnexit = true - else - exit_callback = function() end + command = command .. ' && exit ' + -- else + -- exit_callback = function() end end local status_ok, _ = pcall(require, 'toggleterm') @@ -190,7 +189,7 @@ function M.ToggleTerminal(command, direction, exit_callback) background = 'NormalFloat', }, }, - close_on_exit = true, --closeOnexit, + close_on_exit = false, -- INFO: on_open() on_open = function(t) @@ -220,13 +219,13 @@ function M.ToggleTerminal(command, direction, exit_callback) if config.debug then local name_splt = M.strsplit(t.display_name, ':') vim.api.nvim_echo({ - { 'ToggleTerm ', 'MoreMsg' }, - { '(Term name: ' .. name_splt[1] .. ')', 'MoreMsg' }, + { 'ToggleTerm ', 'MoreMsg' }, + { '(Term name: ' .. name_splt[1] .. ')', 'MoreMsg' }, { '(Prev win ID: ' .. name_splt[2] .. ')', 'MoreMsg' }, - { '(Term Win ID: ' .. t.window .. ')', 'MoreMsg' }, - { '(Term Buffer#: ' .. t.bufnr .. ')', 'MoreMsg' }, - { '(Term id: ' .. t.id .. ')', 'MoreMsg' }, - { '(Job ID: ' .. t.job_id .. ')', 'MoreMsg' }, + { '(Term Win ID: ' .. t.window .. ')', 'MoreMsg' }, + { '(Term Buffer#: ' .. t.bufnr .. ')', 'MoreMsg' }, + { '(Term id: ' .. t.id .. ')', 'MoreMsg' }, + { '(Job ID: ' .. t.job_id .. ')', 'MoreMsg' }, }, true, {}) end end, @@ -240,14 +239,13 @@ function M.ToggleTerminal(command, direction, exit_callback) else vim.api.nvim_set_current_win(0) end - print('close:') - -- exit_callback() end, -- INFO: on_exit() on_exit = function(_) - print('exit:') - exit_callback() + if type(exit_callback) == 'function' then + exit_callback() + end end, -- INFO: on_create() { @@ -353,8 +351,7 @@ function M.cd_pioini() end function M.pio_install_check() - local handel = (jit.os == 'Windows') and assert(io.popen('where.exe pio 2>./nul')) or - assert(io.popen('which pio 2>/dev/null')) + local handel = (jit.os == 'Windows') and assert(io.popen('where.exe pio 2>./nul')) or assert(io.popen('which pio 2>/dev/null')) local pio_path = assert(handel:read('*a')) handel:close() From 7b2135f8441c8959891394d53711be928f5e0aba Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 01:45:15 +0300 Subject: [PATCH 0177/1406] update --- lua/platformio/utils.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index c2b26316..9b1e84e9 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -189,7 +189,7 @@ function M.ToggleTerminal(command, direction, exit_callback) background = 'NormalFloat', }, }, - close_on_exit = false, + close_on_exit = true, -- INFO: on_open() on_open = function(t) From 4e387317663dc2c19efbc5c44ca1d961844e0ddb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 02:10:47 +0300 Subject: [PATCH 0178/1406] update --- lua/platformio/piolsp.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index d0bf6747..a54aa36e 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -35,9 +35,9 @@ function M.piolsp() gitignore_lsp_configs('compile_commands.json') if vim.fn.has('nvim-0.12') then - if #vim.lsp.get_clients() > 0 then - vim.cmd('lsp restart') - end + -- if #vim.lsp.get_clients() > 0 then + vim.cmd('lsp restart') + -- end else vim.cmd('LspRestart') end From ff3c3e56e9202fde721f70f96a73f21b180fde82 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 05:17:34 +0300 Subject: [PATCH 0179/1406] update --- lua/platformio/piolsp.lua | 6 +++--- lua/platformio/utils.lua | 15 +++++++-------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index a54aa36e..d0bf6747 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -35,9 +35,9 @@ function M.piolsp() gitignore_lsp_configs('compile_commands.json') if vim.fn.has('nvim-0.12') then - -- if #vim.lsp.get_clients() > 0 then - vim.cmd('lsp restart') - -- end + if #vim.lsp.get_clients() > 0 then + vim.cmd('lsp restart') + end else vim.cmd('LspRestart') end diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 9b1e84e9..27feba0d 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -116,10 +116,11 @@ end ------------------------------------------------------ -- INFO: ToggleTerminal function M.ToggleTerminal(command, direction, exit_callback) - if type(exit_callback) == 'function' then - command = command .. ' && exit ' - -- else - -- exit_callback = function() end + local closeOnexit = type(exit_callback) == 'function' + if closeOnexit then + command = command .. ' && exit' + else + exit_callback = function() end end local status_ok, _ = pcall(require, 'toggleterm') @@ -189,7 +190,7 @@ function M.ToggleTerminal(command, direction, exit_callback) background = 'NormalFloat', }, }, - close_on_exit = true, + close_on_exit = closeOnexit, -- INFO: on_open() on_open = function(t) @@ -243,9 +244,7 @@ function M.ToggleTerminal(command, direction, exit_callback) -- INFO: on_exit() on_exit = function(_) - if type(exit_callback) == 'function' then - exit_callback() - end + exit_callback() end, -- INFO: on_create() { From 4d1193978b342280d41ebe351eed1294ac9a9821 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 06:19:38 +0300 Subject: [PATCH 0180/1406] update --- lua/platformio/lspClangd.lua | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 65472d79..e525964f 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -64,10 +64,14 @@ end -- end -- end) -require('mason-lspconfig').setup({ - ensure_installed = { 'clangd' }, - automatic_enable = true, -- this will automatically enable LSP servers after install -}) +-- require('mason-lspconfig').setup({ +local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') +if mok then + mason_lspconfig.setup({ + ensure_installed = { 'clangd' }, + automatic_enable = true, -- this will automatically enable LSP servers after install + }) +end ----------------------------------------------------------------------------------------- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen @@ -77,8 +81,6 @@ boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) local cmd = { 'clangd' } - --- local path = vim.fn.getcwd() local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) if vim.fn.filereadable(fname) == 1 then ok, result = pcall(vim.fn.readfile, fname) @@ -122,10 +124,10 @@ local clangd = { vim.lsp.config('clangd', clangd) ---------------------- -local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') -if mok then - mason_lspconfig.setup({}) -end +-- local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') +-- if mok then +-- mason_lspconfig.setup({}) +-- end -- require('platformio.piolsp').piolsp() if vim.fn.has('nvim-0.12') then From 279266727b1b7e27acc7cd94b216ed05c8a91153 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 06:37:50 +0300 Subject: [PATCH 0181/1406] update --- lua/platformio/lspClangd.lua | 82 +++++++++++++++++++++++++++++------- 1 file changed, 67 insertions(+), 15 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index e525964f..91e1e1c1 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -11,9 +11,9 @@ if ok then result.setup({}) end +---------------------------------------------------------------------------------------- +-- INFO: setup and install mason packages ----------------------------------------------------------------------------------------- --- INFO: Mason packages install for lint and formater --- mason.setup() ok, result = pcall(require, 'mason') if ok then result.setup({ @@ -65,21 +65,20 @@ end -- end) -- require('mason-lspconfig').setup({ +---------------------------------------------------------------------------------------- +-- INFO: install clangd using mason-lspconfig +----------------------------------------------------------------------------------------- local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') if mok then mason_lspconfig.setup({ - ensure_installed = { 'clangd' }, - automatic_enable = true, -- this will automatically enable LSP servers after install + ensure_installed = { 'clangd', 'lua_ls' }, + automatic_enable = true, -- this will automatically enable LSP servers after lsp.config }) end +---------------------------------------------------------------------------------------- +-- INFO: configure clangd lsp server ----------------------------------------------------------------------------------------- -local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) -boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) -boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) - local cmd = { 'clangd' } local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) if vim.fn.filereadable(fname) == 1 then @@ -123,11 +122,64 @@ local clangd = { } vim.lsp.config('clangd', clangd) ----------------------- --- local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') --- if mok then --- mason_lspconfig.setup({}) --- end +---------------------------------------------------------------------------------------- +-- INFO: configure clangd lsp server +----------------------------------------------------------------------------------------- +local lua_ls = { + cmd = { 'lua-language-server' }, + filetypes = { 'lua' }, + root_markers = { + '.luarc.json', + '.luarc.jsonc', + '.luacheckrc', + '.stylua.toml', + 'selene.toml', + 'selene.yml', + '.git', + }, + settings = { + Lua = { + hint = { + enable = true, + arrayIndex = 'Enable', + await = true, + paramName = 'All', + paramType = true, + semicolon = 'Disable', + setType = true, + }, + telemetry = { enable = false }, + diagnostics = { globals = { 'vim' } }, + runtime = { + -- Specify LuaJIT for Neovim + version = 'LuaJIT', + -- Include Neovim runtime files + path = vim.split(package.path, ';'), + }, + workspace = { + checkThirdParty = false, + library = { + vim.env.VIMRUNTIME, + '${3rd}/luv/library', + './lua', + vim.api.nvim_get_runtime_file('', true), + -- Depending on the usage, you might want to add additional paths here. + -- "${3rd}/busted/library", + }, + }, + }, + }, +} +vim.lsp.config('lua_ls', lua_ls) + +---------------------------------------------------------------------------------------- +-- INFO: create clangd required files +----------------------------------------------------------------------------------------- +local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) +boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) +boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) -- require('platformio.piolsp').piolsp() if vim.fn.has('nvim-0.12') then From da3eaccf091efdfc859bdb8e028ed3725c0ac038 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 07:03:06 +0300 Subject: [PATCH 0182/1406] update --- lua/platformio/boilerplate.lua | 17 +++++++ lua/platformio/lspClangd.lua | 82 ++++++++++++++++++++-------------- 2 files changed, 65 insertions(+), 34 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index f660571a..19b355fd 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -337,6 +337,23 @@ Diagnostics: ]], } +boilerplate['stylua.toml'] = { + filename = 'stylua.toml', + content = [[ +syntax = "All" +column_width = 132 +line_endings = "Unix" +indent_type = "Spaces" +indent_width = 2 +quote_style = "AutoPreferSingle" +call_parentheses = "Always" +collapse_simple_statement = "Never" +space_after_function_names = "Never" + +[sort_requires] +enabled = false +]], +} function M.boilerplate_gen(framework, src_path) -- print(src_path .. '/0' .. framework) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 91e1e1c1..99a5362b 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -30,39 +30,38 @@ if ok then end -- List of packages you want Mason to ensure are installed --- local ensure_installed = { --- 'clang-format', --- -- 'biome', --- } --- --- -- call mason-registry function to install or ensure formatters/linters are installed --- local mr = require('mason-registry') --- mr.refresh(function() --- for _, tool in ipairs(ensure_installed) do --- ok, result = pcall(mr.get_package, tool) --- if ok and result then --- if not result:is_installed() then --- if not result:is_installing() then --- result:install({}, function(success, _) --- if not success then --- vim.defer_fn(function() --- vim.notify(tool .. ' failed to install', vim.log.levels.ERROR) --- end, 0) --- end --- end) --- else --- vim.defer_fn(function() --- vim.notify(tool .. ' already installed', vim.log.levels.WARN) --- end, 0) --- end --- end --- else --- vim.defer_fn(function() --- vim.notify('Failed to get package: ' .. tool, vim.log.levels.WARN) --- end, 0) --- end --- end --- end) +local ensure_installed = { + -- 'clang-format', embeded in clangd + 'stylua', +} +-- call mason-registry function to install or ensure formatters/linters are installed +local mr = require('mason-registry') +mr.refresh(function() + for _, tool in ipairs(ensure_installed) do + ok, result = pcall(mr.get_package, tool) + if ok and result then + if not result:is_installed() then + if not result:is_installing() then + result:install({}, function(success, _) + if not success then + vim.defer_fn(function() + vim.notify(tool .. ' failed to install', vim.log.levels.ERROR) + end, 0) + end + end) + else + vim.defer_fn(function() + vim.notify(tool .. ' already installed', vim.log.levels.WARN) + end, 0) + end + end + else + vim.defer_fn(function() + vim.notify('Failed to get package: ' .. tool, vim.log.levels.WARN) + end, 0) + end + end +end) -- require('mason-lspconfig').setup({ ---------------------------------------------------------------------------------------- @@ -71,7 +70,7 @@ end local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') if mok then mason_lspconfig.setup({ - ensure_installed = { 'clangd', 'lua_ls' }, + ensure_installed = { 'clangd', 'lua_ls', 'pyrefly' }, automatic_enable = true, -- this will automatically enable LSP servers after lsp.config }) end @@ -172,6 +171,20 @@ local lua_ls = { } vim.lsp.config('lua_ls', lua_ls) +local pyrefly = { + name = 'pyrefly', + cmd = { 'pyrefly', 'lsp' }, + filetypes = { 'python' }, + root_markers = { 'pyrefly.toml', 'pyproject.toml', 'setup.py', 'setup.cfg', 'requirements.txt', 'Pipfile', '.git' }, + settings = { + python = { + pythonPath = vim.env.VIRTUAL_ENV, + -- venvPath = vim.env.VIRTUAL_ENV, + }, + }, +} +vim.lsp.config('pyrefly', pyrefly) + ---------------------------------------------------------------------------------------- -- INFO: create clangd required files ----------------------------------------------------------------------------------------- @@ -180,6 +193,7 @@ boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) +boilerplate_gen([[stylua.toml]], vim.g.platformioRootDir) -- require('platformio.piolsp').piolsp() if vim.fn.has('nvim-0.12') then From 58dbfec15145d3376cc0d05678d894384e919149 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 07:08:51 +0300 Subject: [PATCH 0183/1406] update --- lua/platformio/lspClangd.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 99a5362b..91a0fa9f 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -136,6 +136,7 @@ local lua_ls = { 'selene.yml', '.git', }, + capabilities = capabilities, settings = { Lua = { hint = { From 078950ae3f2255f2379ce058dc3b9c2f406e029b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 07:19:38 +0300 Subject: [PATCH 0184/1406] update --- lua/platformio/lspClangd.lua | 64 ++++++++++++++++++------------------ 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 91a0fa9f..7e335f39 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -30,38 +30,38 @@ if ok then end -- List of packages you want Mason to ensure are installed -local ensure_installed = { - -- 'clang-format', embeded in clangd - 'stylua', -} --- call mason-registry function to install or ensure formatters/linters are installed -local mr = require('mason-registry') -mr.refresh(function() - for _, tool in ipairs(ensure_installed) do - ok, result = pcall(mr.get_package, tool) - if ok and result then - if not result:is_installed() then - if not result:is_installing() then - result:install({}, function(success, _) - if not success then - vim.defer_fn(function() - vim.notify(tool .. ' failed to install', vim.log.levels.ERROR) - end, 0) - end - end) - else - vim.defer_fn(function() - vim.notify(tool .. ' already installed', vim.log.levels.WARN) - end, 0) - end - end - else - vim.defer_fn(function() - vim.notify('Failed to get package: ' .. tool, vim.log.levels.WARN) - end, 0) - end - end -end) +-- local ensure_installed = { +-- -- 'clang-format', embeded in clangd +-- 'stylua', +-- } +-- -- call mason-registry function to install or ensure formatters/linters are installed +-- local mr = require('mason-registry') +-- mr.refresh(function() +-- for _, tool in ipairs(ensure_installed) do +-- ok, result = pcall(mr.get_package, tool) +-- if ok and result then +-- if not result:is_installed() then +-- if not result:is_installing() then +-- result:install({}, function(success, _) +-- if not success then +-- vim.defer_fn(function() +-- vim.notify(tool .. ' failed to install', vim.log.levels.ERROR) +-- end, 0) +-- end +-- end) +-- else +-- vim.defer_fn(function() +-- vim.notify(tool .. ' already installed', vim.log.levels.WARN) +-- end, 0) +-- end +-- end +-- else +-- vim.defer_fn(function() +-- vim.notify('Failed to get package: ' .. tool, vim.log.levels.WARN) +-- end, 0) +-- end +-- end +-- end) -- require('mason-lspconfig').setup({ ---------------------------------------------------------------------------------------- From 747f795867ad466360fb48e3cc0293034b4fdf83 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 07:24:39 +0300 Subject: [PATCH 0185/1406] update --- lua/platformio/lspAttach.lua | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 48ad3034..012a0787 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -11,6 +11,9 @@ vim.api.nvim_create_autocmd('LspAttach', { -- print('Attaching to: ' .. client.name .. ' attached to buffer ' .. bufnr) vim.api.nvim_echo({ { 'Attaching to: ' .. client.name .. ' attached to buffer ' .. bufnr, 'Info' } }, true, {}) + if client.name == 'lua_ls' then + client.server_capabilities.documentFormattingProvider = false + end ------------------------------------------------------------------ if client.name == 'clangd' then vim.api.nvim_buf_create_user_command(0, 'LspClangdSwitchSourceHeader', function() From 11cb0bf815dfbe6d7258421cc34c7506ecbc4d17 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 07:44:43 +0300 Subject: [PATCH 0186/1406] update --- lua/platformio/lspClangd.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 7e335f39..4bf978db 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -91,7 +91,8 @@ end local capabilities = vim.lsp.protocol.make_client_capabilities() local bok, blink = pcall(require, 'blink.cmp') if bok then - capabilities = vim.tbl_deep_extend('force', capabilities, blink.get_lsp_capabilities({}, false)) + -- capabilities = vim.tbl_deep_extend('force', capabilities, blink.get_lsp_capabilities({}, false)) + capabilities = blink.get_lsp_capabilities(capabilities) end local clangd = { From 31e97311ec8ab93a6a6e33e4dd4683bca9b521e4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 07:50:00 +0300 Subject: [PATCH 0187/1406] update --- lua/platformio/lspAttach.lua | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 012a0787..731f92eb 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -14,6 +14,7 @@ vim.api.nvim_create_autocmd('LspAttach', { if client.name == 'lua_ls' then client.server_capabilities.documentFormattingProvider = false end + print('lua_ls 0') ------------------------------------------------------------------ if client.name == 'clangd' then vim.api.nvim_buf_create_user_command(0, 'LspClangdSwitchSourceHeader', function() @@ -31,6 +32,7 @@ vim.api.nvim_create_autocmd('LspAttach', { end, bufnr) end, { desc = 'Switch between source/header' }) end + print('lua_ls 1') -- if client and client.server_capabilities.completionProvider then -- if client:supports_method('textDocument/completion', { bufnr = bufnr }) then @@ -49,17 +51,20 @@ vim.api.nvim_create_autocmd('LspAttach', { end) end end + print('lua_ls 2') -- Inlay hints if client:supports_method('textDocument/inlayHints') then vim.lsp.inlay_hint.enable(true, { bufnr = args.buf }) end + print('lua_ls 3') if client:supports_method('textDocument/documentColor') then vim.lsp.document_color.enable(true, args.buf, { style = 'background', -- 'background', 'foreground', or 'virtual' }) end + print('lua_ls 4') ------------------------------------------------------------------ if client:supports_method('documentHighlightProvider') then @@ -85,6 +90,7 @@ vim.api.nvim_create_autocmd('LspAttach', { }) -- end + print('lua_ls 5') ------------------------------------------------------------------ local config = require('platformio').config @@ -93,9 +99,11 @@ vim.api.nvim_create_autocmd('LspAttach', { lspkeymaps.lspKeymaps(client, bufnr) end end + print('lua_ls 6') ------------------------------------------------------------------ vim.cmd([[autocmd FileType * set formatoptions-=ro]]) + print('lua_ls 7') -- end, }) From 3634137353a44d3f52069e7fd39d1eeaceb9e12f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 07:59:42 +0300 Subject: [PATCH 0188/1406] update --- lua/platformio/lspAttach.lua | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 731f92eb..b85f213b 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -60,8 +60,10 @@ vim.api.nvim_create_autocmd('LspAttach', { print('lua_ls 3') if client:supports_method('textDocument/documentColor') then - vim.lsp.document_color.enable(true, args.buf, { - style = 'background', -- 'background', 'foreground', or 'virtual' + -- vim.lsp.document_color.enable(true, args.buf, { style = 'background', -- 'background', 'foreground', or 'virtual' }) + vim.lsp.document_color.enable(true, { + bufnr = bufnr, + style = 'inline', -- This is the modern 0.11 way to show color icons }) end print('lua_ls 4') From b11642f18119d8cd343242150c40ac29b4242c78 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 08:25:18 +0300 Subject: [PATCH 0189/1406] update --- lua/platformio/lspAttach.lua | 34 ++++++++++++++++++++++------------ lua/platformio/lspClangd.lua | 23 ++++++++++++++--------- 2 files changed, 36 insertions(+), 21 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index b85f213b..9b678de4 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -12,9 +12,11 @@ vim.api.nvim_create_autocmd('LspAttach', { vim.api.nvim_echo({ { 'Attaching to: ' .. client.name .. ' attached to buffer ' .. bufnr, 'Info' } }, true, {}) if client.name == 'lua_ls' then - client.server_capabilities.documentFormattingProvider = false + -- client.server_capabilities.documentFormattingProvider = false + if client:supports_method('textDocument/formatting') then + end end - print('lua_ls 0') + -- print('lua_ls 0') ------------------------------------------------------------------ if client.name == 'clangd' then vim.api.nvim_buf_create_user_command(0, 'LspClangdSwitchSourceHeader', function() @@ -32,7 +34,6 @@ vim.api.nvim_create_autocmd('LspAttach', { end, bufnr) end, { desc = 'Switch between source/header' }) end - print('lua_ls 1') -- if client and client.server_capabilities.completionProvider then -- if client:supports_method('textDocument/completion', { bufnr = bufnr }) then @@ -42,8 +43,6 @@ vim.api.nvim_create_autocmd('LspAttach', { if client:supports_method('textDocument/completion') then vim.opt.completeopt = { 'menu', 'menuone', 'noselect', 'noinsert', 'fuzzy', 'popup' } - print('completion enabled') - -- Enable native completion for this specific client and buffer vim.lsp.completion.enable(true, client.id, args.buf, { autotrigger = true }) vim.keymap.set('i', ' End LspAttach autocommand diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 4bf978db..df2a8f3a 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -75,6 +75,18 @@ if mok then }) end +local capabilities = vim.lsp.protocol.make_client_capabilities() +local bok, blink = pcall(require, 'blink.cmp') +if bok then + -- capabilities = vim.tbl_deep_extend('force', capabilities, blink.get_lsp_capabilities({}, false)) + capabilities = blink.get_lsp_capabilities(capabilities) +end + +-- INFO: 1 +vim.lsp.config('*', { + capabilities = capabilities, + root_markers = { '.git' }, +}) ---------------------------------------------------------------------------------------- -- INFO: configure clangd lsp server ----------------------------------------------------------------------------------------- @@ -88,13 +100,6 @@ if vim.fn.filereadable(fname) == 1 then end end -local capabilities = vim.lsp.protocol.make_client_capabilities() -local bok, blink = pcall(require, 'blink.cmp') -if bok then - -- capabilities = vim.tbl_deep_extend('force', capabilities, blink.get_lsp_capabilities({}, false)) - capabilities = blink.get_lsp_capabilities(capabilities) -end - local clangd = { cmd = cmd, filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, @@ -109,7 +114,7 @@ local clangd = { '.git', vim.uv.cwd(), }, - capabilities = capabilities, + -- capabilities = capabilities, workspace_required = true, single_file_support = true, init_options = { @@ -137,7 +142,7 @@ local lua_ls = { 'selene.yml', '.git', }, - capabilities = capabilities, + -- capabilities = capabilities, settings = { Lua = { hint = { From 867afef636f4125b55a19e63af6eaf3b40eb4e64 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 08:51:17 +0300 Subject: [PATCH 0190/1406] update --- lua/platformio/lspAttach.lua | 45 ++++++++++++++++++++++++------------ lua/platformio/lspClangd.lua | 6 ++--- 2 files changed, 32 insertions(+), 19 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 9b678de4..e72c6a22 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -11,11 +11,20 @@ vim.api.nvim_create_autocmd('LspAttach', { -- print('Attaching to: ' .. client.name .. ' attached to buffer ' .. bufnr) vim.api.nvim_echo({ { 'Attaching to: ' .. client.name .. ' attached to buffer ' .. bufnr, 'Info' } }, true, {}) - if client.name == 'lua_ls' then - -- client.server_capabilities.documentFormattingProvider = false - if client:supports_method('textDocument/formatting') then - end - end + -- if client.name == 'lua_ls' then + -- -- client.server_capabilities.documentFormattingProvider = false + -- if client:supports_method('textDocument/formatting') then + -- vim.lsp.buf.format({ + -- bufnr = bufnr, + -- async = false, + -- timeout_ms = 10000, + -- id = client.id, + -- filter = function(c) + -- return c.id == client.id + -- end, + -- }) + -- end + -- end -- print('lua_ls 0') ------------------------------------------------------------------ if client.name == 'clangd' then @@ -104,20 +113,26 @@ vim.api.nvim_create_autocmd('LspAttach', { }) -- Native StyLua Formatting (0.11 Safe) -vim.api.nvim_create_autocmd("BufWritePre", { - pattern = "*.lua", +vim.api.nvim_create_autocmd('BufWritePre', { + pattern = '*.lua', callback = function(args) - if vim.fn.executable("stylua") == 1 then - vim.fn.system({ "stylua", vim.api.nvim_buf_get_name(args.buf) }) - vim.cmd("checktime") - else + local client = assert(vim.lsp.get_client_by_id(args.data.client_id)) + local bufnr = args.buf + if vim.fn.executable('stylua') == 1 then + vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(args.buf) }) + vim.cmd('checktime') + else -- Fallback to LSP formatting if stylua isn't found - vim.lsp.buf.format({ - bufnr = args.buf, - filter = function(client) return client.name == "lua_ls" end + vim.lsp.buf.format({ + bufnr = bufnr, + async = false, + timeout_ms = 10000, + id = client.id, + filter = function(c) + return c.id == client.id + end, }) end - end end, }) -- --> End LspAttach autocommand diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index df2a8f3a..d86658a4 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -78,8 +78,8 @@ end local capabilities = vim.lsp.protocol.make_client_capabilities() local bok, blink = pcall(require, 'blink.cmp') if bok then - -- capabilities = vim.tbl_deep_extend('force', capabilities, blink.get_lsp_capabilities({}, false)) - capabilities = blink.get_lsp_capabilities(capabilities) + capabilities = vim.tbl_deep_extend('force', capabilities, blink.get_lsp_capabilities({}, false)) + -- capabilities = blink.get_lsp_capabilities(capabilities) end -- INFO: 1 @@ -114,7 +114,6 @@ local clangd = { '.git', vim.uv.cwd(), }, - -- capabilities = capabilities, workspace_required = true, single_file_support = true, init_options = { @@ -142,7 +141,6 @@ local lua_ls = { 'selene.yml', '.git', }, - -- capabilities = capabilities, settings = { Lua = { hint = { From 59b9e8769fbf2152520a4f38561fd6e47e28ce1c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 09:13:41 +0300 Subject: [PATCH 0191/1406] update --- lua/platformio/lspAttach.lua | 48 ++++++++++++++++++----------------- lua/platformio/lspKeymaps.lua | 23 ++++++++++------- 2 files changed, 39 insertions(+), 32 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index e72c6a22..6099d214 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -112,27 +112,29 @@ vim.api.nvim_create_autocmd('LspAttach', { end, }) --- Native StyLua Formatting (0.11 Safe) -vim.api.nvim_create_autocmd('BufWritePre', { - pattern = '*.lua', - callback = function(args) - local client = assert(vim.lsp.get_client_by_id(args.data.client_id)) - local bufnr = args.buf - if vim.fn.executable('stylua') == 1 then - vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(args.buf) }) - vim.cmd('checktime') - else - -- Fallback to LSP formatting if stylua isn't found - vim.lsp.buf.format({ - bufnr = bufnr, - async = false, - timeout_ms = 10000, - id = client.id, - filter = function(c) - return c.id == client.id - end, - }) - end - end, -}) +-- -- Native StyLua Formatting (0.11 Safe) +-- vim.api.nvim_create_autocmd('BufWritePre', { +-- pattern = '*.lua', +-- callback = function(args) +-- local bufnr = args.buf +-- if vim.fn.executable('stylua') == 1 then +-- vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(args.buf) }) +-- vim.cmd('checktime') +-- else +-- -- Fallback to LSP formatting if stylua isn't found +-- vim.lsp.buf.format({ +-- bufnr = bufnr, +-- async = false, +-- timeout_ms = 10000, +-- id = client.id, +-- filter = function(client) +-- return client.name == 'lua_ls' +-- end, +-- -- filter = function(c) +-- -- return c.id == client.id +-- -- end, +-- }) +-- end +-- end, +-- }) -- --> End LspAttach autocommand diff --git a/lua/platformio/lspKeymaps.lua b/lua/platformio/lspKeymaps.lua index 04280519..b30e7206 100644 --- a/lua/platformio/lspKeymaps.lua +++ b/lua/platformio/lspKeymaps.lua @@ -103,15 +103,20 @@ function K.lspKeymaps(client, bufnr) group = fmt_group, desc = 'Fromat current buffer', callback = function() - vim.lsp.buf.format({ - bufnr = bufnr, - async = false, - timeout_ms = 10000, - id = client.id, - filter = function(c) - return c.id == client.id - end, - }) + if (client.name == 'lua_ls') and (vim.fn.executable('stylua') == 1) then + vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(bufnr) }) + vim.cmd('checktime') + else + vim.lsp.buf.format({ + bufnr = bufnr, + async = false, + timeout_ms = 10000, + id = client.id, + filter = function(c) + return c.id == client.id + end, + }) + end end, }) end From 1f29d4c8da54c3cc6cc162280eef7d515d2d178c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 09:20:08 +0300 Subject: [PATCH 0192/1406] update --- lua/platformio/lspAttach.lua | 26 -------------------------- lua/platformio/lspKeymaps.lua | 2 ++ 2 files changed, 2 insertions(+), 26 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 6099d214..7456dfdd 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -111,30 +111,4 @@ vim.api.nvim_create_autocmd('LspAttach', { -- end, }) - --- -- Native StyLua Formatting (0.11 Safe) --- vim.api.nvim_create_autocmd('BufWritePre', { --- pattern = '*.lua', --- callback = function(args) --- local bufnr = args.buf --- if vim.fn.executable('stylua') == 1 then --- vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(args.buf) }) --- vim.cmd('checktime') --- else --- -- Fallback to LSP formatting if stylua isn't found --- vim.lsp.buf.format({ --- bufnr = bufnr, --- async = false, --- timeout_ms = 10000, --- id = client.id, --- filter = function(client) --- return client.name == 'lua_ls' --- end, --- -- filter = function(c) --- -- return c.id == client.id --- -- end, --- }) --- end --- end, --- }) -- --> End LspAttach autocommand diff --git a/lua/platformio/lspKeymaps.lua b/lua/platformio/lspKeymaps.lua index b30e7206..f47eff5c 100644 --- a/lua/platformio/lspKeymaps.lua +++ b/lua/platformio/lspKeymaps.lua @@ -106,6 +106,7 @@ function K.lspKeymaps(client, bufnr) if (client.name == 'lua_ls') and (vim.fn.executable('stylua') == 1) then vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(bufnr) }) vim.cmd('checktime') + print('stylua formatting') else vim.lsp.buf.format({ bufnr = bufnr, @@ -116,6 +117,7 @@ function K.lspKeymaps(client, bufnr) return c.id == client.id end, }) + print('lsp formatting') end end, }) From 20920cfc365449d8a137c43755fd0b21d972d5ee Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 09:22:29 +0300 Subject: [PATCH 0193/1406] update --- lua/platformio/lspClangd.lua | 65 ++++++++++++++++++------------------ 1 file changed, 32 insertions(+), 33 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index d86658a4..f99d3aeb 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -30,40 +30,39 @@ if ok then end -- List of packages you want Mason to ensure are installed --- local ensure_installed = { --- -- 'clang-format', embeded in clangd --- 'stylua', --- } --- -- call mason-registry function to install or ensure formatters/linters are installed --- local mr = require('mason-registry') --- mr.refresh(function() --- for _, tool in ipairs(ensure_installed) do --- ok, result = pcall(mr.get_package, tool) --- if ok and result then --- if not result:is_installed() then --- if not result:is_installing() then --- result:install({}, function(success, _) --- if not success then --- vim.defer_fn(function() --- vim.notify(tool .. ' failed to install', vim.log.levels.ERROR) --- end, 0) --- end --- end) --- else --- vim.defer_fn(function() --- vim.notify(tool .. ' already installed', vim.log.levels.WARN) --- end, 0) --- end --- end --- else --- vim.defer_fn(function() --- vim.notify('Failed to get package: ' .. tool, vim.log.levels.WARN) --- end, 0) --- end --- end --- end) +local ensure_installed = { + -- 'clang-format', embeded in clangd + 'stylua', +} +-- call mason-registry function to install or ensure formatters/linters are installed +local mr = require('mason-registry') +mr.refresh(function() + for _, tool in ipairs(ensure_installed) do + ok, result = pcall(mr.get_package, tool) + if ok and result then + if not result:is_installed() then + if not result:is_installing() then + result:install({}, function(success, _) + if not success then + vim.defer_fn(function() + vim.notify(tool .. ' failed to install', vim.log.levels.ERROR) + end, 0) + end + end) + else + vim.defer_fn(function() + vim.notify(tool .. ' already installed', vim.log.levels.WARN) + end, 0) + end + end + else + vim.defer_fn(function() + vim.notify('Failed to get package: ' .. tool, vim.log.levels.WARN) + end, 0) + end + end +end) --- require('mason-lspconfig').setup({ ---------------------------------------------------------------------------------------- -- INFO: install clangd using mason-lspconfig ----------------------------------------------------------------------------------------- From cd378cbb1f58a4d3150742bf850338298cde6620 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 09:27:43 +0300 Subject: [PATCH 0194/1406] update --- lua/platformio/boilerplate.lua | 4 ++-- lua/platformio/lspClangd.lua | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 19b355fd..edf6a755 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -337,8 +337,8 @@ Diagnostics: ]], } -boilerplate['stylua.toml'] = { - filename = 'stylua.toml', +boilerplate['.stylua.toml'] = { + filename = '.stylua.toml', content = [[ syntax = "All" column_width = 132 diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index f99d3aeb..df39e207 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -197,7 +197,7 @@ boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) -boilerplate_gen([[stylua.toml]], vim.g.platformioRootDir) +boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) -- require('platformio.piolsp').piolsp() if vim.fn.has('nvim-0.12') then From d2964178e5a9e62e7cba73f73ddd1d7b4ca852b4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 09:44:12 +0300 Subject: [PATCH 0195/1406] update --- lua/platformio/lspClangd.lua | 95 ++++++++++++++++++------------------ 1 file changed, 48 insertions(+), 47 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index df39e207..48fabf05 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -69,7 +69,8 @@ end) local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') if mok then mason_lspconfig.setup({ - ensure_installed = { 'clangd', 'lua_ls', 'pyrefly' }, + ensure_installed = { 'clangd', 'pyrefly' }, + -- ensure_installed = { 'clangd', 'lua_ls', 'pyrefly' }, automatic_enable = true, -- this will automatically enable LSP servers after lsp.config }) end @@ -128,52 +129,52 @@ vim.lsp.config('clangd', clangd) ---------------------------------------------------------------------------------------- -- INFO: configure clangd lsp server ----------------------------------------------------------------------------------------- -local lua_ls = { - cmd = { 'lua-language-server' }, - filetypes = { 'lua' }, - root_markers = { - '.luarc.json', - '.luarc.jsonc', - '.luacheckrc', - '.stylua.toml', - 'selene.toml', - 'selene.yml', - '.git', - }, - settings = { - Lua = { - hint = { - enable = true, - arrayIndex = 'Enable', - await = true, - paramName = 'All', - paramType = true, - semicolon = 'Disable', - setType = true, - }, - telemetry = { enable = false }, - diagnostics = { globals = { 'vim' } }, - runtime = { - -- Specify LuaJIT for Neovim - version = 'LuaJIT', - -- Include Neovim runtime files - path = vim.split(package.path, ';'), - }, - workspace = { - checkThirdParty = false, - library = { - vim.env.VIMRUNTIME, - '${3rd}/luv/library', - './lua', - vim.api.nvim_get_runtime_file('', true), - -- Depending on the usage, you might want to add additional paths here. - -- "${3rd}/busted/library", - }, - }, - }, - }, -} -vim.lsp.config('lua_ls', lua_ls) +-- local lua_ls = { +-- cmd = { 'lua-language-server' }, +-- filetypes = { 'lua' }, +-- root_markers = { +-- '.luarc.json', +-- '.luarc.jsonc', +-- '.luacheckrc', +-- '.stylua.toml', +-- 'selene.toml', +-- 'selene.yml', +-- '.git', +-- }, +-- settings = { +-- Lua = { +-- hint = { +-- enable = true, +-- arrayIndex = 'Enable', +-- await = true, +-- paramName = 'All', +-- paramType = true, +-- semicolon = 'Disable', +-- setType = true, +-- }, +-- telemetry = { enable = false }, +-- diagnostics = { globals = { 'vim' } }, +-- runtime = { +-- -- Specify LuaJIT for Neovim +-- version = 'LuaJIT', +-- -- Include Neovim runtime files +-- path = vim.split(package.path, ';'), +-- }, +-- workspace = { +-- checkThirdParty = false, +-- library = { +-- vim.env.VIMRUNTIME, +-- '${3rd}/luv/library', +-- './lua', +-- vim.api.nvim_get_runtime_file('', true), +-- -- Depending on the usage, you might want to add additional paths here. +-- -- "${3rd}/busted/library", +-- }, +-- }, +-- }, +-- }, +-- } +-- vim.lsp.config('lua_ls', lua_ls) local pyrefly = { name = 'pyrefly', From 481fff5b5aac65b5cedb052e65e77e0e114a685b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 10:26:55 +0300 Subject: [PATCH 0196/1406] update --- lua/platformio/lspClangd.lua | 21 ++++++++++++++++++--- mini_nvimPlatformio.lua | 13 ++++++++++++- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 48fabf05..2dd21710 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -75,11 +75,19 @@ if mok then }) end -local capabilities = vim.lsp.protocol.make_client_capabilities() +local capabilities = vim.lsp.protocol.make_client_capabilities({ + textDocument = { + -- Folding capabilities for nvim-ufo + foldingRange = { + dynamicRegistration = false, + lineFoldingOnly = true, + }, + }, +}) local bok, blink = pcall(require, 'blink.cmp') if bok then - capabilities = vim.tbl_deep_extend('force', capabilities, blink.get_lsp_capabilities({}, false)) - -- capabilities = blink.get_lsp_capabilities(capabilities) + -- capabilities = vim.tbl_deep_extend('force', capabilities, blink.get_lsp_capabilities({}, false)) + capabilities = blink.get_lsp_capabilities(capabilities) end -- INFO: 1 @@ -176,6 +184,13 @@ vim.lsp.config('clangd', clangd) -- } -- vim.lsp.config('lua_ls', lua_ls) +local stylua = { + cmd = { 'stylua', '--search-parent-directories', '--stdin-filepath', '$FILENAME', '-' }, + filetypes = { 'lua' }, + root_markers = { 'stylua.toml', '.stylua.toml', '.git' }, +} +vim.lsp.enable('stylua') + local pyrefly = { name = 'pyrefly', cmd = { 'pyrefly', 'lsp' }, diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 18528e68..492e9c42 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -11,6 +11,7 @@ vim.opt.termguicolors = true vim.opt['number'] = true vim.opt.autowrite = true -- Enable auto write + -- only set clipboard if not in ssh, to make sure the OSC 52 -- integration works automatically. Requires Neovim >= 0.10.0 vim.opt.clipboard = vim.env.SSH_TTY and '' or 'unnamedplus' -- Sync with system clipboard @@ -21,7 +22,17 @@ vim.opt.shiftround = true -- Round indent vim.opt.shiftwidth = 2 -- Size of an indent vim.opt.smartindent = true -- Insert indents automatically vim.opt.expandtab = true -- Use spaces instead of tabs -vim.opt.clipboard = vim.env.SSH_TTY and '' or 'unnamedplus' -- Sync with system clipboard + +vim.opt.smoothscroll = true +vim.opt.foldmethod = 'expr' +vim.opt.foldtext = '' +vim.opt.fillchars = '' +vim.opt.foldcolumn = '0' +vim.opt.foldenable = true +vim.opt.foldexpr = 'v:lua.vim.treesitter.foldexpr()' +vim.opt.foldlevel = 99 +vim.opt.foldlevelstart = 99 +vim.opt.foldnestmax = 3 vim.g.have_nerd_font = true vim.g.mapleader = ' ' From 8c7ee45bcca4125d21a770bcb7d86fc9bec83314 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 10:30:26 +0300 Subject: [PATCH 0197/1406] update --- lua/platformio/lspKeymaps.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/lspKeymaps.lua b/lua/platformio/lspKeymaps.lua index f47eff5c..1b106c93 100644 --- a/lua/platformio/lspKeymaps.lua +++ b/lua/platformio/lspKeymaps.lua @@ -103,7 +103,8 @@ function K.lspKeymaps(client, bufnr) group = fmt_group, desc = 'Fromat current buffer', callback = function() - if (client.name == 'lua_ls') and (vim.fn.executable('stylua') == 1) then + -- if (client.name == 'lua_ls') and (vim.fn.executable('stylua') == 1) then + if (client.name == 'stylua') and (vim.fn.executable('stylua') == 1) then vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(bufnr) }) vim.cmd('checktime') print('stylua formatting') From fc74ac737ae56bf1cd93aa063df71bdb81405399 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 10:33:03 +0300 Subject: [PATCH 0198/1406] update --- lua/platformio/lspClangd.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 2dd21710..e160841d 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -189,6 +189,7 @@ local stylua = { filetypes = { 'lua' }, root_markers = { 'stylua.toml', '.stylua.toml', '.git' }, } +vim.lsp.config('stylua', stylua) vim.lsp.enable('stylua') local pyrefly = { From 29e66cf986311e32644a3722e6b15d7c07a497ab Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 10:39:09 +0300 Subject: [PATCH 0199/1406] update --- lua/platformio/lspKeymaps.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspKeymaps.lua b/lua/platformio/lspKeymaps.lua index 1b106c93..299bdc84 100644 --- a/lua/platformio/lspKeymaps.lua +++ b/lua/platformio/lspKeymaps.lua @@ -103,8 +103,8 @@ function K.lspKeymaps(client, bufnr) group = fmt_group, desc = 'Fromat current buffer', callback = function() - -- if (client.name == 'lua_ls') and (vim.fn.executable('stylua') == 1) then - if (client.name == 'stylua') and (vim.fn.executable('stylua') == 1) then + if (client.name == 'lua_ls') and (vim.fn.executable('stylua') == 1) then + -- if (client.name == 'stylua') and (vim.fn.executable('stylua') == 1) then vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(bufnr) }) vim.cmd('checktime') print('stylua formatting') From a1be0519076df6d540f751fa469fe6cfca7f76d6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 10:44:50 +0300 Subject: [PATCH 0200/1406] update --- lua/platformio/lspClangd.lua | 96 +++++++++++++++++------------------ lua/platformio/lspKeymaps.lua | 5 +- 2 files changed, 51 insertions(+), 50 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index e160841d..ec4b4588 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -69,8 +69,8 @@ end) local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') if mok then mason_lspconfig.setup({ - ensure_installed = { 'clangd', 'pyrefly' }, - -- ensure_installed = { 'clangd', 'lua_ls', 'pyrefly' }, + -- ensure_installed = { 'clangd', 'pyrefly' }, + ensure_installed = { 'clangd', 'lua_ls', 'pyrefly' }, automatic_enable = true, -- this will automatically enable LSP servers after lsp.config }) end @@ -137,52 +137,52 @@ vim.lsp.config('clangd', clangd) ---------------------------------------------------------------------------------------- -- INFO: configure clangd lsp server ----------------------------------------------------------------------------------------- --- local lua_ls = { --- cmd = { 'lua-language-server' }, --- filetypes = { 'lua' }, --- root_markers = { --- '.luarc.json', --- '.luarc.jsonc', --- '.luacheckrc', --- '.stylua.toml', --- 'selene.toml', --- 'selene.yml', --- '.git', --- }, --- settings = { --- Lua = { --- hint = { --- enable = true, --- arrayIndex = 'Enable', --- await = true, --- paramName = 'All', --- paramType = true, --- semicolon = 'Disable', --- setType = true, --- }, --- telemetry = { enable = false }, --- diagnostics = { globals = { 'vim' } }, --- runtime = { --- -- Specify LuaJIT for Neovim --- version = 'LuaJIT', --- -- Include Neovim runtime files --- path = vim.split(package.path, ';'), --- }, --- workspace = { --- checkThirdParty = false, --- library = { --- vim.env.VIMRUNTIME, --- '${3rd}/luv/library', --- './lua', --- vim.api.nvim_get_runtime_file('', true), --- -- Depending on the usage, you might want to add additional paths here. --- -- "${3rd}/busted/library", --- }, --- }, --- }, --- }, --- } --- vim.lsp.config('lua_ls', lua_ls) +local lua_ls = { + cmd = { 'lua-language-server' }, + filetypes = { 'lua' }, + root_markers = { + '.luarc.json', + '.luarc.jsonc', + '.luacheckrc', + '.stylua.toml', + 'selene.toml', + 'selene.yml', + '.git', + }, + settings = { + Lua = { + hint = { + enable = true, + arrayIndex = 'Enable', + await = true, + paramName = 'All', + paramType = true, + semicolon = 'Disable', + setType = true, + }, + telemetry = { enable = false }, + diagnostics = { globals = { 'vim' } }, + runtime = { + -- Specify LuaJIT for Neovim + version = 'LuaJIT', + -- Include Neovim runtime files + path = vim.split(package.path, ';'), + }, + workspace = { + checkThirdParty = false, + library = { + vim.env.VIMRUNTIME, + '${3rd}/luv/library', + './lua', + vim.api.nvim_get_runtime_file('', true), + -- Depending on the usage, you might want to add additional paths here. + -- "${3rd}/busted/library", + }, + }, + }, + }, +} +vim.lsp.config('lua_ls', lua_ls) local stylua = { cmd = { 'stylua', '--search-parent-directories', '--stdin-filepath', '$FILENAME', '-' }, diff --git a/lua/platformio/lspKeymaps.lua b/lua/platformio/lspKeymaps.lua index 299bdc84..b62f96d6 100644 --- a/lua/platformio/lspKeymaps.lua +++ b/lua/platformio/lspKeymaps.lua @@ -102,10 +102,11 @@ function K.lspKeymaps(client, bufnr) buffer = bufnr, group = fmt_group, desc = 'Fromat current buffer', - callback = function() + callback = function(args) if (client.name == 'lua_ls') and (vim.fn.executable('stylua') == 1) then -- if (client.name == 'stylua') and (vim.fn.executable('stylua') == 1) then - vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(bufnr) }) + -- vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(bufnr) }) + vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(args.buf) }) vim.cmd('checktime') print('stylua formatting') else From c5676cad3924bf3d969bb70a4a27962a0b9eae63 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 10:58:27 +0300 Subject: [PATCH 0201/1406] update --- lua/platformio/lspClangd.lua | 16 ++++++++-------- lua/platformio/lspKeymaps.lua | 36 +++++++++++++++++------------------ 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index ec4b4588..9875b678 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -32,7 +32,7 @@ end -- List of packages you want Mason to ensure are installed local ensure_installed = { -- 'clang-format', embeded in clangd - 'stylua', + -- 'stylua', } -- call mason-registry function to install or ensure formatters/linters are installed local mr = require('mason-registry') @@ -184,13 +184,13 @@ local lua_ls = { } vim.lsp.config('lua_ls', lua_ls) -local stylua = { - cmd = { 'stylua', '--search-parent-directories', '--stdin-filepath', '$FILENAME', '-' }, - filetypes = { 'lua' }, - root_markers = { 'stylua.toml', '.stylua.toml', '.git' }, -} -vim.lsp.config('stylua', stylua) -vim.lsp.enable('stylua') +-- local stylua = { +-- cmd = { 'stylua', '--search-parent-directories', '--stdin-filepath', '$FILENAME', '-' }, +-- filetypes = { 'lua' }, +-- root_markers = { 'stylua.toml', '.stylua.toml', '.git' }, +-- } +-- vim.lsp.config('stylua', stylua) +-- vim.lsp.enable('stylua') local pyrefly = { name = 'pyrefly', diff --git a/lua/platformio/lspKeymaps.lua b/lua/platformio/lspKeymaps.lua index b62f96d6..cb58c3ba 100644 --- a/lua/platformio/lspKeymaps.lua +++ b/lua/platformio/lspKeymaps.lua @@ -103,24 +103,24 @@ function K.lspKeymaps(client, bufnr) group = fmt_group, desc = 'Fromat current buffer', callback = function(args) - if (client.name == 'lua_ls') and (vim.fn.executable('stylua') == 1) then - -- if (client.name == 'stylua') and (vim.fn.executable('stylua') == 1) then - -- vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(bufnr) }) - vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(args.buf) }) - vim.cmd('checktime') - print('stylua formatting') - else - vim.lsp.buf.format({ - bufnr = bufnr, - async = false, - timeout_ms = 10000, - id = client.id, - filter = function(c) - return c.id == client.id - end, - }) - print('lsp formatting') - end + -- if (client.name == 'lua_ls') and (vim.fn.executable('stylua') == 1) then + -- -- if (client.name == 'stylua') and (vim.fn.executable('stylua') == 1) then + -- -- vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(bufnr) }) + -- vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(args.buf) }) + -- vim.cmd('checktime') + -- print('stylua formatting') + -- else + vim.lsp.buf.format({ + bufnr = bufnr, + async = false, + timeout_ms = 10000, + id = client.id, + filter = function(c) + return c.id == client.id + end, + }) + print('lsp formatting') + -- end end, }) end From 98183478bef3813fced32aa7cebd7c1ed1893a45 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 11:22:10 +0300 Subject: [PATCH 0202/1406] update --- lua/platformio/piolsp.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index d0bf6747..8c227680 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -35,7 +35,8 @@ function M.piolsp() gitignore_lsp_configs('compile_commands.json') if vim.fn.has('nvim-0.12') then - if #vim.lsp.get_clients() > 0 then + -- if #vim.lsp.get_clients() > 0 then + if next(vim.lsp.get_clients()) ~= nil then vim.cmd('lsp restart') end else From b4d8dc6312772ef4864594988ac408f9c61baea0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 11:32:15 +0300 Subject: [PATCH 0203/1406] update --- lua/platformio/piolsp.lua | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 8c227680..6577461c 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -36,8 +36,11 @@ function M.piolsp() if vim.fn.has('nvim-0.12') then -- if #vim.lsp.get_clients() > 0 then - if next(vim.lsp.get_clients()) ~= nil then - vim.cmd('lsp restart') + local getClients = vim.lsp.get_clients() + if getClients then + if next(vim.lsp.get_clients()) ~= nil then + vim.cmd('lsp restart') + end end else vim.cmd('LspRestart') From b71b9d5b60a0ae46abb303e2b397ac4b2d1fd65f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 12:52:59 +0300 Subject: [PATCH 0204/1406] update --- lua/platformio/lspAttach.lua | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 7456dfdd..fa53295c 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -111,4 +111,19 @@ vim.api.nvim_create_autocmd('LspAttach', { -- end, }) + +vim.api.nvim_create_autocmd('LspDetach', { + group = vim.api.nvim_create_augroup('LspCleanup', { clear = true }), + callback = function(args) + local client = vim.lsp.get_client_by_id(args.data.client_id) + if not client then + return + end + + -- Check if the client still has other buffers attached + if vim.tbl_count(client.attached_buffers) == 0 then + client.stop() + end + end, +}) -- --> End LspAttach autocommand From 0c3d2e12a573da4f7768a167f7e189dbc83caf18 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 13:11:23 +0300 Subject: [PATCH 0205/1406] update --- lua/platformio/lspAttach.lua | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index fa53295c..95ec7750 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -1,6 +1,8 @@ +local platformio_lsp_attach = vim.api.nvim_create_augroup('platformio-lsp-attach', { clear = true }) -- INFO: LspAttach autocommand start vim.api.nvim_create_autocmd('LspAttach', { - group = vim.api.nvim_create_augroup('platformio-lsp-attach', { clear = true }), + -- group = vim.api.nvim_create_augroup('platformio-lsp-attach', { clear = true }), + group = platformio_lsp_attach, --desc = 'LSP actions', callback = function(args) local client = assert(vim.lsp.get_client_by_id(args.data.client_id)) @@ -89,7 +91,8 @@ vim.api.nvim_create_autocmd('LspAttach', { }) -- vim.api.nvim_create_autocmd('LspDetach', { - group = vim.api.nvim_create_augroup('platformio-lsp-detach', { clear = true }), + group = highlight_augroup, + -- group = vim.api.nvim_create_augroup('platformio-lsp-detach', { clear = true }), callback = function(event) vim.lsp.buf.clear_references() vim.api.nvim_clear_autocmds({ group = 'platformio-lsp-highlight', buffer = event.buf }) @@ -109,21 +112,22 @@ vim.api.nvim_create_autocmd('LspAttach', { ------------------------------------------------------------------ vim.cmd([[autocmd FileType * set formatoptions-=ro]]) -- - end, -}) - -vim.api.nvim_create_autocmd('LspDetach', { - group = vim.api.nvim_create_augroup('LspCleanup', { clear = true }), - callback = function(args) - local client = vim.lsp.get_client_by_id(args.data.client_id) - if not client then - return - end + vim.api.nvim_create_autocmd('LspDetach', { + group = platformio_lsp_attach, + -- group = vim.api.nvim_create_augroup('LspCleanup', { clear = true }), + callback = function(arg) + local cl = vim.lsp.get_client_by_id(arg.data.client_id) + if not cl then + return + end - -- Check if the client still has other buffers attached - if vim.tbl_count(client.attached_buffers) == 0 then - client.stop() - end + -- Check if the client still has other buffers attached + if vim.tbl_count(client.attached_buffers) == 0 then + client.stop() + end + end, + }) end, }) + -- --> End LspAttach autocommand From 50a506481998bdfed0192855f05224d55cf8f147 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 16:51:40 +0300 Subject: [PATCH 0206/1406] update --- lua/platformio/lspAttach.lua | 3 ++- lua/platformio/piolsp.lua | 7 ++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 95ec7750..06c44a1b 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -122,7 +122,8 @@ vim.api.nvim_create_autocmd('LspAttach', { end -- Check if the client still has other buffers attached - if vim.tbl_count(client.attached_buffers) == 0 then + if vim.tbl_count(cl.attached_buffers) == 0 then + print('client stop') client.stop() end end, diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 6577461c..1fa70695 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -39,7 +39,12 @@ function M.piolsp() local getClients = vim.lsp.get_clients() if getClients then if next(vim.lsp.get_clients()) ~= nil then - vim.cmd('lsp restart') + if vim.tbl_count(getClients.attached_buffers) == 0 then + getClients.stop() + print('client stop piolsp') + else + vim.cmd('lsp restart') + end end end else From 417ae9dc4613df91ba41ad60e57adc23ceb5d15a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 17:03:55 +0300 Subject: [PATCH 0207/1406] update --- lua/platformio/lspAttach.lua | 30 +++++++++++++++--------------- lua/platformio/piolsp.lua | 3 ++- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 06c44a1b..304d2254 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -112,22 +112,22 @@ vim.api.nvim_create_autocmd('LspAttach', { ------------------------------------------------------------------ vim.cmd([[autocmd FileType * set formatoptions-=ro]]) -- - vim.api.nvim_create_autocmd('LspDetach', { - group = platformio_lsp_attach, - -- group = vim.api.nvim_create_augroup('LspCleanup', { clear = true }), - callback = function(arg) - local cl = vim.lsp.get_client_by_id(arg.data.client_id) - if not cl then - return - end + end, +}) +vim.api.nvim_create_autocmd('LspDetach', { + group = platformio_lsp_attach, + -- group = vim.api.nvim_create_augroup('LspCleanup', { clear = true }), + callback = function(arg) + local cl = vim.lsp.get_client_by_id(arg.data.client_id) + if not cl then + return + end - -- Check if the client still has other buffers attached - if vim.tbl_count(cl.attached_buffers) == 0 then - print('client stop') - client.stop() - end - end, - }) + -- Check if the client still has other buffers attached + if vim.tbl_count(cl.attached_buffers) == 0 then + print('client stop') + cl.stop() + end end, }) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 1fa70695..6258cfe1 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -40,9 +40,10 @@ function M.piolsp() if getClients then if next(vim.lsp.get_clients()) ~= nil then if vim.tbl_count(getClients.attached_buffers) == 0 then - getClients.stop() print('client stop piolsp') + -- getClients.stop() else + print('client restart') vim.cmd('lsp restart') end end From 75518a269fcc0db6347d1cdc30660076b150ef51 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 17:10:00 +0300 Subject: [PATCH 0208/1406] update --- lua/platformio/lspAttach.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 304d2254..15a12e50 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -1,4 +1,4 @@ -local platformio_lsp_attach = vim.api.nvim_create_augroup('platformio-lsp-attach', { clear = true }) +local platformio_lsp_attach = vim.api.nvim_create_augroup('platformio-lsp-attach', { clear = false }) -- INFO: LspAttach autocommand start vim.api.nvim_create_autocmd('LspAttach', { -- group = vim.api.nvim_create_augroup('platformio-lsp-attach', { clear = true }), From 16d61e951d4f334f4f16940f5734fc7e98517bf8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 17:17:54 +0300 Subject: [PATCH 0209/1406] update --- lua/platformio/lspAttach.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 15a12e50..134273ce 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -114,9 +114,10 @@ vim.api.nvim_create_autocmd('LspAttach', { -- end, }) + vim.api.nvim_create_autocmd('LspDetach', { - group = platformio_lsp_attach, - -- group = vim.api.nvim_create_augroup('LspCleanup', { clear = true }), + -- group = platformio_lsp_attach, + group = vim.api.nvim_create_augroup('LspCleanup', { clear = true }), callback = function(arg) local cl = vim.lsp.get_client_by_id(arg.data.client_id) if not cl then From 40626992ed38fa7a5edb234c0b5108182893fb51 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 17:21:16 +0300 Subject: [PATCH 0210/1406] update --- lua/platformio/piolsp.lua | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 6258cfe1..980dd1f8 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -34,23 +34,23 @@ function M.piolsp() utils.shell_cmd_blocking('pio run -t compiledb') gitignore_lsp_configs('compile_commands.json') - if vim.fn.has('nvim-0.12') then - -- if #vim.lsp.get_clients() > 0 then - local getClients = vim.lsp.get_clients() - if getClients then - if next(vim.lsp.get_clients()) ~= nil then - if vim.tbl_count(getClients.attached_buffers) == 0 then - print('client stop piolsp') - -- getClients.stop() - else - print('client restart') - vim.cmd('lsp restart') - end - end - end - else - vim.cmd('LspRestart') - end + -- if vim.fn.has('nvim-0.12') then + -- -- if #vim.lsp.get_clients() > 0 then + -- local getClients = vim.lsp.get_clients() + -- if getClients then + -- if next(vim.lsp.get_clients()) ~= nil then + -- if vim.tbl_count(getClients.attached_buffers) == 0 then + -- print('client stop piolsp') + -- -- getClients.stop() + -- else + -- print('client restart') + -- vim.cmd('lsp restart') + -- end + -- end + -- end + -- else + -- vim.cmd('LspRestart') + -- end vim.notify('LSP: compile_commands.jsoncon generation/update completed!', vim.log.levels.INFO) end From 8684d7fb87c328228a4d6b99bac909296d1f6a83 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 17:37:09 +0300 Subject: [PATCH 0211/1406] update --- lua/platformio/lspAttach.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 134273ce..1f423c83 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -124,10 +124,11 @@ vim.api.nvim_create_autocmd('LspDetach', { return end + print('client detatch') -- Check if the client still has other buffers attached if vim.tbl_count(cl.attached_buffers) == 0 then print('client stop') - cl.stop() + cl:stop(true) end end, }) From 76518b1f4de66322bc76a723998320da32da9132 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 17:54:43 +0300 Subject: [PATCH 0212/1406] update --- lua/platformio/lspAttach.lua | 13 +++++++++--- lua/platformio/piolsp.lua | 41 +++++++++++++++++++++--------------- mini_nvimPlatformio.lua | 6 ++++++ 3 files changed, 40 insertions(+), 20 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 1f423c83..bdd7c47c 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -125,11 +125,18 @@ vim.api.nvim_create_autocmd('LspDetach', { end print('client detatch') - -- Check if the client still has other buffers attached - if vim.tbl_count(cl.attached_buffers) == 0 then - print('client stop') + + -- Run this to kill any LSP client not attached to a buffer + if vim.iter(cl.attached_buffers):count() == 0 then + print('detatch: client stop') cl:stop(true) end + + -- Check if the client still has other buffers attached + -- if vim.tbl_count(cl.attached_buffers) == 0 then + -- print('client stop') + -- cl:stop(true) + -- end end, }) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 980dd1f8..8772fef8 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -34,23 +34,30 @@ function M.piolsp() utils.shell_cmd_blocking('pio run -t compiledb') gitignore_lsp_configs('compile_commands.json') - -- if vim.fn.has('nvim-0.12') then - -- -- if #vim.lsp.get_clients() > 0 then - -- local getClients = vim.lsp.get_clients() - -- if getClients then - -- if next(vim.lsp.get_clients()) ~= nil then - -- if vim.tbl_count(getClients.attached_buffers) == 0 then - -- print('client stop piolsp') - -- -- getClients.stop() - -- else - -- print('client restart') - -- vim.cmd('lsp restart') - -- end - -- end - -- end - -- else - -- vim.cmd('LspRestart') - -- end + if vim.fn.has('nvim-0.12') then + -- if #vim.lsp.get_clients() > 0 then + local getClients = vim.lsp.get_clients() + + for _, cli in ipairs(getClients) do + if vim.iter(cli.attached_buffers):count() == 0 then + print('client stop') + cli:stop(true) + end + end + print('piolsp: client restart') + vim.cmd('lsp restart') + -- if next(vim.lsp.get_clients()) ~= nil then + -- if vim.tbl_count(getClients.attached_buffers) == 0 then + -- print('client stop piolsp') + -- -- getClients.stop() + -- else + -- print('client restart') + -- vim.cmd('lsp restart') + -- end + -- end + else + vim.cmd('LspRestart') + end vim.notify('LSP: compile_commands.jsoncon generation/update completed!', vim.log.levels.INFO) end diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 492e9c42..1f2fe917 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -120,6 +120,12 @@ keymap('n', 'bd', function() -- Otherwise, go to the previous buffer and delete the old one vim.cmd('bp | bd #') end + for _, cli in ipairs(vim.lsp.get_clients()) do + if vim.iter(cli.attached_buffers):count() == 0 then + print('bd: client stop') + cli:stop(true) + end + end end, { desc = '[D]elete Buffer' }) keymap('n', 'bP', 'BufferLineGroupClose ungrouped', { desc = 'Delete Non-Pinned Buffers' }) From ff5a12276802d1eb55f131647b1a7219f1058dc7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 18:00:22 +0300 Subject: [PATCH 0213/1406] update --- lua/platformio/lspAttach.lua | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index bdd7c47c..513b66b1 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -126,11 +126,15 @@ vim.api.nvim_create_autocmd('LspDetach', { print('client detatch') - -- Run this to kill any LSP client not attached to a buffer - if vim.iter(cl.attached_buffers):count() == 0 then + if vim.tbl_isempty(cl.attached_buffers) then print('detatch: client stop') cl:stop(true) end + -- Run this to kill any LSP client not attached to a buffer + -- if vim.iter(cl.attached_buffers):count() == 0 then + -- print('detatch: client stop') + -- cl:stop(true) + -- end -- Check if the client still has other buffers attached -- if vim.tbl_count(cl.attached_buffers) == 0 then From e11ddf94455bf10b58907c8d92a88b0043af3e08 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 18:04:32 +0300 Subject: [PATCH 0214/1406] update --- mini_nvimPlatformio.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 1f2fe917..fd83cee9 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -121,7 +121,8 @@ keymap('n', 'bd', function() vim.cmd('bp | bd #') end for _, cli in ipairs(vim.lsp.get_clients()) do - if vim.iter(cli.attached_buffers):count() == 0 then + if vim.tbl_isempty(cli.attached_buffers) then + -- if vim.iter(cli.attached_buffers):count() == 0 then print('bd: client stop') cli:stop(true) end From 74ac37aa4094780ada194abbdc4b01ba5032fb36 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 18:07:20 +0300 Subject: [PATCH 0215/1406] update --- mini_nvimPlatformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index fd83cee9..0dfff072 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -121,7 +121,7 @@ keymap('n', 'bd', function() vim.cmd('bp | bd #') end for _, cli in ipairs(vim.lsp.get_clients()) do - if vim.tbl_isempty(cli.attached_buffers) then + if cli.attached_buffers and vim.tbl_isempty(cli.attached_buffers) then -- if vim.iter(cli.attached_buffers):count() == 0 then print('bd: client stop') cli:stop(true) From 561dd49e3f03c1bb1080787590cb9c6ae7f15224 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 18:32:33 +0300 Subject: [PATCH 0216/1406] update --- lua/platformio/lspAttach.lua | 11 ----------- lua/platformio/piolsp.lua | 16 ++++++++-------- mini_nvimPlatformio.lua | 14 +++++++------- 3 files changed, 15 insertions(+), 26 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 513b66b1..78512a3d 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -130,17 +130,6 @@ vim.api.nvim_create_autocmd('LspDetach', { print('detatch: client stop') cl:stop(true) end - -- Run this to kill any LSP client not attached to a buffer - -- if vim.iter(cl.attached_buffers):count() == 0 then - -- print('detatch: client stop') - -- cl:stop(true) - -- end - - -- Check if the client still has other buffers attached - -- if vim.tbl_count(cl.attached_buffers) == 0 then - -- print('client stop') - -- cl:stop(true) - -- end end, }) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 8772fef8..249a6f19 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -36,14 +36,14 @@ function M.piolsp() if vim.fn.has('nvim-0.12') then -- if #vim.lsp.get_clients() > 0 then - local getClients = vim.lsp.get_clients() - - for _, cli in ipairs(getClients) do - if vim.iter(cli.attached_buffers):count() == 0 then - print('client stop') - cli:stop(true) - end - end + -- local getClients = vim.lsp.get_clients() + -- + -- for _, cli in ipairs(getClients) do + -- if vim.iter(cli.attached_buffers):count() == 0 then + -- print('client stop') + -- cli:stop(true) + -- end + -- end print('piolsp: client restart') vim.cmd('lsp restart') -- if next(vim.lsp.get_clients()) ~= nil then diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 0dfff072..d35c182d 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -120,13 +120,13 @@ keymap('n', 'bd', function() -- Otherwise, go to the previous buffer and delete the old one vim.cmd('bp | bd #') end - for _, cli in ipairs(vim.lsp.get_clients()) do - if cli.attached_buffers and vim.tbl_isempty(cli.attached_buffers) then - -- if vim.iter(cli.attached_buffers):count() == 0 then - print('bd: client stop') - cli:stop(true) - end - end + -- for _, cli in ipairs(vim.lsp.get_clients()) do + -- if cli.attached_buffers and vim.tbl_isempty(cli.attached_buffers) then + -- -- if vim.iter(cli.attached_buffers):count() == 0 then + -- print('bd: client stop') + -- cli:stop(true) + -- end + -- end end, { desc = '[D]elete Buffer' }) keymap('n', 'bP', 'BufferLineGroupClose ungrouped', { desc = 'Delete Non-Pinned Buffers' }) From f950f51a2f84e7675538441c7b161cdfbc4f7954 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 18:45:17 +0300 Subject: [PATCH 0217/1406] update --- lua/platformio/lspAttach.lua | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 78512a3d..ec030fd2 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -126,10 +126,18 @@ vim.api.nvim_create_autocmd('LspDetach', { print('client detatch') - if vim.tbl_isempty(cl.attached_buffers) then - print('detatch: client stop') - cl:stop(true) + for _, cli in ipairs(vim.lsp.get_clients()) do + if cli.attached_buffers and vim.tbl_isempty(cli.attached_buffers) then + -- if vim.iter(cli.attached_buffers):count() == 0 then + print('detatch: client stop') + cli:stop(true) + end end + + -- if cl.attached_buffers and vim.tbl_isempty(cl.attached_buffers) then + -- print('detatch: client stop') + -- cl:stop(true) + -- end end, }) From d1aad6229dbe3922fb6732c3e1ff5a966a37c784 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 19:01:21 +0300 Subject: [PATCH 0218/1406] update --- lua/platformio/lspAttach.lua | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index ec030fd2..a869058e 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -124,19 +124,26 @@ vim.api.nvim_create_autocmd('LspDetach', { return end - print('client detatch') + print('client detatch 0') + if cl.attached_buffers and vim.tbl_isempty(cl.attached_buffers) then + print('detatch0: client stop') + cl:stop(true) + end - for _, cli in ipairs(vim.lsp.get_clients()) do - if cli.attached_buffers and vim.tbl_isempty(cli.attached_buffers) then - -- if vim.iter(cli.attached_buffers):count() == 0 then - print('detatch: client stop') - cli:stop(true) + -- Run this to kill any LSP client not attached to a buffer + for _, client in ipairs(vim.lsp.get_clients()) do + if vim.iter(client.attached_buffers):count() == 0 then + print('detatch1: client stop') + client:stop(true) end end - -- if cl.attached_buffers and vim.tbl_isempty(cl.attached_buffers) then - -- print('detatch: client stop') - -- cl:stop(true) + -- for _, cli in ipairs(vim.lsp.get_clients()) do + -- if cli.attached_buffers and vim.tbl_isempty(cli.attached_buffers) then + -- -- if vim.iter(cli.attached_buffers):count() == 0 then + -- print('detatch: client stop') + -- cli:stop(true) + -- end -- end end, }) From dd90f144cbf58cb2d4af0485ace54924aae79045 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 19:05:50 +0300 Subject: [PATCH 0219/1406] update --- lua/platformio/lspAttach.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index a869058e..a26ea537 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -132,7 +132,8 @@ vim.api.nvim_create_autocmd('LspDetach', { -- Run this to kill any LSP client not attached to a buffer for _, client in ipairs(vim.lsp.get_clients()) do - if vim.iter(client.attached_buffers):count() == 0 then + if client.attached_buffers and vim.tbl_isempty(client.attached_buffers) then + -- if vim.iter(client.attached_buffers):count() == 0 then print('detatch1: client stop') client:stop(true) end From 8e45739d4efe2a9b6bc917dae114d434d405d93e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 19:18:19 +0300 Subject: [PATCH 0220/1406] update --- lua/platformio/lspAttach.lua | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index a26ea537..b1778eba 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -125,6 +125,11 @@ vim.api.nvim_create_autocmd('LspDetach', { end print('client detatch 0') + if cl.attached_buffers then + print('detatch0: client stop') + print(vim.inspect(cl.attached_buffers)) + cl:stop(true) + end if cl.attached_buffers and vim.tbl_isempty(cl.attached_buffers) then print('detatch0: client stop') cl:stop(true) From 15c83ff3fb7f330ada32193514f3252f4a0a85ff Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 19:27:59 +0300 Subject: [PATCH 0221/1406] update --- lua/platformio/lspAttach.lua | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index b1778eba..d981f41b 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -128,21 +128,23 @@ vim.api.nvim_create_autocmd('LspDetach', { if cl.attached_buffers then print('detatch0: client stop') print(vim.inspect(cl.attached_buffers)) - cl:stop(true) - end - if cl.attached_buffers and vim.tbl_isempty(cl.attached_buffers) then - print('detatch0: client stop') - cl:stop(true) - end - - -- Run this to kill any LSP client not attached to a buffer - for _, client in ipairs(vim.lsp.get_clients()) do - if client.attached_buffers and vim.tbl_isempty(client.attached_buffers) then - -- if vim.iter(client.attached_buffers):count() == 0 then - print('detatch1: client stop') - client:stop(true) + if vim.iter(cl.attached_buffers):count() == 1 then + cl:stop(true) end end + -- if cl.attached_buffers and vim.tbl_isempty(cl.attached_buffers) then + -- print('detatch0: client stop') + -- cl:stop(true) + -- end + -- + -- -- Run this to kill any LSP client not attached to a buffer + -- for _, client in ipairs(vim.lsp.get_clients()) do + -- if client.attached_buffers and vim.tbl_isempty(client.attached_buffers) then + -- -- if vim.iter(client.attached_buffers):count() == 0 then + -- print('detatch1: client stop') + -- client:stop(true) + -- end + -- end -- for _, cli in ipairs(vim.lsp.get_clients()) do -- if cli.attached_buffers and vim.tbl_isempty(cli.attached_buffers) then From 904a759a562ec82aeaaacaef47005bc8d9faca8b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 20:13:55 +0300 Subject: [PATCH 0222/1406] update --- lua/platformio/lspClangd.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 9875b678..bf685963 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -94,6 +94,7 @@ end vim.lsp.config('*', { capabilities = capabilities, root_markers = { '.git' }, + workspace_required = false, }) ---------------------------------------------------------------------------------------- -- INFO: configure clangd lsp server From 46a95bc8ab33b43be1d2bdbd2e1b9ea5283d6ed0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 20:31:01 +0300 Subject: [PATCH 0223/1406] update --- lua/platformio/lspAttach.lua | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index d981f41b..60a444cf 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -128,9 +128,19 @@ vim.api.nvim_create_autocmd('LspDetach', { if cl.attached_buffers then print('detatch0: client stop') print(vim.inspect(cl.attached_buffers)) - if vim.iter(cl.attached_buffers):count() == 1 then + + local count = 0 + for _ in pairs(cl.attached_buffers) do + count = count + 1 + end + + if count == 0 then cl:stop(true) end + + -- if vim.iter(cl.attached_buffers):count() == 1 then + -- cl:stop(true) + -- end end -- if cl.attached_buffers and vim.tbl_isempty(cl.attached_buffers) then -- print('detatch0: client stop') From 27174d9393b17b5e53d5303a38206fc2be49c910 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 4 Apr 2026 20:34:29 +0300 Subject: [PATCH 0224/1406] update --- lua/platformio/lspAttach.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 60a444cf..dfd432d4 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -134,7 +134,7 @@ vim.api.nvim_create_autocmd('LspDetach', { count = count + 1 end - if count == 0 then + if count == 1 then cl:stop(true) end From 33030f14ffdb5caa937ff64e9676a0935cdb3a37 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 05:11:19 +0300 Subject: [PATCH 0225/1406] update --- lua/platformio/lspAttach.lua | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index dfd432d4..7b073167 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -118,24 +118,26 @@ vim.api.nvim_create_autocmd('LspAttach', { vim.api.nvim_create_autocmd('LspDetach', { -- group = platformio_lsp_attach, group = vim.api.nvim_create_augroup('LspCleanup', { clear = true }), - callback = function(arg) - local cl = vim.lsp.get_client_by_id(arg.data.client_id) - if not cl then + callback = function(args) + local bufnr = args.buf + local client = vim.lsp.get_client_by_id(arg.data.client_id) + if not client then return end print('client detatch 0') - if cl.attached_buffers then + if client.attached_buffers then print('detatch0: client stop') - print(vim.inspect(cl.attached_buffers)) + print(vim.inspect(client.attached_buffers)) + vim.api.nvim_echo({ { 'Detaching: ' .. client.name .. ' from buffer ' .. bufnr, 'Info' } }, true, {}) local count = 0 - for _ in pairs(cl.attached_buffers) do + for _ in pairs(client.attached_buffers) do count = count + 1 end if count == 1 then - cl:stop(true) + client:stop(true) end -- if vim.iter(cl.attached_buffers):count() == 1 then From 2e9762fa5f408d4b8fdef1dbc579bd241d1ea223 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 05:13:18 +0300 Subject: [PATCH 0226/1406] update --- lua/platformio/lspAttach.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 7b073167..c6fbb7c9 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -11,7 +11,7 @@ vim.api.nvim_create_autocmd('LspAttach', { if client then -- vim.lsp.set_log_level 'trace' -- print('Attaching to: ' .. client.name .. ' attached to buffer ' .. bufnr) - vim.api.nvim_echo({ { 'Attaching to: ' .. client.name .. ' attached to buffer ' .. bufnr, 'Info' } }, true, {}) + vim.api.nvim_echo({ { 'Attaching: ' .. client.name .. ' to buffer ' .. bufnr, 'Info' } }, true, {}) -- if client.name == 'lua_ls' then -- -- client.server_capabilities.documentFormattingProvider = false From dbf870ead117d3f1cedfe2aa5403fb88cadc9b7c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 05:14:59 +0300 Subject: [PATCH 0227/1406] update --- lua/platformio/lspAttach.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index c6fbb7c9..f637dda3 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -118,8 +118,8 @@ vim.api.nvim_create_autocmd('LspAttach', { vim.api.nvim_create_autocmd('LspDetach', { -- group = platformio_lsp_attach, group = vim.api.nvim_create_augroup('LspCleanup', { clear = true }), - callback = function(args) - local bufnr = args.buf + callback = function(arg) + local bufnr = arg.buf local client = vim.lsp.get_client_by_id(arg.data.client_id) if not client then return From b97c9f798c2ddb0f497273c076e396c449501e94 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 05:48:59 +0300 Subject: [PATCH 0228/1406] update --- lua/platformio/lspAttach.lua | 38 +++--------------------------------- 1 file changed, 3 insertions(+), 35 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index f637dda3..0f68e24e 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -116,20 +116,13 @@ vim.api.nvim_create_autocmd('LspAttach', { }) vim.api.nvim_create_autocmd('LspDetach', { - -- group = platformio_lsp_attach, group = vim.api.nvim_create_augroup('LspCleanup', { clear = true }), callback = function(arg) local bufnr = arg.buf local client = vim.lsp.get_client_by_id(arg.data.client_id) - if not client then - return - end - - print('client detatch 0') - if client.attached_buffers then - print('detatch0: client stop') - print(vim.inspect(client.attached_buffers)) - + if client and client.attached_buffers then + -- print(vim.inspect(client.attached_buffers)) + -- if vim.iter(client.attached_buffers):count() == 0 then vim.api.nvim_echo({ { 'Detaching: ' .. client.name .. ' from buffer ' .. bufnr, 'Info' } }, true, {}) local count = 0 for _ in pairs(client.attached_buffers) do @@ -139,32 +132,7 @@ vim.api.nvim_create_autocmd('LspDetach', { if count == 1 then client:stop(true) end - - -- if vim.iter(cl.attached_buffers):count() == 1 then - -- cl:stop(true) - -- end end - -- if cl.attached_buffers and vim.tbl_isempty(cl.attached_buffers) then - -- print('detatch0: client stop') - -- cl:stop(true) - -- end - -- - -- -- Run this to kill any LSP client not attached to a buffer - -- for _, client in ipairs(vim.lsp.get_clients()) do - -- if client.attached_buffers and vim.tbl_isempty(client.attached_buffers) then - -- -- if vim.iter(client.attached_buffers):count() == 0 then - -- print('detatch1: client stop') - -- client:stop(true) - -- end - -- end - - -- for _, cli in ipairs(vim.lsp.get_clients()) do - -- if cli.attached_buffers and vim.tbl_isempty(cli.attached_buffers) then - -- -- if vim.iter(cli.attached_buffers):count() == 0 then - -- print('detatch: client stop') - -- cli:stop(true) - -- end - -- end end, }) From f972b45e3e56a8398a31960048fabb0228cd7445 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 06:04:47 +0300 Subject: [PATCH 0229/1406] update --- lua/platformio/lspAttach.lua | 63 +++++++++++++----------------------- lua/platformio/piolsp.lua | 9 ++++-- mini_nvimPlatformio.lua | 1 - 3 files changed, 29 insertions(+), 44 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 0f68e24e..14e79789 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -1,8 +1,6 @@ -local platformio_lsp_attach = vim.api.nvim_create_augroup('platformio-lsp-attach', { clear = false }) -- INFO: LspAttach autocommand start vim.api.nvim_create_autocmd('LspAttach', { - -- group = vim.api.nvim_create_augroup('platformio-lsp-attach', { clear = true }), - group = platformio_lsp_attach, + group = vim.api.nvim_create_augroup('platformio-lsp-attach', { clear = true }), --desc = 'LSP actions', callback = function(args) local client = assert(vim.lsp.get_client_by_id(args.data.client_id)) @@ -13,21 +11,6 @@ vim.api.nvim_create_autocmd('LspAttach', { -- print('Attaching to: ' .. client.name .. ' attached to buffer ' .. bufnr) vim.api.nvim_echo({ { 'Attaching: ' .. client.name .. ' to buffer ' .. bufnr, 'Info' } }, true, {}) - -- if client.name == 'lua_ls' then - -- -- client.server_capabilities.documentFormattingProvider = false - -- if client:supports_method('textDocument/formatting') then - -- vim.lsp.buf.format({ - -- bufnr = bufnr, - -- async = false, - -- timeout_ms = 10000, - -- id = client.id, - -- filter = function(c) - -- return c.id == client.id - -- end, - -- }) - -- end - -- end - -- print('lua_ls 0') ------------------------------------------------------------------ if client.name == 'clangd' then vim.api.nvim_buf_create_user_command(0, 'LspClangdSwitchSourceHeader', function() @@ -46,9 +29,7 @@ vim.api.nvim_create_autocmd('LspAttach', { end, { desc = 'Switch between source/header' }) end - -- if client and client.server_capabilities.completionProvider then - -- if client:supports_method('textDocument/completion', { bufnr = bufnr }) then - + -- use lsp completion if no blink local ok, _ = pcall(require, 'blink.cmp') if not ok then if client:supports_method('textDocument/completion') then @@ -115,25 +96,25 @@ vim.api.nvim_create_autocmd('LspAttach', { end, }) -vim.api.nvim_create_autocmd('LspDetach', { - group = vim.api.nvim_create_augroup('LspCleanup', { clear = true }), - callback = function(arg) - local bufnr = arg.buf - local client = vim.lsp.get_client_by_id(arg.data.client_id) - if client and client.attached_buffers then - -- print(vim.inspect(client.attached_buffers)) - -- if vim.iter(client.attached_buffers):count() == 0 then - vim.api.nvim_echo({ { 'Detaching: ' .. client.name .. ' from buffer ' .. bufnr, 'Info' } }, true, {}) - local count = 0 - for _ in pairs(client.attached_buffers) do - count = count + 1 - end - - if count == 1 then - client:stop(true) - end - end - end, -}) +-- vim.api.nvim_create_autocmd('LspDetach', { +-- group = vim.api.nvim_create_augroup('LspCleanup', { clear = true }), +-- callback = function(arg) +-- local bufnr = arg.buf +-- local client = vim.lsp.get_client_by_id(arg.data.client_id) +-- if client and client.attached_buffers then +-- -- print(vim.inspect(client.attached_buffers)) +-- -- if vim.iter(client.attached_buffers):count() == 0 then +-- vim.api.nvim_echo({ { 'Detaching: ' .. client.name .. ' from buffer ' .. bufnr, 'Info' } }, true, {}) +-- local count = 0 +-- for _ in pairs(client.attached_buffers) do +-- count = count + 1 +-- end +-- +-- if count == 1 then +-- client:stop(true) +-- end +-- end +-- end, +-- }) -- --> End LspAttach autocommand diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 249a6f19..d15289e7 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -44,8 +44,13 @@ function M.piolsp() -- cli:stop(true) -- end -- end - print('piolsp: client restart') - vim.cmd('lsp restart') + -- + + local clangd = vim.lsp.get_clients({ name = 'clangd' })[1] + if clangd then + print('piolsp: client restart') + vim.cmd('lsp restart clangd') + end -- if next(vim.lsp.get_clients()) ~= nil then -- if vim.tbl_count(getClients.attached_buffers) == 0 then -- print('client stop piolsp') diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index d35c182d..0e0de3fb 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -108,7 +108,6 @@ keymap('n', 'bs', ':ball', { desc = '[S]how AllOpened Buffers' }) keymap('n', 'bp', 'BufferLineTogglePin', { desc = 'Toggle Pin' }) -- keymap('n', 'bd', 'bdelete', { desc = '[D]elete Buffer' }) --- keymap('n', 'bd', ':bp | bd #', { desc = '[D]elete Buffer' }) keymap('n', 'bd', function() -- local bufnr = vim.api.nvim_get_current_buf() local bufs = vim.fn.getbufinfo({ buflisted = 1 }) From 4f97257bc950553a0185fb6bf4948f503daca6f3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 06:14:48 +0300 Subject: [PATCH 0230/1406] update --- lua/platformio/lspAttach.lua | 4 ++-- lua/platformio/piolsp.lua | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 14e79789..e154a8e3 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -9,7 +9,7 @@ vim.api.nvim_create_autocmd('LspAttach', { if client then -- vim.lsp.set_log_level 'trace' -- print('Attaching to: ' .. client.name .. ' attached to buffer ' .. bufnr) - vim.api.nvim_echo({ { 'Attaching: ' .. client.name .. ' to buffer ' .. bufnr, 'Info' } }, true, {}) + vim.api.nvim_echo({ { 'Attaching ' .. client.name .. ' to buffer ' .. bufnr, 'Info' } }, true, {}) ------------------------------------------------------------------ if client.name == 'clangd' then @@ -104,7 +104,7 @@ vim.api.nvim_create_autocmd('LspAttach', { -- if client and client.attached_buffers then -- -- print(vim.inspect(client.attached_buffers)) -- -- if vim.iter(client.attached_buffers):count() == 0 then --- vim.api.nvim_echo({ { 'Detaching: ' .. client.name .. ' from buffer ' .. bufnr, 'Info' } }, true, {}) +-- vim.api.nvim_echo({ { 'Detaching ' .. client.name .. ' from buffer ' .. bufnr, 'Info' } }, true, {}) -- local count = 0 -- for _ in pairs(client.attached_buffers) do -- count = count + 1 diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index d15289e7..a9b7bf61 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -48,7 +48,7 @@ function M.piolsp() local clangd = vim.lsp.get_clients({ name = 'clangd' })[1] if clangd then - print('piolsp: client restart') + print('piolsp: lsp restart ' .. clangd.name) vim.cmd('lsp restart clangd') end -- if next(vim.lsp.get_clients()) ~= nil then From 87fb68eef3880757c7f65c7920060e60813aaeca Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 06:35:45 +0300 Subject: [PATCH 0231/1406] update --- lua/platformio/lspAttach.lua | 38 +++++++++++++++++------------------- lua/platformio/piolsp.lua | 23 ++-------------------- 2 files changed, 20 insertions(+), 41 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index e154a8e3..1f13074c 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -96,25 +96,23 @@ vim.api.nvim_create_autocmd('LspAttach', { end, }) --- vim.api.nvim_create_autocmd('LspDetach', { --- group = vim.api.nvim_create_augroup('LspCleanup', { clear = true }), --- callback = function(arg) --- local bufnr = arg.buf --- local client = vim.lsp.get_client_by_id(arg.data.client_id) --- if client and client.attached_buffers then --- -- print(vim.inspect(client.attached_buffers)) --- -- if vim.iter(client.attached_buffers):count() == 0 then --- vim.api.nvim_echo({ { 'Detaching ' .. client.name .. ' from buffer ' .. bufnr, 'Info' } }, true, {}) --- local count = 0 --- for _ in pairs(client.attached_buffers) do --- count = count + 1 --- end --- --- if count == 1 then --- client:stop(true) --- end --- end --- end, --- }) +vim.api.nvim_create_autocmd('LspDetach', { + group = vim.api.nvim_create_augroup('LspCleanup', { clear = true }), + callback = function(arg) + local bufnr = arg.buf + local client = vim.lsp.get_client_by_id(arg.data.client_id) + if client and client.attached_buffers then + vim.api.nvim_echo({ { 'Detaching ' .. client.name .. ' from buffer ' .. bufnr, 'Info' } }, true, {}) + -- local count = 0 + -- for _ in pairs(client.attached_buffers) do + -- count = count + 1 + -- end + -- + -- if count == 1 then + -- client:stop(true) + -- end + end + end, +}) -- --> End LspAttach autocommand diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index a9b7bf61..8c390922 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -35,31 +35,12 @@ function M.piolsp() gitignore_lsp_configs('compile_commands.json') if vim.fn.has('nvim-0.12') then - -- if #vim.lsp.get_clients() > 0 then - -- local getClients = vim.lsp.get_clients() - -- - -- for _, cli in ipairs(getClients) do - -- if vim.iter(cli.attached_buffers):count() == 0 then - -- print('client stop') - -- cli:stop(true) - -- end - -- end - -- - local clangd = vim.lsp.get_clients({ name = 'clangd' })[1] if clangd then - print('piolsp: lsp restart ' .. clangd.name) + print('number of attaced: ' .. #clangd.attached_buffers) + -- print('piolsp: lsp restart ' .. clangd.name) vim.cmd('lsp restart clangd') end - -- if next(vim.lsp.get_clients()) ~= nil then - -- if vim.tbl_count(getClients.attached_buffers) == 0 then - -- print('client stop piolsp') - -- -- getClients.stop() - -- else - -- print('client restart') - -- vim.cmd('lsp restart') - -- end - -- end else vim.cmd('LspRestart') end From 4c230ed3280611613dcd35e4fcf417868dfa9ae9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 06:44:31 +0300 Subject: [PATCH 0232/1406] update --- lua/platformio/lspAttach.lua | 3 --- lua/platformio/piolsp.lua | 12 ++++++------ 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 1f13074c..1f3b816f 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -1,14 +1,11 @@ -- INFO: LspAttach autocommand start vim.api.nvim_create_autocmd('LspAttach', { group = vim.api.nvim_create_augroup('platformio-lsp-attach', { clear = true }), - --desc = 'LSP actions', callback = function(args) local client = assert(vim.lsp.get_client_by_id(args.data.client_id)) local bufnr = args.buf if client then - -- vim.lsp.set_log_level 'trace' - -- print('Attaching to: ' .. client.name .. ' attached to buffer ' .. bufnr) vim.api.nvim_echo({ { 'Attaching ' .. client.name .. ' to buffer ' .. bufnr, 'Info' } }, true, {}) ------------------------------------------------------------------ diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 8c390922..9fe09d34 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -35,12 +35,12 @@ function M.piolsp() gitignore_lsp_configs('compile_commands.json') if vim.fn.has('nvim-0.12') then - local clangd = vim.lsp.get_clients({ name = 'clangd' })[1] - if clangd then - print('number of attaced: ' .. #clangd.attached_buffers) - -- print('piolsp: lsp restart ' .. clangd.name) - vim.cmd('lsp restart clangd') - end + -- local clangd = vim.lsp.get_clients({ name = 'clangd' })[1] + -- if clangd then + -- -- print('number of attaced: ' .. #clangd.attached_buffers) + -- -- print('piolsp: lsp restart ' .. clangd.name) + vim.cmd('lsp restart clangd') + -- end else vim.cmd('LspRestart') end From 6a48e04ba8f5b0ae5bf9735dbafffe5bb7cba16d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 07:23:17 +0300 Subject: [PATCH 0233/1406] update --- lua/platformio/piolsp.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 9fe09d34..cedc02d4 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -39,7 +39,8 @@ function M.piolsp() -- if clangd then -- -- print('number of attaced: ' .. #clangd.attached_buffers) -- -- print('piolsp: lsp restart ' .. clangd.name) - vim.cmd('lsp restart clangd') + pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) + -- vim.cmd('lsp restart clangd') -- end else vim.cmd('LspRestart') From dde0a812395509c6632663c1a6b192bba487ec81 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 07:32:39 +0300 Subject: [PATCH 0234/1406] update --- lua/platformio/piolsp.lua | 38 +++++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index cedc02d4..e058d629 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -24,6 +24,21 @@ local function gitignore_lsp_configs(config_file) file:close() end end +function M.lsp_restart(name) + if vim.fn.has('nvim-0.12') then + local clients = vim.lsp.get_clients({ name = name }) + + if #clients > 0 then + -- Client is active, try to restart + local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) + if not ok then + vim.notify('LSP ' .. name .. ' restart failed: ' .. err) + end + end + else + vim.cmd('LspRestart') + end +end function M.piolsp() if not utils.pio_install_check() then @@ -34,17 +49,18 @@ function M.piolsp() utils.shell_cmd_blocking('pio run -t compiledb') gitignore_lsp_configs('compile_commands.json') - if vim.fn.has('nvim-0.12') then - -- local clangd = vim.lsp.get_clients({ name = 'clangd' })[1] - -- if clangd then - -- -- print('number of attaced: ' .. #clangd.attached_buffers) - -- -- print('piolsp: lsp restart ' .. clangd.name) - pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) - -- vim.cmd('lsp restart clangd') - -- end - else - vim.cmd('LspRestart') - end + -- if vim.fn.has('nvim-0.12') then + -- local clangd = vim.lsp.get_clients({ name = 'clangd' })[1] + -- if clangd then + -- -- print('number of attaced: ' .. #clangd.attached_buffers) + -- -- print('piolsp: lsp restart ' .. clangd.name) + -- pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) + M.lsp_restart('clangd') + -- vim.cmd('lsp restart clangd') + -- end + -- else + -- vim.cmd('LspRestart') + -- end vim.notify('LSP: compile_commands.jsoncon generation/update completed!', vim.log.levels.INFO) end From 5148bb0f20fdd821d21e2dce03fb3c93a697881b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 07:43:07 +0300 Subject: [PATCH 0235/1406] update --- lua/platformio/piolsp.lua | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index e058d629..81b04942 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -3,7 +3,7 @@ local M = {} local utils = require('platformio.utils') local config = require('platformio').config -local function gitignore_lsp_configs(config_file) +function M.gitignore_lsp_configs(config_file) local gitignore_path = vim.fs.joinpath(vim.g.platformioRootDir, '.gitignore') local file = io.open(gitignore_path, 'r') local pattern = '^%s*' .. vim.pesc(config_file) .. '%s*$' @@ -24,6 +24,7 @@ local function gitignore_lsp_configs(config_file) file:close() end end + function M.lsp_restart(name) if vim.fn.has('nvim-0.12') then local clients = vim.lsp.get_clients({ name = name }) @@ -33,6 +34,8 @@ function M.lsp_restart(name) local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) if not ok then vim.notify('LSP ' .. name .. ' restart failed: ' .. err) + else + vim.notify('LSP ' .. name .. ' restarted : ' .. err) end end else @@ -47,7 +50,8 @@ function M.piolsp() utils.cd_pioini() utils.shell_cmd_blocking('pio run -t compiledb') - gitignore_lsp_configs('compile_commands.json') + vim.notify('LSP: compile_commands.jsoncon generation/update completed!', vim.log.levels.INFO) + M.gitignore_lsp_configs('compile_commands.json') -- if vim.fn.has('nvim-0.12') then -- local clangd = vim.lsp.get_clients({ name = 'clangd' })[1] @@ -61,8 +65,6 @@ function M.piolsp() -- else -- vim.cmd('LspRestart') -- end - - vim.notify('LSP: compile_commands.jsoncon generation/update completed!', vim.log.levels.INFO) end return M From a51f29992552bf60ac9e4093ee9e189d7daf3917 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 07:46:54 +0300 Subject: [PATCH 0236/1406] update --- lua/platformio/piolsp.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 81b04942..f50b8be5 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -27,9 +27,10 @@ end function M.lsp_restart(name) if vim.fn.has('nvim-0.12') then - local clients = vim.lsp.get_clients({ name = name }) + -- local clients = vim.lsp.get_clients({ name = name }) + local clangd = vim.lsp.get_clients({ name = name })[1] - if #clients > 0 then + if clangd > 0 then -- Client is active, try to restart local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) if not ok then From 5251e1d8c816ef9c33a39cfcf23be073bfc57dc1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 07:49:27 +0300 Subject: [PATCH 0237/1406] update --- lua/platformio/piolsp.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index f50b8be5..39ecb7f1 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -30,7 +30,7 @@ function M.lsp_restart(name) -- local clients = vim.lsp.get_clients({ name = name }) local clangd = vim.lsp.get_clients({ name = name })[1] - if clangd > 0 then + if clangd then -- Client is active, try to restart local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) if not ok then From 256c3c265a37fe614d5591d8f1ccf0d5c0fc16dd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 08:02:33 +0300 Subject: [PATCH 0238/1406] update --- lua/platformio/lspAttach.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 1f3b816f..20ad3dd5 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -45,10 +45,10 @@ vim.api.nvim_create_autocmd('LspAttach', { vim.lsp.inlay_hint.enable(true, { bufnr = bufnr }) end - if client:supports_method('textDocument/documentColor') then + if vim.lsp.document_color and client:supports_method('textDocument/documentColor') then -- vim.lsp.document_color.enable(true, args.buf, { style = 'background', -- 'background', 'foreground', or 'virtual' }) vim.lsp.document_color.enable(true, { - bufnr = bufnr, + bufnr = args.buf, style = 'inline', -- This is the modern 0.11 way to show color icons }) end From f1f3ebfd4fbc1de024c441e5c3cac86d5c64dd6c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 08:32:39 +0300 Subject: [PATCH 0239/1406] update --- lua/platformio/piolsp.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 39ecb7f1..d24d2a1a 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -26,7 +26,7 @@ function M.gitignore_lsp_configs(config_file) end function M.lsp_restart(name) - if vim.fn.has('nvim-0.12') then + if vim.fn.has('nvim-0.12') == 1 then -- local clients = vim.lsp.get_clients({ name = name }) local clangd = vim.lsp.get_clients({ name = name })[1] From 6a632986870baaf84d8b10fecda4af8690a1cf39 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 08:46:18 +0300 Subject: [PATCH 0240/1406] update --- lua/platformio/piolsp.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index d24d2a1a..543f2caa 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -26,7 +26,7 @@ function M.gitignore_lsp_configs(config_file) end function M.lsp_restart(name) - if vim.fn.has('nvim-0.12') == 1 then + if vim.fn.has('nvim-0.11') == 1 then -- local clients = vim.lsp.get_clients({ name = name }) local clangd = vim.lsp.get_clients({ name = name })[1] From af222f9bf3c32860aa3726b239b29b512f5f30ad Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 08:56:22 +0300 Subject: [PATCH 0241/1406] update --- lua/platformio/piolsp.lua | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 543f2caa..cd613f7f 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -31,13 +31,14 @@ function M.lsp_restart(name) local clangd = vim.lsp.get_clients({ name = name })[1] if clangd then - -- Client is active, try to restart - local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) - if not ok then - vim.notify('LSP ' .. name .. ' restart failed: ' .. err) - else - vim.notify('LSP ' .. name .. ' restarted : ' .. err) - end + clangd:restart() + -- -- Client is active, try to restart + -- local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) + -- if not ok then + -- vim.notify('LSP ' .. name .. ' restart failed: ' .. err) + -- else + -- vim.notify('LSP ' .. name .. ' restarted : ' .. err) + -- end end else vim.cmd('LspRestart') From 162d4fa1526150a0e2fb75e361a6be22fb1459d9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 09:06:28 +0300 Subject: [PATCH 0242/1406] update --- lua/platformio/piolsp.lua | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index cd613f7f..1c5bdcc1 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -28,18 +28,22 @@ end function M.lsp_restart(name) if vim.fn.has('nvim-0.11') == 1 then -- local clients = vim.lsp.get_clients({ name = name }) - local clangd = vim.lsp.get_clients({ name = name })[1] - - if clangd then - clangd:restart() - -- -- Client is active, try to restart - -- local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) - -- if not ok then - -- vim.notify('LSP ' .. name .. ' restart failed: ' .. err) - -- else - -- vim.notify('LSP ' .. name .. ' restarted : ' .. err) - -- end + local clients = vim.lsp.get_clients({ name = name }) + for _, client in ipairs(clients) do + client:notify('workspace/didChangeConfiguration', { settings = client.config.settings }) end + vim.notify('LSP configuration refreshed', vim.log.levels.INFO) + -- local clangd = vim.lsp.get_clients({ name = name })[1] + -- + -- if clangd then + -- -- Client is active, try to restart + -- local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) + -- if not ok then + -- vim.notify('LSP ' .. name .. ' restart failed: ' .. err) + -- else + -- vim.notify('LSP ' .. name .. ' restarted : ' .. err) + -- end + -- end else vim.cmd('LspRestart') end From a4fbe77040647eb8336e6713aef51318b82a6271 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 09:10:35 +0300 Subject: [PATCH 0243/1406] update --- lua/platformio/piolsp.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 1c5bdcc1..daf4089d 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -31,8 +31,8 @@ function M.lsp_restart(name) local clients = vim.lsp.get_clients({ name = name }) for _, client in ipairs(clients) do client:notify('workspace/didChangeConfiguration', { settings = client.config.settings }) + vim.notify('LSP configuration refreshed', vim.log.levels.INFO) end - vim.notify('LSP configuration refreshed', vim.log.levels.INFO) -- local clangd = vim.lsp.get_clients({ name = name })[1] -- -- if clangd then From c637b2f41b51c71809c12c1a0a6227321660f1b8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 09:14:22 +0300 Subject: [PATCH 0244/1406] update --- lua/platformio/piolsp.lua | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index daf4089d..543f2caa 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -28,22 +28,17 @@ end function M.lsp_restart(name) if vim.fn.has('nvim-0.11') == 1 then -- local clients = vim.lsp.get_clients({ name = name }) - local clients = vim.lsp.get_clients({ name = name }) - for _, client in ipairs(clients) do - client:notify('workspace/didChangeConfiguration', { settings = client.config.settings }) - vim.notify('LSP configuration refreshed', vim.log.levels.INFO) + local clangd = vim.lsp.get_clients({ name = name })[1] + + if clangd then + -- Client is active, try to restart + local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) + if not ok then + vim.notify('LSP ' .. name .. ' restart failed: ' .. err) + else + vim.notify('LSP ' .. name .. ' restarted : ' .. err) + end end - -- local clangd = vim.lsp.get_clients({ name = name })[1] - -- - -- if clangd then - -- -- Client is active, try to restart - -- local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) - -- if not ok then - -- vim.notify('LSP ' .. name .. ' restart failed: ' .. err) - -- else - -- vim.notify('LSP ' .. name .. ' restarted : ' .. err) - -- end - -- end else vim.cmd('LspRestart') end From 00600f60705f610d5ac287dfbb02bb5e07e4d90f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 09:56:13 +0300 Subject: [PATCH 0245/1406] update --- lua/platformio/piolsp.lua | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 543f2caa..3815242f 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -24,6 +24,34 @@ function M.gitignore_lsp_configs(config_file) file:close() end end +function M.lsp_restarti(name) + local clients = vim.lsp.get_clients({ name = name }) + + if #clients == 0 then + -- I'm using my own implementation of `vim.lsp.enable()` + -- To work with default one change group name from `MyLsp` to `nvim.lsp.enable` + -- It is not tested with default one, so not sure if it would 100% work. + vim.api.nvim_exec_autocmds('FileType', { group = 'nvim.lsp.enable', buffer = 0 }) + return + end + + for _, c in ipairs(clients) do + local attached_buffers = vim.tbl_keys(c.attached_buffers) ---@type integer[] + local configc = c.config + vim.lsp.stop_client(c.id, true) + vim.defer_fn(function() + local id = vim.lsp.start(configc) + if id then + for _, b in ipairs(attached_buffers) do + vim.lsp.buf_attach_client(b, id) + end + vim.notify(string.format('Lsp `%s` has been restarted.', config.name)) + else + vim.notify(string.format('Error restarting `%s`.', config.name), vim.log.levels.ERROR) + end + end, 600) + end +end function M.lsp_restart(name) if vim.fn.has('nvim-0.11') == 1 then @@ -51,7 +79,7 @@ function M.piolsp() utils.cd_pioini() utils.shell_cmd_blocking('pio run -t compiledb') - vim.notify('LSP: compile_commands.jsoncon generation/update completed!', vim.log.levels.INFO) + vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) M.gitignore_lsp_configs('compile_commands.json') -- if vim.fn.has('nvim-0.12') then @@ -60,7 +88,7 @@ function M.piolsp() -- -- print('number of attaced: ' .. #clangd.attached_buffers) -- -- print('piolsp: lsp restart ' .. clangd.name) -- pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) - M.lsp_restart('clangd') + M.lsp_restarti('clangd') -- vim.cmd('lsp restart clangd') -- end -- else From e2389d7946ee8a1694b958e3e9963ef91bce1a99 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 11:15:11 +0300 Subject: [PATCH 0246/1406] update --- lua/platformio/piolsp.lua | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 3815242f..16c4e112 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -24,16 +24,17 @@ function M.gitignore_lsp_configs(config_file) file:close() end end + function M.lsp_restarti(name) local clients = vim.lsp.get_clients({ name = name }) - if #clients == 0 then - -- I'm using my own implementation of `vim.lsp.enable()` - -- To work with default one change group name from `MyLsp` to `nvim.lsp.enable` - -- It is not tested with default one, so not sure if it would 100% work. - vim.api.nvim_exec_autocmds('FileType', { group = 'nvim.lsp.enable', buffer = 0 }) - return - end + -- if #clients == 0 then + -- -- I'm using my own implementation of `vim.lsp.enable()` + -- -- To work with default one change group name from `MyLsp` to `nvim.lsp.enable` + -- -- It is not tested with default one, so not sure if it would 100% work. + -- vim.api.nvim_exec_autocmds('FileType', { group = 'nvim.lsp.enable', buffer = 0 }) + -- return + -- end for _, c in ipairs(clients) do local attached_buffers = vim.tbl_keys(c.attached_buffers) ---@type integer[] From ad6ab26d147f8318a88b13e0a6de4000cf7d2148 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 11:22:33 +0300 Subject: [PATCH 0247/1406] update --- lua/platformio/piolsp.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 16c4e112..7d542f33 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -38,6 +38,7 @@ function M.lsp_restarti(name) for _, c in ipairs(clients) do local attached_buffers = vim.tbl_keys(c.attached_buffers) ---@type integer[] + print(vim.inspect(c.attached_buffers)) local configc = c.config vim.lsp.stop_client(c.id, true) vim.defer_fn(function() From 8717e134c5ff3c7b3349644485c0a8a21a872c61 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 11:30:00 +0300 Subject: [PATCH 0248/1406] update --- lua/platformio/piolsp.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 7d542f33..687f4b75 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -40,7 +40,7 @@ function M.lsp_restarti(name) local attached_buffers = vim.tbl_keys(c.attached_buffers) ---@type integer[] print(vim.inspect(c.attached_buffers)) local configc = c.config - vim.lsp.stop_client(c.id, true) + c:stop(c.id, true) vim.defer_fn(function() local id = vim.lsp.start(configc) if id then From b4b2712c4723a84a1dae6e6c3a7a21c12662d21c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 11:55:21 +0300 Subject: [PATCH 0249/1406] update --- lua/platformio/piolsp.lua | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 687f4b75..af690669 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -40,17 +40,18 @@ function M.lsp_restarti(name) local attached_buffers = vim.tbl_keys(c.attached_buffers) ---@type integer[] print(vim.inspect(c.attached_buffers)) local configc = c.config - c:stop(c.id, true) + c:stop(true) + vim.defer_fn(function() local id = vim.lsp.start(configc) - if id then - for _, b in ipairs(attached_buffers) do - vim.lsp.buf_attach_client(b, id) - end - vim.notify(string.format('Lsp `%s` has been restarted.', config.name)) - else - vim.notify(string.format('Error restarting `%s`.', config.name), vim.log.levels.ERROR) - end + -- if id then + -- for _, b in ipairs(attached_buffers) do + -- vim.lsp.buf_attach_client(b, id) + -- end + -- vim.notify(string.format('Lsp `%s` has been restarted.', config.name)) + -- else + -- vim.notify(string.format('Error restarting `%s`.', config.name), vim.log.levels.ERROR) + -- end end, 600) end end From 1d57285c0465a5e9f556a7668ac2d82ac5297e11 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 13:08:10 +0300 Subject: [PATCH 0250/1406] update --- lua/platformio/piolsp.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index af690669..b4663136 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -43,7 +43,7 @@ function M.lsp_restarti(name) c:stop(true) vim.defer_fn(function() - local id = vim.lsp.start(configc) + local id = vim.lsp.enable(configc) -- if id then -- for _, b in ipairs(attached_buffers) do -- vim.lsp.buf_attach_client(b, id) From 6d673446fead6809c647aeb59125a0c54fea3568 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 13:16:01 +0300 Subject: [PATCH 0251/1406] update --- lua/platformio/piolsp.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index b4663136..f90ec8c3 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -43,7 +43,8 @@ function M.lsp_restarti(name) c:stop(true) vim.defer_fn(function() - local id = vim.lsp.enable(configc) + vim.lsp.config(name, config) + vim.lsp.enable(name) -- if id then -- for _, b in ipairs(attached_buffers) do -- vim.lsp.buf_attach_client(b, id) From a89305f99022ce5f64b7e86d49c5b236176651a6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 13:20:19 +0300 Subject: [PATCH 0252/1406] update --- lua/platformio/piolsp.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index f90ec8c3..63c433e0 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -43,7 +43,7 @@ function M.lsp_restarti(name) c:stop(true) vim.defer_fn(function() - vim.lsp.config(name, config) + vim.lsp.config(config) vim.lsp.enable(name) -- if id then -- for _, b in ipairs(attached_buffers) do From 519207009bf2ba62e1c0979f0f93e3b45bea2a22 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 13:26:27 +0300 Subject: [PATCH 0253/1406] update --- lua/platformio/piolsp.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 63c433e0..aeca7252 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -43,7 +43,7 @@ function M.lsp_restarti(name) c:stop(true) vim.defer_fn(function() - vim.lsp.config(config) + vim.lsp.config(name, configc) vim.lsp.enable(name) -- if id then -- for _, b in ipairs(attached_buffers) do From 0b66899f4c28b0541c1b5ec690145787527df96d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 13:37:40 +0300 Subject: [PATCH 0254/1406] update --- lua/platformio/piolsp.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index aeca7252..70bf422a 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -38,8 +38,8 @@ function M.lsp_restarti(name) for _, c in ipairs(clients) do local attached_buffers = vim.tbl_keys(c.attached_buffers) ---@type integer[] - print(vim.inspect(c.attached_buffers)) local configc = c.config + print(vim.inspect(configc)) c:stop(true) vim.defer_fn(function() From 00f03764a38ea9a68dad86ef6ad255cdda3d6acb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 13:57:54 +0300 Subject: [PATCH 0255/1406] update --- lua/platformio/pioinit.lua | 18 +++++++++++++----- lua/platformio/piolsp.lua | 9 --------- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index ddf6f661..b2c82743 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -10,7 +10,7 @@ local make_entry = require('telescope.make_entry') local utils = require('platformio.utils') local previewers = require('telescope.previewers') local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -local piolsp = require('platformio.piolsp').piolsp +local piolsp = require('platformio.piolsp') --.piolsp local boardentry_maker = function(opts) local displayer = entry_display.create({ @@ -59,13 +59,21 @@ local function pick_framework(board_details) local selection = action_state.get_selected_entry() local selected_framework = selection[1] local command = 'pio project init --board ' .. board_details['id'] .. ' --project-option "framework=' .. selected_framework .. '"' + command = command .. ' && pio run -t compiledb' -- .. '" && exit && echo "done"' - utils.ToggleTerminal(command, 'float', function() - -- require('platformio.piolsp').piolsp() - piolsp() + utils.ToggleTerminal(command, 'float') + vim.defer_fn(function() + vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) + piolsp.gitignore_lsp_configs('compile_commands.json') boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') - end) + piolsp.lsp_restarti('clangd') + end, 600) + -- utils.ToggleTerminal(command, 'float', function() + -- -- require('platformio.piolsp').piolsp() + -- piolsp() + -- boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') + -- end) end) return true end, diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 70bf422a..344c70e6 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -37,7 +37,6 @@ function M.lsp_restarti(name) -- end for _, c in ipairs(clients) do - local attached_buffers = vim.tbl_keys(c.attached_buffers) ---@type integer[] local configc = c.config print(vim.inspect(configc)) c:stop(true) @@ -45,14 +44,6 @@ function M.lsp_restarti(name) vim.defer_fn(function() vim.lsp.config(name, configc) vim.lsp.enable(name) - -- if id then - -- for _, b in ipairs(attached_buffers) do - -- vim.lsp.buf_attach_client(b, id) - -- end - -- vim.notify(string.format('Lsp `%s` has been restarted.', config.name)) - -- else - -- vim.notify(string.format('Error restarting `%s`.', config.name), vim.log.levels.ERROR) - -- end end, 600) end end From 7a3c170eadce43631b9181e14fa419879c564b87 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 14:09:29 +0300 Subject: [PATCH 0256/1406] update --- lua/platformio/pioinit.lua | 3 +-- lua/platformio/piolib.lua | 12 ++++++++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index b2c82743..117c884b 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -60,14 +60,13 @@ local function pick_framework(board_details) local selected_framework = selection[1] local command = 'pio project init --board ' .. board_details['id'] .. ' --project-option "framework=' .. selected_framework .. '"' command = command .. ' && pio run -t compiledb' - -- .. '" && exit && echo "done"' utils.ToggleTerminal(command, 'float') vim.defer_fn(function() vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) piolsp.gitignore_lsp_configs('compile_commands.json') boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') - piolsp.lsp_restarti('clangd') + piolsp.lsp_restart('clangd') end, 600) -- utils.ToggleTerminal(command, 'float', function() -- -- require('platformio.piolsp').piolsp() diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 0211b9cf..a0f21630 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -10,7 +10,7 @@ local actions = require('telescope.actions') local action_state = require('telescope.actions.state') local utils = require('platformio.utils') local previewers = require('telescope.previewers') -local piolsp = require('platformio.piolsp').piolsp +local piolsp = require('platformio.piolsp') --.piolsp local libentry_maker = function(opts) local displayer = entry_display.create({ @@ -59,13 +59,21 @@ local function pick_library(json_data) local selection = action_state.get_selected_entry() local pkg_name = selection['value']['owner'] .. '/' .. selection['value']['name'] local command = 'pio pkg install --library "' .. pkg_name .. '"' + command = command .. ' && pio run -t compiledb' + + utils.ToggleTerminal(command, 'float') + vim.defer_fn(function() + vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) + piolsp.gitignore_lsp_configs('compile_commands.json') + piolsp.lsp_restart('clangd') + end, 600) -- local command = 'pio pkg install --library "' .. pkg_name .. '" && exit && echo "done"' -- utils.ToggleTerminal(command, 'float', function() -- -- require('platformio.piolsp').piolsp() -- piolsp() -- end) - utils.ToggleTerminal(command, 'float', piolsp) + -- utils.ToggleTerminal(command, 'float', piolsp) end) return true end, From e35d18bbaf3a8e77b79a1e1137a5dc1854faaf36 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 14:25:46 +0300 Subject: [PATCH 0257/1406] update --- lua/platformio/lspClangd.lua | 1 + lua/platformio/pioinit.lua | 2 +- lua/platformio/piolib.lua | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index bf685963..2e4b53ca 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -213,6 +213,7 @@ vim.lsp.config('pyrefly', pyrefly) local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) +boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 117c884b..0d913037 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -67,7 +67,7 @@ local function pick_framework(board_details) piolsp.gitignore_lsp_configs('compile_commands.json') boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') piolsp.lsp_restart('clangd') - end, 600) + end, 3000) -- utils.ToggleTerminal(command, 'float', function() -- -- require('platformio.piolsp').piolsp() -- piolsp() diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index a0f21630..53a9ad7f 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -66,7 +66,7 @@ local function pick_library(json_data) vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) piolsp.gitignore_lsp_configs('compile_commands.json') piolsp.lsp_restart('clangd') - end, 600) + end, 900) -- local command = 'pio pkg install --library "' .. pkg_name .. '" && exit && echo "done"' -- utils.ToggleTerminal(command, 'float', function() From 2761f95f9549c3d413d66cbd35c6e99b35ffbc12 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 16:25:08 +0300 Subject: [PATCH 0258/1406] update --- lua/platformio/boilerplate.lua | 20 +++++++++++++------- mini_nvimPlatformio.lua | 2 +- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index edf6a755..ebc530a6 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -4,7 +4,7 @@ local uv = vim.loop local boilerplate = {} boilerplate['arduino'] = { - filename = 'main.cpp', + -- filename = 'main.cpp', content = [[ #include @@ -19,7 +19,7 @@ void loop() { } boilerplate['.clangd_cmd'] = { - filename = '.clangd_cmd', + -- filename = '.clangd_cmd', content = [[ clangd --all-scopes-completion @@ -43,7 +43,7 @@ clangd } boilerplate['.clang-format'] = { - filename = '.clang-format', + -- filename = '.clang-format', content = [[ --- Language: Cpp @@ -297,7 +297,7 @@ WhitespaceSensitiveMacros: -- local home = vim.env.HOME -- print(home) boilerplate['.clangd'] = { - filename = '.clangd', + -- filename = '.clangd', content = [[ CompileFlags: Remove: [ @@ -338,7 +338,7 @@ Diagnostics: ]], } boilerplate['.stylua.toml'] = { - filename = '.stylua.toml', + -- filename = '.stylua.toml', content = [[ syntax = "All" column_width = 132 @@ -355,17 +355,23 @@ enabled = false ]], } -function M.boilerplate_gen(framework, src_path) +function M.boilerplate_gen(framework, src_path, filename) + filename = filename or framework -- print(src_path .. '/0' .. framework) local entry = boilerplate[framework] if not entry then return end -- - local file_path = src_path .. '/' .. entry.filename + local file_path = src_path .. '/' .. filename if vim.uv.fs_stat(file_path) then return -- return if file exists end + + if vim.fn.isdirectory(src_path) == 0 then + vim.fn.mkdir(src_path, 'p') + end + -- uv.fs_open(file_path, 'w', 420, function(_, fd) -- crtete file if directory of the path exists if not fd then diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 0e0de3fb..12ae07f5 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -154,6 +154,7 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- pick a temp root local tmp = vim.loop.os_tmpdir() .. '/nvim-temp' +vim.env.XDG_CONFIG_HOME = vim.fn.expand('~/.miniConfig') vim.env.XDG_DATA_HOME = tmp .. '/data' vim.env.XDG_CACHE_HOME = tmp .. '/cache' vim.env.XDG_STATE_HOME = tmp .. '/state' @@ -332,7 +333,6 @@ local output -- local expand_dir = vim.fn.expand(pynvim_env) if not vim.uv.fs_stat(pynvim_env) then if not isWindows then - print('linux:') output = vim.fn.system({ 'python3', '-m', 'venv', pynvim_env }) print(output) vim.fn.system({ 'chmod', '755', '-R', pynvim_bin }) From 15ec930ce1805a10d0b4db42b29d576e169f4512 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 16:28:20 +0300 Subject: [PATCH 0259/1406] update --- lua/platformio/pioinit.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 0d913037..c68d4d1e 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -65,7 +65,7 @@ local function pick_framework(board_details) vim.defer_fn(function() vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) piolsp.gitignore_lsp_configs('compile_commands.json') - boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') + boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') piolsp.lsp_restart('clangd') end, 3000) -- utils.ToggleTerminal(command, 'float', function() From 2fb8aa795ad3070f2f3e343d0ecbe255e704cab0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 16:31:01 +0300 Subject: [PATCH 0260/1406] update --- lua/platformio/lspClangd.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 2e4b53ca..546f523a 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -214,6 +214,7 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) +boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) From 1aed3f4d745fe8e2889eab83df0c982d8cb1e5c4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 17:56:25 +0300 Subject: [PATCH 0261/1406] update --- lua/platformio/lspClangd.lua | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 546f523a..7d78a833 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -214,8 +214,10 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) -boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') -boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) +print(vim.env.XDG_CONFIG_HOME) +-- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') +-- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') +-- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) From 5d01f470c8cf894a588a2e4607d3338eadca8c3b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 18:01:51 +0300 Subject: [PATCH 0262/1406] update --- lua/platformio/lspClangd.lua | 5 ++--- mini_nvimPlatformio.lua | 3 ++- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 7d78a833..4fb4690f 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -215,9 +215,8 @@ boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) print(vim.env.XDG_CONFIG_HOME) --- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') --- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') --- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) +boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') +boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 12ae07f5..16d09865 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -154,7 +154,8 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- pick a temp root local tmp = vim.loop.os_tmpdir() .. '/nvim-temp' -vim.env.XDG_CONFIG_HOME = vim.fn.expand('~/.miniConfig') +-- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') +vim.env.XDG_CONFIG_HOME = tmp .. 'miniConfig' vim.env.XDG_DATA_HOME = tmp .. '/data' vim.env.XDG_CACHE_HOME = tmp .. '/cache' vim.env.XDG_STATE_HOME = tmp .. '/state' From 67f3d3e13007cb44500d914a30c694b70302d2e4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 19:06:04 +0300 Subject: [PATCH 0263/1406] update --- mini_nvimPlatformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 16d09865..975b0c4d 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -155,7 +155,7 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) local tmp = vim.loop.os_tmpdir() .. '/nvim-temp' -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') -vim.env.XDG_CONFIG_HOME = tmp .. 'miniConfig' +vim.env.XDG_CONFIG_HOME = tmp .. '/miniConfig' vim.env.XDG_DATA_HOME = tmp .. '/data' vim.env.XDG_CACHE_HOME = tmp .. '/cache' vim.env.XDG_STATE_HOME = tmp .. '/state' From 98d71e1689d20ec52a7d09453525e9a2f913e4b1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 19:09:51 +0300 Subject: [PATCH 0264/1406] update --- lua/platformio/lspClangd.lua | 1 - mini_nvimPlatformio.lua | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 4fb4690f..546f523a 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -214,7 +214,6 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) -print(vim.env.XDG_CONFIG_HOME) boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 975b0c4d..12ae07f5 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -154,8 +154,7 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- pick a temp root local tmp = vim.loop.os_tmpdir() .. '/nvim-temp' --- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') -vim.env.XDG_CONFIG_HOME = tmp .. '/miniConfig' +vim.env.XDG_CONFIG_HOME = vim.fn.expand('~/.miniConfig') vim.env.XDG_DATA_HOME = tmp .. '/data' vim.env.XDG_CACHE_HOME = tmp .. '/cache' vim.env.XDG_STATE_HOME = tmp .. '/state' From 3ab63f4a753241af042d3c6b0d755d3a04d31e02 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 19:10:20 +0300 Subject: [PATCH 0265/1406] update --- lua/platformio/lspClangd.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 546f523a..4fb4690f 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -214,6 +214,7 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) +print(vim.env.XDG_CONFIG_HOME) boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) From ab9326d554a9a9137ef54f32dcd5d45aa6d9f933 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 21:16:17 +0300 Subject: [PATCH 0266/1406] update --- mini_nvimPlatformio.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 12ae07f5..1b954680 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -352,6 +352,7 @@ if not vim.uv.fs_stat(pynvim_env) then vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'debugpy' }) vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'isort' }) vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'scons' }) + vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'sconscrip' }) vim.fn.system({ pynvim_python, '-m', 'pip', 'install', 'yamllint' }) vim.fn.system({ pynvim_python, '-m', 'pip', 'install', '-U', 'platformio' }) -- vim.fn.system({ 'pip', 'install', '-U', 'platformio' }) From c77a8d83db5b90259165c8877fc2353a13c82203 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 21:27:27 +0300 Subject: [PATCH 0267/1406] update --- lua/platformio/boilerplate.lua | 9 +++++++++ lua/platformio/lspClangd.lua | 1 + 2 files changed, 10 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index ebc530a6..2454cf88 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -18,6 +18,15 @@ void loop() { ]], } +boilerplate['extra_script.py'] = { + -- filename = 'main.cpp', + content = [[ +from SCons.Script import DefaultEnvironment +env = DefaultEnvironment() +env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) +]], +} + boilerplate['.clangd_cmd'] = { -- filename = '.clangd_cmd', content = [[ diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 4fb4690f..32eb6e9c 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -216,6 +216,7 @@ boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) print(vim.env.XDG_CONFIG_HOME) boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') +boilerplate_gen([[extra_script.py]], vim.g.platformioRootDir) boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) From f7e9943283b2e2bbcefd81744254d55cdb351dd7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 5 Apr 2026 21:42:16 +0300 Subject: [PATCH 0268/1406] update --- lua/platformio/boilerplate.lua | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 2454cf88..4ead26c7 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -24,6 +24,9 @@ boilerplate['extra_script.py'] = { from SCons.Script import DefaultEnvironment env = DefaultEnvironment() env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) + +# Optional: ensure it saves to the root of your project +env.Replace(COMPILATIONDB_PATH="compile_commands.json") ]], } From 32dc7e00e7f49e0fcb65da8bd34412315404c46d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 05:21:25 +0300 Subject: [PATCH 0269/1406] update --- lua/platformio/boilerplate.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 4ead26c7..9d8bd01c 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -49,10 +49,11 @@ clangd --offset-encoding=utf-8 --pch-storage=memory --pretty ---query-driver=** --ranking-model=decision_forest +--query-driver=" .. vim.env.HOME .. "/.platformio/packages/toolchain-*/bin/*" ]], } +--query-driver=** boilerplate['.clang-format'] = { -- filename = '.clang-format', From 4913b0eb7bcf8eedbc91089b342ed8ad693d4a95 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 05:42:27 +0300 Subject: [PATCH 0270/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 9d8bd01c..39cfe20a 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -50,7 +50,7 @@ clangd --pch-storage=memory --pretty --ranking-model=decision_forest ---query-driver=" .. vim.env.HOME .. "/.platformio/packages/toolchain-*/bin/*" +--query-driver=vim.env.HOME .. "/.platformio/packages/toolchain-*/bin/*" ]], } --query-driver=** From 613f1ac51d0202fb0004e799d9f09a7dac1f7c70 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 05:55:37 +0300 Subject: [PATCH 0271/1406] update --- lua/platformio/boilerplate.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 39cfe20a..6f87349a 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -50,9 +50,10 @@ clangd --pch-storage=memory --pretty --ranking-model=decision_forest ---query-driver=vim.env.HOME .. "/.platformio/packages/toolchain-*/bin/*" -]], +--query-driver=]] .. vim.env.HOME .. [[.platformio/packages/toolchain-*/bin/*]], } + +local cmd = [[clangd --query-driver=]] .. vim.env.HOME .. [[/.platformio/packages/*]] --query-driver=** boilerplate['.clang-format'] = { From 98b5e95990eb9115e37ac58e2b412ec06c7a5082 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 06:15:40 +0300 Subject: [PATCH 0272/1406] update --- lua/platformio/lspClangd.lua | 42 +++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 32eb6e9c..a4e22025 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -70,7 +70,7 @@ local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') if mok then mason_lspconfig.setup({ -- ensure_installed = { 'clangd', 'pyrefly' }, - ensure_installed = { 'clangd', 'lua_ls', 'pyrefly' }, + ensure_installed = { 'clangd', 'lua_ls', 'pyrefly', 'yamlls' }, automatic_enable = true, -- this will automatically enable LSP servers after lsp.config }) end @@ -185,6 +185,46 @@ local lua_ls = { } vim.lsp.config('lua_ls', lua_ls) +local yamlls = { + -- on_attach = opts.on_attach, + cmd = { 'yaml-language-server', '--stdio' }, + filetypes = { 'yaml', 'yaml.docker-compose', 'yaml.gitlab' }, + settings = { + yaml = { + hover = true, + validate = false, + completion = true, + keyOrdering = false, + format = { enabled = false }, + redhat = { + telemetry = { enabled = false }, + }, + schemaStore = { + enable = true, + url = 'https://www.schemastore.org/api/json/catalog.json', + }, + schemas = { + kubernetes = '*.yaml', + ['http://json.schemastore.org/github-workflow'] = '.github/workflows/*', + ['http://json.schemastore.org/github-action'] = '.github/action.{yml,yaml}', + ['https://raw.githubusercontent.com/microsoft/azure-pipelines-vscode/master/service-schema.json'] = 'azure-pipelines.yml', + ['http://json.schemastore.org/ansible-stable-2.9'] = 'roles/tasks/*.{yml,yaml}', + ['http://json.schemastore.org/prettierrc'] = '.prettierrc.{yml,yaml}', + ['http://json.schemastore.org/kustomization'] = 'kustomization.{yml,yaml}', + ['http://json.schemastore.org/ansible-playbook'] = '*play*.{yml,yaml}', + ['http://json.schemastore.org/chart'] = 'Chart.{yml,yaml}', + ['https://json.schemastore.org/dependabot-v2'] = '.github/dependabot.{yml,yaml}', + ['https://gitlab.com/gitlab-org/gitlab/-/raw/master/app/assets/javascripts/editor/schema/ci.json'] = '*gitlab-ci*.{yml,yaml}', + ['https://raw.githubusercontent.com/OAI/OpenAPI-Specification/main/schemas/v3.1/schema.json'] = '*api*.{yml,yaml}', + ['https://raw.githubusercontent.com/compose-spec/compose-spec/master/schema/compose-spec.json'] = '*docker-compose*.{yml,yaml}', + ['https://raw.githubusercontent.com/argoproj/argo-workflows/master/api/jsonschema/schema.json'] = '*flow*.{yml,yaml}', + ['https://raw.githubusercontent.com/yannh/kubernetes-json-schema/refs/heads/master/v1.32.1-standalone-strict/all.json'] = '/*.k8s.yaml', + }, + }, + }, +} +vim.lsp.config('yamlls', yamlls) + -- local stylua = { -- cmd = { 'stylua', '--search-parent-directories', '--stdin-filepath', '$FILENAME', '-' }, -- filetypes = { 'lua' }, From f660ebac8884fa36cda3aa99b03d99ca5edc7722 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 07:17:12 +0300 Subject: [PATCH 0273/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/piolsp.lua | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 6f87349a..4752c7ab 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -26,7 +26,7 @@ env = DefaultEnvironment() env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) # Optional: ensure it saves to the root of your project -env.Replace(COMPILATIONDB_PATH="compile_commands.json") +#env.Replace(COMPILATIONDB_PATH="compile_commands.json") ]], } diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 344c70e6..df598298 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -38,7 +38,7 @@ function M.lsp_restarti(name) for _, c in ipairs(clients) do local configc = c.config - print(vim.inspect(configc)) + -- print(vim.inspect(configc)) c:stop(true) vim.defer_fn(function() @@ -83,7 +83,7 @@ function M.piolsp() -- -- print('number of attaced: ' .. #clangd.attached_buffers) -- -- print('piolsp: lsp restart ' .. clangd.name) -- pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) - M.lsp_restarti('clangd') + M.lsp_restart('clangd') -- vim.cmd('lsp restart clangd') -- end -- else From 974a830344f17de413a44fdd1efb2421a8c61cd6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 07:56:31 +0300 Subject: [PATCH 0274/1406] update --- lua/platformio/boilerplate.lua | 18 +++++++++++++++--- lua/platformio/lspClangd.lua | 1 - 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 4752c7ab..cfaa7c03 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -21,14 +21,26 @@ void loop() { boilerplate['extra_script.py'] = { -- filename = 'main.cpp', content = [[ +Import("env") + +def set_compilation_db_toolchain(env): + # This runs after the environment is fully initialized + env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) + +# Add the function as a callback for the environment +env.AddMethod(set_compilation_db_toolchain) +set_compilation_db_toolchain(env) + +]], +} +--[[ from SCons.Script import DefaultEnvironment env = DefaultEnvironment() env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) # Optional: ensure it saves to the root of your project #env.Replace(COMPILATIONDB_PATH="compile_commands.json") -]], -} +]] boilerplate['.clangd_cmd'] = { -- filename = '.clangd_cmd', @@ -53,7 +65,7 @@ clangd --query-driver=]] .. vim.env.HOME .. [[.platformio/packages/toolchain-*/bin/*]], } -local cmd = [[clangd --query-driver=]] .. vim.env.HOME .. [[/.platformio/packages/*]] +--query-driver = [[clangd --query-driver=]] .. vim.env.HOME .. [[/.platformio/packages/*]] --query-driver=** boilerplate['.clang-format'] = { diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index a4e22025..e426107c 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -254,7 +254,6 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) -print(vim.env.XDG_CONFIG_HOME) boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') boilerplate_gen([[extra_script.py]], vim.g.platformioRootDir) boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) From 7a49e80c04de14f50c79e794225d12bf0984553d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 08:11:46 +0300 Subject: [PATCH 0275/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index cfaa7c03..e3496940 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -62,7 +62,7 @@ clangd --pch-storage=memory --pretty --ranking-model=decision_forest ---query-driver=]] .. vim.env.HOME .. [[.platformio/packages/toolchain-*/bin/*]], +--query-driver=]] .. vim.env.HOME .. [[/.platformio/packages/toolchain-*/bin/*]], } --query-driver = [[clangd --query-driver=]] .. vim.env.HOME .. [[/.platformio/packages/*]] From a50056e619e64a41b23356a7200c26d8da31aed0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 08:21:01 +0300 Subject: [PATCH 0276/1406] update --- lua/platformio/lspClangd.lua | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index e426107c..73e81f07 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -1,3 +1,15 @@ +---------------------------------------------------------------------------------------- +-- INFO: create clangd required files +----------------------------------------------------------------------------------------- +local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) +boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) +boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') +boilerplate_gen([[extra_script.py]], vim.g.platformioRootDir) +boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) +boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) +boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) --------------------------------------------------------------------------------- local ok, result ok, result = pcall(require, 'fidget') @@ -105,7 +117,7 @@ if vim.fn.filereadable(fname) == 1 then ok, result = pcall(vim.fn.readfile, fname) if ok then cmd = result - -- print(vim.inspect(cmd)) + print(vim.inspect(cmd)) end end @@ -247,19 +259,6 @@ local pyrefly = { } vim.lsp.config('pyrefly', pyrefly) ----------------------------------------------------------------------------------------- --- INFO: create clangd required files ------------------------------------------------------------------------------------------ -local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) -boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) -boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') -boilerplate_gen([[extra_script.py]], vim.g.platformioRootDir) -boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) -boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) -boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) - -- require('platformio.piolsp').piolsp() if vim.fn.has('nvim-0.12') then if #vim.lsp.get_clients() > 0 then From 39dd0a8ed44144c26c16ab916870248c0d35b4cf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 08:26:11 +0300 Subject: [PATCH 0277/1406] update --- lua/platformio/lspClangd.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 73e81f07..36865be4 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -116,8 +116,9 @@ local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) if vim.fn.filereadable(fname) == 1 then ok, result = pcall(vim.fn.readfile, fname) if ok then - cmd = result - print(vim.inspect(cmd)) + -- cmd = result + print(result) + -- print(vim.inspect(cmd)) end end From 4610c308a8950387da0435f5ddf1c6a5faf2e2e4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 08:31:08 +0300 Subject: [PATCH 0278/1406] update --- lua/platformio/lspClangd.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 36865be4..fbc4edd6 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -113,6 +113,7 @@ vim.lsp.config('*', { ----------------------------------------------------------------------------------------- local cmd = { 'clangd' } local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) +print(fname) if vim.fn.filereadable(fname) == 1 then ok, result = pcall(vim.fn.readfile, fname) if ok then From 9e1baf1c298d8f84df9ab3b1b3435bd2d1081bcf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 08:45:33 +0300 Subject: [PATCH 0279/1406] update --- lua/platformio/lspClangd.lua | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index fbc4edd6..fee9e7c9 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -113,12 +113,16 @@ vim.lsp.config('*', { ----------------------------------------------------------------------------------------- local cmd = { 'clangd' } local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) -print(fname) if vim.fn.filereadable(fname) == 1 then ok, result = pcall(vim.fn.readfile, fname) if ok then - -- cmd = result - print(result) + -- local content = table.concat(vim.fn.readfile('my_file.txt'), '\n') + -- local content = table.concat(result, '\n') + -- result = vim.json.decode(result) + -- cmd = vim.tbl_deep_extend('force', cmd or {}, result.cmd) --working fine + -- cmd = cmd.result + cmd = result + print(vim.inspect(result)) -- print(vim.inspect(cmd)) end end From d2d17a6d98eff32db32359d8580973e04fff2547 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 08:50:10 +0300 Subject: [PATCH 0280/1406] update --- lua/platformio/lspClangd.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index fee9e7c9..adf52295 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -113,9 +113,11 @@ vim.lsp.config('*', { ----------------------------------------------------------------------------------------- local cmd = { 'clangd' } local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) +print(fname) if vim.fn.filereadable(fname) == 1 then ok, result = pcall(vim.fn.readfile, fname) if ok then + -- vim.g.platformioRootDir -- local content = table.concat(vim.fn.readfile('my_file.txt'), '\n') -- local content = table.concat(result, '\n') -- result = vim.json.decode(result) From c46cf3fcbc40c749b726cb908336c4df0d087e62 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 08:54:07 +0300 Subject: [PATCH 0281/1406] update --- lua/platformio/lspClangd.lua | 12 ------------ plugin/platformio.lua | 13 +++++++++++++ 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index adf52295..08607959 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -1,15 +1,3 @@ ----------------------------------------------------------------------------------------- --- INFO: create clangd required files ------------------------------------------------------------------------------------------ -local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) -boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) -boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') -boilerplate_gen([[extra_script.py]], vim.g.platformioRootDir) -boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) -boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) -boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) --------------------------------------------------------------------------------- local ok, result ok, result = pcall(require, 'fidget') diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 63bdd48a..1f189480 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -6,6 +6,19 @@ -- +: At least one argument. -- -1: Zero or one argument (like ?, explicitly). +---------------------------------------------------------------------------------------- +-- INFO: create clangd required files +----------------------------------------------------------------------------------------- +local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) +boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) +boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') +boilerplate_gen([[extra_script.py]], vim.g.platformioRootDir) +boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) +boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) +boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) + local utils = require('platformio.utils') local piolsserial = require('platformio.piolsserial') From 63cb982fc2a2384a13fd80386fd333b94a05b2eb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 08:59:38 +0300 Subject: [PATCH 0282/1406] update --- lua/platformio/init.lua | 12 ++++++++++++ plugin/platformio.lua | 13 ------------- 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index 69686ec3..d5838750 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -155,6 +155,18 @@ local function validateMenu(menu) end function M.setup(user_config) + ---------------------------------------------------------------------------------------- + -- INFO: create clangd required files + ----------------------------------------------------------------------------------------- + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) + boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) + boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') + boilerplate_gen([[extra_script.py]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) + boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) if next(user_config) ~= nil then if user_config.lspClangd then vim.validate('lspClangd', user_config.lspClangd, 'table', true) diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 1f189480..63bdd48a 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -6,19 +6,6 @@ -- +: At least one argument. -- -1: Zero or one argument (like ?, explicitly). ----------------------------------------------------------------------------------------- --- INFO: create clangd required files ------------------------------------------------------------------------------------------ -local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) -boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) -boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') -boilerplate_gen([[extra_script.py]], vim.g.platformioRootDir) -boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) -boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) -boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) - local utils = require('platformio.utils') local piolsserial = require('platformio.piolsserial') From a0b6abcc3b9550e8875420f7eecbf4306637c288 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 09:11:02 +0300 Subject: [PATCH 0283/1406] update --- lua/platformio/init.lua | 12 ----------- lua/platformio/lspClangd.lua | 39 +++++++++++++++++++++++++----------- 2 files changed, 27 insertions(+), 24 deletions(-) diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index d5838750..69686ec3 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -155,18 +155,6 @@ local function validateMenu(menu) end function M.setup(user_config) - ---------------------------------------------------------------------------------------- - -- INFO: create clangd required files - ----------------------------------------------------------------------------------------- - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) - boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) - boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') - boilerplate_gen([[extra_script.py]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) - boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) if next(user_config) ~= nil then if user_config.lspClangd then vim.validate('lspClangd', user_config.lspClangd, 'table', true) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 08607959..cdbab38e 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -1,4 +1,17 @@ +---------------------------------------------------------------------------------------- +-- INFO: create clangd required files +----------------------------------------------------------------------------------------- +local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) +boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) +boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') +boilerplate_gen([[extra_script.py]], vim.g.platformioRootDir) +boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) +boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) +boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) --------------------------------------------------------------------------------- + local ok, result ok, result = pcall(require, 'fidget') if ok then @@ -96,6 +109,7 @@ vim.lsp.config('*', { root_markers = { '.git' }, workspace_required = false, }) + ---------------------------------------------------------------------------------------- -- INFO: configure clangd lsp server ----------------------------------------------------------------------------------------- @@ -103,18 +117,19 @@ local cmd = { 'clangd' } local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) print(fname) if vim.fn.filereadable(fname) == 1 then - ok, result = pcall(vim.fn.readfile, fname) - if ok then - -- vim.g.platformioRootDir - -- local content = table.concat(vim.fn.readfile('my_file.txt'), '\n') - -- local content = table.concat(result, '\n') - -- result = vim.json.decode(result) - -- cmd = vim.tbl_deep_extend('force', cmd or {}, result.cmd) --working fine - -- cmd = cmd.result - cmd = result - print(vim.inspect(result)) - -- print(vim.inspect(cmd)) - end + -- ok, result = pcall(vim.fn.readfile, fname) + -- if ok then + result = vim.fn.readfile(fname) + -- vim.g.platformioRootDir + -- local content = table.concat(vim.fn.readfile('my_file.txt'), '\n') + -- local content = table.concat(result, '\n') + -- result = vim.json.decode(result) + -- cmd = vim.tbl_deep_extend('force', cmd or {}, result.cmd) --working fine + -- cmd = cmd.result + cmd = result or cmd + print(vim.inspect(result)) + -- print(vim.inspect(cmd)) + -- end end local clangd = { From 214c57f86b9a091106aed38d4ac3196f998fec9e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 09:23:07 +0300 Subject: [PATCH 0284/1406] update --- lua/platformio/lspClangd.lua | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index cdbab38e..c88f480b 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -115,8 +115,10 @@ vim.lsp.config('*', { ----------------------------------------------------------------------------------------- local cmd = { 'clangd' } local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) +local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) print(fname) -if vim.fn.filereadable(fname) == 1 then +-- if vim.fn.filereadable(fname) == 1 then +if vim.uv.fs_stat(fname) then -- ok, result = pcall(vim.fn.readfile, fname) -- if ok then result = vim.fn.readfile(fname) @@ -127,6 +129,7 @@ if vim.fn.filereadable(fname) == 1 then -- cmd = vim.tbl_deep_extend('force', cmd or {}, result.cmd) --working fine -- cmd = cmd.result cmd = result or cmd + print(vim.inspect(cmd)) print(vim.inspect(result)) -- print(vim.inspect(cmd)) -- end From 250dd37560814a514712d66b15bae985e82990d4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 09:24:54 +0300 Subject: [PATCH 0285/1406] update --- lua/platformio/lspClangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index c88f480b..93f71b55 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -128,9 +128,9 @@ if vim.uv.fs_stat(fname) then -- result = vim.json.decode(result) -- cmd = vim.tbl_deep_extend('force', cmd or {}, result.cmd) --working fine -- cmd = cmd.result - cmd = result or cmd print(vim.inspect(cmd)) print(vim.inspect(result)) + cmd = result or cmd -- print(vim.inspect(cmd)) -- end end From 0b7370547a80be464dbc72c58fecd426ee5a16b2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 09:30:20 +0300 Subject: [PATCH 0286/1406] update --- lua/platformio/lspClangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 93f71b55..53c70b76 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -131,7 +131,7 @@ if vim.uv.fs_stat(fname) then print(vim.inspect(cmd)) print(vim.inspect(result)) cmd = result or cmd - -- print(vim.inspect(cmd)) + print(vim.inspect(cmd)) -- end end From e047e1b7a2d280c831e4d390472aed56558da7cd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 09:31:32 +0300 Subject: [PATCH 0287/1406] update --- lua/platformio/lspClangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 53c70b76..331eda36 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -5,11 +5,11 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) -boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') boilerplate_gen([[extra_script.py]], vim.g.platformioRootDir) boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) +boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') --------------------------------------------------------------------------------- local ok, result From 0095b04be31f6e5465f1f2e9f49ecc15526b51ad Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 09:38:39 +0300 Subject: [PATCH 0288/1406] update --- lua/platformio/lspClangd.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 331eda36..09cd8ed3 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -114,8 +114,8 @@ vim.lsp.config('*', { -- INFO: configure clangd lsp server ----------------------------------------------------------------------------------------- local cmd = { 'clangd' } -local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) -local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) +local fname = string.format('%s/.clangd_cmd', vim.g.platformioRootDir) +-- local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) print(fname) -- if vim.fn.filereadable(fname) == 1 then if vim.uv.fs_stat(fname) then From 04232071c143242a7285a5c4a031952e2d58a608 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 10:20:17 +0300 Subject: [PATCH 0289/1406] update --- lua/platformio/lspClangd.lua | 21 ++++++--------------- mini_nvimPlatformio.lua | 2 +- 2 files changed, 7 insertions(+), 16 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 09cd8ed3..5fb38c94 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -9,7 +9,7 @@ boilerplate_gen([[extra_script.py]], vim.g.platformioRootDir) boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) -boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') +-- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') --------------------------------------------------------------------------------- local ok, result @@ -119,20 +119,11 @@ local fname = string.format('%s/.clangd_cmd', vim.g.platformioRootDir) print(fname) -- if vim.fn.filereadable(fname) == 1 then if vim.uv.fs_stat(fname) then - -- ok, result = pcall(vim.fn.readfile, fname) - -- if ok then - result = vim.fn.readfile(fname) - -- vim.g.platformioRootDir - -- local content = table.concat(vim.fn.readfile('my_file.txt'), '\n') - -- local content = table.concat(result, '\n') - -- result = vim.json.decode(result) - -- cmd = vim.tbl_deep_extend('force', cmd or {}, result.cmd) --working fine - -- cmd = cmd.result - print(vim.inspect(cmd)) - print(vim.inspect(result)) - cmd = result or cmd - print(vim.inspect(cmd)) - -- end + ok, result = pcall(vim.fn.readfile, fname) + if ok then + cmd = result + print(vim.inspect(cmd)) + end end local clangd = { diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 1b954680..df867017 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -154,7 +154,7 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- pick a temp root local tmp = vim.loop.os_tmpdir() .. '/nvim-temp' -vim.env.XDG_CONFIG_HOME = vim.fn.expand('~/.miniConfig') +-- vim.env.XDG_CONFIG_HOME = vim.fn.expand('~/.miniConfig') vim.env.XDG_DATA_HOME = tmp .. '/data' vim.env.XDG_CACHE_HOME = tmp .. '/cache' vim.env.XDG_STATE_HOME = tmp .. '/state' From c82934c44e775621f44393f703f6c3ce60333003 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 10:28:05 +0300 Subject: [PATCH 0290/1406] update --- lua/platformio/lspClangd.lua | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 5fb38c94..e06e5486 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -117,6 +117,16 @@ local cmd = { 'clangd' } local fname = string.format('%s/.clangd_cmd', vim.g.platformioRootDir) -- local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) print(fname) + +local f = io.open(fname, 'r') +if f then + local content = f:read('*all') + f:close() + print(content) +else + print('Could not open file') +end + -- if vim.fn.filereadable(fname) == 1 then if vim.uv.fs_stat(fname) then ok, result = pcall(vim.fn.readfile, fname) From e64bd357eb0c8e01e33996b882f4c0e7988e4dbe Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 10:31:14 +0300 Subject: [PATCH 0291/1406] update --- lua/platformio/lspClangd.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index e06e5486..8d99d7a8 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -122,6 +122,7 @@ local f = io.open(fname, 'r') if f then local content = f:read('*all') f:close() + print('read file') print(content) else print('Could not open file') From 63653857b0fdbd964c555834f5cbaa12ea923fb6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 10:41:28 +0300 Subject: [PATCH 0292/1406] update --- lua/platformio/boilerplate.lua | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index e3496940..77d092d6 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -404,19 +404,20 @@ function M.boilerplate_gen(framework, src_path, filename) print('failed to create file: ' .. file_path .. '/' .. entry.filename) return end - uv.fs_write(fd, entry.content, 0, function(werr, _) - if werr then - print('failed to write to file: ' .. file_path .. '/' .. entry.filename) - return - end - uv.fs_close(fd, function(cerr) - if cerr then - print('failed to close file: ' .. file_path .. '/' .. entry.filename) - return - end - end) - end) + -- uv.fs_write(fd, entry.content, 0, function(werr, _) + -- if werr then + -- print('failed to write to file: ' .. file_path .. '/' .. entry.filename) + -- return + -- end + -- uv.fs_close(fd, function(cerr) + -- if cerr then + -- print('failed to close file: ' .. file_path .. '/' .. entry.filename) + -- return + -- end + -- end) -- end) + uv.fs_write(fd, entry.content, 0) + uv.fs_close(fd) end) end return M From 35dd85344bfb274515ca891119713dcfcd8b70e4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 10:45:46 +0300 Subject: [PATCH 0293/1406] update --- lua/platformio/boilerplate.lua | 41 +++++++++++++++++----------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 77d092d6..e9b3b881 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -399,25 +399,26 @@ function M.boilerplate_gen(framework, src_path, filename) end -- - uv.fs_open(file_path, 'w', 420, function(_, fd) -- crtete file if directory of the path exists - if not fd then - print('failed to create file: ' .. file_path .. '/' .. entry.filename) - return - end - -- uv.fs_write(fd, entry.content, 0, function(werr, _) - -- if werr then - -- print('failed to write to file: ' .. file_path .. '/' .. entry.filename) - -- return - -- end - -- uv.fs_close(fd, function(cerr) - -- if cerr then - -- print('failed to close file: ' .. file_path .. '/' .. entry.filename) - -- return - -- end - -- end) - -- end) - uv.fs_write(fd, entry.content, 0) - uv.fs_close(fd) - end) + local fd = assert(uv.fs_open(file_path, 'w', 420)) + -- uv.fs_open(file_path, 'w', 420, function(_, fd) -- crtete file if directory of the path exists + if not fd then + print('failed to create file: ' .. file_path .. '/' .. entry.filename) + return + end + -- uv.fs_write(fd, entry.content, 0, function(werr, _) + -- if werr then + -- print('failed to write to file: ' .. file_path .. '/' .. entry.filename) + -- return + -- end + -- uv.fs_close(fd, function(cerr) + -- if cerr then + -- print('failed to close file: ' .. file_path .. '/' .. entry.filename) + -- return + -- end + -- end) + -- end) + uv.fs_write(fd, entry.content, 0) + uv.fs_close(fd) + -- end) end return M From 03a2c7ec60bde862a3701c87a5c37cc56c2892ab Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 10:52:22 +0300 Subject: [PATCH 0294/1406] update --- lua/platformio/boilerplate.lua | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index e9b3b881..76cecd5a 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -383,7 +383,6 @@ enabled = false function M.boilerplate_gen(framework, src_path, filename) filename = filename or framework - -- print(src_path .. '/0' .. framework) local entry = boilerplate[framework] if not entry then return @@ -398,27 +397,31 @@ function M.boilerplate_gen(framework, src_path, filename) vim.fn.mkdir(src_path, 'p') end - -- local fd = assert(uv.fs_open(file_path, 'w', 420)) - -- uv.fs_open(file_path, 'w', 420, function(_, fd) -- crtete file if directory of the path exists if not fd then print('failed to create file: ' .. file_path .. '/' .. entry.filename) return end - -- uv.fs_write(fd, entry.content, 0, function(werr, _) - -- if werr then - -- print('failed to write to file: ' .. file_path .. '/' .. entry.filename) + uv.fs_write(fd, entry.content, 0) + uv.fs_close(fd) + + -- uv.fs_open(file_path, 'w', 420, function(_, fd) -- crtete file if directory of the path exists + -- if not fd then + -- print('failed to create file: ' .. file_path .. '/' .. entry.filename) -- return -- end - -- uv.fs_close(fd, function(cerr) - -- if cerr then - -- print('failed to close file: ' .. file_path .. '/' .. entry.filename) + -- uv.fs_write(fd, entry.content, 0, function(werr, _) + -- if werr then + -- print('failed to write to file: ' .. file_path .. '/' .. entry.filename) -- return -- end + -- uv.fs_close(fd, function(cerr) + -- if cerr then + -- print('failed to close file: ' .. file_path .. '/' .. entry.filename) + -- return + -- end + -- end) -- end) -- end) - uv.fs_write(fd, entry.content, 0) - uv.fs_close(fd) - -- end) end return M From 622bf59e9309f16594b47aadd619321d41709b68 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 10:55:26 +0300 Subject: [PATCH 0295/1406] update --- lua/platformio/lspClangd.lua | 19 +++---------------- mini_nvimPlatformio.lua | 2 +- 2 files changed, 4 insertions(+), 17 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 8d99d7a8..068012fd 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -9,7 +9,7 @@ boilerplate_gen([[extra_script.py]], vim.g.platformioRootDir) boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) --- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') +boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') --------------------------------------------------------------------------------- local ok, result @@ -114,26 +114,13 @@ vim.lsp.config('*', { -- INFO: configure clangd lsp server ----------------------------------------------------------------------------------------- local cmd = { 'clangd' } -local fname = string.format('%s/.clangd_cmd', vim.g.platformioRootDir) --- local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) -print(fname) - -local f = io.open(fname, 'r') -if f then - local content = f:read('*all') - f:close() - print('read file') - print(content) -else - print('Could not open file') -end - +local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) -- if vim.fn.filereadable(fname) == 1 then if vim.uv.fs_stat(fname) then ok, result = pcall(vim.fn.readfile, fname) if ok then cmd = result - print(vim.inspect(cmd)) + -- print(vim.inspect(cmd)) end end diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index df867017..1b954680 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -154,7 +154,7 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- pick a temp root local tmp = vim.loop.os_tmpdir() .. '/nvim-temp' --- vim.env.XDG_CONFIG_HOME = vim.fn.expand('~/.miniConfig') +vim.env.XDG_CONFIG_HOME = vim.fn.expand('~/.miniConfig') vim.env.XDG_DATA_HOME = tmp .. '/data' vim.env.XDG_CACHE_HOME = tmp .. '/cache' vim.env.XDG_STATE_HOME = tmp .. '/state' From 14b225968095cc7d3f3234a5f1e7c6fa696cb489 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 11:02:44 +0300 Subject: [PATCH 0296/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 76cecd5a..cc9e6261 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -399,7 +399,7 @@ function M.boilerplate_gen(framework, src_path, filename) local fd = assert(uv.fs_open(file_path, 'w', 420)) if not fd then - print('failed to create file: ' .. file_path .. '/' .. entry.filename) + print('failed to create file: ' .. file_path) return end uv.fs_write(fd, entry.content, 0) From 4b5f22869bdb6bfb8428aa7a1aae800d9e2e1e4e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 11:26:49 +0300 Subject: [PATCH 0297/1406] update --- lua/platformio/boilerplate.lua | 1 + lua/platformio/pioinit.lua | 7 ++++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index cc9e6261..747b3cc4 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -397,6 +397,7 @@ function M.boilerplate_gen(framework, src_path, filename) vim.fn.mkdir(src_path, 'p') end + ------------------------------------------------------------------------------------- local fd = assert(uv.fs_open(file_path, 'w', 420)) if not fd then print('failed to create file: ' .. file_path) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index c68d4d1e..89498a9f 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -58,7 +58,12 @@ local function pick_framework(board_details) actions.close(prompt_bufnr) local selection = action_state.get_selected_entry() local selected_framework = selection[1] - local command = 'pio project init --board ' .. board_details['id'] .. ' --project-option "framework=' .. selected_framework .. '"' + + local command = 'pio project init --board ' + .. board_details['id'] + .. ' -O "lib_ldf_mode = deep" -O "extra_scripts = pre:extra_script.py" -O "framework=' + .. selected_framework + .. '"' command = command .. ' && pio run -t compiledb' utils.ToggleTerminal(command, 'float') From 7fe07830047f8ef8d894ad2ce8d7366f101a16fb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 11:39:18 +0300 Subject: [PATCH 0298/1406] update --- lua/platformio/pioinit.lua | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 89498a9f..6830c9b8 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -61,6 +61,9 @@ local function pick_framework(board_details) local command = 'pio project init --board ' .. board_details['id'] + .. ' -O "core_dir = ' + .. vim.env.PLATFORMIO_CORE_DIR + .. '"' .. ' -O "lib_ldf_mode = deep" -O "extra_scripts = pre:extra_script.py" -O "framework=' .. selected_framework .. '"' From 0b196a9f2c82b77657128e0bf8d386ddb28be9bb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 11:51:06 +0300 Subject: [PATCH 0299/1406] update --- lua/platformio/pioinit.lua | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 6830c9b8..9d57eb61 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -59,11 +59,15 @@ local function pick_framework(board_details) local selection = action_state.get_selected_entry() local selected_framework = selection[1] + -- pio project init --board \ + -- -O "packages_dir = ${platformio.core_dir}/esp32c3/packages" \ + -- -O "platforms_dir = ${platformio.core_dir}/esp32c3/platforms" local command = 'pio project init --board ' .. board_details['id'] .. ' -O "core_dir = ' .. vim.env.PLATFORMIO_CORE_DIR - .. '"' + .. '" -O "platforms_dir = ${platformio.core_dir}/platforms"' + .. ' -O "packages_dir = ${platformio.core_dir}/packages"' .. ' -O "lib_ldf_mode = deep" -O "extra_scripts = pre:extra_script.py" -O "framework=' .. selected_framework .. '"' From 7d1a6373dc2df1b0c3636d9def34b8a9adf9a5ef Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 11:56:29 +0300 Subject: [PATCH 0300/1406] update --- lua/platformio/pioinit.lua | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 9d57eb61..b70669eb 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -62,16 +62,16 @@ local function pick_framework(board_details) -- pio project init --board \ -- -O "packages_dir = ${platformio.core_dir}/esp32c3/packages" \ -- -O "platforms_dir = ${platformio.core_dir}/esp32c3/platforms" - local command = 'pio project init --board ' + local command = [[pio project init --board ]] .. board_details['id'] - .. ' -O "core_dir = ' + .. [[ -O "core_dir = ]] .. vim.env.PLATFORMIO_CORE_DIR - .. '" -O "platforms_dir = ${platformio.core_dir}/platforms"' - .. ' -O "packages_dir = ${platformio.core_dir}/packages"' - .. ' -O "lib_ldf_mode = deep" -O "extra_scripts = pre:extra_script.py" -O "framework=' + .. [[" -O "platforms_dir = ${platformio.core_dir}/platforms"]] + .. [[ -O "packages_dir = ${platformio.core_dir}/packages"]] + .. [[ -O "lib_ldf_mode = deep" -O "extra_scripts = pre:extra_script.py" -O "framework=]] .. selected_framework - .. '"' - command = command .. ' && pio run -t compiledb' + .. [["]] + command = command .. [[ && pio run -t compiledb]] utils.ToggleTerminal(command, 'float') vim.defer_fn(function() From 9cb96e8036da083e1df4503dc73194ad2c8c7e4b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 11:59:00 +0300 Subject: [PATCH 0301/1406] update --- lua/platformio/pioinit.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index b70669eb..cb19738c 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -66,8 +66,8 @@ local function pick_framework(board_details) .. board_details['id'] .. [[ -O "core_dir = ]] .. vim.env.PLATFORMIO_CORE_DIR - .. [[" -O "platforms_dir = ${platformio.core_dir}/platforms"]] - .. [[ -O "packages_dir = ${platformio.core_dir}/packages"]] + .. [[" -O "platforms_dir = \${platformio.core_dir}/platforms"]] + .. [[ -O "packages_dir = \${platformio.core_dir}/packages"]] .. [[ -O "lib_ldf_mode = deep" -O "extra_scripts = pre:extra_script.py" -O "framework=]] .. selected_framework .. [["]] From 3f60429c69b4c77c8b00fa0f6db152b9de73b21b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 13:00:20 +0300 Subject: [PATCH 0302/1406] update --- lua/platformio/pioinit.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index cb19738c..f4c76d1f 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -64,10 +64,10 @@ local function pick_framework(board_details) -- -O "platforms_dir = ${platformio.core_dir}/esp32c3/platforms" local command = [[pio project init --board ]] .. board_details['id'] - .. [[ -O "core_dir = ]] - .. vim.env.PLATFORMIO_CORE_DIR - .. [[" -O "platforms_dir = \${platformio.core_dir}/platforms"]] - .. [[ -O "packages_dir = \${platformio.core_dir}/packages"]] + -- .. [[ -O "core_dir = ]] + -- .. vim.env.PLATFORMIO_CORE_DIR + -- .. [[" -O "platforms_dir = \${platformio.core_dir}/platforms"]] + -- .. [[ -O "packages_dir = \${platformio.core_dir}/packages"]] .. [[ -O "lib_ldf_mode = deep" -O "extra_scripts = pre:extra_script.py" -O "framework=]] .. selected_framework .. [["]] From 86d8a0a3849a2f1c4de06091fcc4414c2d83c028 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 13:39:04 +0300 Subject: [PATCH 0303/1406] update --- lua/platformio/pioinit.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index f4c76d1f..39861ec4 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -64,6 +64,7 @@ local function pick_framework(board_details) -- -O "platforms_dir = ${platformio.core_dir}/esp32c3/platforms" local command = [[pio project init --board ]] .. board_details['id'] + .. [[ -O "default_envs =" ]] -- .. [[ -O "core_dir = ]] -- .. vim.env.PLATFORMIO_CORE_DIR -- .. [[" -O "platforms_dir = \${platformio.core_dir}/platforms"]] From 24954a1c2a722458b08cc8551421e297c8aec094 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 14:12:03 +0300 Subject: [PATCH 0304/1406] update --- lua/platformio/boilerplate.lua | 24 ++++++++++++++++++++++++ lua/platformio/lspClangd.lua | 3 ++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 747b3cc4..bd904ec7 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -18,6 +18,30 @@ void loop() { ]], } +boilerplate['platformio.ini'] = { + content = [[ +[platformio] + +default_envs = +;default_envs = uno, nodemcu +platforms_dir = ${platformio.core_dir}/platforms +packages_dir = ${platformio.core_dir}/packages + +;-------------------------------------------------------------------------- +[env] + +upload_speed = 115200 +monitor_speed = 9600 +monitor_rts = 1 ; 1 combination to reset esp32c6 (Table 32.3-2. CDC-ACM Settings with RTS and DTR) +monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dtr=0 + +;extra_scripts = pre:extra_script.py +;extra_scripts = post:generate_compilation_database.py + +lib_ldf_mode = deep ;Library dependencies Finder ldf +]], +} + boilerplate['extra_script.py'] = { -- filename = 'main.cpp', content = [[ diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 068012fd..30321604 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -2,14 +2,15 @@ -- INFO: create clangd required files ----------------------------------------------------------------------------------------- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) +boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') boilerplate_gen([[extra_script.py]], vim.g.platformioRootDir) boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) -boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') --------------------------------------------------------------------------------- local ok, result From df3383b086e4da8930029261f75799e276d3ad12 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 14:23:04 +0300 Subject: [PATCH 0305/1406] update --- lua/platformio/boilerplate.lua | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index bd904ec7..42d8fd00 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -21,8 +21,7 @@ void loop() { boilerplate['platformio.ini'] = { content = [[ [platformio] - -default_envs = +core_dir = ]] .. vim.env.PLATFORMIO_CORE_DIR .. [[default_envs = ;default_envs = uno, nodemcu platforms_dir = ${platformio.core_dir}/platforms packages_dir = ${platformio.core_dir}/packages From 467368767700c54e66b1d607184d91a5153be170 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 14:26:36 +0300 Subject: [PATCH 0306/1406] update --- lua/platformio/boilerplate.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 42d8fd00..143d3a1a 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -21,7 +21,8 @@ void loop() { boilerplate['platformio.ini'] = { content = [[ [platformio] -core_dir = ]] .. vim.env.PLATFORMIO_CORE_DIR .. [[default_envs = +core_dir = $vim.env.PLATFORMIO_CORE_DIR +default_envs = ;default_envs = uno, nodemcu platforms_dir = ${platformio.core_dir}/platforms packages_dir = ${platformio.core_dir}/packages From 3b82b05b016e3b10c51ece41c75536e6490123bd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 14:31:55 +0300 Subject: [PATCH 0307/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 143d3a1a..f00abd32 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -427,7 +427,7 @@ function M.boilerplate_gen(framework, src_path, filename) print('failed to create file: ' .. file_path) return end - uv.fs_write(fd, entry.content, 0) + uv.fs_write(fd, vim.fn.expand(entry.content), 0) uv.fs_close(fd) -- uv.fs_open(file_path, 'w', 420, function(_, fd) -- crtete file if directory of the path exists From 86bef3d0a5718a281c844afb7402f8ffe51ee525 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 14:35:08 +0300 Subject: [PATCH 0308/1406] update --- lua/platformio/boilerplate.lua | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index f00abd32..63f9ce89 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -21,8 +21,7 @@ void loop() { boilerplate['platformio.ini'] = { content = [[ [platformio] -core_dir = $vim.env.PLATFORMIO_CORE_DIR -default_envs = +core_dir = ]] .. vim.env.PLATFORMIO_CORE_DIR .. [[\ndefault_envs = ;default_envs = uno, nodemcu platforms_dir = ${platformio.core_dir}/platforms packages_dir = ${platformio.core_dir}/packages @@ -427,7 +426,7 @@ function M.boilerplate_gen(framework, src_path, filename) print('failed to create file: ' .. file_path) return end - uv.fs_write(fd, vim.fn.expand(entry.content), 0) + uv.fs_write(fd, entry.content, 0) uv.fs_close(fd) -- uv.fs_open(file_path, 'w', 420, function(_, fd) -- crtete file if directory of the path exists From 0f3679e3f304cc046e624071e2478bf1d2e724bb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 14:53:32 +0300 Subject: [PATCH 0309/1406] update --- lua/platformio/boilerplate.lua | 37 +++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 63f9ce89..b7e19b51 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -3,6 +3,7 @@ local uv = vim.loop local boilerplate = {} +-- stylua: ignore boilerplate['arduino'] = { -- filename = 'main.cpp', content = [[ @@ -18,10 +19,12 @@ void loop() { ]], } +-- stylua: ignore boilerplate['platformio.ini'] = { content = [[ [platformio] -core_dir = ]] .. vim.env.PLATFORMIO_CORE_DIR .. [[\ndefault_envs = +core_dir = ]] .. vim.env.PLATFORMIO_CORE_DIR .. +[[default_envs = ;default_envs = uno, nodemcu platforms_dir = ${platformio.core_dir}/platforms packages_dir = ${platformio.core_dir}/packages @@ -41,29 +44,31 @@ lib_ldf_mode = deep ;Library dependencies Finder ldf ]], } +-- boilerplate['extra_script.py'] = { +-- content = [[ +-- Import("env") +-- +-- def set_compilation_db_toolchain(env): +-- # This runs after the environment is fully initialized +-- env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) +-- +-- # Add the function as a callback for the environment +-- env.AddMethod(set_compilation_db_toolchain) +-- set_compilation_db_toolchain(env) +-- +-- ]], +-- } + boilerplate['extra_script.py'] = { - -- filename = 'main.cpp', content = [[ -Import("env") - -def set_compilation_db_toolchain(env): - # This runs after the environment is fully initialized - env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) - -# Add the function as a callback for the environment -env.AddMethod(set_compilation_db_toolchain) -set_compilation_db_toolchain(env) - -]], -} ---[[ from SCons.Script import DefaultEnvironment env = DefaultEnvironment() env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) # Optional: ensure it saves to the root of your project #env.Replace(COMPILATIONDB_PATH="compile_commands.json") -]] +]], +} boilerplate['.clangd_cmd'] = { -- filename = '.clangd_cmd', From 147b11e0091cb69bc8854005f10dd72cb9a77bc4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 14:56:12 +0300 Subject: [PATCH 0310/1406] update --- lua/platformio/boilerplate.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index b7e19b51..13f95d1b 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -23,8 +23,8 @@ void loop() { boilerplate['platformio.ini'] = { content = [[ [platformio] -core_dir = ]] .. vim.env.PLATFORMIO_CORE_DIR .. -[[default_envs = +core_dir = ]] .. vim.env.PLATFORMIO_CORE_DIR .. [[ +default_envs = ;default_envs = uno, nodemcu platforms_dir = ${platformio.core_dir}/platforms packages_dir = ${platformio.core_dir}/packages From eac96697035fd3721ac145c477e7ff91caee8d52 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 15:03:14 +0300 Subject: [PATCH 0311/1406] update --- lua/platformio/boilerplate.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 13f95d1b..8cb88045 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -24,7 +24,8 @@ boilerplate['platformio.ini'] = { content = [[ [platformio] core_dir = ]] .. vim.env.PLATFORMIO_CORE_DIR .. [[ -default_envs = +]] .. +[[default_envs = ;default_envs = uno, nodemcu platforms_dir = ${platformio.core_dir}/platforms packages_dir = ${platformio.core_dir}/packages From aa7faf749a68cbef4abbed1281f7a2ae81603917 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 15:06:59 +0300 Subject: [PATCH 0312/1406] update --- lua/platformio/boilerplate.lua | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 8cb88045..7885af78 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -3,7 +3,7 @@ local uv = vim.loop local boilerplate = {} --- stylua: ignore +--- stylua: ignore boilerplate['arduino'] = { -- filename = 'main.cpp', content = [[ @@ -19,13 +19,12 @@ void loop() { ]], } --- stylua: ignore +--- stylua: ignore boilerplate['platformio.ini'] = { content = [[ [platformio] core_dir = ]] .. vim.env.PLATFORMIO_CORE_DIR .. [[ -]] .. -[[default_envs = +]] .. [[default_envs = ;default_envs = uno, nodemcu platforms_dir = ${platformio.core_dir}/platforms packages_dir = ${platformio.core_dir}/packages From ac812e1e70763843b78363e678fde38ab5cdf0fb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 15:23:31 +0300 Subject: [PATCH 0313/1406] update --- lua/platformio/boilerplate.lua | 38 +++++++++++++++++++++++++++++----- 1 file changed, 33 insertions(+), 5 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 7885af78..2d8cd5ae 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -19,16 +19,16 @@ void loop() { ]], } ---- stylua: ignore boilerplate['platformio.ini'] = { - content = [[ + template = [[ [platformio] -core_dir = ]] .. vim.env.PLATFORMIO_CORE_DIR .. [[ -]] .. [[default_envs = -;default_envs = uno, nodemcu +core_dir = %s platforms_dir = ${platformio.core_dir}/platforms packages_dir = ${platformio.core_dir}/packages +default_envs = +;default_envs = uno, nodemcu + ;-------------------------------------------------------------------------- [env] @@ -42,8 +42,36 @@ monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dt lib_ldf_mode = deep ;Library dependencies Finder ldf ]], + content = function(self) + return string.format(self.template, vim.env.PLATFORMIO_CORE_DIR) + end, } +--- stylua: ignore +-- boilerplate['platformio.ini'] = { +-- content = [[ +-- [platformio] +-- core_dir = ]] .. vim.env.PLATFORMIO_CORE_DIR .. [[ +-- ]] .. [[default_envs = +-- ;default_envs = uno, nodemcu +-- platforms_dir = ${platformio.core_dir}/platforms +-- packages_dir = ${platformio.core_dir}/packages +-- +-- ;-------------------------------------------------------------------------- +-- [env] +-- +-- upload_speed = 115200 +-- monitor_speed = 9600 +-- monitor_rts = 1 ; 1 combination to reset esp32c6 (Table 32.3-2. CDC-ACM Settings with RTS and DTR) +-- monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dtr=0 +-- +-- ;extra_scripts = pre:extra_script.py +-- ;extra_scripts = post:generate_compilation_database.py +-- +-- lib_ldf_mode = deep ;Library dependencies Finder ldf +-- ]], +-- } +-- -- boilerplate['extra_script.py'] = { -- content = [[ -- Import("env") From d8090c7a1065d4b7ce3f80c90c80936e36ce5352 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 15:28:59 +0300 Subject: [PATCH 0314/1406] update --- lua/platformio/boilerplate.lua | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 2d8cd5ae..55755011 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -459,7 +459,10 @@ function M.boilerplate_gen(framework, src_path, filename) print('failed to create file: ' .. file_path) return end - uv.fs_write(fd, entry.content, 0) + + -- local closeOnexit = type(exit_callback) == 'function' + local text = type(entry.content) == 'function' and entry.content() or entry.content + uv.fs_write(fd, text, 0) uv.fs_close(fd) -- uv.fs_open(file_path, 'w', 420, function(_, fd) -- crtete file if directory of the path exists From 75feb487c17b0ee91f29db3263e06dedf9f3319c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 15:58:25 +0300 Subject: [PATCH 0315/1406] update --- lua/platformio/boilerplate.lua | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 55755011..f2bab861 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -42,9 +42,12 @@ monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dt lib_ldf_mode = deep ;Library dependencies Finder ldf ]], - content = function(self) - return string.format(self.template, vim.env.PLATFORMIO_CORE_DIR) + content = function() + return string.format(boilerplate['platformio.ini'].template, vim.env.PLATFORMIO_CORE_DIR) end, + -- content = function(self) + -- return string.format(self.template, vim.env.PLATFORMIO_CORE_DIR) + -- end, } --- stylua: ignore From 862a3798f85bba69bd1931d84cd08902e1448b96 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 16:04:01 +0300 Subject: [PATCH 0316/1406] update --- lua/platformio/boilerplate.lua | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index f2bab861..b9ef3897 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -42,12 +42,12 @@ monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dt lib_ldf_mode = deep ;Library dependencies Finder ldf ]], - content = function() - return string.format(boilerplate['platformio.ini'].template, vim.env.PLATFORMIO_CORE_DIR) - end, - -- content = function(self) - -- return string.format(self.template, vim.env.PLATFORMIO_CORE_DIR) + -- content = function() + -- return string.format(boilerplate['platformio.ini'].template, vim.env.PLATFORMIO_CORE_DIR) -- end, + content = function(self) + return string.format(self.template, vim.env.PLATFORMIO_CORE_DIR) + end, } --- stylua: ignore @@ -464,7 +464,7 @@ function M.boilerplate_gen(framework, src_path, filename) end -- local closeOnexit = type(exit_callback) == 'function' - local text = type(entry.content) == 'function' and entry.content() or entry.content + local text = type(entry.content) == 'function' and entry:content() or entry.content uv.fs_write(fd, text, 0) uv.fs_close(fd) From 42387371c73f6ea3d9b6e1b68be78067ad4e0702 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 16:06:51 +0300 Subject: [PATCH 0317/1406] update --- lua/platformio/boilerplate.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index b9ef3897..9dad592a 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -31,7 +31,6 @@ default_envs = ;-------------------------------------------------------------------------- [env] - upload_speed = 115200 monitor_speed = 9600 monitor_rts = 1 ; 1 combination to reset esp32c6 (Table 32.3-2. CDC-ACM Settings with RTS and DTR) From 767d0edfd9f46d4bb11f3cc3d0fb8abcde92e40e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 16:12:18 +0300 Subject: [PATCH 0318/1406] update --- lua/platformio/pioinit.lua | 5 ----- 1 file changed, 5 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 39861ec4..2750980b 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -64,11 +64,6 @@ local function pick_framework(board_details) -- -O "platforms_dir = ${platformio.core_dir}/esp32c3/platforms" local command = [[pio project init --board ]] .. board_details['id'] - .. [[ -O "default_envs =" ]] - -- .. [[ -O "core_dir = ]] - -- .. vim.env.PLATFORMIO_CORE_DIR - -- .. [[" -O "platforms_dir = \${platformio.core_dir}/platforms"]] - -- .. [[ -O "packages_dir = \${platformio.core_dir}/packages"]] .. [[ -O "lib_ldf_mode = deep" -O "extra_scripts = pre:extra_script.py" -O "framework=]] .. selected_framework .. [["]] From c7dfb766d4482b06469c1346287ca6b23a58f077 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 16:38:24 +0300 Subject: [PATCH 0319/1406] update --- lua/platformio/boilerplate.lua | 23 ++++++++++++++++++++--- lua/platformio/lspClangd.lua | 3 ++- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 9dad592a..11566d50 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -36,8 +36,8 @@ monitor_speed = 9600 monitor_rts = 1 ; 1 combination to reset esp32c6 (Table 32.3-2. CDC-ACM Settings with RTS and DTR) monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dtr=0 -;extra_scripts = pre:extra_script.py -;extra_scripts = post:generate_compilation_database.py +extra_scripts = pre:extra_script.py +extra_scripts = post:generate_compile_commands.py lib_ldf_mode = deep ;Library dependencies Finder ldf ]], @@ -89,7 +89,7 @@ lib_ldf_mode = deep ;Library dependencies Finder ldf -- ]], -- } -boilerplate['extra_script.py'] = { +boilerplate['pre_script.py'] = { content = [[ from SCons.Script import DefaultEnvironment env = DefaultEnvironment() @@ -100,6 +100,23 @@ env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) ]], } +boilerplate['generate_compile_commands.py'] = { + content = [[ +import subprocess +Import("env") + +def regenerate_database(source, target, prev_env): + print("Regenerating compile_commands.json...") + # 'pio run -t compiledb' is the standard command to generate the file + # We use subprocess to avoid interfering with the current build process + subprocess.run(["pio", "run", "-t", "compiledb"]) + +# Add a post-action to a common target (like the firmware binary) +# to trigger regeneration after every successful build +env.AddPostAction("$BUILD_DIR/${PROGNAME}.elf", regenerate_database) +]], +} + boilerplate['.clangd_cmd'] = { -- filename = '.clangd_cmd', content = [[ diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 30321604..8265fc4f 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -7,7 +7,8 @@ boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') -boilerplate_gen([[extra_script.py]], vim.g.platformioRootDir) +boilerplate_gen([[pre_script.py]], vim.g.platformioRootDir) +boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) From e3c31deeac8af484312098509162c0c8606302fc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 16:43:00 +0300 Subject: [PATCH 0320/1406] update --- lua/platformio/boilerplate.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 11566d50..85b37480 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -33,6 +33,7 @@ default_envs = [env] upload_speed = 115200 monitor_speed = 9600 + monitor_rts = 1 ; 1 combination to reset esp32c6 (Table 32.3-2. CDC-ACM Settings with RTS and DTR) monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dtr=0 From dcf850428f87a9de826fd101cc01300f5fcf7ac4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 16:47:19 +0300 Subject: [PATCH 0321/1406] update --- lua/platformio/pioinit.lua | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 2750980b..fd22d7f0 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -62,12 +62,8 @@ local function pick_framework(board_details) -- pio project init --board \ -- -O "packages_dir = ${platformio.core_dir}/esp32c3/packages" \ -- -O "platforms_dir = ${platformio.core_dir}/esp32c3/platforms" - local command = [[pio project init --board ]] - .. board_details['id'] - .. [[ -O "lib_ldf_mode = deep" -O "extra_scripts = pre:extra_script.py" -O "framework=]] - .. selected_framework - .. [["]] - command = command .. [[ && pio run -t compiledb]] + local command = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. selected_framework .. '"' + command = command .. ' && pio run -t compiledb' utils.ToggleTerminal(command, 'float') vim.defer_fn(function() From 16456e8afa75983b5639ff17a7188af10ec813ef Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 16:55:21 +0300 Subject: [PATCH 0322/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 85b37480..daab9bbe 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -38,7 +38,7 @@ monitor_rts = 1 ; 1 combination to reset esp32c6 (Table 32.3-2. CDC-ACM Settin monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dtr=0 extra_scripts = pre:extra_script.py -extra_scripts = post:generate_compile_commands.py + post:generate_compile_commands.py lib_ldf_mode = deep ;Library dependencies Finder ldf ]], From 044b74690b49103ece02deb3044206a5aced810f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 16:56:18 +0300 Subject: [PATCH 0323/1406] update --- lua/platformio/pioinit.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index fd22d7f0..6d679f2d 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -63,7 +63,7 @@ local function pick_framework(board_details) -- -O "packages_dir = ${platformio.core_dir}/esp32c3/packages" \ -- -O "platforms_dir = ${platformio.core_dir}/esp32c3/platforms" local command = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. selected_framework .. '"' - command = command .. ' && pio run -t compiledb' + -- command = command .. ' && pio run -t compiledb' utils.ToggleTerminal(command, 'float') vim.defer_fn(function() From abf28c47d8c71575f5da39b56cbda7f112457785 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 17:04:18 +0300 Subject: [PATCH 0324/1406] update --- lua/platformio/boilerplate.lua | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index daab9bbe..2c90dab5 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -37,9 +37,12 @@ monitor_speed = 9600 monitor_rts = 1 ; 1 combination to reset esp32c6 (Table 32.3-2. CDC-ACM Settings with RTS and DTR) monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dtr=0 -extra_scripts = pre:extra_script.py - post:generate_compile_commands.py +extra_scripts = + pre:extra_script.py + post:generate_compile_commands.py +build_flags = + -D COMPILATIONDB_INCLUDE_TOOLCHAIN=1 lib_ldf_mode = deep ;Library dependencies Finder ldf ]], -- content = function() From 6146c62af7a38e9be9b77401029604f5bc6be94c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 17:18:18 +0300 Subject: [PATCH 0325/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 2c90dab5..6183ae02 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -38,7 +38,7 @@ monitor_rts = 1 ; 1 combination to reset esp32c6 (Table 32.3-2. CDC-ACM Settin monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dtr=0 extra_scripts = - pre:extra_script.py + pre:pre_script.py post:generate_compile_commands.py build_flags = From e7c793f214cb45c811736af97b1b3dd2d95f6296 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 17:33:24 +0300 Subject: [PATCH 0326/1406] update --- lua/platformio/boilerplate.lua | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 6183ae02..b3d99a47 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -106,18 +106,26 @@ env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) boilerplate['generate_compile_commands.py'] = { content = [[ +import os import subprocess Import("env") -def regenerate_database(source, target, prev_env): - print("Regenerating compile_commands.json...") - # 'pio run -t compiledb' is the standard command to generate the file - # We use subprocess to avoid interfering with the current build process - subprocess.run(["pio", "run", "-t", "compiledb"]) +# 1. Prevent Infinite Recursion +# Check if we are ALREADY running the 'compiledb' target to avoid an infinite loop +if "compiledb" not in COMMAND_LINE_TARGETS: -# Add a post-action to a common target (like the firmware binary) -# to trigger regeneration after every successful build -env.AddPostAction("$BUILD_DIR/${PROGNAME}.elf", regenerate_database) + def regenerate_database(source, target, prev_env): + print("--- REGENERATING compile_commands.json ---") + # Use subprocess to run the PIO command separately + # 'shell=True' might be needed on Windows if 'pio' isn't in your PATH directly + try: + subprocess.run(["pio", "run", "-t", "compiledb"], check=True) + except Exception as e: + print(f"Error regenerating database: {e}") + + # 2. Use a specific file as a hook rather than a generic alias + # This ensures it runs AFTER the ELF file is actually created/updated + env.AddPostAction("$BUILD_DIR/${PROGNAME}.elf", regenerate_database) ]], } From a9ff7d3a81f8c204a329b82cf078f9707a51629a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 17:36:09 +0300 Subject: [PATCH 0327/1406] update --- lua/platformio/boilerplate.lua | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index b3d99a47..c4fe3b5c 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -106,6 +106,23 @@ env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) boilerplate['generate_compile_commands.py'] = { content = [[ +# No 'import env' here! +import subprocess +from SCons.Script import COMMAND_LINE_TARGETS # Optional: for better IDE support + +# This line MUST be here for PIO to provide the environment +Import("env") + +def regenerate_database(source, target, env): + print("Regenerating...") + subprocess.run(["pio", "run", "-t", "compiledb"]) + +# Use the 'env' object that was imported above +env.AddPostAction("$BUILD_DIR/${PROGNAME}.elf", regenerate_database) +]], +} + +--[[ import os import subprocess Import("env") @@ -126,8 +143,7 @@ if "compiledb" not in COMMAND_LINE_TARGETS: # 2. Use a specific file as a hook rather than a generic alias # This ensures it runs AFTER the ELF file is actually created/updated env.AddPostAction("$BUILD_DIR/${PROGNAME}.elf", regenerate_database) -]], -} +]] boilerplate['.clangd_cmd'] = { -- filename = '.clangd_cmd', From fbd9913563db34cccdc0743f7cce6986561c4a72 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 18:07:54 +0300 Subject: [PATCH 0328/1406] update --- lua/platformio/boilerplate.lua | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index c4fe3b5c..c9aa824a 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -37,8 +37,8 @@ monitor_speed = 9600 monitor_rts = 1 ; 1 combination to reset esp32c6 (Table 32.3-2. CDC-ACM Settings with RTS and DTR) monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dtr=0 -extra_scripts = - pre:pre_script.py +extra_scripts = + pre:enable_toolchain.py post:generate_compile_commands.py build_flags = @@ -93,14 +93,20 @@ lib_ldf_mode = deep ;Library dependencies Finder ldf -- ]], -- } -boilerplate['pre_script.py'] = { - content = [[ +--[[working from SCons.Script import DefaultEnvironment env = DefaultEnvironment() env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) # Optional: ensure it saves to the root of your project #env.Replace(COMPILATIONDB_PATH="compile_commands.json") +]] + +boilerplate['enable_toolchain.py'] = { + content = [[ +Import("env") +# This must be done in a PRE script to affect the database generation +env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) ]], } From 6d6b55129dd0b53dd394a5ae493f8e0018bb4804 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 18:08:31 +0300 Subject: [PATCH 0329/1406] update --- lua/platformio/boilerplate.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index c9aa824a..ead6bbca 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -41,8 +41,8 @@ extra_scripts = pre:enable_toolchain.py post:generate_compile_commands.py -build_flags = - -D COMPILATIONDB_INCLUDE_TOOLCHAIN=1 +;build_flags = +; -D COMPILATIONDB_INCLUDE_TOOLCHAIN=1 lib_ldf_mode = deep ;Library dependencies Finder ldf ]], -- content = function() From b1bc59d7e0332bb8eefbd8a228635dd7090ff613 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 18:11:27 +0300 Subject: [PATCH 0330/1406] update --- lua/platformio/lspClangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 8265fc4f..ff780d46 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -7,7 +7,7 @@ boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') -boilerplate_gen([[pre_script.py]], vim.g.platformioRootDir) +boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) From d2ef658f68a354485dac3cb51f93b11972ba30a2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 18:44:10 +0300 Subject: [PATCH 0331/1406] update --- lua/platformio/boilerplate.lua | 106 ++++++--------------------------- lua/platformio/lspClangd.lua | 6 +- 2 files changed, 22 insertions(+), 90 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index ead6bbca..28835edb 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -39,10 +39,7 @@ monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dt extra_scripts = pre:enable_toolchain.py - post:generate_compile_commands.py -;build_flags = -; -D COMPILATIONDB_INCLUDE_TOOLCHAIN=1 lib_ldf_mode = deep ;Library dependencies Finder ldf ]], -- content = function() @@ -53,47 +50,8 @@ lib_ldf_mode = deep ;Library dependencies Finder ldf end, } ---- stylua: ignore --- boilerplate['platformio.ini'] = { --- content = [[ --- [platformio] --- core_dir = ]] .. vim.env.PLATFORMIO_CORE_DIR .. [[ --- ]] .. [[default_envs = --- ;default_envs = uno, nodemcu --- platforms_dir = ${platformio.core_dir}/platforms --- packages_dir = ${platformio.core_dir}/packages --- --- ;-------------------------------------------------------------------------- --- [env] --- --- upload_speed = 115200 --- monitor_speed = 9600 --- monitor_rts = 1 ; 1 combination to reset esp32c6 (Table 32.3-2. CDC-ACM Settings with RTS and DTR) --- monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dtr=0 --- --- ;extra_scripts = pre:extra_script.py --- ;extra_scripts = post:generate_compilation_database.py --- --- lib_ldf_mode = deep ;Library dependencies Finder ldf --- ]], --- } --- --- boilerplate['extra_script.py'] = { --- content = [[ --- Import("env") --- --- def set_compilation_db_toolchain(env): --- # This runs after the environment is fully initialized --- env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) --- --- # Add the function as a callback for the environment --- env.AddMethod(set_compilation_db_toolchain) --- set_compilation_db_toolchain(env) --- --- ]], --- } - ---[[working +boilerplate['enable_toolchain.py'] = { + --[[working from SCons.Script import DefaultEnvironment env = DefaultEnvironment() env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) @@ -101,8 +59,6 @@ env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) # Optional: ensure it saves to the root of your project #env.Replace(COMPILATIONDB_PATH="compile_commands.json") ]] - -boilerplate['enable_toolchain.py'] = { content = [[ Import("env") # This must be done in a PRE script to affect the database generation @@ -110,46 +66,23 @@ env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) ]], } -boilerplate['generate_compile_commands.py'] = { - content = [[ -# No 'import env' here! -import subprocess -from SCons.Script import COMMAND_LINE_TARGETS # Optional: for better IDE support - -# This line MUST be here for PIO to provide the environment -Import("env") - -def regenerate_database(source, target, env): - print("Regenerating...") - subprocess.run(["pio", "run", "-t", "compiledb"]) - -# Use the 'env' object that was imported above -env.AddPostAction("$BUILD_DIR/${PROGNAME}.elf", regenerate_database) -]], -} - ---[[ -import os -import subprocess -Import("env") - -# 1. Prevent Infinite Recursion -# Check if we are ALREADY running the 'compiledb' target to avoid an infinite loop -if "compiledb" not in COMMAND_LINE_TARGETS: - - def regenerate_database(source, target, prev_env): - print("--- REGENERATING compile_commands.json ---") - # Use subprocess to run the PIO command separately - # 'shell=True' might be needed on Windows if 'pio' isn't in your PATH directly - try: - subprocess.run(["pio", "run", "-t", "compiledb"], check=True) - except Exception as e: - print(f"Error regenerating database: {e}") - - # 2. Use a specific file as a hook rather than a generic alias - # This ensures it runs AFTER the ELF file is actually created/updated - env.AddPostAction("$BUILD_DIR/${PROGNAME}.elf", regenerate_database) -]] +-- boilerplate['generate_compile_commands.py'] = { +-- content = [[ +-- # No 'import env' here! +-- import subprocess +-- from SCons.Script import COMMAND_LINE_TARGETS # Optional: for better IDE support +-- +-- # This line MUST be here for PIO to provide the environment +-- Import("env") +-- +-- def regenerate_database(source, target, env): +-- print("Regenerating...") +-- subprocess.run(["pio", "run", "-t", "compiledb"]) +-- +-- # Use the 'env' object that was imported above +-- env.AddPostAction("$BUILD_DIR/${PROGNAME}.elf", regenerate_database) +-- ]], +-- } boilerplate['.clangd_cmd'] = { -- filename = '.clangd_cmd', @@ -173,7 +106,6 @@ clangd --ranking-model=decision_forest --query-driver=]] .. vim.env.HOME .. [[/.platformio/packages/toolchain-*/bin/*]], } - --query-driver = [[clangd --query-driver=]] .. vim.env.HOME .. [[/.platformio/packages/*]] --query-driver=** diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index ff780d46..3c569151 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -5,10 +5,10 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) -boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) -boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') +-- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) +-- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) -boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) +-- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) From 0567e426bc15a7ef490f1ba0a21439724afa240a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 19:06:09 +0300 Subject: [PATCH 0332/1406] update --- lua/platformio/pioinit.lua | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 6d679f2d..2c064add 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -59,11 +59,8 @@ local function pick_framework(board_details) local selection = action_state.get_selected_entry() local selected_framework = selection[1] - -- pio project init --board \ - -- -O "packages_dir = ${platformio.core_dir}/esp32c3/packages" \ - -- -O "platforms_dir = ${platformio.core_dir}/esp32c3/platforms" local command = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. selected_framework .. '"' - -- command = command .. ' && pio run -t compiledb' + command = command .. ' && pio run -t compiledb' utils.ToggleTerminal(command, 'float') vim.defer_fn(function() From d760c9f747077368a10207290e720e4142bea791 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 19:20:13 +0300 Subject: [PATCH 0333/1406] update --- lua/platformio/boilerplate.lua | 13 +++++++------ lua/platformio/lspClangd.lua | 2 +- mini_nvimPlatformio.lua | 3 ++- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 28835edb..e768df86 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -51,19 +51,20 @@ lib_ldf_mode = deep ;Library dependencies Finder ldf } boilerplate['enable_toolchain.py'] = { - --[[working + content = [[ from SCons.Script import DefaultEnvironment env = DefaultEnvironment() env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) +print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") # Optional: ensure it saves to the root of your project #env.Replace(COMPILATIONDB_PATH="compile_commands.json") -]] - content = [[ -Import("env") -# This must be done in a PRE script to affect the database generation -env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) ]], + -- content = [[ + -- Import("env") + -- # This must be done in a PRE script to affect the database generation + -- env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) + -- ]], } -- boilerplate['generate_compile_commands.py'] = { diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 3c569151..bc9fe55b 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -7,7 +7,7 @@ boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') -boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) +-- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) -- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 1b954680..b66f6782 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -153,7 +153,6 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- INFO: Set mini lazy config -- pick a temp root local tmp = vim.loop.os_tmpdir() .. '/nvim-temp' - vim.env.XDG_CONFIG_HOME = vim.fn.expand('~/.miniConfig') vim.env.XDG_DATA_HOME = tmp .. '/data' vim.env.XDG_CACHE_HOME = tmp .. '/cache' @@ -314,6 +313,8 @@ else end vim.uv.os_setenv('PLATFORMIO_CORE_DIR', platformio_core_dir) +-- vim.env.PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN = true +vim.uv.os_setenv('PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN', 'true') vim.g.python_host_prog = pynvim_python vim.g.python3_host_prog = pynvim_python vim.env.PATH = pynvim_bin .. (isWindows and ';' or ':') .. vim.env.PATH From 2bbb6b54e33142a079b4486a7ed96edc54855545 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 19:27:24 +0300 Subject: [PATCH 0334/1406] update --- mini_nvimPlatformio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index b66f6782..214f8568 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -312,8 +312,8 @@ else pynvim_activate = pynvim_bin .. '/activate' end -vim.uv.os_setenv('PLATFORMIO_CORE_DIR', platformio_core_dir) --- vim.env.PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN = true +-- vim.uv.os_setenv('PLATFORMIO_CORE_DIR', platformio_core_dir) +vim.env.PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN = true vim.uv.os_setenv('PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN', 'true') vim.g.python_host_prog = pynvim_python vim.g.python3_host_prog = pynvim_python From 88f66440c01f704395f0e60343dbfe28bb480a44 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 19:30:10 +0300 Subject: [PATCH 0335/1406] update --- lua/platformio/boilerplate.lua | 4 ++-- mini_nvimPlatformio.lua | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index e768df86..a975bd05 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -37,8 +37,8 @@ monitor_speed = 9600 monitor_rts = 1 ; 1 combination to reset esp32c6 (Table 32.3-2. CDC-ACM Settings with RTS and DTR) monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dtr=0 -extra_scripts = - pre:enable_toolchain.py +;extra_scripts = +; pre:enable_toolchain.py lib_ldf_mode = deep ;Library dependencies Finder ldf ]], diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 214f8568..88a64fd6 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -312,9 +312,9 @@ else pynvim_activate = pynvim_bin .. '/activate' end --- vim.uv.os_setenv('PLATFORMIO_CORE_DIR', platformio_core_dir) +vim.uv.os_setenv('PLATFORMIO_CORE_DIR', platformio_core_dir) vim.env.PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN = true -vim.uv.os_setenv('PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN', 'true') +-- vim.uv.os_setenv('PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN', 'true') vim.g.python_host_prog = pynvim_python vim.g.python3_host_prog = pynvim_python vim.env.PATH = pynvim_bin .. (isWindows and ';' or ':') .. vim.env.PATH From 708f5b1f75e4a94970572982b5312916d4bf4687 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 19:31:40 +0300 Subject: [PATCH 0336/1406] update --- mini_nvimPlatformio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 88a64fd6..8a69193f 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -312,9 +312,9 @@ else pynvim_activate = pynvim_bin .. '/activate' end -vim.uv.os_setenv('PLATFORMIO_CORE_DIR', platformio_core_dir) -vim.env.PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN = true -- vim.uv.os_setenv('PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN', 'true') +vim.env.PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN = true +vim.uv.os_setenv('PLATFORMIO_CORE_DIR', platformio_core_dir) vim.g.python_host_prog = pynvim_python vim.g.python3_host_prog = pynvim_python vim.env.PATH = pynvim_bin .. (isWindows and ';' or ':') .. vim.env.PATH From d74d70ddec669397fefae0091ab8aec222c526cc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 19:33:18 +0300 Subject: [PATCH 0337/1406] update --- mini_nvimPlatformio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 8a69193f..ec969431 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -312,8 +312,8 @@ else pynvim_activate = pynvim_bin .. '/activate' end --- vim.uv.os_setenv('PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN', 'true') -vim.env.PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN = true +vim.uv.os_setenv('PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN', 'true') +-- vim.env.PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN = true vim.uv.os_setenv('PLATFORMIO_CORE_DIR', platformio_core_dir) vim.g.python_host_prog = pynvim_python vim.g.python3_host_prog = pynvim_python From 1bb5b20fa69c9c6614d16602e7affc8bc338ff5a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 19:39:31 +0300 Subject: [PATCH 0338/1406] update --- mini_nvimPlatformio.lua | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index ec969431..160abdcf 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -312,8 +312,7 @@ else pynvim_activate = pynvim_bin .. '/activate' end -vim.uv.os_setenv('PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN', 'true') --- vim.env.PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN = true +-- vim.uv.os_setenv('PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN', 'true') vim.uv.os_setenv('PLATFORMIO_CORE_DIR', platformio_core_dir) vim.g.python_host_prog = pynvim_python vim.g.python3_host_prog = pynvim_python From 94081aab377b08fd633edf3881a992201b044ee6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 21:06:24 +0300 Subject: [PATCH 0339/1406] update --- lua/platformio/boilerplate.lua | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index a975bd05..ba048038 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -40,7 +40,7 @@ monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dt ;extra_scripts = ; pre:enable_toolchain.py -lib_ldf_mode = deep ;Library dependencies Finder ldf +lib_ldf_mode = chain+ ;Library dependencies Finder ldf ]], -- content = function() -- return string.format(boilerplate['platformio.ini'].template, vim.env.PLATFORMIO_CORE_DIR) @@ -86,8 +86,7 @@ print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") -- } boilerplate['.clangd_cmd'] = { - -- filename = '.clangd_cmd', - content = [[ + template = [[ clangd --all-scopes-completion --background-index @@ -105,13 +104,17 @@ clangd --pch-storage=memory --pretty --ranking-model=decision_forest ---query-driver=]] .. vim.env.HOME .. [[/.platformio/packages/toolchain-*/bin/*]], +--query-driver=%s/.platformio/**/packages/toolchain-*/**/bin/* +]], + content = function(self) + return string.format(self.template, vim.env.HOME) + end, + --query-driver = [[clangd --query-driver=]] .. vim.env.HOME .. [[/.platformio/packages/*]] + --query-driver=** + --query-driver=**/.platformio/packages/toolchain*/**/bin/*gcc* } ---query-driver = [[clangd --query-driver=]] .. vim.env.HOME .. [[/.platformio/packages/*]] ---query-driver=** boilerplate['.clang-format'] = { - -- filename = '.clang-format', content = [[ --- Language: Cpp @@ -365,7 +368,6 @@ WhitespaceSensitiveMacros: -- local home = vim.env.HOME -- print(home) boilerplate['.clangd'] = { - -- filename = '.clangd', content = [[ CompileFlags: Remove: [ @@ -406,7 +408,6 @@ Diagnostics: ]], } boilerplate['.stylua.toml'] = { - -- filename = '.stylua.toml', content = [[ syntax = "All" column_width = 132 From 4ef795ccfe96764411e88066c1f966f23416deff Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 21:07:50 +0300 Subject: [PATCH 0340/1406] update --- lua/platformio/boilerplate.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index ba048038..c5a7b4c4 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -37,8 +37,8 @@ monitor_speed = 9600 monitor_rts = 1 ; 1 combination to reset esp32c6 (Table 32.3-2. CDC-ACM Settings with RTS and DTR) monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dtr=0 -;extra_scripts = -; pre:enable_toolchain.py +extra_scripts = + pre:enable_toolchain.py lib_ldf_mode = chain+ ;Library dependencies Finder ldf ]], From b415fcf2268ce62a154a3c0097a8f221aa7b532e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 21:08:42 +0300 Subject: [PATCH 0341/1406] update --- lua/platformio/lspClangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index bc9fe55b..3c569151 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -7,7 +7,7 @@ boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') --- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) +boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) -- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) From e0654fb17b665a5536ddbcf5f19f42755ec58de9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 6 Apr 2026 21:31:37 +0300 Subject: [PATCH 0342/1406] update --- lua/platformio/boilerplate.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index c5a7b4c4..cceecf77 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -54,6 +54,7 @@ boilerplate['enable_toolchain.py'] = { content = [[ from SCons.Script import DefaultEnvironment env = DefaultEnvironment() +print(env.Dump()) env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") From 11334673101e1a5f1652d0e36ad2432df0115a01 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 05:22:23 +0300 Subject: [PATCH 0343/1406] update --- lua/platformio/pioinit.lua | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 2c064add..639c297e 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -12,6 +12,31 @@ local previewers = require('telescope.previewers') local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local piolsp = require('platformio.piolsp') --.piolsp +local function fix_pio_compile_commands() + local fname = 'compile_commands.json' + local f = io.open(fname, 'r') + if not f then + return + end + + local content = f:read('*all') + f:close() + + -- Find the actual toolchain path + local toolchain_path = vim.fn.expand('~/.platformio/packages/toolchain-*/bin/') + local full_path = vim.fn.glob(toolchain_path):split('\n')[1] -- Get the first match + + if full_path then + -- Replace short compiler name with full path (example for avr-gcc) + -- You can repeat this for xtensa-esp32-elf-gcc, etc. + local fixed_content = content:gsub('"command": "([^/][^"]*%-gcc)', '"command": "' .. full_path .. '%1') + + local f_out = io.open(fname, 'w') + f_out:write(fixed_content) + f_out:close() + end +end + local boardentry_maker = function(opts) local displayer = entry_display.create({ separator = '▏', @@ -67,6 +92,7 @@ local function pick_framework(board_details) vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) piolsp.gitignore_lsp_configs('compile_commands.json') boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') + fix_pio_compile_commands() piolsp.lsp_restart('clangd') end, 3000) -- utils.ToggleTerminal(command, 'float', function() From 077770b050d8347cd1d85fb9ad60073120178518 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 05:26:27 +0300 Subject: [PATCH 0344/1406] update --- lua/platformio/boilerplate.lua | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index cceecf77..bf695b96 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -57,6 +57,13 @@ env = DefaultEnvironment() print(env.Dump()) env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) +#Import("env") + +# Method 1: Safe retrieval with a default message +print(f"Toolchain Inclusion Status: {env.get('COMPILATIONDB_INCLUDE_TOOLCHAIN', 'Not Set')}") + +# Method 2: Direct access (will raise an error if the key is missing) +# print(env["COMPILATIONDB_INCLUDE_TOOLCHAIN"]) print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") # Optional: ensure it saves to the root of your project #env.Replace(COMPILATIONDB_PATH="compile_commands.json") From f53457da050757ef2bfa4649060e316c1948f890 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 05:36:07 +0300 Subject: [PATCH 0345/1406] update --- lua/platformio/boilerplate.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index bf695b96..d7ed916c 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -54,7 +54,6 @@ boilerplate['enable_toolchain.py'] = { content = [[ from SCons.Script import DefaultEnvironment env = DefaultEnvironment() -print(env.Dump()) env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) #Import("env") From b180e2066fa3d08ec308cedf1567a76d989dbc4c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 05:44:42 +0300 Subject: [PATCH 0346/1406] update --- lua/platformio/pioinit.lua | 79 ++++++++++++++++++++++++++++++-------- 1 file changed, 64 insertions(+), 15 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 639c297e..ac59144e 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -13,30 +13,79 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local piolsp = require('platformio.piolsp') --.piolsp local function fix_pio_compile_commands() - local fname = 'compile_commands.json' - local f = io.open(fname, 'r') - if not f then + local json_path = vim.fn.getcwd() .. '/compile_commands.json' + if vim.fn.filereadable(json_path) == 0 then return end - local content = f:read('*all') - f:close() + -- 1. Read and Parse JSON + local file = io.open(json_path, 'r') + local content = file:read('*all') + file:close() - -- Find the actual toolchain path - local toolchain_path = vim.fn.expand('~/.platformio/packages/toolchain-*/bin/') - local full_path = vim.fn.glob(toolchain_path):split('\n')[1] -- Get the first match + local ok, data = pcall(vim.fn.json_decode, content) + if not ok or type(data) ~= 'table' then + return + end - if full_path then - -- Replace short compiler name with full path (example for avr-gcc) - -- You can repeat this for xtensa-esp32-elf-gcc, etc. - local fixed_content = content:gsub('"command": "([^/][^"]*%-gcc)', '"command": "' .. full_path .. '%1') + -- 2. Find the PIO Toolchain Bin directory + -- This glob finds the first toolchain bin folder available in your PIO packages + local toolchain_bin = vim.fn.glob(vim.env.HOME .. '/.platformio/packages/toolchain-*/bin/') + if toolchain_bin == '' then + return + end + toolchain_bin = toolchain_bin:split('\n')[1] -- Use the first match + + local changed = false + for _, entry in ipairs(data) do + -- 3. Check if 'command' starts with a raw compiler name (no leading slash) + -- This pattern looks for "compiler-name" and prepends the full path + if entry.command and not entry.command:match('^/') then + entry.command = toolchain_bin .. entry.command + changed = true + end + end - local f_out = io.open(fname, 'w') - f_out:write(fixed_content) - f_out:close() + -- 4. Only write if we actually modified something + if changed then + local out_file = io.open(json_path, 'w') + out_file:write(vim.fn.json_encode(data)) + out_file:close() + print('PIO: Fixed compiler paths in compile_commands.json') end end +-- Run it automatically when entering a C/C++ file +vim.api.nvim_create_autocmd({ 'BufReadPost', 'BufNewFile' }, { + pattern = { '*.c', '*.cpp', '*.h', '*.hpp' }, + callback = fix_pio_compile_commands, +}) + +-- local function fix_pio_compile_commands() +-- local fname = 'compile_commands.json' +-- local f = io.open(fname, 'r') +-- if not f then +-- return +-- end +-- +-- local content = f:read('*all') +-- f:close() +-- +-- -- Find the actual toolchain path +-- local toolchain_path = vim.fn.expand('~/.platformio/packages/toolchain-*/bin/') +-- local full_path = vim.fn.glob(toolchain_path):split('\n')[1] -- Get the first match +-- +-- if full_path then +-- -- Replace short compiler name with full path (example for avr-gcc) +-- -- You can repeat this for xtensa-esp32-elf-gcc, etc. +-- local fixed_content = content:gsub('"command": "([^/][^"]*%-gcc)', '"command": "' .. full_path .. '%1') +-- +-- local f_out = io.open(fname, 'w') +-- f_out:write(fixed_content) +-- f_out:close() +-- end +-- end + local boardentry_maker = function(opts) local displayer = entry_display.create({ separator = '▏', From b3667bb28cb4e0b43a5d7a731d12628319129679 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 05:49:01 +0300 Subject: [PATCH 0347/1406] update --- lua/platformio/boilerplate.lua | 5 ----- 1 file changed, 5 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index d7ed916c..3a3feba8 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -60,12 +60,7 @@ env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) # Method 1: Safe retrieval with a default message print(f"Toolchain Inclusion Status: {env.get('COMPILATIONDB_INCLUDE_TOOLCHAIN', 'Not Set')}") - -# Method 2: Direct access (will raise an error if the key is missing) -# print(env["COMPILATIONDB_INCLUDE_TOOLCHAIN"]) print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") -# Optional: ensure it saves to the root of your project -#env.Replace(COMPILATIONDB_PATH="compile_commands.json") ]], -- content = [[ -- Import("env") From 5da07f18a73749df7943f28ba2950e33674fdfbd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 05:56:30 +0300 Subject: [PATCH 0348/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/pioinit.lua | 46 +++++----------------------------- 2 files changed, 7 insertions(+), 41 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 3a3feba8..4f64008b 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -58,7 +58,7 @@ env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) #Import("env") -# Method 1: Safe retrieval with a default message +## Method 1: Safe retrieval with a default message print(f"Toolchain Inclusion Status: {env.get('COMPILATIONDB_INCLUDE_TOOLCHAIN', 'Not Set')}") print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") ]], diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index ac59144e..d78e5328 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -18,7 +18,6 @@ local function fix_pio_compile_commands() return end - -- 1. Read and Parse JSON local file = io.open(json_path, 'r') local content = file:read('*all') file:close() @@ -28,25 +27,23 @@ local function fix_pio_compile_commands() return end - -- 2. Find the PIO Toolchain Bin directory - -- This glob finds the first toolchain bin folder available in your PIO packages - local toolchain_bin = vim.fn.glob(vim.env.HOME .. '/.platformio/packages/toolchain-*/bin/') - if toolchain_bin == '' then + -- Use vim.fn.glob and vim.split for Neovim compatibility + local glob_result = vim.fn.glob(vim.env.HOME .. '/.platformio/packages/toolchain-*/bin/') + if glob_result == '' then return end - toolchain_bin = toolchain_bin:split('\n')[1] -- Use the first match + + -- CORRECTED: Use vim.split() instead of :split() + local toolchain_bin = vim.split(glob_result, '\n')[1] local changed = false for _, entry in ipairs(data) do - -- 3. Check if 'command' starts with a raw compiler name (no leading slash) - -- This pattern looks for "compiler-name" and prepends the full path if entry.command and not entry.command:match('^/') then entry.command = toolchain_bin .. entry.command changed = true end end - -- 4. Only write if we actually modified something if changed then local out_file = io.open(json_path, 'w') out_file:write(vim.fn.json_encode(data)) @@ -55,37 +52,6 @@ local function fix_pio_compile_commands() end end --- Run it automatically when entering a C/C++ file -vim.api.nvim_create_autocmd({ 'BufReadPost', 'BufNewFile' }, { - pattern = { '*.c', '*.cpp', '*.h', '*.hpp' }, - callback = fix_pio_compile_commands, -}) - --- local function fix_pio_compile_commands() --- local fname = 'compile_commands.json' --- local f = io.open(fname, 'r') --- if not f then --- return --- end --- --- local content = f:read('*all') --- f:close() --- --- -- Find the actual toolchain path --- local toolchain_path = vim.fn.expand('~/.platformio/packages/toolchain-*/bin/') --- local full_path = vim.fn.glob(toolchain_path):split('\n')[1] -- Get the first match --- --- if full_path then --- -- Replace short compiler name with full path (example for avr-gcc) --- -- You can repeat this for xtensa-esp32-elf-gcc, etc. --- local fixed_content = content:gsub('"command": "([^/][^"]*%-gcc)', '"command": "' .. full_path .. '%1') --- --- local f_out = io.open(fname, 'w') --- f_out:write(fixed_content) --- f_out:close() --- end --- end - local boardentry_maker = function(opts) local displayer = entry_display.create({ separator = '▏', From ce8603c5207c02f88850e0ae22c93a90ab4c513b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 06:04:45 +0300 Subject: [PATCH 0349/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/pioinit.lua | 40 ---------------- lua/platformio/piolsp.lua | 84 ++++++++++++++++++++++++++-------- 3 files changed, 65 insertions(+), 61 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 4f64008b..dfe81996 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -58,7 +58,7 @@ env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) #Import("env") -## Method 1: Safe retrieval with a default message +# ..Method 1: Safe retrieval with a default message print(f"Toolchain Inclusion Status: {env.get('COMPILATIONDB_INCLUDE_TOOLCHAIN', 'Not Set')}") print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") ]], diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index d78e5328..9852b130 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -12,46 +12,6 @@ local previewers = require('telescope.previewers') local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local piolsp = require('platformio.piolsp') --.piolsp -local function fix_pio_compile_commands() - local json_path = vim.fn.getcwd() .. '/compile_commands.json' - if vim.fn.filereadable(json_path) == 0 then - return - end - - local file = io.open(json_path, 'r') - local content = file:read('*all') - file:close() - - local ok, data = pcall(vim.fn.json_decode, content) - if not ok or type(data) ~= 'table' then - return - end - - -- Use vim.fn.glob and vim.split for Neovim compatibility - local glob_result = vim.fn.glob(vim.env.HOME .. '/.platformio/packages/toolchain-*/bin/') - if glob_result == '' then - return - end - - -- CORRECTED: Use vim.split() instead of :split() - local toolchain_bin = vim.split(glob_result, '\n')[1] - - local changed = false - for _, entry in ipairs(data) do - if entry.command and not entry.command:match('^/') then - entry.command = toolchain_bin .. entry.command - changed = true - end - end - - if changed then - local out_file = io.open(json_path, 'w') - out_file:write(vim.fn.json_encode(data)) - out_file:close() - print('PIO: Fixed compiler paths in compile_commands.json') - end -end - local boardentry_maker = function(opts) local displayer = entry_display.create({ separator = '▏', diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index df598298..90e80d99 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -3,6 +3,46 @@ local M = {} local utils = require('platformio.utils') local config = require('platformio').config +function M.fix_pio_compile_commands() + local json_path = vim.fn.getcwd() .. '/compile_commands.json' + if vim.fn.filereadable(json_path) == 0 then + return + end + + local file = io.open(json_path, 'r') + local content = file:read('*all') + file:close() + + local ok, data = pcall(vim.fn.json_decode, content) + if not ok or type(data) ~= 'table' then + return + end + + -- Use vim.fn.glob and vim.split for Neovim compatibility + local glob_result = vim.fn.glob(vim.env.HOME .. '/.platformio/packages/toolchain-*/bin/') + if glob_result == '' then + return + end + + -- CORRECTED: Use vim.split() instead of :split() + local toolchain_bin = vim.split(glob_result, '\n')[1] + + local changed = false + for _, entry in ipairs(data) do + if entry.command and not entry.command:match('^/') then + entry.command = toolchain_bin .. entry.command + changed = true + end + end + + if changed then + local out_file = io.open(json_path, 'w') + out_file:write(vim.fn.json_encode(data)) + out_file:close() + print('PIO: Fixed compiler paths in compile_commands.json') + end +end + function M.gitignore_lsp_configs(config_file) local gitignore_path = vim.fs.joinpath(vim.g.platformioRootDir, '.gitignore') local file = io.open(gitignore_path, 'r') @@ -68,27 +108,31 @@ function M.lsp_restart(name) end function M.piolsp() - if not utils.pio_install_check() then - return - end - utils.cd_pioini() - - utils.shell_cmd_blocking('pio run -t compiledb') - vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) - M.gitignore_lsp_configs('compile_commands.json') - - -- if vim.fn.has('nvim-0.12') then - -- local clangd = vim.lsp.get_clients({ name = 'clangd' })[1] - -- if clangd then - -- -- print('number of attaced: ' .. #clangd.attached_buffers) - -- -- print('piolsp: lsp restart ' .. clangd.name) - -- pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) - M.lsp_restart('clangd') - -- vim.cmd('lsp restart clangd') - -- end - -- else - -- vim.cmd('LspRestart') + M.fix_pio_compile_commands() + + -- + -- + -- if not utils.pio_install_check() then + -- return -- end + -- utils.cd_pioini() + -- + -- utils.shell_cmd_blocking('pio run -t compiledb') + -- vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) + -- M.gitignore_lsp_configs('compile_commands.json') + -- + -- -- if vim.fn.has('nvim-0.12') then + -- -- local clangd = vim.lsp.get_clients({ name = 'clangd' })[1] + -- -- if clangd then + -- -- -- print('number of attaced: ' .. #clangd.attached_buffers) + -- -- -- print('piolsp: lsp restart ' .. clangd.name) + -- -- pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) + -- M.lsp_restart('clangd') + -- -- vim.cmd('lsp restart clangd') + -- -- end + -- -- else + -- -- vim.cmd('LspRestart') + -- -- end end return M From 143218a942479bd337a5a507672bcaf9b0bf5eb8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 06:06:44 +0300 Subject: [PATCH 0350/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/pioinit.lua | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index dfe81996..3a3feba8 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -58,7 +58,7 @@ env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) #Import("env") -# ..Method 1: Safe retrieval with a default message +# Method 1: Safe retrieval with a default message print(f"Toolchain Inclusion Status: {env.get('COMPILATIONDB_INCLUDE_TOOLCHAIN', 'Not Set')}") print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") ]], diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 9852b130..2c064add 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -67,7 +67,6 @@ local function pick_framework(board_details) vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) piolsp.gitignore_lsp_configs('compile_commands.json') boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') - fix_pio_compile_commands() piolsp.lsp_restart('clangd') end, 3000) -- utils.ToggleTerminal(command, 'float', function() From 5834a7e6e721f0a1db48a6edad3fe27b8b10c5f7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 06:14:45 +0300 Subject: [PATCH 0351/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/piolsp.lua | 37 ++++++++++++++++++++++++---------- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 3a3feba8..dfe81996 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -58,7 +58,7 @@ env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) #Import("env") -# Method 1: Safe retrieval with a default message +# ..Method 1: Safe retrieval with a default message print(f"Toolchain Inclusion Status: {env.get('COMPILATIONDB_INCLUDE_TOOLCHAIN', 'Not Set')}") print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") ]], diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 90e80d99..b5970595 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -3,12 +3,21 @@ local M = {} local utils = require('platformio.utils') local config = require('platformio').config -function M.fix_pio_compile_commands() - local json_path = vim.fn.getcwd() .. '/compile_commands.json' +local function fix_pio_compile_commands() + local cwd = vim.fn.getcwd() + local json_path = cwd .. '/compile_commands.json' + + -- 1. Generate if missing if vim.fn.filereadable(json_path) == 0 then - return + if vim.fn.filereadable(cwd .. '/platformio.ini') == 1 then + print('PIO: Generating compilation database...') + vim.fn.system('pio run -t compiledb') + else + return + end end + -- 2. Read and Decode local file = io.open(json_path, 'r') local content = file:read('*all') file:close() @@ -18,28 +27,34 @@ function M.fix_pio_compile_commands() return end - -- Use vim.fn.glob and vim.split for Neovim compatibility + -- 3. Get Toolchain Path local glob_result = vim.fn.glob(vim.env.HOME .. '/.platformio/packages/toolchain-*/bin/') if glob_result == '' then return end - - -- CORRECTED: Use vim.split() instead of :split() - local toolchain_bin = vim.split(glob_result, '\n')[1] + local toolchain_bin = vim.split(glob_result, '\n')[1] -- Ensure we get a single string local changed = false for _, entry in ipairs(data) do - if entry.command and not entry.command:match('^/') then - entry.command = toolchain_bin .. entry.command - changed = true + if entry.command then + -- IMPROVEMENT: Only prepend if it's NOT already an absolute path + -- AND it doesn't already contain the toolchain path (prevents double-prepending) + if not entry.command:match('^/') and not entry.command:find(toolchain_bin, 1, true) then + entry.command = toolchain_bin .. entry.command + changed = true + end end end + -- 4. Save with Formatting if changed then local out_file = io.open(json_path, 'w') + -- Using indent makes the file human-readable and less likely to "mess up" out_file:write(vim.fn.json_encode(data)) out_file:close() - print('PIO: Fixed compiler paths in compile_commands.json') + + print('PIO: Paths localized in compile_commands.json') + vim.cmd('LspRestart clangd') end end From 585f1d16ead47219a963fd40e4451ec62ef935a9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 06:19:31 +0300 Subject: [PATCH 0352/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/piolsp.lua | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index dfe81996..727949ca 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -58,7 +58,7 @@ env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) #Import("env") -# ..Method 1: Safe retrieval with a default message +# ...Method 1: Safe retrieval with a default message print(f"Toolchain Inclusion Status: {env.get('COMPILATIONDB_INCLUDE_TOOLCHAIN', 'Not Set')}") print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") ]], diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index b5970595..653b2868 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -3,7 +3,7 @@ local M = {} local utils = require('platformio.utils') local config = require('platformio').config -local function fix_pio_compile_commands() +function M.fix_pio_compile_commands() local cwd = vim.fn.getcwd() local json_path = cwd .. '/compile_commands.json' From 5b778ee59486d4af8f53c8f8c926b8582b93d2a8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 06:23:51 +0300 Subject: [PATCH 0353/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/piolsp.lua | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 727949ca..3a3feba8 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -58,7 +58,7 @@ env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) #Import("env") -# ...Method 1: Safe retrieval with a default message +# Method 1: Safe retrieval with a default message print(f"Toolchain Inclusion Status: {env.get('COMPILATIONDB_INCLUDE_TOOLCHAIN', 'Not Set')}") print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") ]], diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 653b2868..bd21fff5 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -54,7 +54,7 @@ function M.fix_pio_compile_commands() out_file:close() print('PIO: Paths localized in compile_commands.json') - vim.cmd('LspRestart clangd') + M.lsp_restart('clangd') end end From 1cd694723904fce7505882208d0294cb05623057 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 06:36:38 +0300 Subject: [PATCH 0354/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/piolsp.lua | 76 +++++++++++++++++++--------------- 2 files changed, 43 insertions(+), 35 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 3a3feba8..727949ca 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -58,7 +58,7 @@ env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) #Import("env") -# Method 1: Safe retrieval with a default message +# ...Method 1: Safe retrieval with a default message print(f"Toolchain Inclusion Status: {env.get('COMPILATIONDB_INCLUDE_TOOLCHAIN', 'Not Set')}") print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") ]], diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index bd21fff5..a9866522 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -19,42 +19,50 @@ function M.fix_pio_compile_commands() -- 2. Read and Decode local file = io.open(json_path, 'r') - local content = file:read('*all') - file:close() - - local ok, data = pcall(vim.fn.json_decode, content) - if not ok or type(data) ~= 'table' then - return - end - - -- 3. Get Toolchain Path - local glob_result = vim.fn.glob(vim.env.HOME .. '/.platformio/packages/toolchain-*/bin/') - if glob_result == '' then - return - end - local toolchain_bin = vim.split(glob_result, '\n')[1] -- Ensure we get a single string - - local changed = false - for _, entry in ipairs(data) do - if entry.command then - -- IMPROVEMENT: Only prepend if it's NOT already an absolute path - -- AND it doesn't already contain the toolchain path (prevents double-prepending) - if not entry.command:match('^/') and not entry.command:find(toolchain_bin, 1, true) then - entry.command = toolchain_bin .. entry.command - changed = true + if file then + local content = file:read('*all') + file:close() + local ok, data = pcall(vim.fn.json_decode, content) + if not ok or type(data) ~= 'table' then + return + end + -- 3. Get Toolchain Path + local glob_result = vim.fn.glob(vim.env.HOME .. '/.platformio/packages/toolchain-*/bin/') + if glob_result == '' then + return + end + local toolchain_bin = vim.split(glob_result, '\n')[1] -- Ensure we get a single string + + local changed = false + for _, entry in ipairs(data) do + if entry.command then + -- IMPROVEMENT: Only prepend if it's NOT already an absolute path + -- AND it doesn't already contain the toolchain path (prevents double-prepending) + if not entry.command:match('^/') and not entry.command:find(toolchain_bin, 1, true) then + entry.command = toolchain_bin .. entry.command + changed = true + end end end - end - - -- 4. Save with Formatting - if changed then - local out_file = io.open(json_path, 'w') - -- Using indent makes the file human-readable and less likely to "mess up" - out_file:write(vim.fn.json_encode(data)) - out_file:close() - - print('PIO: Paths localized in compile_commands.json') - M.lsp_restart('clangd') + -- 4. Save with Formatting + if changed then + local out_file = io.open(json_path, 'w') + -- Check if vim.json is available (Neovim 0.9+) + if out_file then + if vim.json and vim.json.encode then + out_file:write(vim.json.encode(data, { indent = ' ' })) + else + -- Fallback for older versions (minified) + out_file:write(vim.fn.json_encode(data)) + end + out_file:close() + + print('PIO: Paths fixed and JSON formatted') + M.lsp_restart('clangd') + end + end + else + return end end From ef873e910e942be64babd8dec8c33c02a1af3c8f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 06:43:04 +0300 Subject: [PATCH 0355/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/piolsp.lua | 171 ++++++++++++++++++++++++--------- 2 files changed, 126 insertions(+), 47 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 727949ca..3a3feba8 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -58,7 +58,7 @@ env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) #Import("env") -# ...Method 1: Safe retrieval with a default message +# Method 1: Safe retrieval with a default message print(f"Toolchain Inclusion Status: {env.get('COMPILATIONDB_INCLUDE_TOOLCHAIN', 'Not Set')}") print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") ]], diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index a9866522..e35bda7e 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -3,69 +3,148 @@ local M = {} local utils = require('platformio.utils') local config = require('platformio').config +-- Cache the toolchain path once globally so we don't glob on every save +local cached_toolchain = nil + function M.fix_pio_compile_commands() local cwd = vim.fn.getcwd() local json_path = cwd .. '/compile_commands.json' - -- 1. Generate if missing - if vim.fn.filereadable(json_path) == 0 then + -- 1. Performance: Check if file exists and get last modified time + local stats = vim.loop.fs_stat(json_path) + if not stats then if vim.fn.filereadable(cwd .. '/platformio.ini') == 1 then - print('PIO: Generating compilation database...') vim.fn.system('pio run -t compiledb') - else - return + stats = vim.loop.fs_stat(json_path) -- Re-check after gen end end + if not stats then + return + end - -- 2. Read and Decode - local file = io.open(json_path, 'r') - if file then - local content = file:read('*all') - file:close() - local ok, data = pcall(vim.fn.json_decode, content) - if not ok or type(data) ~= 'table' then - return - end - -- 3. Get Toolchain Path - local glob_result = vim.fn.glob(vim.env.HOME .. '/.platformio/packages/toolchain-*/bin/') - if glob_result == '' then + -- 2. Performance: Only run if the file was modified in the last 5 seconds + -- This prevents re-parsing the JSON every time you hit :w + local now = os.time() + if (now - stats.mtime.sec) > 5 and _G.PIO_FIXED_ONCE then + return + end + + -- 3. Get Toolchain (Cached) + if not cached_toolchain then + local glob = vim.fn.glob(vim.env.HOME .. '/.platformio/packages/toolchain-*/bin/') + if glob == '' then return end - local toolchain_bin = vim.split(glob_result, '\n')[1] -- Ensure we get a single string - - local changed = false - for _, entry in ipairs(data) do - if entry.command then - -- IMPROVEMENT: Only prepend if it's NOT already an absolute path - -- AND it doesn't already contain the toolchain path (prevents double-prepending) - if not entry.command:match('^/') and not entry.command:find(toolchain_bin, 1, true) then - entry.command = toolchain_bin .. entry.command - changed = true - end + cached_toolchain = vim.split(glob, '\n')[1] -- Ensure single string + end + + -- 4. Safe Read + local file = io.open(json_path, 'r') + if not file then + return + end + local content = file:read('*all') + file:close() + if not content or content == '' then + return + end + + -- 5. Safe Decode + local ok, data = pcall(vim.json.decode, content) + if not ok or type(data) ~= 'table' then + return + end + + local changed = false + for _, entry in ipairs(data) do + -- Defensive Nil Checks + if type(entry) == 'table' and entry.command then + -- Prepend only if relative and not already fixed + if not entry.command:match('^/') and not entry.command:find(cached_toolchain, 1, true) then + entry.command = cached_toolchain .. entry.command + changed = true end end - -- 4. Save with Formatting - if changed then - local out_file = io.open(json_path, 'w') - -- Check if vim.json is available (Neovim 0.9+) - if out_file then - if vim.json and vim.json.encode then - out_file:write(vim.json.encode(data, { indent = ' ' })) - else - -- Fallback for older versions (minified) - out_file:write(vim.fn.json_encode(data)) - end - out_file:close() - - print('PIO: Paths fixed and JSON formatted') - M.lsp_restart('clangd') - end + end + + -- 6. Safe Save + if changed then + local out = io.open(json_path, 'w') + if out then + out:write(vim.json.encode(data, { indent = ' ' })) + out:close() + _G.PIO_FIXED_ONCE = true + vim.schedule(function() + print('PIO: Database optimized') + M.lsp_restarti('clangd') + end) end - else - return end end +-- function M.fix_pio_compile_commands() +-- local cwd = vim.fn.getcwd() +-- local json_path = cwd .. '/compile_commands.json' +-- +-- -- 1. Generate if missing +-- if vim.fn.filereadable(json_path) == 0 then +-- if vim.fn.filereadable(cwd .. '/platformio.ini') == 1 then +-- print('PIO: Generating compilation database...') +-- vim.fn.system('pio run -t compiledb') +-- else +-- return +-- end +-- end +-- +-- -- 2. Read and Decode +-- local file = io.open(json_path, 'r') +-- if file then +-- local content = file:read('*all') +-- file:close() +-- local ok, data = pcall(vim.fn.json_decode, content) +-- if not ok or type(data) ~= 'table' then +-- return +-- end +-- -- 3. Get Toolchain Path +-- local glob_result = vim.fn.glob(vim.env.HOME .. '/.platformio/packages/toolchain-*/bin/') +-- if glob_result == '' then +-- return +-- end +-- local toolchain_bin = vim.split(glob_result, '\n')[1] -- Ensure we get a single string +-- +-- local changed = false +-- for _, entry in ipairs(data) do +-- if entry.command then +-- -- IMPROVEMENT: Only prepend if it's NOT already an absolute path +-- -- AND it doesn't already contain the toolchain path (prevents double-prepending) +-- if not entry.command:match('^/') and not entry.command:find(toolchain_bin, 1, true) then +-- entry.command = toolchain_bin .. entry.command +-- changed = true +-- end +-- end +-- end +-- -- 4. Save with Formatting +-- if changed then +-- local out_file = io.open(json_path, 'w') +-- -- Check if vim.json is available (Neovim 0.9+) +-- if out_file then +-- if vim.json and vim.json.encode then +-- out_file:write(vim.json.encode(data, { indent = ' ' })) +-- else +-- -- Fallback for older versions (minified) +-- out_file:write(vim.fn.json_encode(data)) +-- end +-- out_file:close() +-- +-- print('PIO: Paths fixed and JSON formatted') +-- M.lsp_restart('clangd') +-- end +-- end +-- else +-- return +-- end +-- end + function M.gitignore_lsp_configs(config_file) local gitignore_path = vim.fs.joinpath(vim.g.platformioRootDir, '.gitignore') local file = io.open(gitignore_path, 'r') From d55fc0b456751fd5dec7c753600cda0fcf1e2eab Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 07:29:04 +0300 Subject: [PATCH 0356/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 3a3feba8..9c9d7bb8 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -58,7 +58,7 @@ env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) #Import("env") -# Method 1: Safe retrieval with a default message +# Safe retrieval with a default message print(f"Toolchain Inclusion Status: {env.get('COMPILATIONDB_INCLUDE_TOOLCHAIN', 'Not Set')}") print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") ]], From 9dc42b6092df7fd55aae43755473320d065bb786 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 07:36:22 +0300 Subject: [PATCH 0357/1406] update --- lua/platformio/lspClangd.lua | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 3c569151..71fa7281 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -257,8 +257,11 @@ local pyrefly = { root_markers = { 'pyrefly.toml', 'pyproject.toml', 'setup.py', 'setup.cfg', 'requirements.txt', 'Pipfile', '.git' }, settings = { python = { - pythonPath = vim.env.VIRTUAL_ENV, - -- venvPath = vim.env.VIRTUAL_ENV, + pyrefly = { + displayTypeErrors = 'force-on', + }, + -- pythonPath = vim.env.VIRTUAL_ENV, + venvPath = vim.env.VIRTUAL_ENV, }, }, } From 18746aff13415a942fca925c88f7949c2a88bf74 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 08:35:41 +0300 Subject: [PATCH 0358/1406] update --- lua/platformio/boilerplate.lua | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 9c9d7bb8..b148354b 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -372,6 +372,9 @@ WhitespaceSensitiveMacros: boilerplate['.clangd'] = { content = [[ CompileFlags: + Add: [ + --target=riscv32-esp-elf, + ] Remove: [ -misc-definitions-in-headers, -fno-tree-switch-conversion, From b8dbe93c58fc568e31160bfbc0d754db7d876f0a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 08:36:02 +0300 Subject: [PATCH 0359/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index b148354b..3e4114b8 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -58,7 +58,7 @@ env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) #Import("env") -# Safe retrieval with a default message +# ..Safe retrieval with a default message print(f"Toolchain Inclusion Status: {env.get('COMPILATIONDB_INCLUDE_TOOLCHAIN', 'Not Set')}") print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") ]], From 26e9152fe8daaeea91488c88ddb156e2ed53f57a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 11:32:37 +0300 Subject: [PATCH 0360/1406] update --- lua/platformio/lspAttach.lua | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 20ad3dd5..21b50a79 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -54,17 +54,18 @@ vim.api.nvim_create_autocmd('LspAttach', { end ------------------------------------------------------------------ - if client:supports_method('documentHighlightProvider') then + if client and client:supports_method('textDocument/documentHighlight') then local highlight_augroup = vim.api.nvim_create_augroup('platformio-lsp-highlight', { clear = false }) + vim.api.nvim_create_autocmd({ 'CursorHold', 'CursorHoldI' }, { - buffer = bufnr, group = highlight_augroup, + buffer = bufnr, callback = vim.lsp.buf.document_highlight, }) - -- - vim.api.nvim_create_autocmd({ 'CursorMoved', 'CursorMovedI' }, { - buffer = bufnr, + + vim.api.nvim_create_autocmd({ 'CursorMoved' }, { group = highlight_augroup, + buffer = bufnr, callback = vim.lsp.buf.clear_references, }) -- From 65faa237d28059a5d1745316d040a43cd31480f1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 11:38:37 +0300 Subject: [PATCH 0361/1406] update --- lua/platformio/lspClangd.lua | 8 ++++++-- mini_nvimPlatformio.lua | 3 ++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 71fa7281..d22a3322 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -3,15 +3,19 @@ ----------------------------------------------------------------------------------------- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') -boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) --- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) + boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) +-- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) +-- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) --------------------------------------------------------------------------------- local ok, result diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 160abdcf..7e10208e 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -312,7 +312,8 @@ else pynvim_activate = pynvim_bin .. '/activate' end --- vim.uv.os_setenv('PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN', 'true') +--Toolchain inclusion forced in Global Environment +vim.uv.os_setenv('PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN', 'true') vim.uv.os_setenv('PLATFORMIO_CORE_DIR', platformio_core_dir) vim.g.python_host_prog = pynvim_python vim.g.python3_host_prog = pynvim_python From b8f9de79b1fd787847e53b785b4317fa9c64b088 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 11:39:06 +0300 Subject: [PATCH 0362/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 3e4114b8..b148354b 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -58,7 +58,7 @@ env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) #Import("env") -# ..Safe retrieval with a default message +# Safe retrieval with a default message print(f"Toolchain Inclusion Status: {env.get('COMPILATIONDB_INCLUDE_TOOLCHAIN', 'Not Set')}") print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") ]], From 824de5406031af1e0d4bef202f7b49481e2cf14d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 11:44:01 +0300 Subject: [PATCH 0363/1406] update --- lua/platformio/boilerplate.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index b148354b..f31eba30 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -37,8 +37,8 @@ monitor_speed = 9600 monitor_rts = 1 ; 1 combination to reset esp32c6 (Table 32.3-2. CDC-ACM Settings with RTS and DTR) monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dtr=0 -extra_scripts = - pre:enable_toolchain.py +;extra_scripts = +; pre:enable_toolchain.py ; enabled global env 'PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN' lib_ldf_mode = chain+ ;Library dependencies Finder ldf ]], From ded4f6790e48f9d2e919c159726aadb2bc152f18 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 11:49:35 +0300 Subject: [PATCH 0364/1406] update --- lua/platformio/boilerplate.lua | 61 +++++++++++++++++----------------- 1 file changed, 30 insertions(+), 31 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index f31eba30..2ad5dd40 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -373,43 +373,42 @@ boilerplate['.clangd'] = { content = [[ CompileFlags: Add: [ - --target=riscv32-esp-elf, + --target=riscv32-esp-elf, ] Remove: [ - -misc-definitions-in-headers, - -fno-tree-switch-conversion, - -mtext-section-literals, - -mlong-calls, - -mlongcalls, - -fstrict-volatile-bitfields, - -free*, - -fipa-pta*, - -march=*, - -mabi=*, - -mcpu=*, - ] + -misc-definitions-in-headers, + -fno-tree-switch-conversion, + -mtext-section-literals, + -mlong-calls, + -mlongcalls, + -fstrict-volatile-bitfields, + -free*, + -fipa-pta*, + -march=*, + -mabi=*, + -mcpu=*, + ] Diagnostics: Suppress: [ - "misc-definitions-in-headers", - "pp_including_mainfile_in_preamble", - "misc-unused-using-decls", - "unused-includes", - ] + "misc-definitions-in-headers", + "pp_including_mainfile_in_preamble", + "misc-unused-using-decls", + "unused-includes", + ] ClangTidy: Remove: [ - readability-*, - cert-err58-cpp, - llvmlibc-*, - fuchsia-*, - hicpp-avoid-c-arrays, - cppcoreguidelines-*, - llvm-*, - google-*, - bugprone-*, - hicpp-vararg, - modernize-*, - ] - + readability-*, + cert-err58-cpp, + llvmlibc-*, + fuchsia-*, + hicpp-avoid-c-arrays, + cppcoreguidelines-*, + llvm-*, + google-*, + bugprone-*, + hicpp-vararg, + modernize-*, + ] ]], } boilerplate['.stylua.toml'] = { From f65b20e11d3bebfc7b2fe61a1cb7012692c625a3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 11:58:47 +0300 Subject: [PATCH 0365/1406] update --- lua/platformio/boilerplate.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 2ad5dd40..efc7ba29 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -106,11 +106,12 @@ clangd --pch-storage=memory --pretty --ranking-model=decision_forest ---query-driver=%s/.platformio/**/packages/toolchain-*/**/bin/* +--query-driver=%s/.platformio/packages/*/bin/riscv32-esp-elf-* ]], content = function(self) return string.format(self.template, vim.env.HOME) end, + --query-driver=%s/.platformio/**/packages/toolchain-*/**/bin/* --query-driver = [[clangd --query-driver=]] .. vim.env.HOME .. [[/.platformio/packages/*]] --query-driver=** --query-driver=**/.platformio/packages/toolchain*/**/bin/*gcc* From 1863e3a5a160055c72bbfa74d47889b6735e34c9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 12:27:31 +0300 Subject: [PATCH 0366/1406] update --- lua/platformio/boilerplate.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index efc7ba29..df0c6f2e 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -106,11 +106,12 @@ clangd --pch-storage=memory --pretty --ranking-model=decision_forest ---query-driver=%s/.platformio/packages/*/bin/riscv32-esp-elf-* +--query-driver=**/*riscv32-esp-elf-*,**/*gcc*,**/*g++* ]], content = function(self) return string.format(self.template, vim.env.HOME) end, + --query-driver=%s/.platformio/packages/*/bin/riscv32-esp-elf-* --query-driver=%s/.platformio/**/packages/toolchain-*/**/bin/* --query-driver = [[clangd --query-driver=]] .. vim.env.HOME .. [[/.platformio/packages/*]] --query-driver=** From b0d76e474ff4f3efd45a48794c1d2da80ca6a5ba Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 12:50:51 +0300 Subject: [PATCH 0367/1406] update --- lua/platformio/lspAttach.lua | 12 ++ lua/platformio/piolsp.lua | 207 +++++++++++++++++------------------ 2 files changed, 115 insertions(+), 104 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 21b50a79..67b97712 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -91,6 +91,18 @@ vim.api.nvim_create_autocmd('LspAttach', { ------------------------------------------------------------------ vim.cmd([[autocmd FileType * set formatoptions-=ro]]) -- + -- fix paths in compile_commands.json + local piolsp = require('platformio.piolsp') --.piolsp + -- Create a manual command: :PioFixPaths + vim.api.nvim_create_user_command('PioFixPaths', piolsp.fix_pio_compile_commands, {}) + + -- Optional: Auto-run every time you attach an LSP to a C/C++ file + vim.api.nvim_create_autocmd('LspAttach', { + pattern = { '*.c', '*.cpp', '*.h', '*.hpp' }, + callback = function() + piolsp.fix_pio_compile_commands() + end, + }) end, }) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index e35bda7e..e69b9c61 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -3,145 +3,144 @@ local M = {} local utils = require('platformio.utils') local config = require('platformio').config --- Cache the toolchain path once globally so we don't glob on every save -local cached_toolchain = nil - function M.fix_pio_compile_commands() - local cwd = vim.fn.getcwd() - local json_path = cwd .. '/compile_commands.json' - - -- 1. Performance: Check if file exists and get last modified time - local stats = vim.loop.fs_stat(json_path) - if not stats then - if vim.fn.filereadable(cwd .. '/platformio.ini') == 1 then - vim.fn.system('pio run -t compiledb') - stats = vim.loop.fs_stat(json_path) -- Re-check after gen - end - end - if not stats then - return - end - - -- 2. Performance: Only run if the file was modified in the last 5 seconds - -- This prevents re-parsing the JSON every time you hit :w - local now = os.time() - if (now - stats.mtime.sec) > 5 and _G.PIO_FIXED_ONCE then - return - end - - -- 3. Get Toolchain (Cached) - if not cached_toolchain then - local glob = vim.fn.glob(vim.env.HOME .. '/.platformio/packages/toolchain-*/bin/') - if glob == '' then - return - end - cached_toolchain = vim.split(glob, '\n')[1] -- Ensure single string - end - - -- 4. Safe Read - local file = io.open(json_path, 'r') + local filename = 'compile_commands.json' + local file = io.open(filename, 'r') if not file then return - end - local content = file:read('*all') + end -- Gracefully exit if file is missing + + local content = file:read('*a') file:close() - if not content or content == '' then - return - end - -- 5. Safe Decode + -- Safe JSON decoding with error handling local ok, data = pcall(vim.json.decode, content) if not ok or type(data) ~= 'table' then + vim.notify('LSP: Failed to parse compile_commands.json', vim.log.levels.ERROR) return end - local changed = false + local path_map = {} + local modified = 0 + + -- Phase 1: Discover absolute paths from existing entries for _, entry in ipairs(data) do - -- Defensive Nil Checks - if type(entry) == 'table' and entry.command then - -- Prepend only if relative and not already fixed - if not entry.command:match('^/') and not entry.command:find(cached_toolchain, 1, true) then - entry.command = cached_toolchain .. entry.command - changed = true + if type(entry.command) == 'string' then + local cmd_parts = vim.split(entry.command, ' ') + local driver_path = cmd_parts[1] + -- Check for Linux (/...) or Windows (C:...) absolute paths + if driver_path and (driver_path:sub(1, 1) == '/' or driver_path:match('^%a:')) then + local driver_name = driver_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') + path_map[driver_name] = driver_path end end end - -- 6. Safe Save - if changed then - local out = io.open(json_path, 'w') - if out then - out:write(vim.json.encode(data, { indent = ' ' })) - out:close() - _G.PIO_FIXED_ONCE = true - vim.schedule(function() - print('PIO: Database optimized') - M.lsp_restarti('clangd') - end) + -- Phase 2: Replace bare driver names with discovered absolute paths + for _, entry in ipairs(data) do + if type(entry.command) == 'string' then + local cmd_parts = vim.split(entry.command, ' ') + local first = cmd_parts[1] + if first and not (first:sub(1, 1) == '/' or first:match('^%a:')) then + local short_name = first:gsub('%.exe$', '') + if path_map[short_name] then + cmd_parts[1] = path_map[short_name] + entry.command = table.concat(cmd_parts, ' ') + modified = modified + 1 + end + end + end + end + + -- Save changes only if modifications were made + if modified > 0 then + local out_file = io.open(filename, 'w') + if out_file then + out_file:write(vim.json.encode(data)) + out_file:close() + vim.notify('Fixed ' .. modified .. ' paths in compile_commands.json', vim.log.levels.INFO) + -- Trigger LSP reload to pick up new paths + vim.cmd('LspRestart') end end end +-- -- Cache the toolchain path once globally so we don't glob on every save +-- local cached_toolchain = nil +-- -- function M.fix_pio_compile_commands() -- local cwd = vim.fn.getcwd() -- local json_path = cwd .. '/compile_commands.json' -- --- -- 1. Generate if missing --- if vim.fn.filereadable(json_path) == 0 then +-- -- 1. Performance: Check if file exists and get last modified time +-- local stats = vim.loop.fs_stat(json_path) +-- if not stats then -- if vim.fn.filereadable(cwd .. '/platformio.ini') == 1 then --- print('PIO: Generating compilation database...') -- vim.fn.system('pio run -t compiledb') --- else --- return +-- stats = vim.loop.fs_stat(json_path) -- Re-check after gen -- end -- end +-- if not stats then +-- return +-- end -- --- -- 2. Read and Decode --- local file = io.open(json_path, 'r') --- if file then --- local content = file:read('*all') --- file:close() --- local ok, data = pcall(vim.fn.json_decode, content) --- if not ok or type(data) ~= 'table' then --- return --- end --- -- 3. Get Toolchain Path --- local glob_result = vim.fn.glob(vim.env.HOME .. '/.platformio/packages/toolchain-*/bin/') --- if glob_result == '' then +-- -- 2. Performance: Only run if the file was modified in the last 5 seconds +-- -- This prevents re-parsing the JSON every time you hit :w +-- local now = os.time() +-- if (now - stats.mtime.sec) > 5 and _G.PIO_FIXED_ONCE then +-- return +-- end +-- +-- -- 3. Get Toolchain (Cached) +-- if not cached_toolchain then +-- local glob = vim.fn.glob(vim.env.HOME .. '/.platformio/packages/toolchain-*/bin/') +-- if glob == '' then -- return -- end --- local toolchain_bin = vim.split(glob_result, '\n')[1] -- Ensure we get a single string +-- cached_toolchain = vim.split(glob, '\n')[1] -- Ensure single string +-- end +-- +-- -- 4. Safe Read +-- local file = io.open(json_path, 'r') +-- if not file then +-- return +-- end +-- local content = file:read('*all') +-- file:close() +-- if not content or content == '' then +-- return +-- end -- --- local changed = false --- for _, entry in ipairs(data) do --- if entry.command then --- -- IMPROVEMENT: Only prepend if it's NOT already an absolute path --- -- AND it doesn't already contain the toolchain path (prevents double-prepending) --- if not entry.command:match('^/') and not entry.command:find(toolchain_bin, 1, true) then --- entry.command = toolchain_bin .. entry.command --- changed = true --- end +-- -- 5. Safe Decode +-- local ok, data = pcall(vim.json.decode, content) +-- if not ok or type(data) ~= 'table' then +-- return +-- end +-- +-- local changed = false +-- for _, entry in ipairs(data) do +-- -- Defensive Nil Checks +-- if type(entry) == 'table' and entry.command then +-- -- Prepend only if relative and not already fixed +-- if not entry.command:match('^/') and not entry.command:find(cached_toolchain, 1, true) then +-- entry.command = cached_toolchain .. entry.command +-- changed = true -- end -- end --- -- 4. Save with Formatting --- if changed then --- local out_file = io.open(json_path, 'w') --- -- Check if vim.json is available (Neovim 0.9+) --- if out_file then --- if vim.json and vim.json.encode then --- out_file:write(vim.json.encode(data, { indent = ' ' })) --- else --- -- Fallback for older versions (minified) --- out_file:write(vim.fn.json_encode(data)) --- end --- out_file:close() +-- end -- --- print('PIO: Paths fixed and JSON formatted') --- M.lsp_restart('clangd') --- end +-- -- 6. Safe Save +-- if changed then +-- local out = io.open(json_path, 'w') +-- if out then +-- out:write(vim.json.encode(data, { indent = ' ' })) +-- out:close() +-- _G.PIO_FIXED_ONCE = true +-- vim.schedule(function() +-- print('PIO: Database optimized') +-- M.lsp_restarti('clangd') +-- end) -- end --- else --- return -- end -- end From 262c45ceb385210e2d1f0867e7a54ffba33a9bb8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 12:59:41 +0300 Subject: [PATCH 0368/1406] update --- lua/platformio/lspAttach.lua | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 67b97712..8744fae7 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -1,3 +1,4 @@ +local piolsp = require('platformio.piolsp') --.piolsp -- INFO: LspAttach autocommand start vim.api.nvim_create_autocmd('LspAttach', { group = vim.api.nvim_create_augroup('platformio-lsp-attach', { clear = true }), @@ -24,6 +25,7 @@ vim.api.nvim_create_autocmd('LspAttach', { vim.cmd.edit(vim.uri_to_fname(result)) end, bufnr) end, { desc = 'Switch between source/header' }) + piolsp.fix_pio_compile_commands() end -- use lsp completion if no blink @@ -91,21 +93,20 @@ vim.api.nvim_create_autocmd('LspAttach', { ------------------------------------------------------------------ vim.cmd([[autocmd FileType * set formatoptions-=ro]]) -- - -- fix paths in compile_commands.json - local piolsp = require('platformio.piolsp') --.piolsp - -- Create a manual command: :PioFixPaths - vim.api.nvim_create_user_command('PioFixPaths', piolsp.fix_pio_compile_commands, {}) - - -- Optional: Auto-run every time you attach an LSP to a C/C++ file - vim.api.nvim_create_autocmd('LspAttach', { - pattern = { '*.c', '*.cpp', '*.h', '*.hpp' }, - callback = function() - piolsp.fix_pio_compile_commands() - end, - }) + -- -- Optional: Auto-run every time you attach an LSP to a C/C++ file + -- vim.api.nvim_create_autocmd('LspAttach', { + -- pattern = { '*.c', '*.cpp', '*.h', '*.hpp' }, + -- callback = function() + -- piolsp.fix_pio_compile_commands() + -- end, + -- }) end, }) +-- fix paths in compile_commands.json +-- Create a manual command: :PioFixPaths +vim.api.nvim_create_user_command('PioFixPaths', piolsp.fix_pio_compile_commands, {}) + vim.api.nvim_create_autocmd('LspDetach', { group = vim.api.nvim_create_augroup('LspCleanup', { clear = true }), callback = function(arg) From 7c4dabb16c3008ac74a4bfda014742f670b9c051 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 13:02:20 +0300 Subject: [PATCH 0369/1406] update --- lua/platformio/piolsp.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index e69b9c61..8b4dc511 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -60,7 +60,8 @@ function M.fix_pio_compile_commands() out_file:close() vim.notify('Fixed ' .. modified .. ' paths in compile_commands.json', vim.log.levels.INFO) -- Trigger LSP reload to pick up new paths - vim.cmd('LspRestart') + -- vim.cmd('LspRestart') + M.lsp_restart() end end end From 2bd797194f22201943d2f936ff166b39c87fb52a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 13:04:29 +0300 Subject: [PATCH 0370/1406] update --- lua/platformio/piolsp.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 8b4dc511..9109a2c5 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -201,7 +201,7 @@ function M.lsp_restart(name) if not ok then vim.notify('LSP ' .. name .. ' restart failed: ' .. err) else - vim.notify('LSP ' .. name .. ' restarted : ' .. err) + vim.notify('LSP ' .. name .. ' restarted') end end else From 0753c7ec3e75415fe644824d36b65da10cc91ab7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 13:07:56 +0300 Subject: [PATCH 0371/1406] update --- lua/platformio/piolsp.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 9109a2c5..492df64a 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -61,7 +61,7 @@ function M.fix_pio_compile_commands() vim.notify('Fixed ' .. modified .. ' paths in compile_commands.json', vim.log.levels.INFO) -- Trigger LSP reload to pick up new paths -- vim.cmd('LspRestart') - M.lsp_restart() + M.lsp_restart('clangd') end end end @@ -201,7 +201,7 @@ function M.lsp_restart(name) if not ok then vim.notify('LSP ' .. name .. ' restart failed: ' .. err) else - vim.notify('LSP ' .. name .. ' restarted') + vim.notify('LSP ' .. name .. ' restarted' .. err) end end else From 907d25b030d98bef1b485d9de557c0ec5be84873 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 14:59:51 +0300 Subject: [PATCH 0372/1406] update --- lua/platformio/lspClangd.lua | 27 +++++++++++++++++++- lua/platformio/piolsp.lua | 49 ++++++++++++++++++++---------------- 2 files changed, 54 insertions(+), 22 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index d22a3322..8dd97763 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -89,7 +89,8 @@ local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') if mok then mason_lspconfig.setup({ -- ensure_installed = { 'clangd', 'pyrefly' }, - ensure_installed = { 'clangd', 'lua_ls', 'pyrefly', 'yamlls' }, + ensure_installed = { 'ccls', 'lua_ls', 'pyrefly', 'yamlls' }, + -- ensure_installed = { 'clangd', 'lua_ls', 'pyrefly', 'yamlls' }, automatic_enable = true, -- this will automatically enable LSP servers after lsp.config }) end @@ -116,6 +117,30 @@ vim.lsp.config('*', { workspace_required = false, }) +---------------------------------------------------------------------------------------- +-- INFO: configure ccls lsp server +----------------------------------------------------------------------------------------- +-- vim.lsp.config('ccls', { +-- filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, +-- root_markers = { +-- 'CMakeLists.txt', +-- '.clangd', +-- '.clang-tidy', +-- '.clang-format', +-- 'compile_commands.json', +-- 'compile_flags.txt', +-- 'configure.ac', +-- '.git', +-- vim.uv.cwd(), +-- }, +-- init_options = { +-- diagnostics = { +-- onChange = 100, +-- }, +-- }, +-- }) +-- vim.lsp.enable('ccls') + ---------------------------------------------------------------------------------------- -- INFO: configure clangd lsp server ----------------------------------------------------------------------------------------- diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 492df64a..979b3e7d 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -4,64 +4,71 @@ local utils = require('platformio.utils') local config = require('platformio').config function M.fix_pio_compile_commands() - local filename = 'compile_commands.json' + local cwd = vim.fn.getcwd() + local filename = cwd .. 'compile_commands.json' local file = io.open(filename, 'r') if not file then return - end -- Gracefully exit if file is missing + end local content = file:read('*a') file:close() - -- Safe JSON decoding with error handling local ok, data = pcall(vim.json.decode, content) if not ok or type(data) ~= 'table' then - vim.notify('LSP: Failed to parse compile_commands.json', vim.log.levels.ERROR) return end local path_map = {} local modified = 0 - -- Phase 1: Discover absolute paths from existing entries + -- Phase 1: Discover paths for _, entry in ipairs(data) do if type(entry.command) == 'string' then + -- Handle both spaces and potential escaped quotes in commands local cmd_parts = vim.split(entry.command, ' ') local driver_path = cmd_parts[1] - -- Check for Linux (/...) or Windows (C:...) absolute paths - if driver_path and (driver_path:sub(1, 1) == '/' or driver_path:match('^%a:')) then - local driver_name = driver_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') - path_map[driver_name] = driver_path + + if driver_path then + -- Detect Absolute Path: Starts with / (Linux) or X:\ (Windows) + local is_abs = driver_path:sub(1, 1) == '/' or driver_path:match('^%a:[/\\]') + + if is_abs then + -- Extract name: works for /path/to/gcc and C:\path\to\gcc.exe + local name = driver_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') + path_map[name] = driver_path + end end end end - -- Phase 2: Replace bare driver names with discovered absolute paths + -- Phase 2: Replace bare names for _, entry in ipairs(data) do if type(entry.command) == 'string' then local cmd_parts = vim.split(entry.command, ' ') local first = cmd_parts[1] - if first and not (first:sub(1, 1) == '/' or first:match('^%a:')) then - local short_name = first:gsub('%.exe$', '') - if path_map[short_name] then - cmd_parts[1] = path_map[short_name] - entry.command = table.concat(cmd_parts, ' ') - modified = modified + 1 + + if first then + local is_abs = first:sub(1, 1) == '/' or first:match('^%a:[/\\]') + if not is_abs then + local short_name = first:gsub('%.exe$', '') + if path_map[short_name] then + cmd_parts[1] = path_map[short_name] + entry.command = table.concat(cmd_parts, ' ') + modified = modified + 1 + end end end end end - -- Save changes only if modifications were made if modified > 0 then local out_file = io.open(filename, 'w') if out_file then out_file:write(vim.json.encode(data)) out_file:close() - vim.notify('Fixed ' .. modified .. ' paths in compile_commands.json', vim.log.levels.INFO) - -- Trigger LSP reload to pick up new paths - -- vim.cmd('LspRestart') - M.lsp_restart('clangd') + vim.notify('PIO: Fixed ' .. modified .. ' toolchain paths (' .. vim.loop.os_uname().sysname .. ')', vim.log.levels.INFO) + vim.cmd('LspRestart') end end end From 7cc4444564544cb784b01234d0049f78a9a74280 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 15:02:10 +0300 Subject: [PATCH 0373/1406] update --- lua/platformio/piolsp.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 979b3e7d..daf411cb 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -37,6 +37,7 @@ function M.fix_pio_compile_commands() -- Extract name: works for /path/to/gcc and C:\path\to\gcc.exe local name = driver_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = driver_path + print(driver_path) end end end @@ -68,7 +69,7 @@ function M.fix_pio_compile_commands() out_file:write(vim.json.encode(data)) out_file:close() vim.notify('PIO: Fixed ' .. modified .. ' toolchain paths (' .. vim.loop.os_uname().sysname .. ')', vim.log.levels.INFO) - vim.cmd('LspRestart') + M.lsp_restart('clangd') end end end From 14861d7a812fa8c4c96fdf808efda6096958b7dd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 15:07:52 +0300 Subject: [PATCH 0374/1406] update --- lua/platformio/piolsp.lua | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index daf411cb..02760abf 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -21,7 +21,7 @@ function M.fix_pio_compile_commands() local path_map = {} local modified = 0 - + print('PioFix0') -- Phase 1: Discover paths for _, entry in ipairs(data) do if type(entry.command) == 'string' then @@ -37,12 +37,13 @@ function M.fix_pio_compile_commands() -- Extract name: works for /path/to/gcc and C:\path\to\gcc.exe local name = driver_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = driver_path - print(driver_path) + print('PioFix1') end end end end + print('PioFix2') -- Phase 2: Replace bare names for _, entry in ipairs(data) do if type(entry.command) == 'string' then @@ -63,6 +64,7 @@ function M.fix_pio_compile_commands() end end + print('PioFix3') if modified > 0 then local out_file = io.open(filename, 'w') if out_file then From ec8c8537149ac8abe76b84a61e431517a4e504d2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 15:09:33 +0300 Subject: [PATCH 0375/1406] update --- lua/platformio/lspClangd.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/lspClangd.lua index 8dd97763..2a943236 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/lspClangd.lua @@ -89,8 +89,8 @@ local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') if mok then mason_lspconfig.setup({ -- ensure_installed = { 'clangd', 'pyrefly' }, - ensure_installed = { 'ccls', 'lua_ls', 'pyrefly', 'yamlls' }, - -- ensure_installed = { 'clangd', 'lua_ls', 'pyrefly', 'yamlls' }, + -- ensure_installed = { 'ccls', 'lua_ls', 'pyrefly', 'yamlls' }, + ensure_installed = { 'clangd', 'lua_ls', 'pyrefly', 'yamlls' }, automatic_enable = true, -- this will automatically enable LSP servers after lsp.config }) end From 4b9751319f259a1c633a138c63f8b66efc4519a2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 15:14:43 +0300 Subject: [PATCH 0376/1406] update --- lua/platformio/piolsp.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 02760abf..6cf47299 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -5,7 +5,8 @@ local config = require('platformio').config function M.fix_pio_compile_commands() local cwd = vim.fn.getcwd() - local filename = cwd .. 'compile_commands.json' + local filename = cwd .. '/compile_commands.json' + print('PioFix0:' .. filename) local file = io.open(filename, 'r') if not file then return From ab6a6aac9ddc2ee21fe1592d2a89de58b361def1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 15:19:25 +0300 Subject: [PATCH 0377/1406] update --- lua/platformio/piolsp.lua | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 6cf47299..22bf0b55 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -69,10 +69,19 @@ function M.fix_pio_compile_commands() if modified > 0 then local out_file = io.open(filename, 'w') if out_file then - out_file:write(vim.json.encode(data)) - out_file:close() - vim.notify('PIO: Fixed ' .. modified .. ' toolchain paths (' .. vim.loop.os_uname().sysname .. ')', vim.log.levels.INFO) - M.lsp_restart('clangd') + -- Encode with 2-space indentation + local success, json_str = pcall(vim.json.encode, data, { indent = ' ' }) + + print('PioFix4') + if success then + out_file:write(json_str) + out_file:close() + vim.notify('PIO: Paths fixed and JSON formatted.', vim.log.levels.INFO) + vim.cmd('LspRestart') + else + out_file:close() + vim.notify('LSP: Failed to encode JSON', vim.log.levels.ERROR) + end end end end From 5d7a44f54672e892b73a053fd054b527a993e50d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 15:21:35 +0300 Subject: [PATCH 0378/1406] update --- lua/platformio/piolsp.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 22bf0b55..4e76aac6 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -77,7 +77,7 @@ function M.fix_pio_compile_commands() out_file:write(json_str) out_file:close() vim.notify('PIO: Paths fixed and JSON formatted.', vim.log.levels.INFO) - vim.cmd('LspRestart') + M.lsp_restart('clangd') else out_file:close() vim.notify('LSP: Failed to encode JSON', vim.log.levels.ERROR) From daa3347f8cdb798d7a0e32fe5f2b292b433ec915 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 15:27:57 +0300 Subject: [PATCH 0379/1406] update --- lua/platformio/piolsp.lua | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 4e76aac6..ed2b9bad 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -67,18 +67,21 @@ function M.fix_pio_compile_commands() print('PioFix3') if modified > 0 then + print('PioFix4') local out_file = io.open(filename, 'w') if out_file then -- Encode with 2-space indentation local success, json_str = pcall(vim.json.encode, data, { indent = ' ' }) - print('PioFix4') + print('PioFix5') if success then + print('PioFix6') out_file:write(json_str) out_file:close() vim.notify('PIO: Paths fixed and JSON formatted.', vim.log.levels.INFO) M.lsp_restart('clangd') else + print('PioFix7') out_file:close() vim.notify('LSP: Failed to encode JSON', vim.log.levels.ERROR) end From bfe5fde996681ae730b46bc7e35f3f123ab9bc41 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 15:29:09 +0300 Subject: [PATCH 0380/1406] update --- lua/platformio/piolsp.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index ed2b9bad..e63cb167 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -38,7 +38,7 @@ function M.fix_pio_compile_commands() -- Extract name: works for /path/to/gcc and C:\path\to\gcc.exe local name = driver_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = driver_path - print('PioFix1') + print('PioFix1:' .. driver_path) end end end From a790801254468515e71ebd5907737cd4b86899f0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 15:57:57 +0300 Subject: [PATCH 0381/1406] update --- lua/platformio/piolsp.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index e63cb167..e07c055d 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -38,7 +38,7 @@ function M.fix_pio_compile_commands() -- Extract name: works for /path/to/gcc and C:\path\to\gcc.exe local name = driver_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = driver_path - print('PioFix1:' .. driver_path) + print('PioFix1: driver_path=' .. driver_path .. ' name=' .. name) end end end @@ -55,6 +55,7 @@ function M.fix_pio_compile_commands() local is_abs = first:sub(1, 1) == '/' or first:match('^%a:[/\\]') if not is_abs then local short_name = first:gsub('%.exe$', '') + print('PioFix20:' .. short_name) if path_map[short_name] then cmd_parts[1] = path_map[short_name] entry.command = table.concat(cmd_parts, ' ') From 862ca3146d325b0cb83567b4df5a2ded363a1031 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 16:25:48 +0300 Subject: [PATCH 0382/1406] update --- lua/platformio/piolsp.lua | 155 +++++++++++++++++++++++++++----------- 1 file changed, 111 insertions(+), 44 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index e07c055d..8f8072ae 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -6,7 +6,6 @@ local config = require('platformio').config function M.fix_pio_compile_commands() local cwd = vim.fn.getcwd() local filename = cwd .. '/compile_commands.json' - print('PioFix0:' .. filename) local file = io.open(filename, 'r') if not file then return @@ -20,42 +19,35 @@ function M.fix_pio_compile_commands() return end + -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path local path_map = {} - local modified = 0 - print('PioFix0') - -- Phase 1: Discover paths - for _, entry in ipairs(data) do - if type(entry.command) == 'string' then - -- Handle both spaces and potential escaped quotes in commands - local cmd_parts = vim.split(entry.command, ' ') - local driver_path = cmd_parts[1] - - if driver_path then - -- Detect Absolute Path: Starts with / (Linux) or X:\ (Windows) - local is_abs = driver_path:sub(1, 1) == '/' or driver_path:match('^%a:[/\\]') + local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') + if pio_home then + -- Recursively find all binaries in PIO packages + local pio_packages = pio_home .. '/.platformio/packages/*/bin/*' + local found_binaries = vim.fn.glob(pio_packages, false, true) - if is_abs then - -- Extract name: works for /path/to/gcc and C:\path\to\gcc.exe - local name = driver_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') - path_map[name] = driver_path - print('PioFix1: driver_path=' .. driver_path .. ' name=' .. name) - end - end + for _, full_path in ipairs(found_binaries) do + -- Extract filename (e.g., riscv32-esp-elf-gcc) + local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') + path_map[name] = full_path end end - print('PioFix2') - -- Phase 2: Replace bare names + -- PHASE 2: Update JSON using the Map + local modified = 0 for _, entry in ipairs(data) do if type(entry.command) == 'string' then local cmd_parts = vim.split(entry.command, ' ') - local first = cmd_parts[1] + local first_token = cmd_parts[1] + + if first_token then + -- Check if it's already a short name (not an absolute path) + local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') - if first then - local is_abs = first:sub(1, 1) == '/' or first:match('^%a:[/\\]') if not is_abs then - local short_name = first:gsub('%.exe$', '') - print('PioFix20:' .. short_name) + local short_name = first_token:gsub('%.exe$', '') + -- Direct Query: Does this name exist in our discovered list? if path_map[short_name] then cmd_parts[1] = path_map[short_name] entry.command = table.concat(cmd_parts, ' ') @@ -66,30 +58,105 @@ function M.fix_pio_compile_commands() end end - print('PioFix3') + -- PHASE 3: Save and Refresh if modified > 0 then - print('PioFix4') local out_file = io.open(filename, 'w') if out_file then - -- Encode with 2-space indentation - local success, json_str = pcall(vim.json.encode, data, { indent = ' ' }) - - print('PioFix5') - if success then - print('PioFix6') - out_file:write(json_str) - out_file:close() - vim.notify('PIO: Paths fixed and JSON formatted.', vim.log.levels.INFO) - M.lsp_restart('clangd') - else - print('PioFix7') - out_file:close() - vim.notify('LSP: Failed to encode JSON', vim.log.levels.ERROR) - end + out_file:write(vim.json.encode(data, { indent = ' ' })) + out_file:close() + vim.notify('PIO: Auto-resolved ' .. modified .. ' driver paths', vim.log.levels.INFO) + M.lsp_restart('clangd') end end end +-- function M.fix_pio_compile_commands() +-- local cwd = vim.fn.getcwd() +-- local filename = cwd .. '/compile_commands.json' +-- print('PioFix0:' .. filename) +-- local file = io.open(filename, 'r') +-- if not file then +-- return +-- end +-- +-- local content = file:read('*a') +-- file:close() +-- +-- local ok, data = pcall(vim.json.decode, content) +-- if not ok or type(data) ~= 'table' then +-- return +-- end +-- +-- local path_map = {} +-- local modified = 0 +-- print('PioFix0') +-- -- Phase 1: Discover paths +-- for _, entry in ipairs(data) do +-- if type(entry.command) == 'string' then +-- -- Handle both spaces and potential escaped quotes in commands +-- local cmd_parts = vim.split(entry.command, ' ') +-- local driver_path = cmd_parts[1] +-- +-- if driver_path then +-- -- Detect Absolute Path: Starts with / (Linux) or X:\ (Windows) +-- local is_abs = driver_path:sub(1, 1) == '/' or driver_path:match('^%a:[/\\]') +-- +-- if is_abs then +-- -- Extract name: works for /path/to/gcc and C:\path\to\gcc.exe +-- local name = driver_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') +-- path_map[name] = driver_path +-- print('PioFix1: driver_path=' .. driver_path .. ' name=' .. name) +-- end +-- end +-- end +-- end +-- +-- print('PioFix2') +-- -- Phase 2: Replace bare names +-- for _, entry in ipairs(data) do +-- if type(entry.command) == 'string' then +-- local cmd_parts = vim.split(entry.command, ' ') +-- local first = cmd_parts[1] +-- +-- if first then +-- local is_abs = first:sub(1, 1) == '/' or first:match('^%a:[/\\]') +-- if not is_abs then +-- local short_name = first:gsub('%.exe$', '') +-- print('PioFix20:' .. short_name) +-- if path_map[short_name] then +-- cmd_parts[1] = path_map[short_name] +-- entry.command = table.concat(cmd_parts, ' ') +-- modified = modified + 1 +-- end +-- end +-- end +-- end +-- end +-- +-- print('PioFix3') +-- if modified > 0 then +-- print('PioFix4') +-- local out_file = io.open(filename, 'w') +-- if out_file then +-- -- Encode with 2-space indentation +-- local success, json_str = pcall(vim.json.encode, data, { indent = ' ' }) +-- +-- print('PioFix5') +-- if success then +-- print('PioFix6') +-- out_file:write(json_str) +-- out_file:close() +-- vim.notify('PIO: Paths fixed and JSON formatted.', vim.log.levels.INFO) +-- M.lsp_restart('clangd') +-- else +-- print('PioFix7') +-- out_file:close() +-- vim.notify('LSP: Failed to encode JSON', vim.log.levels.ERROR) +-- end +-- end +-- end +-- end + -- -- Cache the toolchain path once globally so we don't glob on every save -- local cached_toolchain = nil -- From e336d9bf46f6158dc7179136e2f0e1794fca8e08 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 16:29:10 +0300 Subject: [PATCH 0383/1406] update --- lua/platformio/piolsp.lua | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 8f8072ae..35166885 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -19,6 +19,7 @@ function M.fix_pio_compile_commands() return end + print('PioFix0') -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path local path_map = {} local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') @@ -31,6 +32,7 @@ function M.fix_pio_compile_commands() -- Extract filename (e.g., riscv32-esp-elf-gcc) local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = full_path + print('PioFix: driver_path=' .. full_path .. ' name=' .. name) end end @@ -47,6 +49,7 @@ function M.fix_pio_compile_commands() if not is_abs then local short_name = first_token:gsub('%.exe$', '') + print('PioFix: short_name=' .. short_name) -- Direct Query: Does this name exist in our discovered list? if path_map[short_name] then cmd_parts[1] = path_map[short_name] From 9ecc0b7afe2038033a7871132e2be591cd73dd75 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 18:11:01 +0300 Subject: [PATCH 0384/1406] update --- lua/platformio/pioinit.lua | 19 ++++++++++++------- lua/platformio/piolsp.lua | 26 ++++++++++++++++++++------ lua/platformio/utils.lua | 34 +++++++++++++++++++++++++++++++++- 3 files changed, 65 insertions(+), 14 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 2c064add..6726da97 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -59,16 +59,21 @@ local function pick_framework(board_details) local selection = action_state.get_selected_entry() local selected_framework = selection[1] + utils.watch_once_and_run('.pio_done', piolsp.cleanup(selected_framework), 40000) + + local is_win = vim.uv.os_uname().sysname == 'Windows_NT' + local marker = is_win and 'type nul > .pio_done' or 'touch .pio_done' + local command = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. selected_framework .. '"' - command = command .. ' && pio run -t compiledb' + command = command .. ' && pio run -t compiledb && ' .. marker utils.ToggleTerminal(command, 'float') - vim.defer_fn(function() - vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) - piolsp.gitignore_lsp_configs('compile_commands.json') - boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') - piolsp.lsp_restart('clangd') - end, 3000) + -- vim.defer_fn(function() + -- vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) + -- piolsp.gitignore_lsp_configs('compile_commands.json') + -- boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') + -- piolsp.lsp_restart('clangd') + -- end, 3000) -- utils.ToggleTerminal(command, 'float', function() -- -- require('platformio.piolsp').piolsp() -- piolsp() diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 35166885..8a0696c5 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -2,10 +2,18 @@ local M = {} local utils = require('platformio.utils') local config = require('platformio').config +local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + +function M.cleanup(selected_framework) + vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) + M.fix_pio_compile_commands() + M.gitignore_lsp_configs('compile_commands.json') + boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') + M.lsp_restart('clangd') +end function M.fix_pio_compile_commands() - local cwd = vim.fn.getcwd() - local filename = cwd .. '/compile_commands.json' + local filename = 'compile_commands.json' local file = io.open(filename, 'r') if not file then return @@ -13,9 +21,14 @@ function M.fix_pio_compile_commands() local content = file:read('*a') file:close() + if not content or content == '' then + return + end + -- Safe JSON decoding local ok, data = pcall(vim.json.decode, content) if not ok or type(data) ~= 'table' then + vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) return end @@ -62,13 +75,14 @@ function M.fix_pio_compile_commands() end -- PHASE 3: Save and Refresh - if modified > 0 then + -- Safe JSON encoding + local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) + if encode_ok and json_str then local out_file = io.open(filename, 'w') if out_file then - out_file:write(vim.json.encode(data, { indent = ' ' })) + out_file:write(json_str) out_file:close() - vim.notify('PIO: Auto-resolved ' .. modified .. ' driver paths', vim.log.levels.INFO) - M.lsp_restart('clangd') + vim.cmd('LspRestart') end end end diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 27feba0d..9e4dfbf5 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -3,8 +3,40 @@ local M = {} local config = require('platformio').config -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' +-- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' +------------------------------------------------------ +local uv, active = vim.uv or vim.loop, {} +-- stylua: ignore +function M.watch_once_and_run(file, callback, timeout) + local path = vim.fn.fnamemodify(file, ":p") -- Get absolute path + if type(callback) ~= "function" or active[path] then return end + + local event, timer = uv.new_fs_event(), uv.new_timer() + if not event or not timer then return end + + local function cleanup() + active[path] = nil + if not timer:is_closing() then timer:stop(); timer:close() end + if not event:is_closing() then event:stop(); event:close() end + end + + active[path] = true + timer:start(timeout or 60000, 0, vim.schedule_wrap(function() + if active[path] then cleanup(); vim.notify("Timeout: "..file, 3) end + end)) + + event:start(path, {}, vim.schedule_wrap(function(err) + if not err and uv.fs_stat(path) then + cleanup() + local ok, msg = pcall(callback) + if not ok then vim.notify("Error: "..tostring(msg), 4) end + pcall(os.remove, path) + end + end)) +end + +------------------------------------------------------ function M.strsplit(inputstr, del) local t = {} if type(inputstr) == 'string' and inputstr and inputstr ~= '' then From 12508df7df4f2ccbcd6e593202f6dbdf1e269878 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 18:44:38 +0300 Subject: [PATCH 0385/1406] update --- lua/platformio/utils.lua | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 9e4dfbf5..dd2023be 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -31,7 +31,14 @@ function M.watch_once_and_run(file, callback, timeout) cleanup() local ok, msg = pcall(callback) if not ok then vim.notify("Error: "..tostring(msg), 4) end - pcall(os.remove, path) + -- pcall(os.remove, path) + -- Use the native libuv unlink for better cross-platform deletion + uv.fs_unlink(path, function(unlink_err) + if unlink_err then + -- If it fails, try a delayed retry (common for Windows locks) + vim.defer_fn(function() pcall(os.remove, path) end, 500) + end + end) end end)) end From 9bb3766b3042a15e3e14751f0c8f71e0ee0220e5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 19:00:05 +0300 Subject: [PATCH 0386/1406] update --- lua/platformio/utils.lua | 102 +++++++++++++++++++++++++++------------ 1 file changed, 72 insertions(+), 30 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index dd2023be..3e896fa7 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -5,43 +5,85 @@ local config = require('platformio').config -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' ------------------------------------------------------- local uv, active = vim.uv or vim.loop, {} --- stylua: ignore + +--stylua: ignore function M.watch_once_and_run(file, callback, timeout) - local path = vim.fn.fnamemodify(file, ":p") -- Get absolute path - if type(callback) ~= "function" or active[path] then return end + local cwd, full = vim.fn.getcwd(), vim.fn.getcwd()..'/'..file + if type(callback) ~= 'function' or active[full] then return end - local event, timer = uv.new_fs_event(), uv.new_timer() - if not event or not timer then return end + local event, timer = uv.new_fs_event(), uv.new_timer() + if not event or not timer then return end - local function cleanup() - active[path] = nil - if not timer:is_closing() then timer:stop(); timer:close() end - if not event:is_closing() then event:stop(); event:close() end - end + local function cleanup() + active[full] = nil + if not timer:is_closing() then timer:stop(); timer:close() end + if not event:is_closing() then event:stop(); event:close() end + end - active[path] = true - timer:start(timeout or 60000, 0, vim.schedule_wrap(function() - if active[path] then cleanup(); vim.notify("Timeout: "..file, 3) end - end)) - - event:start(path, {}, vim.schedule_wrap(function(err) - if not err and uv.fs_stat(path) then - cleanup() - local ok, msg = pcall(callback) - if not ok then vim.notify("Error: "..tostring(msg), 4) end - -- pcall(os.remove, path) - -- Use the native libuv unlink for better cross-platform deletion - uv.fs_unlink(path, function(unlink_err) - if unlink_err then - -- If it fails, try a delayed retry (common for Windows locks) - vim.defer_fn(function() pcall(os.remove, path) end, 500) + active[full] = true + timer:start(timeout or 300000, 0, vim.schedule_wrap(function() + if active[full] then cleanup(); vim.notify('Timeout: '..file, 3) end + end)) + + event:start(cwd, {}, vim.schedule_wrap(function(err, fname) + if not err and fname == file then + vim.defer_fn(function() + if uv.fs_stat(full) then + cleanup() + local ok, msg = pcall(callback) + if ok then + -- pcall(os.remove, full) + local deleted = pcall(os.remove, full) + if not deleted then + -- Final fallback for stubborn Windows locks + vim.fn.system(string.format('rm "%s"', full)) + end + else + vim.notify('Callback Error: '..tostring(msg), 4) + end + end + end, 200) end - end) - end - end)) + end)) end +------------------------------------------------------ +-- local uv, active = vim.uv or vim.loop, {} +-- -- stylua: ignore +-- function M.watch_once_and_run(file, callback, timeout) +-- local path = vim.fn.fnamemodify(file, ":p") -- Get absolute path +-- if type(callback) ~= "function" or active[path] then return end +-- +-- local event, timer = uv.new_fs_event(), uv.new_timer() +-- if not event or not timer then return end +-- +-- local function cleanup() +-- active[path] = nil +-- if not timer:is_closing() then timer:stop(); timer:close() end +-- if not event:is_closing() then event:stop(); event:close() end +-- end +-- +-- active[path] = true +-- timer:start(timeout or 60000, 0, vim.schedule_wrap(function() +-- if active[path] then cleanup(); vim.notify("Timeout: "..file, 3) end +-- end)) +-- +-- event:start(path, {}, vim.schedule_wrap(function(err) +-- if not err and uv.fs_stat(path) then +-- cleanup() +-- local ok, msg = pcall(callback) +-- if not ok then vim.notify("Error: "..tostring(msg), 4) end +-- -- pcall(os.remove, path) +-- -- Use the native libuv unlink for better cross-platform deletion +-- uv.fs_unlink(path, function(unlink_err) +-- if unlink_err then +-- -- If it fails, try a delayed retry (common for Windows locks) +-- vim.defer_fn(function() pcall(os.remove, path) end, 500) +-- end +-- end) +-- end +-- end)) +-- end ------------------------------------------------------ function M.strsplit(inputstr, del) From 946922e53bef6a8c1bcabddcc0d59700cc6f7878 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 19:09:55 +0300 Subject: [PATCH 0387/1406] update --- lua/platformio/lspAttach.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 8744fae7..d1d926fc 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -25,7 +25,7 @@ vim.api.nvim_create_autocmd('LspAttach', { vim.cmd.edit(vim.uri_to_fname(result)) end, bufnr) end, { desc = 'Switch between source/header' }) - piolsp.fix_pio_compile_commands() + -- piolsp.fix_pio_compile_commands() end -- use lsp completion if no blink From d6e812f8e890c8ce24abd03dfe91c272d054a89c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 22:51:35 +0300 Subject: [PATCH 0388/1406] update --- lua/platformio/pioinit.lua | 39 +++++++++--- lua/platformio/utils.lua | 125 +++++++++++++------------------------ 2 files changed, 77 insertions(+), 87 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 6726da97..0c4be18e 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -59,15 +59,40 @@ local function pick_framework(board_details) local selection = action_state.get_selected_entry() local selected_framework = selection[1] - utils.watch_once_and_run('.pio_done', piolsp.cleanup(selected_framework), 40000) - - local is_win = vim.uv.os_uname().sysname == 'Windows_NT' - local marker = is_win and 'type nul > .pio_done' or 'touch .pio_done' - local command = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. selected_framework .. '"' - command = command .. ' && pio run -t compiledb && ' .. marker + -- command = command .. ' && pio run -t compiledb' - utils.ToggleTerminal(command, 'float') + -- Handle after 'pio run -t compiledb' execution + local function handleDb(_, _, data, _) + for _, line in ipairs(data) do + local clean_line = line:gsub('%s+', '') + if clean_line:find('___PIO_SUCCESS___') then + vim.schedule(function() + vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) + piolsp.fix_pio_compile_commands() + vim.notify('compiledb: fixed', vim.log.levels.INFO) + piolsp.gitignore_lsp_configs('compile_commands.json') + piolsp.lsp_restart('clangd') + vim.notify('compiledb: Success', vim.log.levels.INFO) + end) + end + end + end + -- Handle after poioinit execution + local function handlePioinit(_, _, data, _) + for _, line in ipairs(data) do + local clean_line = line:gsub('%s+', '') + if clean_line:find('___PIO_SUCCESS___') then + vim.schedule(function() + vim.notify('Pioinit: Success', vim.log.levels.INFO) + boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') + command = 'pio run -t compiledb' + utils.ToggleTerminal(command, 'float', handleDb) + end) + end + end + end + utils.ToggleTerminal(command, 'float', handlePioinit) -- vim.defer_fn(function() -- vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) -- piolsp.gitignore_lsp_configs('compile_commands.json') diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 3e896fa7..2a84cb32 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -5,84 +5,47 @@ local config = require('platformio').config -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' -local uv, active = vim.uv or vim.loop, {} - ---stylua: ignore -function M.watch_once_and_run(file, callback, timeout) - local cwd, full = vim.fn.getcwd(), vim.fn.getcwd()..'/'..file - if type(callback) ~= 'function' or active[full] then return end - - local event, timer = uv.new_fs_event(), uv.new_timer() - if not event or not timer then return end - - local function cleanup() - active[full] = nil - if not timer:is_closing() then timer:stop(); timer:close() end - if not event:is_closing() then event:stop(); event:close() end - end - - active[full] = true - timer:start(timeout or 300000, 0, vim.schedule_wrap(function() - if active[full] then cleanup(); vim.notify('Timeout: '..file, 3) end - end)) - - event:start(cwd, {}, vim.schedule_wrap(function(err, fname) - if not err and fname == file then - vim.defer_fn(function() - if uv.fs_stat(full) then - cleanup() - local ok, msg = pcall(callback) - if ok then - -- pcall(os.remove, full) - local deleted = pcall(os.remove, full) - if not deleted then - -- Final fallback for stubborn Windows locks - vim.fn.system(string.format('rm "%s"', full)) - end - else - vim.notify('Callback Error: '..tostring(msg), 4) - end - end - end, 200) - end - end)) -end ------------------------------------------------------ -- local uv, active = vim.uv or vim.loop, {} --- -- stylua: ignore +-- --stylua: ignore -- function M.watch_once_and_run(file, callback, timeout) --- local path = vim.fn.fnamemodify(file, ":p") -- Get absolute path --- if type(callback) ~= "function" or active[path] then return end +-- local cwd, full = vim.fn.getcwd(), vim.fn.getcwd()..'/'..file +-- if type(callback) ~= 'function' or active[full] then return end -- --- local event, timer = uv.new_fs_event(), uv.new_timer() --- if not event or not timer then return end +-- local event, timer = uv.new_fs_event(), uv.new_timer() +-- if not event or not timer then return end -- --- local function cleanup() --- active[path] = nil --- if not timer:is_closing() then timer:stop(); timer:close() end --- if not event:is_closing() then event:stop(); event:close() end --- end +-- local function cleanup() +-- active[full] = nil +-- if not timer:is_closing() then timer:stop(); timer:close() end +-- if not event:is_closing() then event:stop(); event:close() end +-- end -- --- active[path] = true --- timer:start(timeout or 60000, 0, vim.schedule_wrap(function() --- if active[path] then cleanup(); vim.notify("Timeout: "..file, 3) end --- end)) +-- active[full] = true +-- timer:start(timeout or 300000, 0, vim.schedule_wrap(function() +-- if active[full] then cleanup(); vim.notify('Timeout: '..file, 3) end +-- end)) -- --- event:start(path, {}, vim.schedule_wrap(function(err) --- if not err and uv.fs_stat(path) then --- cleanup() --- local ok, msg = pcall(callback) --- if not ok then vim.notify("Error: "..tostring(msg), 4) end --- -- pcall(os.remove, path) --- -- Use the native libuv unlink for better cross-platform deletion --- uv.fs_unlink(path, function(unlink_err) --- if unlink_err then --- -- If it fails, try a delayed retry (common for Windows locks) --- vim.defer_fn(function() pcall(os.remove, path) end, 500) +-- event:start(cwd, {}, vim.schedule_wrap(function(err, fname) +-- if not err and fname == file then +-- vim.defer_fn(function() +-- if uv.fs_stat(full) then +-- cleanup() +-- local ok, msg = pcall(callback) +-- if ok then +-- -- pcall(os.remove, full) +-- local deleted = pcall(os.remove, full) +-- if not deleted then +-- -- Final fallback for stubborn Windows locks +-- vim.fn.system(string.format('rm "%s"', full)) +-- end +-- else +-- vim.notify('Callback Error: '..tostring(msg), 4) +-- end +-- end +-- end, 200) -- end --- end) --- end --- end)) +-- end)) -- end ------------------------------------------------------ @@ -196,12 +159,11 @@ end ------------------------------------------------------ -- INFO: ToggleTerminal -function M.ToggleTerminal(command, direction, exit_callback) - local closeOnexit = type(exit_callback) == 'function' - if closeOnexit then - command = command .. ' && exit' +function M.ToggleTerminal(command, direction, stdout_callback) + if type(stdout_callback) == 'function' then + command = command .. ' && echo ___PIO_SUCCESS___ || echo ___PIO_FAILED__' else - exit_callback = function() end + stdout_callback = function(_, _, _, _) end end local status_ok, _ = pcall(require, 'toggleterm') @@ -271,7 +233,7 @@ function M.ToggleTerminal(command, direction, exit_callback) background = 'NormalFloat', }, }, - close_on_exit = closeOnexit, + close_on_exit = false, --closeOnexit, -- INFO: on_open() on_open = function(t) @@ -323,10 +285,13 @@ function M.ToggleTerminal(command, direction, exit_callback) end end, - -- INFO: on_exit() - on_exit = function(_) - exit_callback() - end, + -- -- INFO: on_exit() + -- on_exit = function(_) + -- exit_callback() + -- end, + + -- INFO: on_stdout + stdout = stdout_callback, -- INFO: on_create() { on_create = function(t) From 902ea8b8e83816e8991c159456b7d094bf4aff5b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 23:19:57 +0300 Subject: [PATCH 0389/1406] update --- lua/platformio/pioinit.lua | 39 ++++---------------------------------- lua/platformio/utils.lua | 34 +++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 35 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 0c4be18e..eea1c8fb 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -9,8 +9,6 @@ local entry_display = require('telescope.pickers.entry_display') local make_entry = require('telescope.make_entry') local utils = require('platformio.utils') local previewers = require('telescope.previewers') -local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -local piolsp = require('platformio.piolsp') --.piolsp local boardentry_maker = function(opts) local displayer = entry_display.create({ @@ -45,6 +43,7 @@ local boardentry_maker = function(opts) end end +M.selected_framework = '' local function pick_framework(board_details) local opts = {} pickers @@ -57,42 +56,12 @@ local function pick_framework(board_details) actions.select_default:replace(function() actions.close(prompt_bufnr) local selection = action_state.get_selected_entry() - local selected_framework = selection[1] + M.selected_framework = selection[1] - local command = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. selected_framework .. '"' + local command = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. M.selected_framework .. '"' -- command = command .. ' && pio run -t compiledb' - -- Handle after 'pio run -t compiledb' execution - local function handleDb(_, _, data, _) - for _, line in ipairs(data) do - local clean_line = line:gsub('%s+', '') - if clean_line:find('___PIO_SUCCESS___') then - vim.schedule(function() - vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) - piolsp.fix_pio_compile_commands() - vim.notify('compiledb: fixed', vim.log.levels.INFO) - piolsp.gitignore_lsp_configs('compile_commands.json') - piolsp.lsp_restart('clangd') - vim.notify('compiledb: Success', vim.log.levels.INFO) - end) - end - end - end - -- Handle after poioinit execution - local function handlePioinit(_, _, data, _) - for _, line in ipairs(data) do - local clean_line = line:gsub('%s+', '') - if clean_line:find('___PIO_SUCCESS___') then - vim.schedule(function() - vim.notify('Pioinit: Success', vim.log.levels.INFO) - boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') - command = 'pio run -t compiledb' - utils.ToggleTerminal(command, 'float', handleDb) - end) - end - end - end - utils.ToggleTerminal(command, 'float', handlePioinit) + utils.ToggleTerminal(command, 'float', utils.handlePioinit) -- vim.defer_fn(function() -- vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) -- piolsp.gitignore_lsp_configs('compile_commands.json') diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 2a84cb32..50c955e9 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -1,3 +1,6 @@ +local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +local piolsp = require('platformio.piolsp') --.piolsp +local pioinit = require('platformio.pioinit') local M = {} local config = require('platformio').config @@ -5,6 +8,37 @@ local config = require('platformio').config -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' +-- Handle after 'pio run -t compiledb' execution +function M.handleDb(_, _, data, _) + for _, line in ipairs(data) do + local clean_line = line:gsub('%s+', '') + if clean_line:find('___PIO_SUCCESS___') then + vim.schedule(function() + vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) + piolsp.fix_pio_compile_commands() + vim.notify('compiledb: fixed', vim.log.levels.INFO) + piolsp.gitignore_lsp_configs('compile_commands.json') + piolsp.lsp_restart('clangd') + vim.notify('compiledb: Success', vim.log.levels.INFO) + end) + end + end +end +-- Handle after poioinit execution +function M.handlePioinit(_, _, data, _) + vim.notify('Pioinit: Success', vim.log.levels.INFO) + for _, line in ipairs(data) do + local clean_line = line:gsub('%s+', '') + if clean_line:find('___PIO_SUCCESS___') then + vim.schedule(function() + vim.notify('Pioinit: Success', vim.log.levels.INFO) + boilerplate_gen(pioinit.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') + local command = 'pio run -t compiledb' + M.ToggleTerminal(command, 'float', M.handleDb) + end) + end + end +end ------------------------------------------------------ -- local uv, active = vim.uv or vim.loop, {} -- --stylua: ignore From e4d44f7c33617f64b1606273498e2f721272fb9e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 23:43:41 +0300 Subject: [PATCH 0390/1406] update --- lua/platformio/lspAttach.lua | 4 ++-- lua/platformio/pioinit.lua | 5 ++--- lua/platformio/piolsp.lua | 2 -- lua/platformio/utils.lua | 1 + 4 files changed, 5 insertions(+), 7 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index d1d926fc..787f2763 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -1,4 +1,4 @@ -local piolsp = require('platformio.piolsp') --.piolsp +-- local piolsp = require('platformio.piolsp') --.piolsp -- INFO: LspAttach autocommand start vim.api.nvim_create_autocmd('LspAttach', { group = vim.api.nvim_create_augroup('platformio-lsp-attach', { clear = true }), @@ -105,7 +105,7 @@ vim.api.nvim_create_autocmd('LspAttach', { -- fix paths in compile_commands.json -- Create a manual command: :PioFixPaths -vim.api.nvim_create_user_command('PioFixPaths', piolsp.fix_pio_compile_commands, {}) +-- vim.api.nvim_create_user_command('PioFixPaths', piolsp.fix_pio_compile_commands, {}) vim.api.nvim_create_autocmd('LspDetach', { group = vim.api.nvim_create_augroup('LspCleanup', { clear = true }), diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index eea1c8fb..bffa78d0 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -43,7 +43,6 @@ local boardentry_maker = function(opts) end end -M.selected_framework = '' local function pick_framework(board_details) local opts = {} pickers @@ -56,9 +55,9 @@ local function pick_framework(board_details) actions.select_default:replace(function() actions.close(prompt_bufnr) local selection = action_state.get_selected_entry() - M.selected_framework = selection[1] + utils.selected_framework = selection[1] - local command = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. M.selected_framework .. '"' + local command = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. utils.selected_framework .. '"' -- command = command .. ' && pio run -t compiledb' utils.ToggleTerminal(command, 'float', utils.handlePioinit) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 8a0696c5..ce9c4a1e 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -1,7 +1,5 @@ local M = {} -local utils = require('platformio.utils') -local config = require('platformio').config local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen function M.cleanup(selected_framework) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 50c955e9..349a8dcb 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -2,6 +2,7 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local piolsp = require('platformio.piolsp') --.piolsp local pioinit = require('platformio.pioinit') local M = {} +M.selected_framework = '' local config = require('platformio').config From 421ab5e5221d54171bb6d4728f2e5189a5553074 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 7 Apr 2026 23:47:36 +0300 Subject: [PATCH 0391/1406] update --- lua/platformio/utils.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 349a8dcb..181783db 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -1,6 +1,6 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local piolsp = require('platformio.piolsp') --.piolsp -local pioinit = require('platformio.pioinit') +-- local pioinit = require('platformio.pioinit') local M = {} M.selected_framework = '' @@ -33,7 +33,7 @@ function M.handlePioinit(_, _, data, _) if clean_line:find('___PIO_SUCCESS___') then vim.schedule(function() vim.notify('Pioinit: Success', vim.log.levels.INFO) - boilerplate_gen(pioinit.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') + boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') local command = 'pio run -t compiledb' M.ToggleTerminal(command, 'float', M.handleDb) end) From 86d75f03c0eddcf107588f9d074e209946a17615 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 05:09:20 +0300 Subject: [PATCH 0392/1406] update --- lua/platformio/utils.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 181783db..f4015e43 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -326,7 +326,7 @@ function M.ToggleTerminal(command, direction, stdout_callback) -- end, -- INFO: on_stdout - stdout = stdout_callback, + on_stdout = stdout_callback, -- INFO: on_create() { on_create = function(t) From c090462ce8a4b8f779814acb4869e1953559fb73 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 05:14:39 +0300 Subject: [PATCH 0393/1406] update --- lua/platformio/utils.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index f4015e43..700ebcb5 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -27,7 +27,6 @@ function M.handleDb(_, _, data, _) end -- Handle after poioinit execution function M.handlePioinit(_, _, data, _) - vim.notify('Pioinit: Success', vim.log.levels.INFO) for _, line in ipairs(data) do local clean_line = line:gsub('%s+', '') if clean_line:find('___PIO_SUCCESS___') then From 614ca09cf205f13ed5f91de84eeb770d9ea47eb8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 05:26:03 +0300 Subject: [PATCH 0394/1406] update --- lua/platformio/utils.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 700ebcb5..5e2d93d6 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -197,7 +197,8 @@ function M.ToggleTerminal(command, direction, stdout_callback) if type(stdout_callback) == 'function' then command = command .. ' && echo ___PIO_SUCCESS___ || echo ___PIO_FAILED__' else - stdout_callback = function(_, _, _, _) end + -- stdout_callback = function(_, _, _, _) end + stdout_callback = nil end local status_ok, _ = pcall(require, 'toggleterm') From 98ffbc0bdd62a80f78e67dcf88d36eaa1f031d01 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 05:44:16 +0300 Subject: [PATCH 0395/1406] update --- lua/platformio/lspAttach.lua | 4 ---- lua/platformio/utils.lua | 4 ++-- plugin/platformio.lua | 4 ++++ 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/lspAttach.lua index 787f2763..7d21e24c 100644 --- a/lua/platformio/lspAttach.lua +++ b/lua/platformio/lspAttach.lua @@ -103,10 +103,6 @@ vim.api.nvim_create_autocmd('LspAttach', { end, }) --- fix paths in compile_commands.json --- Create a manual command: :PioFixPaths --- vim.api.nvim_create_user_command('PioFixPaths', piolsp.fix_pio_compile_commands, {}) - vim.api.nvim_create_autocmd('LspDetach', { group = vim.api.nvim_create_augroup('LspCleanup', { clear = true }), callback = function(arg) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 5e2d93d6..68c01110 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -33,8 +33,8 @@ function M.handlePioinit(_, _, data, _) vim.schedule(function() vim.notify('Pioinit: Success', vim.log.levels.INFO) boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') - local command = 'pio run -t compiledb' - M.ToggleTerminal(command, 'float', M.handleDb) + -- local command = 'pio run -t compiledb' + -- M.ToggleTerminal(command, 'float', M.handleDb) end) end end diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 63bdd48a..2a35b24a 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -93,6 +93,10 @@ end, {}) ------------------------------------------------------ +-- INFO: fix paths in compile_commands.json +vim.api.nvim_create_user_command('PioFixPaths', require('platformio.piolsp').fix_pio_compile_commands, {}) +------------------------------------------------------ + -- require('telescope').load_extension('ui-select') -- INFO: List ToggleTerminals vim.api.nvim_create_user_command('PioTermList', function() From 86b7aa20082fc7b82c080ffbf60bedd44b51b368 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 05:54:08 +0300 Subject: [PATCH 0396/1406] update --- plugin/platformio.lua | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 2a35b24a..e067c8a5 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -94,7 +94,11 @@ end, {}) ------------------------------------------------------ -- INFO: fix paths in compile_commands.json -vim.api.nvim_create_user_command('PioFixPaths', require('platformio.piolsp').fix_pio_compile_commands, {}) +-- vim.api.nvim_create_user_command('PioFixPaths', require('platformio.piolsp').fix_pio_compile_commands, {}) +vim.api.nvim_create_user_command('PioFixPaths', function() + local command = 'pio run -t compiledb' + utils.ToggleTerminal(command, 'float', require('platformio.piolsp').fix_pio_compile_commands) +end, {}) ------------------------------------------------------ -- require('telescope').load_extension('ui-select') From 51643d760e70fe307b59ca5163ad74ec9aa84a53 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 05:59:34 +0300 Subject: [PATCH 0397/1406] update --- lua/platformio/utils.lua | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 68c01110..7a4970e0 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -10,11 +10,12 @@ local config = require('platformio').config -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' -- Handle after 'pio run -t compiledb' execution -function M.handleDb(_, _, data, _) +function M.handleDb(t, _, data, _) for _, line in ipairs(data) do local clean_line = line:gsub('%s+', '') if clean_line:find('___PIO_SUCCESS___') then vim.schedule(function() + t.on_stdout = nil vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) piolsp.fix_pio_compile_commands() vim.notify('compiledb: fixed', vim.log.levels.INFO) @@ -26,15 +27,16 @@ function M.handleDb(_, _, data, _) end end -- Handle after poioinit execution -function M.handlePioinit(_, _, data, _) +function M.handlePioinit(t, _, data, _) for _, line in ipairs(data) do local clean_line = line:gsub('%s+', '') if clean_line:find('___PIO_SUCCESS___') then vim.schedule(function() + t.on_stdout = nil vim.notify('Pioinit: Success', vim.log.levels.INFO) boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') - -- local command = 'pio run -t compiledb' - -- M.ToggleTerminal(command, 'float', M.handleDb) + local command = 'pio run -t compiledb' + M.ToggleTerminal(command, 'float', M.handleDb) end) end end From 2d9ef3a3456905c4216aee637769924b5df75e7d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 06:05:09 +0300 Subject: [PATCH 0398/1406] update --- lua/platformio/utils.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 7a4970e0..764bf3e1 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -14,8 +14,8 @@ function M.handleDb(t, _, data, _) for _, line in ipairs(data) do local clean_line = line:gsub('%s+', '') if clean_line:find('___PIO_SUCCESS___') then + t.on_stdout = nil vim.schedule(function() - t.on_stdout = nil vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) piolsp.fix_pio_compile_commands() vim.notify('compiledb: fixed', vim.log.levels.INFO) @@ -31,8 +31,8 @@ function M.handlePioinit(t, _, data, _) for _, line in ipairs(data) do local clean_line = line:gsub('%s+', '') if clean_line:find('___PIO_SUCCESS___') then + t.on_stdout = nil vim.schedule(function() - t.on_stdout = nil vim.notify('Pioinit: Success', vim.log.levels.INFO) boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') local command = 'pio run -t compiledb' From 06635563b15d6e4b8fd04d1aefae88101b3b84b6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 06:12:41 +0300 Subject: [PATCH 0399/1406] update --- lua/platformio/utils.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 764bf3e1..699c1874 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -13,7 +13,7 @@ local config = require('platformio').config function M.handleDb(t, _, data, _) for _, line in ipairs(data) do local clean_line = line:gsub('%s+', '') - if clean_line:find('___PIO_SUCCESS___') then + if clean_line:find('^___PIO_SUCCESS___') then t.on_stdout = nil vim.schedule(function() vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) @@ -30,7 +30,7 @@ end function M.handlePioinit(t, _, data, _) for _, line in ipairs(data) do local clean_line = line:gsub('%s+', '') - if clean_line:find('___PIO_SUCCESS___') then + if clean_line:find('^___PIO_SUCCESS___') then t.on_stdout = nil vim.schedule(function() vim.notify('Pioinit: Success', vim.log.levels.INFO) From bca79c086da9aff050e8a16854e4ac2e8f6ff083 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 06:38:39 +0300 Subject: [PATCH 0400/1406] update --- lua/platformio/utils.lua | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 699c1874..5b70e67d 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -11,10 +11,16 @@ local config = require('platformio').config -- Handle after 'pio run -t compiledb' execution function M.handleDb(t, _, data, _) + -- Check if we've already marked this specific terminal as 'done' + if t.pio_done then + return + end for _, line in ipairs(data) do local clean_line = line:gsub('%s+', '') if clean_line:find('^___PIO_SUCCESS___') then - t.on_stdout = nil + -- Set the flag on the terminal object so we never enter this 'for' loop again + t.pio_done = true + t.on_stdout = function() end vim.schedule(function() vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) piolsp.fix_pio_compile_commands() @@ -28,10 +34,14 @@ function M.handleDb(t, _, data, _) end -- Handle after poioinit execution function M.handlePioinit(t, _, data, _) + if t.pio_done then + return + end for _, line in ipairs(data) do local clean_line = line:gsub('%s+', '') if clean_line:find('^___PIO_SUCCESS___') then - t.on_stdout = nil + t.pio_done = true + t.on_stdout = function() end vim.schedule(function() vim.notify('Pioinit: Success', vim.log.levels.INFO) boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') From 1da1d18d40d162c385d2c6038605c204e7a7ae0d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 06:47:27 +0300 Subject: [PATCH 0401/1406] update --- lua/platformio/utils.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 5b70e67d..10109412 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -40,12 +40,13 @@ function M.handlePioinit(t, _, data, _) for _, line in ipairs(data) do local clean_line = line:gsub('%s+', '') if clean_line:find('^___PIO_SUCCESS___') then - t.pio_done = true + -- t.pio_done = true t.on_stdout = function() end vim.schedule(function() vim.notify('Pioinit: Success', vim.log.levels.INFO) boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') local command = 'pio run -t compiledb' + t.pio_done = false M.ToggleTerminal(command, 'float', M.handleDb) end) end From 6021ac1ec78b031f077b8558013440682049bcc8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 08:13:35 +0300 Subject: [PATCH 0402/1406] update --- lua/platformio/utils.lua | 52 +++++++++++++++++++++++++++++++++------- 1 file changed, 43 insertions(+), 9 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 10109412..bb43112c 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -9,18 +9,50 @@ local config = require('platformio').config -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' --- Handle after 'pio run -t compiledb' execution -function M.handleDb(t, _, data, _) - -- Check if we've already marked this specific terminal as 'done' +function M.pio_sequence_handler(t, _, data, _) + -- Table mapping terminal 'echo' signals to specific Lua functions + local actions = { + ['___FIX_PATHS___'] = function() + M.fix_pio_compile_commands() + vim.notify('Step 1: Paths Fixed') + end, + ['___RUN_LINT___'] = function() + -- Call a different function here + vim.notify('Step 2: Linter triggered') + end, + ['___CLEANUP___'] = function() + t.pio_done = true -- Mark terminal as finished + vim.notify('Sequence Complete') + end, + } + if t.pio_done then return end + + for _, line in ipairs(data) do + local clean_line = line:gsub('%s+', '') + + -- Check if the line matches any of our defined signals + for signal, action_fn in pairs(actions) do + if clean_line:find(signal) then + vim.schedule(action_fn) + end + end + end +end +-- Handle after 'pio run -t compiledb' execution +function M.handleDb(t, _, data, _) + -- Check if we've already marked this specific terminal as 'done' + -- if t.pio_done then + -- return + -- end for _, line in ipairs(data) do local clean_line = line:gsub('%s+', '') if clean_line:find('^___PIO_SUCCESS___') then -- Set the flag on the terminal object so we never enter this 'for' loop again - t.pio_done = true - t.on_stdout = function() end + -- t.pio_done = true + -- t.on_stdout = function() end vim.schedule(function() vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) piolsp.fix_pio_compile_commands() @@ -28,15 +60,17 @@ function M.handleDb(t, _, data, _) piolsp.gitignore_lsp_configs('compile_commands.json') piolsp.lsp_restart('clangd') vim.notify('compiledb: Success', vim.log.levels.INFO) + local command = 'echo ___COMPILEDB_SUCCESS___' + M.ToggleTerminal(command, 'float') end) end end end -- Handle after poioinit execution function M.handlePioinit(t, _, data, _) - if t.pio_done then - return - end + -- if t.pio_done then + -- return + -- end for _, line in ipairs(data) do local clean_line = line:gsub('%s+', '') if clean_line:find('^___PIO_SUCCESS___') then @@ -45,8 +79,8 @@ function M.handlePioinit(t, _, data, _) vim.schedule(function() vim.notify('Pioinit: Success', vim.log.levels.INFO) boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') + -- t.pio_done = false local command = 'pio run -t compiledb' - t.pio_done = false M.ToggleTerminal(command, 'float', M.handleDb) end) end From c938fc9abf4cd29d2f98f1a7928086c82b8cdf1c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 08:53:30 +0300 Subject: [PATCH 0403/1406] update --- lua/platformio/utils.lua | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index bb43112c..083dd444 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -43,16 +43,9 @@ function M.pio_sequence_handler(t, _, data, _) end -- Handle after 'pio run -t compiledb' execution function M.handleDb(t, _, data, _) - -- Check if we've already marked this specific terminal as 'done' - -- if t.pio_done then - -- return - -- end for _, line in ipairs(data) do local clean_line = line:gsub('%s+', '') if clean_line:find('^___PIO_SUCCESS___') then - -- Set the flag on the terminal object so we never enter this 'for' loop again - -- t.pio_done = true - -- t.on_stdout = function() end vim.schedule(function() vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) piolsp.fix_pio_compile_commands() @@ -60,6 +53,7 @@ function M.handleDb(t, _, data, _) piolsp.gitignore_lsp_configs('compile_commands.json') piolsp.lsp_restart('clangd') vim.notify('compiledb: Success', vim.log.levels.INFO) + t.config.on_stdout = nil local command = 'echo ___COMPILEDB_SUCCESS___' M.ToggleTerminal(command, 'float') end) @@ -68,18 +62,14 @@ function M.handleDb(t, _, data, _) end -- Handle after poioinit execution function M.handlePioinit(t, _, data, _) - -- if t.pio_done then - -- return - -- end for _, line in ipairs(data) do local clean_line = line:gsub('%s+', '') if clean_line:find('^___PIO_SUCCESS___') then - -- t.pio_done = true t.on_stdout = function() end vim.schedule(function() vim.notify('Pioinit: Success', vim.log.levels.INFO) boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') - -- t.pio_done = false + t.config.on_stdout = nil local command = 'pio run -t compiledb' M.ToggleTerminal(command, 'float', M.handleDb) end) From 707cc627c8643b71da9d9450d6d62748ed27e6ff Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 11:27:29 +0300 Subject: [PATCH 0404/1406] update --- lua/platformio/pioinit.lua | 17 +++++-- lua/platformio/utils.lua | 97 +++++++++++++++++--------------------- 2 files changed, 57 insertions(+), 57 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index bffa78d0..5d0074c4 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -57,10 +57,21 @@ local function pick_framework(board_details) local selection = action_state.get_selected_entry() utils.selected_framework = selection[1] - local command = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. utils.selected_framework .. '"' - -- command = command .. ' && pio run -t compiledb' + utils.run_sequence({ + { + cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. utils.selected_framework .. '"', + cb = utils.handlePioinit, + }, + { + cmd = 'pio run -t compiledb', + cb = utils.handleDb, + }, + }) + + -- local command = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. utils.selected_framework .. '"' + -- -- command = command .. ' && pio run -t compiledb' + -- utils.ToggleTerminal(command, 'float', utils.handlePioinit) - utils.ToggleTerminal(command, 'float', utils.handlePioinit) -- vim.defer_fn(function() -- vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) -- piolsp.gitignore_lsp_configs('compile_commands.json') diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 083dd444..8db50b53 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -9,72 +9,61 @@ local config = require('platformio').config -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' -function M.pio_sequence_handler(t, _, data, _) - -- Table mapping terminal 'echo' signals to specific Lua functions - local actions = { - ['___FIX_PATHS___'] = function() - M.fix_pio_compile_commands() - vim.notify('Step 1: Paths Fixed') - end, - ['___RUN_LINT___'] = function() - -- Call a different function here - vim.notify('Step 2: Linter triggered') - end, - ['___CLEANUP___'] = function() - t.pio_done = true -- Mark terminal as finished - vim.notify('Sequence Complete') - end, - } +M.queue = {} - if t.pio_done then +-- Unified Dispatcher +function M.dispatcher(_, _, data) + if #M.queue == 0 then return end for _, line in ipairs(data) do - local clean_line = line:gsub('%s+', '') - - -- Check if the line matches any of our defined signals - for signal, action_fn in pairs(actions) do - if clean_line:find(signal) then - vim.schedule(action_fn) + -- Match format ___DONE___:SUCCESS or ___DONE___:FAILED + local status = line:match('___DONE___:(%a+)') + if status then + if status == 'SUCCESS' then + local task = table.remove(M.queue, 1) + if task then + vim.schedule(task) + end + else + M.queue = {} -- Clear queue on any other status (failure) + vim.schedule(function() + vim.notify('Sequence Aborted', 4) + end) end + break end end end --- Handle after 'pio run -t compiledb' execution -function M.handleDb(t, _, data, _) - for _, line in ipairs(data) do - local clean_line = line:gsub('%s+', '') - if clean_line:find('^___PIO_SUCCESS___') then - vim.schedule(function() - vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) - piolsp.fix_pio_compile_commands() - vim.notify('compiledb: fixed', vim.log.levels.INFO) - piolsp.gitignore_lsp_configs('compile_commands.json') - piolsp.lsp_restart('clangd') - vim.notify('compiledb: Success', vim.log.levels.INFO) - t.config.on_stdout = nil - local command = 'echo ___COMPILEDB_SUCCESS___' - M.ToggleTerminal(command, 'float') - end) - end + +-- M.term = Terminal:new({ on_stdout = M.dispatcher, hidden = true }) + +-- Improved Runner: Accepts a table of { cmd = "...", cb = function } +M.run_sequence = function(tasks) + local full_cmd = '' + for _, task in ipairs(tasks) do + table.insert(M.queue, task.cb) + -- Chain: (cmd && success_signal) || failure_signal + local part = string.format('(%s && echo "___DONE___:SUCCESS") || (echo "___DONE___:FAILED" && exit 1)', task.cmd) + full_cmd = full_cmd == '' and part or full_cmd .. ' && ' .. part end + M.ToggleTerminal(full_cmd, 'float') +end + +-- Handle after 'pio run -t compiledb' execution +function M.handleDb() + vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) + piolsp.fix_pio_compile_commands() + vim.notify('compiledb: fixed', vim.log.levels.INFO) + piolsp.gitignore_lsp_configs('compile_commands.json') + piolsp.lsp_restart('clangd') + vim.notify('compiledb: Success', vim.log.levels.INFO) end -- Handle after poioinit execution -function M.handlePioinit(t, _, data, _) - for _, line in ipairs(data) do - local clean_line = line:gsub('%s+', '') - if clean_line:find('^___PIO_SUCCESS___') then - t.on_stdout = function() end - vim.schedule(function() - vim.notify('Pioinit: Success', vim.log.levels.INFO) - boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') - t.config.on_stdout = nil - local command = 'pio run -t compiledb' - M.ToggleTerminal(command, 'float', M.handleDb) - end) - end - end +function M.handlePioinit() + vim.notify('Pioinit: Success', vim.log.levels.INFO) + boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') end ------------------------------------------------------ -- local uv, active = vim.uv or vim.loop, {} From c3313f2cd21f8b29ea65ede2083cb598038ca8b0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 11:40:11 +0300 Subject: [PATCH 0405/1406] update --- lua/platformio/pioinit.lua | 8 +++++++- lua/platformio/utils.lua | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 5d0074c4..45e1b30d 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -9,6 +9,8 @@ local entry_display = require('telescope.pickers.entry_display') local make_entry = require('telescope.make_entry') local utils = require('platformio.utils') local previewers = require('telescope.previewers') +-- local piolsp = require('platformio.piolsp') +local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local boardentry_maker = function(opts) local displayer = entry_display.create({ @@ -60,7 +62,11 @@ local function pick_framework(board_details) utils.run_sequence({ { cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. utils.selected_framework .. '"', - cb = utils.handlePioinit, + -- cb = utils.handlePioinit, + cb = function() + vim.notify('Pioinit: Success', vim.log.levels.INFO) + boilerplate_gen(utils.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') + end, }, { cmd = 'pio run -t compiledb', diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 8db50b53..636cbd50 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -19,7 +19,7 @@ function M.dispatcher(_, _, data) for _, line in ipairs(data) do -- Match format ___DONE___:SUCCESS or ___DONE___:FAILED - local status = line:match('___DONE___:(%a+)') + local status = line:match('^___DONE___:(%a+)') if status then if status == 'SUCCESS' then local task = table.remove(M.queue, 1) From 76ea3da557ad584e6432d6672f6e65bab8fab5b1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 11:49:06 +0300 Subject: [PATCH 0406/1406] update --- lua/platformio/pioinit.lua | 12 ++++---- lua/platformio/utils.lua | 60 ++++---------------------------------- 2 files changed, 12 insertions(+), 60 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 45e1b30d..a2f4ab1d 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -10,7 +10,7 @@ local make_entry = require('telescope.make_entry') local utils = require('platformio.utils') local previewers = require('telescope.previewers') -- local piolsp = require('platformio.piolsp') -local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +-- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local boardentry_maker = function(opts) local displayer = entry_display.create({ @@ -62,11 +62,11 @@ local function pick_framework(board_details) utils.run_sequence({ { cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. utils.selected_framework .. '"', - -- cb = utils.handlePioinit, - cb = function() - vim.notify('Pioinit: Success', vim.log.levels.INFO) - boilerplate_gen(utils.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') - end, + cb = utils.handlePioinit, + -- cb = function() + -- vim.notify('Pioinit: Success', vim.log.levels.INFO) + -- boilerplate_gen(utils.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') + -- end, }, { cmd = 'pio run -t compiledb', diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 636cbd50..916dcdf6 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -9,8 +9,9 @@ local config = require('platformio').config -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' +------------------------------------------------------ +-- INFO: Dispatcher M.queue = {} - -- Unified Dispatcher function M.dispatcher(_, _, data) if #M.queue == 0 then @@ -36,9 +37,6 @@ function M.dispatcher(_, _, data) end end end - --- M.term = Terminal:new({ on_stdout = M.dispatcher, hidden = true }) - -- Improved Runner: Accepts a table of { cmd = "...", cb = function } M.run_sequence = function(tasks) local full_cmd = '' @@ -65,48 +63,8 @@ function M.handlePioinit() vim.notify('Pioinit: Success', vim.log.levels.INFO) boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') end +-- INFO: endDispatcher ------------------------------------------------------ --- local uv, active = vim.uv or vim.loop, {} --- --stylua: ignore --- function M.watch_once_and_run(file, callback, timeout) --- local cwd, full = vim.fn.getcwd(), vim.fn.getcwd()..'/'..file --- if type(callback) ~= 'function' or active[full] then return end --- --- local event, timer = uv.new_fs_event(), uv.new_timer() --- if not event or not timer then return end --- --- local function cleanup() --- active[full] = nil --- if not timer:is_closing() then timer:stop(); timer:close() end --- if not event:is_closing() then event:stop(); event:close() end --- end --- --- active[full] = true --- timer:start(timeout or 300000, 0, vim.schedule_wrap(function() --- if active[full] then cleanup(); vim.notify('Timeout: '..file, 3) end --- end)) --- --- event:start(cwd, {}, vim.schedule_wrap(function(err, fname) --- if not err and fname == file then --- vim.defer_fn(function() --- if uv.fs_stat(full) then --- cleanup() --- local ok, msg = pcall(callback) --- if ok then --- -- pcall(os.remove, full) --- local deleted = pcall(os.remove, full) --- if not deleted then --- -- Final fallback for stubborn Windows locks --- vim.fn.system(string.format('rm "%s"', full)) --- end --- else --- vim.notify('Callback Error: '..tostring(msg), 4) --- end --- end --- end, 200) --- end --- end)) --- end ------------------------------------------------------ function M.strsplit(inputstr, del) @@ -219,14 +177,7 @@ end ------------------------------------------------------ -- INFO: ToggleTerminal -function M.ToggleTerminal(command, direction, stdout_callback) - if type(stdout_callback) == 'function' then - command = command .. ' && echo ___PIO_SUCCESS___ || echo ___PIO_FAILED__' - else - -- stdout_callback = function(_, _, _, _) end - stdout_callback = nil - end - +function M.ToggleTerminal(command, direction) local status_ok, _ = pcall(require, 'toggleterm') if not status_ok then vim.api.nvim_echo({ { 'toggleterm not found!', 'ErrorMsg' } }, true, {}) @@ -352,7 +303,8 @@ function M.ToggleTerminal(command, direction, stdout_callback) -- end, -- INFO: on_stdout - on_stdout = stdout_callback, + -- on_stdout = stdout_callback, + on_stdout = M.dispatcher, -- INFO: on_create() { on_create = function(t) From 9a109eb2572344a0d4f25311e48581733458e688 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 11:53:12 +0300 Subject: [PATCH 0407/1406] update --- lua/platformio/piolsp.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index ce9c4a1e..3eb3f767 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -297,7 +297,7 @@ function M.lsp_restarti(name) end function M.lsp_restart(name) - if vim.fn.has('nvim-0.11') == 1 then + if vim.fn.has('nvim-0.12') == 1 then -- local clients = vim.lsp.get_clients({ name = name }) local clangd = vim.lsp.get_clients({ name = name })[1] From f51cee935bfbd70231d95e9192bdd94ab084e653 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 11:56:43 +0300 Subject: [PATCH 0408/1406] update --- lua/platformio/piolsp.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 3eb3f767..c933f59f 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -80,7 +80,8 @@ function M.fix_pio_compile_commands() if out_file then out_file:write(json_str) out_file:close() - vim.cmd('LspRestart') + -- vim.cmd('LspRestart') + M.lsp_restart('clangd') end end end From b7e0e13630db0d3b284686742aa5e900f65adbc3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 13:29:06 +0300 Subject: [PATCH 0409/1406] update --- lua/platformio/piolsp.lua | 204 +++----------------------------------- 1 file changed, 16 insertions(+), 188 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index c933f59f..d6fdfc2c 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -1,15 +1,5 @@ local M = {} -local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - -function M.cleanup(selected_framework) - vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) - M.fix_pio_compile_commands() - M.gitignore_lsp_configs('compile_commands.json') - boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') - M.lsp_restart('clangd') -end - function M.fix_pio_compile_commands() local filename = 'compile_commands.json' local file = io.open(filename, 'r') @@ -30,20 +20,20 @@ function M.fix_pio_compile_commands() return end - print('PioFix0') + -- print('PioFix0') -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path local path_map = {} local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') if pio_home then -- Recursively find all binaries in PIO packages - local pio_packages = pio_home .. '/.platformio/packages/*/bin/*' + local pio_packages = pio_home .. '/.platformio/*/packages/*/bin/*' local found_binaries = vim.fn.glob(pio_packages, false, true) for _, full_path in ipairs(found_binaries) do -- Extract filename (e.g., riscv32-esp-elf-gcc) local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = full_path - print('PioFix: driver_path=' .. full_path .. ' name=' .. name) + -- print('PioFix: driver_path=' .. full_path .. ' name=' .. name) end end @@ -60,7 +50,7 @@ function M.fix_pio_compile_commands() if not is_abs then local short_name = first_token:gsub('%.exe$', '') - print('PioFix: short_name=' .. short_name) + -- print('PioFix: short_name=' .. short_name) -- Direct Query: Does this name exist in our discovered list? if path_map[short_name] then cmd_parts[1] = path_map[short_name] @@ -86,172 +76,6 @@ function M.fix_pio_compile_commands() end end --- function M.fix_pio_compile_commands() --- local cwd = vim.fn.getcwd() --- local filename = cwd .. '/compile_commands.json' --- print('PioFix0:' .. filename) --- local file = io.open(filename, 'r') --- if not file then --- return --- end --- --- local content = file:read('*a') --- file:close() --- --- local ok, data = pcall(vim.json.decode, content) --- if not ok or type(data) ~= 'table' then --- return --- end --- --- local path_map = {} --- local modified = 0 --- print('PioFix0') --- -- Phase 1: Discover paths --- for _, entry in ipairs(data) do --- if type(entry.command) == 'string' then --- -- Handle both spaces and potential escaped quotes in commands --- local cmd_parts = vim.split(entry.command, ' ') --- local driver_path = cmd_parts[1] --- --- if driver_path then --- -- Detect Absolute Path: Starts with / (Linux) or X:\ (Windows) --- local is_abs = driver_path:sub(1, 1) == '/' or driver_path:match('^%a:[/\\]') --- --- if is_abs then --- -- Extract name: works for /path/to/gcc and C:\path\to\gcc.exe --- local name = driver_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') --- path_map[name] = driver_path --- print('PioFix1: driver_path=' .. driver_path .. ' name=' .. name) --- end --- end --- end --- end --- --- print('PioFix2') --- -- Phase 2: Replace bare names --- for _, entry in ipairs(data) do --- if type(entry.command) == 'string' then --- local cmd_parts = vim.split(entry.command, ' ') --- local first = cmd_parts[1] --- --- if first then --- local is_abs = first:sub(1, 1) == '/' or first:match('^%a:[/\\]') --- if not is_abs then --- local short_name = first:gsub('%.exe$', '') --- print('PioFix20:' .. short_name) --- if path_map[short_name] then --- cmd_parts[1] = path_map[short_name] --- entry.command = table.concat(cmd_parts, ' ') --- modified = modified + 1 --- end --- end --- end --- end --- end --- --- print('PioFix3') --- if modified > 0 then --- print('PioFix4') --- local out_file = io.open(filename, 'w') --- if out_file then --- -- Encode with 2-space indentation --- local success, json_str = pcall(vim.json.encode, data, { indent = ' ' }) --- --- print('PioFix5') --- if success then --- print('PioFix6') --- out_file:write(json_str) --- out_file:close() --- vim.notify('PIO: Paths fixed and JSON formatted.', vim.log.levels.INFO) --- M.lsp_restart('clangd') --- else --- print('PioFix7') --- out_file:close() --- vim.notify('LSP: Failed to encode JSON', vim.log.levels.ERROR) --- end --- end --- end --- end - --- -- Cache the toolchain path once globally so we don't glob on every save --- local cached_toolchain = nil --- --- function M.fix_pio_compile_commands() --- local cwd = vim.fn.getcwd() --- local json_path = cwd .. '/compile_commands.json' --- --- -- 1. Performance: Check if file exists and get last modified time --- local stats = vim.loop.fs_stat(json_path) --- if not stats then --- if vim.fn.filereadable(cwd .. '/platformio.ini') == 1 then --- vim.fn.system('pio run -t compiledb') --- stats = vim.loop.fs_stat(json_path) -- Re-check after gen --- end --- end --- if not stats then --- return --- end --- --- -- 2. Performance: Only run if the file was modified in the last 5 seconds --- -- This prevents re-parsing the JSON every time you hit :w --- local now = os.time() --- if (now - stats.mtime.sec) > 5 and _G.PIO_FIXED_ONCE then --- return --- end --- --- -- 3. Get Toolchain (Cached) --- if not cached_toolchain then --- local glob = vim.fn.glob(vim.env.HOME .. '/.platformio/packages/toolchain-*/bin/') --- if glob == '' then --- return --- end --- cached_toolchain = vim.split(glob, '\n')[1] -- Ensure single string --- end --- --- -- 4. Safe Read --- local file = io.open(json_path, 'r') --- if not file then --- return --- end --- local content = file:read('*all') --- file:close() --- if not content or content == '' then --- return --- end --- --- -- 5. Safe Decode --- local ok, data = pcall(vim.json.decode, content) --- if not ok or type(data) ~= 'table' then --- return --- end --- --- local changed = false --- for _, entry in ipairs(data) do --- -- Defensive Nil Checks --- if type(entry) == 'table' and entry.command then --- -- Prepend only if relative and not already fixed --- if not entry.command:match('^/') and not entry.command:find(cached_toolchain, 1, true) then --- entry.command = cached_toolchain .. entry.command --- changed = true --- end --- end --- end --- --- -- 6. Safe Save --- if changed then --- local out = io.open(json_path, 'w') --- if out then --- out:write(vim.json.encode(data, { indent = ' ' })) --- out:close() --- _G.PIO_FIXED_ONCE = true --- vim.schedule(function() --- print('PIO: Database optimized') --- M.lsp_restarti('clangd') --- end) --- end --- end --- end - function M.gitignore_lsp_configs(config_file) local gitignore_path = vim.fs.joinpath(vim.g.platformioRootDir, '.gitignore') local file = io.open(gitignore_path, 'r') @@ -317,10 +141,14 @@ function M.lsp_restart(name) end function M.piolsp() - M.fix_pio_compile_commands() + local ok, err = pcall(vim.cmd.lsp, { args = { 'restart' } }) + if ok then + vim.notify('LSP restarted' .. err) + else + vim.notify('LSP restart failed: ' .. err) + end + -- M.fix_pio_compile_commands() - -- - -- -- if not utils.pio_install_check() then -- return -- end @@ -337,11 +165,11 @@ function M.piolsp() -- -- -- print('piolsp: lsp restart ' .. clangd.name) -- -- pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) -- M.lsp_restart('clangd') - -- -- vim.cmd('lsp restart clangd') - -- -- end - -- -- else - -- -- vim.cmd('LspRestart') - -- -- end + -- vim.cmd('lsp restart clangd') + -- end + -- else + -- vim.cmd('LspRestart') + -- end end return M From acf6f3d993166432306df7269cea13b0d727cbf3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 13:46:44 +0300 Subject: [PATCH 0410/1406] update --- lua/platformio/pioinit.lua | 4 ---- lua/platformio/piolsp.lua | 2 +- lua/platformio/utils.lua | 4 +--- mini_nvimPlatformio.lua | 1 + 4 files changed, 3 insertions(+), 8 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index a2f4ab1d..b748ca05 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -63,10 +63,6 @@ local function pick_framework(board_details) { cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. utils.selected_framework .. '"', cb = utils.handlePioinit, - -- cb = function() - -- vim.notify('Pioinit: Success', vim.log.levels.INFO) - -- boilerplate_gen(utils.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') - -- end, }, { cmd = 'pio run -t compiledb', diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index d6fdfc2c..d4ef9158 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -70,7 +70,7 @@ function M.fix_pio_compile_commands() if out_file then out_file:write(json_str) out_file:close() - -- vim.cmd('LspRestart') + vim.notify('compiledb: fixed', vim.log.levels.INFO) M.lsp_restart('clangd') end end diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 916dcdf6..ccfc1709 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -52,11 +52,9 @@ end -- Handle after 'pio run -t compiledb' execution function M.handleDb() vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) - piolsp.fix_pio_compile_commands() - vim.notify('compiledb: fixed', vim.log.levels.INFO) piolsp.gitignore_lsp_configs('compile_commands.json') + piolsp.fix_pio_compile_commands() piolsp.lsp_restart('clangd') - vim.notify('compiledb: Success', vim.log.levels.INFO) end -- Handle after poioinit execution function M.handlePioinit() diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 7e10208e..748d8f72 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -88,6 +88,7 @@ local keymap = function(mode, lhs, rhs, opts) vim.keymap.set(mode, lhs, rhs, options) end +keymap('n', 'gll', vim.cmd.edit(vim.lsp.log.get_filename()), 'open LSP [l]og') -- Keybinds to make split navigation easier. -- Use CTRL+ to switch between windows -- See `:help wincmd` for a list of all window commands From 80769043dbac6e28d2f2901fdd15cfe5d430d26f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 13:49:16 +0300 Subject: [PATCH 0411/1406] update --- mini_nvimPlatformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 748d8f72..f7351de3 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -88,7 +88,7 @@ local keymap = function(mode, lhs, rhs, opts) vim.keymap.set(mode, lhs, rhs, options) end -keymap('n', 'gll', vim.cmd.edit(vim.lsp.log.get_filename()), 'open LSP [l]og') +keymap('n', 'gll', vim.cmd.edit(vim.lsp.log.get_filename()), { desc = 'open LSP [l]og' }) -- Keybinds to make split navigation easier. -- Use CTRL+ to switch between windows -- See `:help wincmd` for a list of all window commands From 918a9bd1af8bff636b9cbb4a0b5cdb1372533437 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 13:52:28 +0300 Subject: [PATCH 0412/1406] update --- mini_nvimPlatformio.lua | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index f7351de3..2a9fbacf 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -88,7 +88,9 @@ local keymap = function(mode, lhs, rhs, opts) vim.keymap.set(mode, lhs, rhs, options) end -keymap('n', 'gll', vim.cmd.edit(vim.lsp.log.get_filename()), { desc = 'open LSP [l]og' }) +keymap('n', 'gll', function() + vim.cmd.edit(vim.lsp.log.get_filename()) +end, { desc = 'open LSP [l]og' }) -- Keybinds to make split navigation easier. -- Use CTRL+ to switch between windows -- See `:help wincmd` for a list of all window commands From 41f9e6fd122b975e8a12ea158ef7ed8e00273f64 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 14:04:28 +0300 Subject: [PATCH 0413/1406] update --- lua/platformio/piolsp.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index d4ef9158..2c7e3985 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -33,7 +33,7 @@ function M.fix_pio_compile_commands() -- Extract filename (e.g., riscv32-esp-elf-gcc) local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = full_path - -- print('PioFix: driver_path=' .. full_path .. ' name=' .. name) + print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) end end @@ -50,10 +50,11 @@ function M.fix_pio_compile_commands() if not is_abs then local short_name = first_token:gsub('%.exe$', '') - -- print('PioFix: short_name=' .. short_name) + print('PioFix2: short_name=' .. short_name) -- Direct Query: Does this name exist in our discovered list? if path_map[short_name] then cmd_parts[1] = path_map[short_name] + print('PioFix3: short_name=' .. cmd_parts[1]) entry.command = table.concat(cmd_parts, ' ') modified = modified + 1 end From 703510e735457e379329c994eb86a4a44a13e921 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 14:20:48 +0300 Subject: [PATCH 0414/1406] update --- lua/platformio/piolsp.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 2c7e3985..4c27ba48 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -23,10 +23,11 @@ function M.fix_pio_compile_commands() -- print('PioFix0') -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path local path_map = {} - local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') + -- local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') + local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') if pio_home then -- Recursively find all binaries in PIO packages - local pio_packages = pio_home .. '/.platformio/*/packages/*/bin/*' + local pio_packages = pio_home .. '/.platformio/packages/*/bin/*' local found_binaries = vim.fn.glob(pio_packages, false, true) for _, full_path in ipairs(found_binaries) do From 8101895bad7ea7c2d34069b55a89b8cfeada5480 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 14:27:23 +0300 Subject: [PATCH 0415/1406] update --- lua/platformio/piolsp.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 4c27ba48..7b3662ae 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -25,6 +25,7 @@ function M.fix_pio_compile_commands() local path_map = {} -- local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') + print('PIO Home ' .. pio_home) if pio_home then -- Recursively find all binaries in PIO packages local pio_packages = pio_home .. '/.platformio/packages/*/bin/*' From 1163df90a33201079e80ee4f0c427486c2d76f15 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 14:58:34 +0300 Subject: [PATCH 0416/1406] update --- lua/platformio/piolsp.lua | 105 +++++++++++++++++++++++++++++++------- 1 file changed, 87 insertions(+), 18 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 7b3662ae..6905bbf1 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -1,7 +1,8 @@ local M = {} function M.fix_pio_compile_commands() - local filename = 'compile_commands.json' + local cwd = vim.fn.getcwd() + local filename = cwd .. '/compile_commands.json' local file = io.open(filename, 'r') if not file then return @@ -9,23 +10,16 @@ function M.fix_pio_compile_commands() local content = file:read('*a') file:close() - if not content or content == '' then - return - end - -- Safe JSON decoding local ok, data = pcall(vim.json.decode, content) if not ok or type(data) ~= 'table' then - vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) return end - -- print('PioFix0') + print('PioFix0') -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path local path_map = {} - -- local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') - local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') - print('PIO Home ' .. pio_home) + local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') if pio_home then -- Recursively find all binaries in PIO packages local pio_packages = pio_home .. '/.platformio/packages/*/bin/*' @@ -35,7 +29,7 @@ function M.fix_pio_compile_commands() -- Extract filename (e.g., riscv32-esp-elf-gcc) local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = full_path - print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) + print('PioFix: driver_path=' .. full_path .. ' name=' .. name) end end @@ -52,11 +46,10 @@ function M.fix_pio_compile_commands() if not is_abs then local short_name = first_token:gsub('%.exe$', '') - print('PioFix2: short_name=' .. short_name) + print('PioFix: short_name=' .. short_name) -- Direct Query: Does this name exist in our discovered list? if path_map[short_name] then cmd_parts[1] = path_map[short_name] - print('PioFix3: short_name=' .. cmd_parts[1]) entry.command = table.concat(cmd_parts, ' ') modified = modified + 1 end @@ -66,18 +59,94 @@ function M.fix_pio_compile_commands() end -- PHASE 3: Save and Refresh - -- Safe JSON encoding - local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) - if encode_ok and json_str then + if modified > 0 then local out_file = io.open(filename, 'w') if out_file then - out_file:write(json_str) + out_file:write(vim.json.encode(data, { indent = ' ' })) out_file:close() - vim.notify('compiledb: fixed', vim.log.levels.INFO) + vim.notify('PIO: Auto-resolved ' .. modified .. ' driver paths', vim.log.levels.INFO) M.lsp_restart('clangd') end end end +-- function M.fix_pio_compile_commands() +-- local filename = 'compile_commands.json' +-- local file = io.open(filename, 'r') +-- if not file then +-- return +-- end +-- +-- local content = file:read('*a') +-- file:close() +-- if not content or content == '' then +-- return +-- end +-- +-- -- Safe JSON decoding +-- local ok, data = pcall(vim.json.decode, content) +-- if not ok or type(data) ~= 'table' then +-- vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) +-- return +-- end +-- +-- -- print('PioFix0') +-- -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path +-- local path_map = {} +-- -- local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') +-- local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') +-- print('PIO Home ' .. pio_home) +-- if pio_home then +-- -- Recursively find all binaries in PIO packages +-- local pio_packages = pio_home .. '/.platformio/packages/*/bin/*' +-- local found_binaries = vim.fn.glob(pio_packages, false, true) +-- +-- for _, full_path in ipairs(found_binaries) do +-- -- Extract filename (e.g., riscv32-esp-elf-gcc) +-- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') +-- path_map[name] = full_path +-- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) +-- end +-- end +-- +-- -- PHASE 2: Update JSON using the Map +-- local modified = 0 +-- for _, entry in ipairs(data) do +-- if type(entry.command) == 'string' then +-- local cmd_parts = vim.split(entry.command, ' ') +-- local first_token = cmd_parts[1] +-- +-- if first_token then +-- -- Check if it's already a short name (not an absolute path) +-- local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') +-- +-- if not is_abs then +-- local short_name = first_token:gsub('%.exe$', '') +-- print('PioFix2: short_name=' .. short_name) +-- -- Direct Query: Does this name exist in our discovered list? +-- if path_map[short_name] then +-- cmd_parts[1] = path_map[short_name] +-- print('PioFix3: short_name=' .. cmd_parts[1]) +-- entry.command = table.concat(cmd_parts, ' ') +-- modified = modified + 1 +-- end +-- end +-- end +-- end +-- end +-- +-- -- PHASE 3: Save and Refresh +-- -- Safe JSON encoding +-- local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) +-- if encode_ok and json_str then +-- local out_file = io.open(filename, 'w') +-- if out_file then +-- out_file:write(json_str) +-- out_file:close() +-- vim.notify('compiledb: fixed', vim.log.levels.INFO) +-- M.lsp_restart('clangd') +-- end +-- end +-- end function M.gitignore_lsp_configs(config_file) local gitignore_path = vim.fs.joinpath(vim.g.platformioRootDir, '.gitignore') From 2db48701062e25906b6f591b3e6591b48bf2121b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 15:20:51 +0300 Subject: [PATCH 0417/1406] update --- lua/platformio/piolsp.lua | 39 +++++++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 6905bbf1..0a79ba46 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -10,26 +10,33 @@ function M.fix_pio_compile_commands() local content = file:read('*a') file:close() + if not content or content == '' then + return + end + -- Safe JSON decoding local ok, data = pcall(vim.json.decode, content) if not ok or type(data) ~= 'table' then + vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) return end print('PioFix0') -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path local path_map = {} - local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') + -- local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') + local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') if pio_home then -- Recursively find all binaries in PIO packages - local pio_packages = pio_home .. '/.platformio/packages/*/bin/*' + -- local pio_packages = pio_home .. '/.platformio/packages/*/bin/*' + local pio_packages = pio_home .. '/.platformio/packages/toolchain-*/bin/*' local found_binaries = vim.fn.glob(pio_packages, false, true) for _, full_path in ipairs(found_binaries) do -- Extract filename (e.g., riscv32-esp-elf-gcc) local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = full_path - print('PioFix: driver_path=' .. full_path .. ' name=' .. name) + print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) end end @@ -46,10 +53,11 @@ function M.fix_pio_compile_commands() if not is_abs then local short_name = first_token:gsub('%.exe$', '') - print('PioFix: short_name=' .. short_name) + print('PioFix2: short_name=' .. short_name) -- Direct Query: Does this name exist in our discovered list? if path_map[short_name] then cmd_parts[1] = path_map[short_name] + print('PioFix3: short_name=' .. cmd_parts[1]) entry.command = table.concat(cmd_parts, ' ') modified = modified + 1 end @@ -60,13 +68,24 @@ function M.fix_pio_compile_commands() -- PHASE 3: Save and Refresh if modified > 0 then - local out_file = io.open(filename, 'w') - if out_file then - out_file:write(vim.json.encode(data, { indent = ' ' })) - out_file:close() - vim.notify('PIO: Auto-resolved ' .. modified .. ' driver paths', vim.log.levels.INFO) - M.lsp_restart('clangd') + -- Safe JSON encoding + local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) + if encode_ok and json_str then + local out_file = io.open(filename, 'w') + if out_file then + out_file:write(json_str) + out_file:close() + vim.notify('compiledb: fixed', vim.log.levels.INFO) + M.lsp_restart('clangd') + end end + -- local out_file = io.open(filename, 'w') + -- if out_file then + -- out_file:write(vim.json.encode(data, { indent = ' ' })) + -- out_file:close() + -- vim.notify('PIO: Auto-resolved ' .. modified .. ' driver paths', vim.log.levels.INFO) + -- M.lsp_restart('clangd') + -- end end end -- function M.fix_pio_compile_commands() From 21e77f1e108dba3e292a693c4a65032055cac07e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 15:24:42 +0300 Subject: [PATCH 0418/1406] update --- lua/platformio/piolsp.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 0a79ba46..1ee05141 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -28,8 +28,8 @@ function M.fix_pio_compile_commands() local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') if pio_home then -- Recursively find all binaries in PIO packages - -- local pio_packages = pio_home .. '/.platformio/packages/*/bin/*' - local pio_packages = pio_home .. '/.platformio/packages/toolchain-*/bin/*' + local pio_packages = pio_home .. '/.platformio/packages/*/bin/*' + -- local pio_packages = pio_home .. '/.platformio/packages/toolchain-*/bin/*' local found_binaries = vim.fn.glob(pio_packages, false, true) for _, full_path in ipairs(found_binaries) do From d5a4036516831f61828ba71242846d135b131043 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 15:28:04 +0300 Subject: [PATCH 0419/1406] update --- lua/platformio/piolsp.lua | 34 +++++++++------------------------- 1 file changed, 9 insertions(+), 25 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 1ee05141..922de052 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -14,29 +14,25 @@ function M.fix_pio_compile_commands() return end - -- Safe JSON decoding local ok, data = pcall(vim.json.decode, content) if not ok or type(data) ~= 'table' then - vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) return end print('PioFix0') -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path local path_map = {} - -- local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') - local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') + local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') if pio_home then -- Recursively find all binaries in PIO packages local pio_packages = pio_home .. '/.platformio/packages/*/bin/*' - -- local pio_packages = pio_home .. '/.platformio/packages/toolchain-*/bin/*' local found_binaries = vim.fn.glob(pio_packages, false, true) for _, full_path in ipairs(found_binaries) do -- Extract filename (e.g., riscv32-esp-elf-gcc) local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = full_path - print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) + print('PioFix: driver_path=' .. full_path .. ' name=' .. name) end end @@ -53,11 +49,10 @@ function M.fix_pio_compile_commands() if not is_abs then local short_name = first_token:gsub('%.exe$', '') - print('PioFix2: short_name=' .. short_name) + print('PioFix: short_name=' .. short_name) -- Direct Query: Does this name exist in our discovered list? if path_map[short_name] then cmd_parts[1] = path_map[short_name] - print('PioFix3: short_name=' .. cmd_parts[1]) entry.command = table.concat(cmd_parts, ' ') modified = modified + 1 end @@ -68,24 +63,13 @@ function M.fix_pio_compile_commands() -- PHASE 3: Save and Refresh if modified > 0 then - -- Safe JSON encoding - local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) - if encode_ok and json_str then - local out_file = io.open(filename, 'w') - if out_file then - out_file:write(json_str) - out_file:close() - vim.notify('compiledb: fixed', vim.log.levels.INFO) - M.lsp_restart('clangd') - end + local out_file = io.open(filename, 'w') + if out_file then + out_file:write(vim.json.encode(data, { indent = ' ' })) + out_file:close() + vim.notify('PIO: Auto-resolved ' .. modified .. ' driver paths', vim.log.levels.INFO) + M.lsp_restart('clangd') end - -- local out_file = io.open(filename, 'w') - -- if out_file then - -- out_file:write(vim.json.encode(data, { indent = ' ' })) - -- out_file:close() - -- vim.notify('PIO: Auto-resolved ' .. modified .. ' driver paths', vim.log.levels.INFO) - -- M.lsp_restart('clangd') - -- end end end -- function M.fix_pio_compile_commands() From 294fb4d7b64dca8867004fe3bac5f40639dc5399 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 15:54:56 +0300 Subject: [PATCH 0420/1406] update --- lua/platformio/piolsp.lua | 36 ++++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 922de052..672490ab 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -14,25 +14,29 @@ function M.fix_pio_compile_commands() return end + -- Safe JSON decoding local ok, data = pcall(vim.json.decode, content) if not ok or type(data) ~= 'table' then + vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) return end print('PioFix0') -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path local path_map = {} - local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') + -- local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') + local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') if pio_home then -- Recursively find all binaries in PIO packages - local pio_packages = pio_home .. '/.platformio/packages/*/bin/*' + local pio_packages = pio_home .. '/packages/*/bin/*' + -- local pio_packages = pio_home .. '/.platformio/packages/toolchain-*/bin/*' local found_binaries = vim.fn.glob(pio_packages, false, true) for _, full_path in ipairs(found_binaries) do -- Extract filename (e.g., riscv32-esp-elf-gcc) local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = full_path - print('PioFix: driver_path=' .. full_path .. ' name=' .. name) + print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) end end @@ -49,10 +53,11 @@ function M.fix_pio_compile_commands() if not is_abs then local short_name = first_token:gsub('%.exe$', '') - print('PioFix: short_name=' .. short_name) + print('PioFix2: short_name=' .. short_name) -- Direct Query: Does this name exist in our discovered list? if path_map[short_name] then cmd_parts[1] = path_map[short_name] + print('PioFix3: short_name=' .. cmd_parts[1]) entry.command = table.concat(cmd_parts, ' ') modified = modified + 1 end @@ -63,13 +68,24 @@ function M.fix_pio_compile_commands() -- PHASE 3: Save and Refresh if modified > 0 then - local out_file = io.open(filename, 'w') - if out_file then - out_file:write(vim.json.encode(data, { indent = ' ' })) - out_file:close() - vim.notify('PIO: Auto-resolved ' .. modified .. ' driver paths', vim.log.levels.INFO) - M.lsp_restart('clangd') + -- Safe JSON encoding + local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) + if encode_ok and json_str then + local out_file = io.open(filename, 'w') + if out_file then + out_file:write(json_str) + out_file:close() + vim.notify('compiledb: fixed', vim.log.levels.INFO) + M.lsp_restart('clangd') + end end + -- local out_file = io.open(filename, 'w') + -- if out_file then + -- out_file:write(vim.json.encode(data, { indent = ' ' })) + -- out_file:close() + -- vim.notify('PIO: Auto-resolved ' .. modified .. ' driver paths', vim.log.levels.INFO) + -- M.lsp_restart('clangd') + -- end end end -- function M.fix_pio_compile_commands() From 14c8821f0d7c37abeee39f5609b116976cee520d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 15:59:27 +0300 Subject: [PATCH 0421/1406] update --- lua/platformio/piolsp.lua | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 672490ab..e979c2b0 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -21,22 +21,22 @@ function M.fix_pio_compile_commands() return end - print('PioFix0') + -- print('PioFix0') -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path local path_map = {} -- local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') if pio_home then -- Recursively find all binaries in PIO packages - local pio_packages = pio_home .. '/packages/*/bin/*' - -- local pio_packages = pio_home .. '/.platformio/packages/toolchain-*/bin/*' + -- local pio_packages = pio_home .. '/packages/*/bin/*' + local pio_packages = pio_home .. '/packages/toolchain-*/*/bin/*' local found_binaries = vim.fn.glob(pio_packages, false, true) for _, full_path in ipairs(found_binaries) do -- Extract filename (e.g., riscv32-esp-elf-gcc) local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = full_path - print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) + -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) end end @@ -53,11 +53,11 @@ function M.fix_pio_compile_commands() if not is_abs then local short_name = first_token:gsub('%.exe$', '') - print('PioFix2: short_name=' .. short_name) + -- print('PioFix2: short_name=' .. short_name) -- Direct Query: Does this name exist in our discovered list? if path_map[short_name] then cmd_parts[1] = path_map[short_name] - print('PioFix3: short_name=' .. cmd_parts[1]) + -- print('PioFix3: full_name=' .. cmd_parts[1]) entry.command = table.concat(cmd_parts, ' ') modified = modified + 1 end From 7c02bc4763622773e322c763177b5691014894bf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 16:00:56 +0300 Subject: [PATCH 0422/1406] update --- lua/platformio/piolsp.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index e979c2b0..a2d473a0 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -36,7 +36,7 @@ function M.fix_pio_compile_commands() -- Extract filename (e.g., riscv32-esp-elf-gcc) local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = full_path - -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) + print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) end end From 39d581b9dd1540f58a15a9d57183cd5e70ac3a41 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 16:17:13 +0300 Subject: [PATCH 0423/1406] update --- lua/platformio/piolsp.lua | 195 +++++++++++++++++++------------------- 1 file changed, 95 insertions(+), 100 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index a2d473a0..b2b09170 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -1,5 +1,87 @@ local M = {} +-- function M.fix_pio_compile_commands() +-- local cwd = vim.fn.getcwd() +-- local filename = cwd .. '/compile_commands.json' +-- local file = io.open(filename, 'r') +-- if not file then +-- return +-- end +-- +-- local content = file:read('*a') +-- file:close() +-- if not content or content == '' then +-- return +-- end +-- +-- -- Safe JSON decoding +-- local ok, data = pcall(vim.json.decode, content) +-- if not ok or type(data) ~= 'table' then +-- vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) +-- return +-- end +-- +-- -- print('PioFix0') +-- -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path +-- local path_map = {} +-- -- local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') +-- local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') +-- if pio_home then +-- -- Recursively find all binaries in PIO packages +-- -- local pio_packages = pio_home .. '/packages/*/bin/*' +-- local pio_packages = pio_home .. '/packages/toolchain-*/*/bin/*' +-- local found_binaries = vim.fn.glob(pio_packages, false, true) +-- +-- for _, full_path in ipairs(found_binaries) do +-- -- Extract filename (e.g., riscv32-esp-elf-gcc) +-- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') +-- path_map[name] = full_path +-- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) +-- end +-- end +-- +-- -- PHASE 2: Update JSON using the Map +-- local modified = 0 +-- for _, entry in ipairs(data) do +-- if type(entry.command) == 'string' then +-- local cmd_parts = vim.split(entry.command, ' ') +-- local first_token = cmd_parts[1] +-- +-- if first_token then +-- -- Check if it's already a short name (not an absolute path) +-- local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') +-- +-- if not is_abs then +-- local short_name = first_token:gsub('%.exe$', '') +-- -- print('PioFix2: short_name=' .. short_name) +-- -- Direct Query: Does this name exist in our discovered list? +-- if path_map[short_name] then +-- cmd_parts[1] = path_map[short_name] +-- -- print('PioFix3: full_name=' .. cmd_parts[1]) +-- entry.command = table.concat(cmd_parts, ' ') +-- modified = modified + 1 +-- end +-- end +-- end +-- end +-- end +-- +-- -- PHASE 3: Save and Refresh +-- if modified > 0 then +-- -- Safe JSON encoding +-- local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) +-- if encode_ok and json_str then +-- local out_file = io.open(filename, 'w') +-- if out_file then +-- out_file:write(json_str) +-- out_file:close() +-- vim.notify('compiledb: fixed', vim.log.levels.INFO) +-- M.lsp_restart('clangd') +-- end +-- end +-- end +-- end + function M.fix_pio_compile_commands() local cwd = vim.fn.getcwd() local filename = cwd .. '/compile_commands.json' @@ -26,10 +108,10 @@ function M.fix_pio_compile_commands() local path_map = {} -- local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') + print('PIO Home ' .. pio_home) if pio_home then -- Recursively find all binaries in PIO packages - -- local pio_packages = pio_home .. '/packages/*/bin/*' - local pio_packages = pio_home .. '/packages/toolchain-*/*/bin/*' + local pio_packages = pio_home .. '/packages/*/bin/*' local found_binaries = vim.fn.glob(pio_packages, false, true) for _, full_path in ipairs(found_binaries) do @@ -53,11 +135,11 @@ function M.fix_pio_compile_commands() if not is_abs then local short_name = first_token:gsub('%.exe$', '') - -- print('PioFix2: short_name=' .. short_name) + print('PioFix2: short_name=' .. short_name) -- Direct Query: Does this name exist in our discovered list? if path_map[short_name] then cmd_parts[1] = path_map[short_name] - -- print('PioFix3: full_name=' .. cmd_parts[1]) + print('PioFix3: short_name=' .. cmd_parts[1]) entry.command = table.concat(cmd_parts, ' ') modified = modified + 1 end @@ -67,105 +149,18 @@ function M.fix_pio_compile_commands() end -- PHASE 3: Save and Refresh - if modified > 0 then - -- Safe JSON encoding - local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) - if encode_ok and json_str then - local out_file = io.open(filename, 'w') - if out_file then - out_file:write(json_str) - out_file:close() - vim.notify('compiledb: fixed', vim.log.levels.INFO) - M.lsp_restart('clangd') - end + -- Safe JSON encoding + local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) + if encode_ok and json_str then + local out_file = io.open(filename, 'w') + if out_file then + out_file:write(json_str) + out_file:close() + vim.notify('compiledb: fixed', vim.log.levels.INFO) + M.lsp_restart('clangd') end - -- local out_file = io.open(filename, 'w') - -- if out_file then - -- out_file:write(vim.json.encode(data, { indent = ' ' })) - -- out_file:close() - -- vim.notify('PIO: Auto-resolved ' .. modified .. ' driver paths', vim.log.levels.INFO) - -- M.lsp_restart('clangd') - -- end end end --- function M.fix_pio_compile_commands() --- local filename = 'compile_commands.json' --- local file = io.open(filename, 'r') --- if not file then --- return --- end --- --- local content = file:read('*a') --- file:close() --- if not content or content == '' then --- return --- end --- --- -- Safe JSON decoding --- local ok, data = pcall(vim.json.decode, content) --- if not ok or type(data) ~= 'table' then --- vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) --- return --- end --- --- -- print('PioFix0') --- -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path --- local path_map = {} --- -- local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') --- local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') --- print('PIO Home ' .. pio_home) --- if pio_home then --- -- Recursively find all binaries in PIO packages --- local pio_packages = pio_home .. '/.platformio/packages/*/bin/*' --- local found_binaries = vim.fn.glob(pio_packages, false, true) --- --- for _, full_path in ipairs(found_binaries) do --- -- Extract filename (e.g., riscv32-esp-elf-gcc) --- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') --- path_map[name] = full_path --- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) --- end --- end --- --- -- PHASE 2: Update JSON using the Map --- local modified = 0 --- for _, entry in ipairs(data) do --- if type(entry.command) == 'string' then --- local cmd_parts = vim.split(entry.command, ' ') --- local first_token = cmd_parts[1] --- --- if first_token then --- -- Check if it's already a short name (not an absolute path) --- local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') --- --- if not is_abs then --- local short_name = first_token:gsub('%.exe$', '') --- print('PioFix2: short_name=' .. short_name) --- -- Direct Query: Does this name exist in our discovered list? --- if path_map[short_name] then --- cmd_parts[1] = path_map[short_name] --- print('PioFix3: short_name=' .. cmd_parts[1]) --- entry.command = table.concat(cmd_parts, ' ') --- modified = modified + 1 --- end --- end --- end --- end --- end --- --- -- PHASE 3: Save and Refresh --- -- Safe JSON encoding --- local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) --- if encode_ok and json_str then --- local out_file = io.open(filename, 'w') --- if out_file then --- out_file:write(json_str) --- out_file:close() --- vim.notify('compiledb: fixed', vim.log.levels.INFO) --- M.lsp_restart('clangd') --- end --- end --- end function M.gitignore_lsp_configs(config_file) local gitignore_path = vim.fs.joinpath(vim.g.platformioRootDir, '.gitignore') From 0651b90bc5890aed46e0ceb68caa7856ddf5d6b6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 16:57:26 +0300 Subject: [PATCH 0424/1406] update --- lua/platformio/piolsp.lua | 84 +-------------------------------------- lua/platformio/utils.lua | 41 ++++++++++--------- 2 files changed, 24 insertions(+), 101 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index b2b09170..ab89ab6d 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -1,87 +1,5 @@ local M = {} --- function M.fix_pio_compile_commands() --- local cwd = vim.fn.getcwd() --- local filename = cwd .. '/compile_commands.json' --- local file = io.open(filename, 'r') --- if not file then --- return --- end --- --- local content = file:read('*a') --- file:close() --- if not content or content == '' then --- return --- end --- --- -- Safe JSON decoding --- local ok, data = pcall(vim.json.decode, content) --- if not ok or type(data) ~= 'table' then --- vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) --- return --- end --- --- -- print('PioFix0') --- -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path --- local path_map = {} --- -- local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') --- local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') --- if pio_home then --- -- Recursively find all binaries in PIO packages --- -- local pio_packages = pio_home .. '/packages/*/bin/*' --- local pio_packages = pio_home .. '/packages/toolchain-*/*/bin/*' --- local found_binaries = vim.fn.glob(pio_packages, false, true) --- --- for _, full_path in ipairs(found_binaries) do --- -- Extract filename (e.g., riscv32-esp-elf-gcc) --- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') --- path_map[name] = full_path --- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) --- end --- end --- --- -- PHASE 2: Update JSON using the Map --- local modified = 0 --- for _, entry in ipairs(data) do --- if type(entry.command) == 'string' then --- local cmd_parts = vim.split(entry.command, ' ') --- local first_token = cmd_parts[1] --- --- if first_token then --- -- Check if it's already a short name (not an absolute path) --- local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') --- --- if not is_abs then --- local short_name = first_token:gsub('%.exe$', '') --- -- print('PioFix2: short_name=' .. short_name) --- -- Direct Query: Does this name exist in our discovered list? --- if path_map[short_name] then --- cmd_parts[1] = path_map[short_name] --- -- print('PioFix3: full_name=' .. cmd_parts[1]) --- entry.command = table.concat(cmd_parts, ' ') --- modified = modified + 1 --- end --- end --- end --- end --- end --- --- -- PHASE 3: Save and Refresh --- if modified > 0 then --- -- Safe JSON encoding --- local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) --- if encode_ok and json_str then --- local out_file = io.open(filename, 'w') --- if out_file then --- out_file:write(json_str) --- out_file:close() --- vim.notify('compiledb: fixed', vim.log.levels.INFO) --- M.lsp_restart('clangd') --- end --- end --- end --- end - function M.fix_pio_compile_commands() local cwd = vim.fn.getcwd() local filename = cwd .. '/compile_commands.json' @@ -139,7 +57,7 @@ function M.fix_pio_compile_commands() -- Direct Query: Does this name exist in our discovered list? if path_map[short_name] then cmd_parts[1] = path_map[short_name] - print('PioFix3: short_name=' .. cmd_parts[1]) + print('PioFix3: full_name=' .. cmd_parts[1]) entry.command = table.concat(cmd_parts, ' ') modified = modified + 1 end diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index ccfc1709..b5095d64 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -1,10 +1,13 @@ +local config = require('platformio').config local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local piolsp = require('platformio.piolsp') --.piolsp +local is_windows = jit.os == 'Windows' -- local pioinit = require('platformio.pioinit') + local M = {} -M.selected_framework = '' -local config = require('platformio').config +M.selected_framework = '' +M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' @@ -13,38 +16,43 @@ local config = require('platformio').config -- INFO: Dispatcher M.queue = {} -- Unified Dispatcher +-- stylua: ignore function M.dispatcher(_, _, data) - if #M.queue == 0 then - return - end + if #M.queue == 0 then return end for _, line in ipairs(data) do - -- Match format ___DONE___:SUCCESS or ___DONE___:FAILED + -- Regex match: captures 'SUCCESS' or 'FAILED' local status = line:match('^___DONE___:(%a+)') if status then if status == 'SUCCESS' then local task = table.remove(M.queue, 1) - if task then - vim.schedule(task) - end + if task then vim.schedule(task) end else M.queue = {} -- Clear queue on any other status (failure) - vim.schedule(function() - vim.notify('Sequence Aborted', 4) - end) + vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) end break end end end + -- Improved Runner: Accepts a table of { cmd = "...", cb = function } +-- stylua: ignore M.run_sequence = function(tasks) local full_cmd = '' for _, task in ipairs(tasks) do table.insert(M.queue, task.cb) - -- Chain: (cmd && success_signal) || failure_signal - local part = string.format('(%s && echo "___DONE___:SUCCESS") || (echo "___DONE___:FAILED" && exit 1)', task.cmd) - full_cmd = full_cmd == '' and part or full_cmd .. ' && ' .. part + + -- Windows CMD/PowerShell specific syntax: + -- No parentheses ensures compatibility with basic 'cmd.exe' + local success = 'echo ___DONE___:SUCCESS' + local failure = 'echo ___DONE___:FAILED' + + -- Chain: command && success || failure + local part = string.format('%s && %s || %s', task.cmd, success, failure) + + if full_cmd == '' then full_cmd = part + else full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands end M.ToggleTerminal(full_cmd, 'float') end @@ -84,9 +92,6 @@ local function pathmul(n) end ------------------------------------------------------ -local is_windows = jit.os == 'Windows' - -M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' -- INFO: get current OS enter function M.enter() From bddd9a1b1f7853461a402fca99c284715404e9c9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 17:14:20 +0300 Subject: [PATCH 0425/1406] update --- lua/platformio/utils.lua | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index b5095d64..b2e807d7 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -21,8 +21,14 @@ function M.dispatcher(_, _, data) if #M.queue == 0 then return end for _, line in ipairs(data) do + + -- 1. Strip ALL whitespace and non-printable control characters (like \r) + -- %s is whitespace, %c is control characters + local clean_line = line:gsub("[%s%c]", "") + + -- 2. Look for the pattern in the fully sanitized string -- Regex match: captures 'SUCCESS' or 'FAILED' - local status = line:match('^___DONE___:(%a+)') + local status = clean_line:match('^___DONE___:(%a+)') if status then if status == 'SUCCESS' then local task = table.remove(M.queue, 1) From 22b0172a3e9ad4f332a999dd464a02448f9caf42 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 17:35:49 +0300 Subject: [PATCH 0426/1406] update --- lua/platformio/utils.lua | 81 ++++++++++++++++++++++++++++------------ 1 file changed, 58 insertions(+), 23 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index b2e807d7..c8e99f1c 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -15,32 +15,67 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' ------------------------------------------------------ -- INFO: Dispatcher M.queue = {} --- Unified Dispatcher --- stylua: ignore -function M.dispatcher(_, _, data) - if #M.queue == 0 then return end - - for _, line in ipairs(data) do - - -- 1. Strip ALL whitespace and non-printable control characters (like \r) - -- %s is whitespace, %c is control characters - local clean_line = line:gsub("[%s%c]", "") - - -- 2. Look for the pattern in the fully sanitized string - -- Regex match: captures 'SUCCESS' or 'FAILED' - local status = clean_line:match('^___DONE___:(%a+)') - if status then - if status == 'SUCCESS' then - local task = table.remove(M.queue, 1) - if task then vim.schedule(task) end - else - M.queue = {} -- Clear queue on any other status (failure) - vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) - end - break +local pio_buffer = '' + +M.dispatcher = function(_, _, data) + if #M.queue == 0 then + return + end + + -- 1. Merge the list of lines into the persistent buffer + pio_buffer = pio_buffer .. table.concat(data, '') + + -- 2. Strip ALL whitespace and control characters (like \r) + -- This ensures "___DONE___:SUCCESS\r\n" becomes "___DONE___:SUCCESS" + local clean_buffer = pio_buffer:gsub('[%s%c]', '') + + -- 3. Check if our marker is in the clean buffer + if clean_buffer:find('___DONE___:SUCCESS') then + pio_buffer = '' -- Clear buffer immediately to prevent double-firing + + local task = table.remove(M.queue, 1) + if task then + vim.schedule(task) end + elseif clean_buffer:find('___DONE___:FAILED') then + pio_buffer = '' + M.queue = {} + vim.schedule(function() + vim.notify('PIO Sequence: Aborted', 4) + end) + end + + -- 4. Safety: Cap buffer size so it doesn't grow forever + if #pio_buffer > 5000 then + pio_buffer = pio_buffer:sub(-2000) end end +-- Unified Dispatcher +-- stylua: ignore +-- function M.dispatcher(_, _, data) +-- if #M.queue == 0 then return end +-- +-- for _, line in ipairs(data) do +-- +-- -- 1. Strip ALL whitespace and non-printable control characters (like \r) +-- -- %s is whitespace, %c is control characters +-- local clean_line = line:gsub("[%s%c]", "") +-- +-- -- 2. Look for the pattern in the fully sanitized string +-- -- Regex match: captures 'SUCCESS' or 'FAILED' +-- local status = clean_line:match('^___DONE___:(%a+)') +-- if status then +-- if status == 'SUCCESS' then +-- local task = table.remove(M.queue, 1) +-- if task then vim.schedule(task) end +-- else +-- M.queue = {} -- Clear queue on any other status (failure) +-- vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) +-- end +-- break +-- end +-- end +-- end -- Improved Runner: Accepts a table of { cmd = "...", cb = function } -- stylua: ignore From 1485b0f55526857d253ab028a5b80f5bf75a7957 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 17:45:30 +0300 Subject: [PATCH 0427/1406] update --- lua/platformio/utils.lua | 111 ++++++++++++++++++++------------------- 1 file changed, 56 insertions(+), 55 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index c8e99f1c..6663bcd8 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -15,68 +15,69 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' ------------------------------------------------------ -- INFO: Dispatcher M.queue = {} -local pio_buffer = '' - -M.dispatcher = function(_, _, data) - if #M.queue == 0 then - return - end - - -- 1. Merge the list of lines into the persistent buffer - pio_buffer = pio_buffer .. table.concat(data, '') - - -- 2. Strip ALL whitespace and control characters (like \r) - -- This ensures "___DONE___:SUCCESS\r\n" becomes "___DONE___:SUCCESS" - local clean_buffer = pio_buffer:gsub('[%s%c]', '') - - -- 3. Check if our marker is in the clean buffer - if clean_buffer:find('___DONE___:SUCCESS') then - pio_buffer = '' -- Clear buffer immediately to prevent double-firing - - local task = table.remove(M.queue, 1) - if task then - vim.schedule(task) - end - elseif clean_buffer:find('___DONE___:FAILED') then - pio_buffer = '' - M.queue = {} - vim.schedule(function() - vim.notify('PIO Sequence: Aborted', 4) - end) - end - - -- 4. Safety: Cap buffer size so it doesn't grow forever - if #pio_buffer > 5000 then - pio_buffer = pio_buffer:sub(-2000) - end -end --- Unified Dispatcher --- stylua: ignore --- function M.dispatcher(_, _, data) --- if #M.queue == 0 then return end +-- local pio_buffer = '' -- --- for _, line in ipairs(data) do +-- M.dispatcher = function(_, _, data) +-- if #M.queue == 0 then +-- return +-- end +-- +-- -- 1. Merge the list of lines into the persistent buffer +-- pio_buffer = pio_buffer .. table.concat(data, '') -- --- -- 1. Strip ALL whitespace and non-printable control characters (like \r) --- -- %s is whitespace, %c is control characters --- local clean_line = line:gsub("[%s%c]", "") +-- -- 2. Strip ALL whitespace and control characters (like \r) +-- -- This ensures "___DONE___:SUCCESS\r\n" becomes "___DONE___:SUCCESS" +-- local clean_buffer = pio_buffer:gsub('[%s%c]', '') -- --- -- 2. Look for the pattern in the fully sanitized string --- -- Regex match: captures 'SUCCESS' or 'FAILED' --- local status = clean_line:match('^___DONE___:(%a+)') --- if status then --- if status == 'SUCCESS' then --- local task = table.remove(M.queue, 1) --- if task then vim.schedule(task) end --- else --- M.queue = {} -- Clear queue on any other status (failure) --- vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) --- end --- break +-- -- 3. Check if our marker is in the clean buffer +-- if clean_buffer:find('___DONE___:SUCCESS') then +-- pio_buffer = '' -- Clear buffer immediately to prevent double-firing +-- +-- local task = table.remove(M.queue, 1) +-- if task then +-- vim.schedule(task) -- end +-- elseif clean_buffer:find('___DONE___:FAILED') then +-- pio_buffer = '' +-- M.queue = {} +-- vim.schedule(function() +-- vim.notify('PIO Sequence: Aborted', 4) +-- end) +-- end +-- +-- -- 4. Safety: Cap buffer size so it doesn't grow forever +-- if #pio_buffer > 5000 then +-- pio_buffer = pio_buffer:sub(-2000) -- end -- end +-- Unified Dispatcher +-- stylua: ignore +function M.dispatcher(_, _, data) + if #M.queue == 0 then return end + + for _, line in ipairs(data) do + + -- 1. Strip ALL whitespace and non-printable control characters (like \r) + -- %s is whitespace, %c is control characters + local clean_line = line:gsub("[%s%c]", "") + + -- 2. Look for the pattern in the fully sanitized string + -- Regex match: captures 'SUCCESS' or 'FAILED' + local status = clean_line:match('^___DONE___:(%a+)') + if status then + if status == 'SUCCESS' then + local task = table.remove(M.queue, 1) + if task then vim.schedule(task) end + else + M.queue = {} -- Clear queue on any other status (failure) + vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) + end + break + end + end +end + -- Improved Runner: Accepts a table of { cmd = "...", cb = function } -- stylua: ignore M.run_sequence = function(tasks) From d6e22c180571a42d84ef4c9eddea2c1aa8dcade5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 17:50:09 +0300 Subject: [PATCH 0428/1406] update --- lua/platformio/utils.lua | 112 +++++++++++++++++++-------------------- 1 file changed, 56 insertions(+), 56 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 6663bcd8..b20a16d5 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -15,69 +15,69 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' ------------------------------------------------------ -- INFO: Dispatcher M.queue = {} --- local pio_buffer = '' --- --- M.dispatcher = function(_, _, data) --- if #M.queue == 0 then --- return --- end --- --- -- 1. Merge the list of lines into the persistent buffer --- pio_buffer = pio_buffer .. table.concat(data, '') +-- Outside the function to persist across multiple stdout calls +local pio_buffer = '' + +function M.dispatcher(_, _, data, _) + if #M.queue == 0 then + return + end + + -- 1. Join the list of strings into one string and append to buffer + -- On some OSs, 'data' is a list of partial lines + pio_buffer = pio_buffer .. table.concat(data, '') + + -- 2. Clean the buffer of all whitespace and control characters (\r, \n, etc.) + local clean_output = pio_buffer:gsub('[%s%c]', '') + + -- 3. Search for the success signal + if clean_output:find('___DONE___:SUCCESS') then + pio_buffer = '' -- Clear buffer immediately + local task = table.remove(M.queue, 1) + if task then + vim.schedule(task) + end + elseif clean_output:find('___DONE___:FAILED') then + pio_buffer = '' + M.queue = {} -- Clear queue on failure + vim.schedule(function() + vim.notify('PIO Sequence: Aborted', 4) + end) + end + + -- 4. Safety: Prevent buffer overflow in very long logs + if #pio_buffer > 10000 then + pio_buffer = pio_buffer:sub(-5000) + end +end + +-- Unified Dispatcher +-- stylua: ignore +-- function M.dispatcher(_, _, data) +-- if #M.queue == 0 then return end -- --- -- 2. Strip ALL whitespace and control characters (like \r) --- -- This ensures "___DONE___:SUCCESS\r\n" becomes "___DONE___:SUCCESS" --- local clean_buffer = pio_buffer:gsub('[%s%c]', '') +-- for _, line in ipairs(data) do -- --- -- 3. Check if our marker is in the clean buffer --- if clean_buffer:find('___DONE___:SUCCESS') then --- pio_buffer = '' -- Clear buffer immediately to prevent double-firing +-- -- 1. Strip ALL whitespace and non-printable control characters (like \r) +-- -- %s is whitespace, %c is control characters +-- local clean_line = line:gsub("[%s%c]", "") -- --- local task = table.remove(M.queue, 1) --- if task then --- vim.schedule(task) +-- -- 2. Look for the pattern in the fully sanitized string +-- -- Regex match: captures 'SUCCESS' or 'FAILED' +-- local status = clean_line:match('^___DONE___:(%a+)') +-- if status then +-- if status == 'SUCCESS' then +-- local task = table.remove(M.queue, 1) +-- if task then vim.schedule(task) end +-- else +-- M.queue = {} -- Clear queue on any other status (failure) +-- vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) +-- end +-- break -- end --- elseif clean_buffer:find('___DONE___:FAILED') then --- pio_buffer = '' --- M.queue = {} --- vim.schedule(function() --- vim.notify('PIO Sequence: Aborted', 4) --- end) --- end --- --- -- 4. Safety: Cap buffer size so it doesn't grow forever --- if #pio_buffer > 5000 then --- pio_buffer = pio_buffer:sub(-2000) -- end -- end --- Unified Dispatcher --- stylua: ignore -function M.dispatcher(_, _, data) - if #M.queue == 0 then return end - - for _, line in ipairs(data) do - - -- 1. Strip ALL whitespace and non-printable control characters (like \r) - -- %s is whitespace, %c is control characters - local clean_line = line:gsub("[%s%c]", "") - - -- 2. Look for the pattern in the fully sanitized string - -- Regex match: captures 'SUCCESS' or 'FAILED' - local status = clean_line:match('^___DONE___:(%a+)') - if status then - if status == 'SUCCESS' then - local task = table.remove(M.queue, 1) - if task then vim.schedule(task) end - else - M.queue = {} -- Clear queue on any other status (failure) - vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) - end - break - end - end -end - -- Improved Runner: Accepts a table of { cmd = "...", cb = function } -- stylua: ignore M.run_sequence = function(tasks) From a5b700b5b1077c62bc52088002c67cb9c0157c10 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 19:07:15 +0300 Subject: [PATCH 0429/1406] update --- lua/platformio/piolsp.lua | 13 ++++++- lua/platformio/utils.lua | 80 +++++++++++---------------------------- 2 files changed, 35 insertions(+), 58 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index ab89ab6d..22c2b301 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -140,7 +140,18 @@ function M.lsp_restart(name) end end else - vim.cmd('LspRestart') + local client_name = 'clangd' + local clients = vim.lsp.get_clients({ name = client_name }) + + for _, client in ipairs(clients) do + -- 1. Stop the specific client + client:stop() + end + + -- 2. Reload all loaded buffers to trigger re-attachment for that client + -- (Note: 'checktime' is safer than 'bufdo edit' as it respects unsaved changes) + vim.cmd('checktime') + -- vim.cmd('LspRestart') end end diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index b20a16d5..9e8c41ce 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -16,68 +16,34 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' -- INFO: Dispatcher M.queue = {} -- Outside the function to persist across multiple stdout calls -local pio_buffer = '' -function M.dispatcher(_, _, data, _) - if #M.queue == 0 then - return - end - - -- 1. Join the list of strings into one string and append to buffer - -- On some OSs, 'data' is a list of partial lines - pio_buffer = pio_buffer .. table.concat(data, '') - - -- 2. Clean the buffer of all whitespace and control characters (\r, \n, etc.) - local clean_output = pio_buffer:gsub('[%s%c]', '') - - -- 3. Search for the success signal - if clean_output:find('___DONE___:SUCCESS') then - pio_buffer = '' -- Clear buffer immediately - local task = table.remove(M.queue, 1) - if task then - vim.schedule(task) +-- Unified Dispatcher +-- stylua: ignore +function M.dispatcher(_, _, data) + if #M.queue == 0 then return end + + for _, line in ipairs(data) do + + -- 1. Strip ALL whitespace and non-printable control characters (like \r) + -- %s is whitespace, %c is control characters + local clean_line = line:gsub("[%s%c]", "") + + -- 2. Look for the pattern in the fully sanitized string + -- Regex match: captures 'SUCCESS' or 'FAILED' + local status = clean_line:match('^___DONE___:(%a+)') + if status then + if status == 'SUCCESS' then + local task = table.remove(M.queue, 1) + if task then vim.schedule(task) end + else + M.queue = {} -- Clear queue on any other status (failure) + vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) + end + break end - elseif clean_output:find('___DONE___:FAILED') then - pio_buffer = '' - M.queue = {} -- Clear queue on failure - vim.schedule(function() - vim.notify('PIO Sequence: Aborted', 4) - end) - end - - -- 4. Safety: Prevent buffer overflow in very long logs - if #pio_buffer > 10000 then - pio_buffer = pio_buffer:sub(-5000) end end --- Unified Dispatcher --- stylua: ignore --- function M.dispatcher(_, _, data) --- if #M.queue == 0 then return end --- --- for _, line in ipairs(data) do --- --- -- 1. Strip ALL whitespace and non-printable control characters (like \r) --- -- %s is whitespace, %c is control characters --- local clean_line = line:gsub("[%s%c]", "") --- --- -- 2. Look for the pattern in the fully sanitized string --- -- Regex match: captures 'SUCCESS' or 'FAILED' --- local status = clean_line:match('^___DONE___:(%a+)') --- if status then --- if status == 'SUCCESS' then --- local task = table.remove(M.queue, 1) --- if task then vim.schedule(task) end --- else --- M.queue = {} -- Clear queue on any other status (failure) --- vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) --- end --- break --- end --- end --- end - -- Improved Runner: Accepts a table of { cmd = "...", cb = function } -- stylua: ignore M.run_sequence = function(tasks) From 24154119def95926c2ffc738df18648350a6bbce Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 21:14:32 +0300 Subject: [PATCH 0430/1406] update --- lua/platformio/utils.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 9e8c41ce..b2a317ea 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -57,7 +57,7 @@ M.run_sequence = function(tasks) local failure = 'echo ___DONE___:FAILED' -- Chain: command && success || failure - local part = string.format('%s && %s || %s', task.cmd, success, failure) + local part = string.format('(%s && %s || %s)', task.cmd, success, failure) if full_cmd == '' then full_cmd = part else full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands From 13b9e75836716e5188e95f4ed3e09716a04ea850 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 21:49:20 +0300 Subject: [PATCH 0431/1406] update --- lua/platformio/utils.lua | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index b2a317ea..6f4d5a22 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -48,20 +48,22 @@ end -- stylua: ignore M.run_sequence = function(tasks) local full_cmd = '' + local success = 'echo ___DONE___:SUCCESS' + local failure = 'echo ___DONE___:FAILED' + for _, task in ipairs(tasks) do table.insert(M.queue, task.cb) -- Windows CMD/PowerShell specific syntax: -- No parentheses ensures compatibility with basic 'cmd.exe' - local success = 'echo ___DONE___:SUCCESS' - local failure = 'echo ___DONE___:FAILED' - -- Chain: command && success || failure - local part = string.format('(%s && %s || %s)', task.cmd, success, failure) + -- local part = string.format('(%s && %s || %s)', task.cmd, success, failure) + local part = string.format('%s && %s', task.cmd, success) if full_cmd == '' then full_cmd = part else full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands end + full_cmd = full_cmd .. ' && ' .. failure M.ToggleTerminal(full_cmd, 'float') end From 7c599fa8393e9b9eb53c28db756e955822e16dc7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 21:58:20 +0300 Subject: [PATCH 0432/1406] update --- lua/platformio/utils.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 6f4d5a22..a32eb68d 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -58,7 +58,7 @@ M.run_sequence = function(tasks) -- No parentheses ensures compatibility with basic 'cmd.exe' -- Chain: command && success || failure -- local part = string.format('(%s && %s || %s)', task.cmd, success, failure) - local part = string.format('%s && %s', task.cmd, success) + local part = string.format(('%s && %s'), task.cmd, success) if full_cmd == '' then full_cmd = part else full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands From e7255cf6dbcf7ec71b9e76bdd7e3b3dac846af39 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 22:04:03 +0300 Subject: [PATCH 0433/1406] update --- lua/platformio/utils.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index a32eb68d..ffe6c371 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -63,7 +63,7 @@ M.run_sequence = function(tasks) if full_cmd == '' then full_cmd = part else full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands end - full_cmd = full_cmd .. ' && ' .. failure + full_cmd = full_cmd .. ' || ' .. failure M.ToggleTerminal(full_cmd, 'float') end From 154270e4ea2ba9581470b37d39c4a151dac2ed5d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 8 Apr 2026 22:13:00 +0300 Subject: [PATCH 0434/1406] update --- lua/platformio/utils.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index ffe6c371..ff5c4b97 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -47,7 +47,7 @@ end -- Improved Runner: Accepts a table of { cmd = "...", cb = function } -- stylua: ignore M.run_sequence = function(tasks) - local full_cmd = '' + local full_cmd = '(' local success = 'echo ___DONE___:SUCCESS' local failure = 'echo ___DONE___:FAILED' @@ -63,7 +63,7 @@ M.run_sequence = function(tasks) if full_cmd == '' then full_cmd = part else full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands end - full_cmd = full_cmd .. ' || ' .. failure + full_cmd = full_cmd .. ') || ' .. failure M.ToggleTerminal(full_cmd, 'float') end From 20ecadc85429be34b5dfeb4ea72a8d99190aebe8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 05:32:20 +0300 Subject: [PATCH 0435/1406] update --- lua/platformio/utils.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index ff5c4b97..ffe6c371 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -47,7 +47,7 @@ end -- Improved Runner: Accepts a table of { cmd = "...", cb = function } -- stylua: ignore M.run_sequence = function(tasks) - local full_cmd = '(' + local full_cmd = '' local success = 'echo ___DONE___:SUCCESS' local failure = 'echo ___DONE___:FAILED' @@ -63,7 +63,7 @@ M.run_sequence = function(tasks) if full_cmd == '' then full_cmd = part else full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands end - full_cmd = full_cmd .. ') || ' .. failure + full_cmd = full_cmd .. ' || ' .. failure M.ToggleTerminal(full_cmd, 'float') end From 2fad88c9c43d29e6dcec89c50d927fba90c1b39c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 05:47:14 +0300 Subject: [PATCH 0436/1406] update --- lua/platformio/utils.lua | 104 ++++++++++++++++++++++++++++----------- 1 file changed, 75 insertions(+), 29 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index ffe6c371..d49c91b0 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -14,39 +14,82 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' ------------------------------------------------------ -- INFO: Dispatcher + M.queue = {} --- Outside the function to persist across multiple stdout calls - --- Unified Dispatcher --- stylua: ignore -function M.dispatcher(_, _, data) - if #M.queue == 0 then return end - - for _, line in ipairs(data) do - - -- 1. Strip ALL whitespace and non-printable control characters (like \r) - -- %s is whitespace, %c is control characters - local clean_line = line:gsub("[%s%c]", "") - - -- 2. Look for the pattern in the fully sanitized string - -- Regex match: captures 'SUCCESS' or 'FAILED' - local status = clean_line:match('^___DONE___:(%a+)') - if status then - if status == 'SUCCESS' then - local task = table.remove(M.queue, 1) - if task then vim.schedule(task) end - else - M.queue = {} -- Clear queue on any other status (failure) - vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) - end - break +local pio_buffer = '' -- Persistent stream buffer + +-- 1. The Dispatcher (The Brain) +function M.dispatcher(_, _, data, _) + if #M.queue == 0 then + return + end + + -- Reassemble fragmented chunks into the persistent stream + pio_buffer = pio_buffer .. table.concat(data, '') + + -- Clean buffer: Remove whitespace and control characters (\r, \n) + -- This is the "secret sauce" for Windows compatibility + local clean_stream = pio_buffer:gsub('[%s%c]', '') + + -- Check for Success Signal + if clean_stream:find('___DONE___:SUCCESS') then + pio_buffer = '' -- Reset buffer to prevent double-firing + local task = table.remove(M.queue, 1) + if task then + vim.schedule(task) end + + -- Check for Failure Signal + elseif clean_stream:find('___DONE___:FAILED') then + pio_buffer = '' + M.queue = {} -- Wipe the queue on failure + vim.schedule(function() + vim.notify('PIO Sequence: Aborted', vim.log.levels.ERROR) + end) + end + + -- Safety: Prevent memory leak by capping buffer size + if #pio_buffer > 10000 then + pio_buffer = pio_buffer:sub(-5000) end end +-- M.queue = {} +-- -- Outside the function to persist across multiple stdout calls +-- +-- -- Unified Dispatcher +-- -- stylua: ignore +-- function M.dispatcher(_, _, data) +-- if #M.queue == 0 then return end +-- +-- for _, line in ipairs(data) do +-- +-- -- 1. Strip ALL whitespace and non-printable control characters (like \r) +-- -- %s is whitespace, %c is control characters +-- local clean_line = line:gsub("[%s%c]", "") +-- +-- -- 2. Look for the pattern in the fully sanitized string +-- -- Regex match: captures 'SUCCESS' or 'FAILED' +-- local status = clean_line:match('^___DONE___:(%a+)') +-- if status then +-- if status == 'SUCCESS' then +-- local task = table.remove(M.queue, 1) +-- if task then vim.schedule(task) end +-- else +-- M.queue = {} -- Clear queue on any other status (failure) +-- vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) +-- end +-- break +-- end +-- end +-- end + -- Improved Runner: Accepts a table of { cmd = "...", cb = function } --- stylua: ignore +--- stylua: ignore M.run_sequence = function(tasks) + -- Reset local state for new run + M.queue = {} + pio_buffer = '' local full_cmd = '' local success = 'echo ___DONE___:SUCCESS' local failure = 'echo ___DONE___:FAILED' @@ -58,10 +101,13 @@ M.run_sequence = function(tasks) -- No parentheses ensures compatibility with basic 'cmd.exe' -- Chain: command && success || failure -- local part = string.format('(%s && %s || %s)', task.cmd, success, failure) - local part = string.format(('%s && %s'), task.cmd, success) + local part = string.format('%s && %s', task.cmd, success) - if full_cmd == '' then full_cmd = part - else full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands + if full_cmd == '' then + full_cmd = part + else + full_cmd = full_cmd .. ' && ' .. part + end -- Chain multiple commands end full_cmd = full_cmd .. ' || ' .. failure M.ToggleTerminal(full_cmd, 'float') From 1b491d6c797cdb56e00be61a00bb6edd1bf08064 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 06:09:01 +0300 Subject: [PATCH 0437/1406] update --- lua/platformio/utils.lua | 31 ++++++++++++------------------- 1 file changed, 12 insertions(+), 19 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index d49c91b0..688eb9f5 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -19,38 +19,31 @@ M.queue = {} local pio_buffer = '' -- Persistent stream buffer -- 1. The Dispatcher (The Brain) -function M.dispatcher(_, _, data, _) +function M.dispatcher(t, _, data) if #M.queue == 0 then return end -- Reassemble fragmented chunks into the persistent stream pio_buffer = pio_buffer .. table.concat(data, '') - - -- Clean buffer: Remove whitespace and control characters (\r, \n) - -- This is the "secret sauce" for Windows compatibility local clean_stream = pio_buffer:gsub('[%s%c]', '') + -- We check for the brackets. + -- The terminal command sent was: echo ___DONE___:SUCCESS + -- The terminal output will be: ___DONE___:SUCCESS + -- Because the sent string doesn't have the brackets, Lua ignores the echo-back! -- Check for Success Signal - if clean_stream:find('___DONE___:SUCCESS') then - pio_buffer = '' -- Reset buffer to prevent double-firing + if clean_stream:find('%[___DONE___:SUCCESS%]') then + pio_buffer = '' local task = table.remove(M.queue, 1) if task then vim.schedule(task) end - -- Check for Failure Signal - elseif clean_stream:find('___DONE___:FAILED') then + elseif clean_stream:find('%[___DONE___:FAILED%]') then pio_buffer = '' - M.queue = {} -- Wipe the queue on failure - vim.schedule(function() - vim.notify('PIO Sequence: Aborted', vim.log.levels.ERROR) - end) - end - - -- Safety: Prevent memory leak by capping buffer size - if #pio_buffer > 10000 then - pio_buffer = pio_buffer:sub(-5000) + M.queue = {} + vim.notify('Aborted', 4) end end @@ -91,8 +84,8 @@ M.run_sequence = function(tasks) M.queue = {} pio_buffer = '' local full_cmd = '' - local success = 'echo ___DONE___:SUCCESS' - local failure = 'echo ___DONE___:FAILED' + local success = '[echo ___DONE___:SUCCESS]' + local failure = '[echo ___DONE___:FAILED]' for _, task in ipairs(tasks) do table.insert(M.queue, task.cb) From 8999c2ecbb09af4fcaab4ee2e49a1f75717aa518 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 06:12:23 +0300 Subject: [PATCH 0438/1406] update --- lua/platformio/utils.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 688eb9f5..de6762a3 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -84,8 +84,8 @@ M.run_sequence = function(tasks) M.queue = {} pio_buffer = '' local full_cmd = '' - local success = '[echo ___DONE___:SUCCESS]' - local failure = '[echo ___DONE___:FAILED]' + local success = 'echo [___DONE___:SUCCESS]' + local failure = 'echo [___DONE___:FAILED]' for _, task in ipairs(tasks) do table.insert(M.queue, task.cb) From c50f172a933b2b4ff616b06ae7f2b3b5c62e8fd2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 06:35:25 +0300 Subject: [PATCH 0439/1406] update --- lua/platformio/utils.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index de6762a3..570494a3 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -33,14 +33,14 @@ function M.dispatcher(t, _, data) -- The terminal output will be: ___DONE___:SUCCESS -- Because the sent string doesn't have the brackets, Lua ignores the echo-back! -- Check for Success Signal - if clean_stream:find('%[___DONE___:SUCCESS%]') then + if clean_stream:find('___DONE___:SUCCESS') then pio_buffer = '' local task = table.remove(M.queue, 1) if task then vim.schedule(task) end -- Check for Failure Signal - elseif clean_stream:find('%[___DONE___:FAILED%]') then + elseif clean_stream:find('___DONE___:FAILED') then pio_buffer = '' M.queue = {} vim.notify('Aborted', 4) @@ -84,8 +84,8 @@ M.run_sequence = function(tasks) M.queue = {} pio_buffer = '' local full_cmd = '' - local success = 'echo [___DONE___:SUCCESS]' - local failure = 'echo [___DONE___:FAILED]' + local success = 'echo ___DONE___":"SUCCESS' + local failure = 'echo ___DONE___":"FAILED' for _, task in ipairs(tasks) do table.insert(M.queue, task.cb) From f15881599cde2ecb14dc7a627ff65d74984e214f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 06:46:04 +0300 Subject: [PATCH 0440/1406] update --- lua/platformio/utils.lua | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 570494a3..1755e688 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -84,8 +84,10 @@ M.run_sequence = function(tasks) M.queue = {} pio_buffer = '' local full_cmd = '' - local success = 'echo ___DONE___":"SUCCESS' - local failure = 'echo ___DONE___":"FAILED' + + local var = is_windows and '%EMPTY%' or '${EMPTY}' + local success = 'echo ___DONE___' .. var .. ':SUCCESS' + local failure = 'echo ___DONE___' .. var .. ':FAILED' for _, task in ipairs(tasks) do table.insert(M.queue, task.cb) From 44003eda78878bd7b6e5e997aaa7b547c8d70080 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 07:58:21 +0300 Subject: [PATCH 0441/1406] update --- lua/platformio/utils.lua | 4 +++- mini_nvimPlatformio.lua | 15 ++++++++------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 1755e688..d99eb1e7 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -19,7 +19,7 @@ M.queue = {} local pio_buffer = '' -- Persistent stream buffer -- 1. The Dispatcher (The Brain) -function M.dispatcher(t, _, data) +function M.dispatcher(_, _, data) if #M.queue == 0 then return end @@ -294,6 +294,8 @@ function M.ToggleTerminal(command, direction) height = function() return math.ceil(vim.o.lines * 0.85) end, + -- shell = vim.o.shell, + shell = vim.o.shell, highlights = { border = 'FloatBorder', background = 'NormalFloat', diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 2a9fbacf..a2573347 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -44,13 +44,14 @@ if not isWindows then vim.g.shellpipe = '|' -- Pipes output of external commands vim.g.shellredir = '> ' -- Redirects output of external commands else - vim.g.shell = vim.fn.executable('pwsh') and 'pwsh' or 'powershell' - vim.g.shellcmdflag = - '-NoLogo -ExecutionPolicy RemoteSigned -Command [Console]::InputEncoding=[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new();$PSDefaultParameterValues[Out-File:Encoding]=utf8;Remove-Alias -Force -ErrorAction SilentlyContinue tee;' - vim.g.shellredir = '2>&1 | %%{ "$_" } | Out-File %s; exit $LastExitCode' - vim.g.shellpipe = '2>&1 | %%{ "$_" } | tee %s; exit $LastExitCode' - vim.g.shellquote = '' - vim.g.shellxquote = '' + local pwsh = vim.fn.executable('pwsh') == 1 and 'pwsh' or 'powershell' + vim.opt.shell = pwsh + vim.opt.shellcmdflag = + '-NoLogo -NoProfile -ExecutionPolicy RemoteSigned -Command [Console]::InputEncoding=[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new();' + vim.opt.shellredir = '2>&1 | Out-File -Encoding UTF8 %s; exit $LastExitCode' + vim.opt.shellpipe = '2>&1 | Out-File -Encoding UTF8 %s; exit $LastExitCode' + vim.opt.shellquote = '' + vim.opt.shellxquote = '' end ---------------------------------------------------------------------------------------- From 5c0e35ec52944b1f5010fc36eb6df5a00952aa05 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 08:13:56 +0300 Subject: [PATCH 0442/1406] update --- lua/platformio/utils.lua | 112 +++++++++++++++++++-------------------- 1 file changed, 56 insertions(+), 56 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index d99eb1e7..a7cd55be 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -15,79 +15,79 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' ------------------------------------------------------ -- INFO: Dispatcher -M.queue = {} -local pio_buffer = '' -- Persistent stream buffer - --- 1. The Dispatcher (The Brain) -function M.dispatcher(_, _, data) - if #M.queue == 0 then - return - end - - -- Reassemble fragmented chunks into the persistent stream - pio_buffer = pio_buffer .. table.concat(data, '') - local clean_stream = pio_buffer:gsub('[%s%c]', '') - - -- We check for the brackets. - -- The terminal command sent was: echo ___DONE___:SUCCESS - -- The terminal output will be: ___DONE___:SUCCESS - -- Because the sent string doesn't have the brackets, Lua ignores the echo-back! - -- Check for Success Signal - if clean_stream:find('___DONE___:SUCCESS') then - pio_buffer = '' - local task = table.remove(M.queue, 1) - if task then - vim.schedule(task) - end - -- Check for Failure Signal - elseif clean_stream:find('___DONE___:FAILED') then - pio_buffer = '' - M.queue = {} - vim.notify('Aborted', 4) - end -end - -- M.queue = {} --- -- Outside the function to persist across multiple stdout calls +-- local pio_buffer = '' -- Persistent stream buffer -- --- -- Unified Dispatcher --- -- stylua: ignore +-- -- 1. The Dispatcher (The Brain) -- function M.dispatcher(_, _, data) --- if #M.queue == 0 then return end --- --- for _, line in ipairs(data) do +-- if #M.queue == 0 then +-- return +-- end -- --- -- 1. Strip ALL whitespace and non-printable control characters (like \r) --- -- %s is whitespace, %c is control characters --- local clean_line = line:gsub("[%s%c]", "") +-- -- Reassemble fragmented chunks into the persistent stream +-- pio_buffer = pio_buffer .. table.concat(data, '') +-- local clean_stream = pio_buffer:gsub('[%s%c]', '') -- --- -- 2. Look for the pattern in the fully sanitized string --- -- Regex match: captures 'SUCCESS' or 'FAILED' --- local status = clean_line:match('^___DONE___:(%a+)') --- if status then --- if status == 'SUCCESS' then --- local task = table.remove(M.queue, 1) --- if task then vim.schedule(task) end --- else --- M.queue = {} -- Clear queue on any other status (failure) --- vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) --- end --- break +-- -- We check for the brackets. +-- -- The terminal command sent was: echo ___DONE___:SUCCESS +-- -- The terminal output will be: ___DONE___:SUCCESS +-- -- Because the sent string doesn't have the brackets, Lua ignores the echo-back! +-- -- Check for Success Signal +-- if clean_stream:find('___DONE___:SUCCESS') then +-- pio_buffer = '' +-- local task = table.remove(M.queue, 1) +-- if task then +-- vim.schedule(task) -- end +-- -- Check for Failure Signal +-- elseif clean_stream:find('___DONE___:FAILED') then +-- pio_buffer = '' +-- M.queue = {} +-- vim.notify('Aborted', 4) -- end -- end +M.queue = {} +-- Outside the function to persist across multiple stdout calls + +-- Unified Dispatcher +-- stylua: ignore +function M.dispatcher(_, _, data) + if #M.queue == 0 then return end + + for _, line in ipairs(data) do + + -- 1. Strip ALL whitespace and non-printable control characters (like \r) + -- %s is whitespace, %c is control characters + local clean_line = line:gsub("[%s%c]", "") + + -- 2. Look for the pattern in the fully sanitized string + -- Regex match: captures 'SUCCESS' or 'FAILED' + local status = clean_line:match('^___DONE___:(%a+)') + if status then + if status == 'SUCCESS' then + local task = table.remove(M.queue, 1) + if task then vim.schedule(task) end + else + M.queue = {} -- Clear queue on any other status (failure) + vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) + end + break + end + end +end + -- Improved Runner: Accepts a table of { cmd = "...", cb = function } --- stylua: ignore M.run_sequence = function(tasks) -- Reset local state for new run M.queue = {} - pio_buffer = '' + -- pio_buffer = '' local full_cmd = '' local var = is_windows and '%EMPTY%' or '${EMPTY}' - local success = 'echo ___DONE___' .. var .. ':SUCCESS' - local failure = 'echo ___DONE___' .. var .. ':FAILED' + local success = 'echo ___DONE___":"SUCCESS' + local failure = 'echo ___DONE___":"FAILED' for _, task in ipairs(tasks) do table.insert(M.queue, task.cb) From 53af27ce76cf93ba2daef6a014c1f1a3eb3cc747 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 09:15:20 +0300 Subject: [PATCH 0443/1406] update --- lua/platformio/utils.lua | 97 ++++++++++++++++++---------------------- 1 file changed, 44 insertions(+), 53 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index a7cd55be..badb901b 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -15,68 +15,59 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' ------------------------------------------------------ -- INFO: Dispatcher --- M.queue = {} --- local pio_buffer = '' -- Persistent stream buffer --- --- -- 1. The Dispatcher (The Brain) --- function M.dispatcher(_, _, data) --- if #M.queue == 0 then --- return --- end --- --- -- Reassemble fragmented chunks into the persistent stream --- pio_buffer = pio_buffer .. table.concat(data, '') --- local clean_stream = pio_buffer:gsub('[%s%c]', '') --- --- -- We check for the brackets. --- -- The terminal command sent was: echo ___DONE___:SUCCESS --- -- The terminal output will be: ___DONE___:SUCCESS --- -- Because the sent string doesn't have the brackets, Lua ignores the echo-back! --- -- Check for Success Signal --- if clean_stream:find('___DONE___:SUCCESS') then --- pio_buffer = '' --- local task = table.remove(M.queue, 1) --- if task then --- vim.schedule(task) --- end --- -- Check for Failure Signal --- elseif clean_stream:find('___DONE___:FAILED') then --- pio_buffer = '' --- M.queue = {} --- vim.notify('Aborted', 4) --- end --- end - M.queue = {} --- Outside the function to persist across multiple stdout calls - --- Unified Dispatcher +local pio_buffer = '' -- Persistent stream buffer +-- +-- 1. The Dispatcher (The Brain) -- stylua: ignore function M.dispatcher(_, _, data) if #M.queue == 0 then return end - for _, line in ipairs(data) do - - -- 1. Strip ALL whitespace and non-printable control characters (like \r) - -- %s is whitespace, %c is control characters - local clean_line = line:gsub("[%s%c]", "") - - -- 2. Look for the pattern in the fully sanitized string - -- Regex match: captures 'SUCCESS' or 'FAILED' - local status = clean_line:match('^___DONE___:(%a+)') - if status then - if status == 'SUCCESS' then - local task = table.remove(M.queue, 1) - if task then vim.schedule(task) end - else - M.queue = {} -- Clear queue on any other status (failure) - vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) - end - break + -- Reassemble fragmented chunks into the persistent stream + pio_buffer = pio_buffer .. table.concat(data, '') + local clean_line = pio_buffer:gsub('[%s%c]', '') + local status = clean_line:match('^___DONE___:(%a+)') + if status then + if status == 'SUCCESS' then + pio_buffer = '' + local task = table.remove(M.queue, 1) + if task then vim.schedule(task) end + elseif status == 'FAILED' then + pio_buffer = '' + M.queue = {} -- Clear queue on any other status (failure) + vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) end end + -- Safety: Prevent memory leak by capping buffer size + if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end end +-- Outside the function to persist across multiple stdout calls + +-- stylua: ignore +-- function M.dispatcher(_, _, data) +-- if #M.queue == 0 then return end +-- for _, line in ipairs(data) do +-- -- 1. Strip ALL whitespace and non-printable control characters (like \r) +-- -- %s is whitespace, %c is control characters +-- local clean_line = line:gsub('[%s%c]', '') +-- +-- -- 2. Look for the pattern in the fully sanitized string +-- -- Regex match: captures 'SUCCESS' or 'FAILED' +-- local status = clean_line:match('^___DONE___:(%a+)') +-- if status then +-- if status == 'SUCCESS' then +-- local task = table.remove(M.queue, 1) +-- if task then vim.schedule(task) end +-- elseif status == 'FAILED' then +-- M.queue = {} -- Clear queue on any other status (failure) +-- vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) +-- end +-- break +-- end +-- end +-- end + -- Improved Runner: Accepts a table of { cmd = "...", cb = function } --- stylua: ignore M.run_sequence = function(tasks) From e2e566fd66a666b4530508e54044ead480ff57e8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 09:17:16 +0300 Subject: [PATCH 0444/1406] update --- lua/platformio/piolsp.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 22c2b301..6a18d56e 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -36,7 +36,7 @@ function M.fix_pio_compile_commands() -- Extract filename (e.g., riscv32-esp-elf-gcc) local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = full_path - print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) + -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) end end @@ -53,11 +53,11 @@ function M.fix_pio_compile_commands() if not is_abs then local short_name = first_token:gsub('%.exe$', '') - print('PioFix2: short_name=' .. short_name) + -- print('PioFix2: short_name=' .. short_name) -- Direct Query: Does this name exist in our discovered list? if path_map[short_name] then cmd_parts[1] = path_map[short_name] - print('PioFix3: full_name=' .. cmd_parts[1]) + -- print('PioFix3: full_name=' .. cmd_parts[1]) entry.command = table.concat(cmd_parts, ' ') modified = modified + 1 end From e2d4b3ae1c8c4578a7081fd8853b5467847419ee Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 10:41:40 +0300 Subject: [PATCH 0445/1406] update --- lua/platformio/utils.lua | 88 ++++++++++++++++++++++++++++++++-------- 1 file changed, 72 insertions(+), 16 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index badb901b..dd31f992 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -19,27 +19,83 @@ M.queue = {} local pio_buffer = '' -- Persistent stream buffer -- -- 1. The Dispatcher (The Brain) --- stylua: ignore +--- stylua: ignore function M.dispatcher(_, _, data) - if #M.queue == 0 then return end + if #M.queue == 0 then + return + end - -- Reassemble fragmented chunks into the persistent stream - pio_buffer = pio_buffer .. table.concat(data, '') - local clean_line = pio_buffer:gsub('[%s%c]', '') - local status = clean_line:match('^___DONE___:(%a+)') - if status then - if status == 'SUCCESS' then - pio_buffer = '' - local task = table.remove(M.queue, 1) - if task then vim.schedule(task) end - elseif status == 'FAILED' then - pio_buffer = '' - M.queue = {} -- Clear queue on any other status (failure) - vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) + pio_buffer = pio_buffer .. data[1] + -- 2. If the chunk has more than one element, we've encountered newlines + if #data > 1 then + -- 3. Process any "middle" lines which are guaranteed to be complete + for i = 2, #data - 1 do + pio_buffer = pio_buffer .. data[i] + end + + for status in pio_buffer:gmatch('___DONE___:(%a+)') do + if status then + if status == 'SUCCESS' then + -- 4. Store the last element as the new partial buffer for the next call + pio_buffer = data[#data] + local task = table.remove(M.queue, 1) + if task then + vim.schedule(task) + end + elseif status == 'FAILED' then + M.queue = {} -- Clear queue on any other status (failure) + pio_buffer = '' + vim.schedule(function() + vim.notify('PIO Sequence: Aborted', 4) + end) + end + break + end end + -- + -- for _, line in ipairs(data) do + -- -- 1. Strip ALL whitespace and non-printable control characters (like \r) + -- -- %s is whitespace, %c is control characters + -- local clean_line = line:gsub('[%s%c]', '') + -- + -- -- 2. Look for the pattern in the fully sanitized string + -- -- Regex match: captures 'SUCCESS' or 'FAILED' + -- local status = clean_line:match('^___DONE___:(%a+)') + -- if status then + -- if status == 'SUCCESS' then + -- local task = table.remove(M.queue, 1) + -- if task then + -- vim.schedule(task) + -- end + -- elseif status == 'FAILED' then + -- M.queue = {} -- Clear queue on any other status (failure) + -- vim.schedule(function() + -- vim.notify('PIO Sequence: Aborted', 4) + -- end) + -- end + -- break + -- end + -- end end + -- Reassemble fragmented chunks into the persistent stream + -- pio_buffer = pio_buffer .. table.concat(data, '') + -- local clean_line = pio_buffer:gsub('[%s%c]', '') + -- local status = clean_line:match('[\r\n]___DONE___:(%a+)') + -- if status then + -- if status == 'SUCCESS' then + -- pio_buffer = '' + -- local task = table.remove(M.queue, 1) + -- if task then vim.schedule(task) end + -- elseif status == 'FAILED' then + -- pio_buffer = '' + -- M.queue = {} -- Clear queue on any other status (failure) + -- vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) + -- end + -- end -- Safety: Prevent memory leak by capping buffer size - if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end + if #pio_buffer > 10000 then + pio_buffer = pio_buffer:sub(-5000) + end end -- Outside the function to persist across multiple stdout calls From d8d6527856bbb5368a13b63065b9a3f5a278edc9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 11:24:34 +0300 Subject: [PATCH 0446/1406] update --- lua/platformio/piolsp.lua | 79 +++++++++------------------------------ mini_nvimPlatformio.lua | 14 +++++++ 2 files changed, 32 insertions(+), 61 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 6a18d56e..f339cad9 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -68,14 +68,16 @@ function M.fix_pio_compile_commands() -- PHASE 3: Save and Refresh -- Safe JSON encoding - local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) - if encode_ok and json_str then + if modified > 0 then local out_file = io.open(filename, 'w') if out_file then - out_file:write(json_str) - out_file:close() - vim.notify('compiledb: fixed', vim.log.levels.INFO) - M.lsp_restart('clangd') + local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) + if encode_ok and json_str then + out_file:write(json_str) + out_file:close() + vim.notify('compiledb: fixed', vim.log.levels.INFO) + M.lsp_restart('clangd') + end end end end @@ -102,89 +104,44 @@ function M.gitignore_lsp_configs(config_file) end end +-- stylua: ignore function M.lsp_restarti(name) local clients = vim.lsp.get_clients({ name = name }) - - -- if #clients == 0 then - -- -- I'm using my own implementation of `vim.lsp.enable()` - -- -- To work with default one change group name from `MyLsp` to `nvim.lsp.enable` - -- -- It is not tested with default one, so not sure if it would 100% work. - -- vim.api.nvim_exec_autocmds('FileType', { group = 'nvim.lsp.enable', buffer = 0 }) - -- return - -- end - for _, c in ipairs(clients) do local configc = c.config - -- print(vim.inspect(configc)) c:stop(true) - - vim.defer_fn(function() - vim.lsp.config(name, configc) - vim.lsp.enable(name) - end, 600) + vim.defer_fn(function() vim.lsp.config(name, configc) vim.lsp.enable(name) end, 600) end end +-- stylua: ignore function M.lsp_restart(name) if vim.fn.has('nvim-0.12') == 1 then -- local clients = vim.lsp.get_clients({ name = name }) local clangd = vim.lsp.get_clients({ name = name })[1] - if clangd then - -- Client is active, try to restart local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) - if not ok then - vim.notify('LSP ' .. name .. ' restart failed: ' .. err) - else - vim.notify('LSP ' .. name .. ' restarted' .. err) - end + if not ok then vim.notify('LSP ' .. name .. ' restart failed: ' .. err) + else vim.notify('LSP ' .. name .. ' restarted' .. err) end end else local client_name = 'clangd' local clients = vim.lsp.get_clients({ name = client_name }) - - for _, client in ipairs(clients) do - -- 1. Stop the specific client - client:stop() - end + -- 1. Stop the specific client + for _, client in ipairs(clients) do client:stop() end -- 2. Reload all loaded buffers to trigger re-attachment for that client -- (Note: 'checktime' is safer than 'bufdo edit' as it respects unsaved changes) vim.cmd('checktime') - -- vim.cmd('LspRestart') end end +-- stylua: ignore function M.piolsp() local ok, err = pcall(vim.cmd.lsp, { args = { 'restart' } }) - if ok then - vim.notify('LSP restarted' .. err) - else - vim.notify('LSP restart failed: ' .. err) - end + if ok then vim.notify('LSP restarted' .. err) + else vim.notify('LSP restart failed: ' .. err) end -- M.fix_pio_compile_commands() - - -- if not utils.pio_install_check() then - -- return - -- end - -- utils.cd_pioini() - -- - -- utils.shell_cmd_blocking('pio run -t compiledb') - -- vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) - -- M.gitignore_lsp_configs('compile_commands.json') - -- - -- -- if vim.fn.has('nvim-0.12') then - -- -- local clangd = vim.lsp.get_clients({ name = 'clangd' })[1] - -- -- if clangd then - -- -- -- print('number of attaced: ' .. #clangd.attached_buffers) - -- -- -- print('piolsp: lsp restart ' .. clangd.name) - -- -- pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) - -- M.lsp_restart('clangd') - -- vim.cmd('lsp restart clangd') - -- end - -- else - -- vim.cmd('LspRestart') - -- end end return M diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index a2573347..144519f1 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -284,6 +284,20 @@ require('lazy').setup(plugins, { }) ---------------------------------------------------------------------------------------- +-- stylua: ignore +if vim.fn.has('nvim-0.11') == 1 then + -- Create an augroup to manage the autocmd + local json_format_group = vim.api.nvim_create_augroup('JsonFormat', { clear = true }) + vim.api.nvim_create_autocmd('BufWritePre', { + group = json_format_group, + pattern = '*.json', + -- This runs 'python -m json.tool' on the current buffer content + -- It updates the buffer in-place before the file is written to disk + callback = function() vim.cmd('%!python -m json.tool') end, + }) +elseif vim.fn.has('nvim-0.12') == 1 then +end + ---------------------------------------------------------------------------------------- -- INFO: autocommand to Update lazy.nvim plugins in the background vim.api.nvim_create_autocmd('User', { From ac70df548aa675cc9d95f4a17b87911fb3366a9c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 11:35:04 +0300 Subject: [PATCH 0447/1406] update --- lua/platformio/piolsp.lua | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index f339cad9..5569db7c 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -73,7 +73,17 @@ function M.fix_pio_compile_commands() if out_file then local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) if encode_ok and json_str then - out_file:write(json_str) + -- 1. Format the string using python's json.tool + -- The second argument to vim.fn.system() is the "stdin" passed to the command + local formatted_json = vim.fn.system('python -m json.tool', json_str) + + -- 2. Write it to a file + -- -- vim.split is used because writefile expects a list of lines + -- local file_path = "config.json" + -- vim.fn.writefile(vim.split(formatted_json, "\n"), file_path) + + -- out_file:write(json_str) + out_file:write(formatted_json) out_file:close() vim.notify('compiledb: fixed', vim.log.levels.INFO) M.lsp_restart('clangd') From 423bd03b8a54c44be5485431818a5b0113f04fa3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 12:26:07 +0300 Subject: [PATCH 0448/1406] update --- lua/platformio/piolsp.lua | 44 ++++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 5569db7c..dc7bcf67 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -1,18 +1,45 @@ local M = {} +function M.get_pio_packages_dir(envdir) + -- Run the pio command to dump config in JSON format + local cmd = 'pio project config --json-output' + local output = vim.fn.system(cmd) + + -- Check for errors in the command execution + if vim.v.shell_error ~= 0 then + print('Error running pio command: ' .. output) + return nil + end + + -- Decode the JSON output + local ok, config = pcall(vim.json.decode, output) + if not ok then + print('Failed to decode JSON from PlatformIO') + return nil + end + envdir = envdir .. '_dir' + -- The output is structured by [section], usually under 'platformio' + -- or specific environments. We look for the global 'platformio' section. + if config and config.platformio then --and config.platformio.packages_dir + local result = config.platformio[envdir] + if result then + return result + end + -- return config.platformio.packages_dir + end + + return nil +end +-- stylua: ignore function M.fix_pio_compile_commands() local cwd = vim.fn.getcwd() local filename = cwd .. '/compile_commands.json' local file = io.open(filename, 'r') - if not file then - return - end + if not file then return end local content = file:read('*a') file:close() - if not content or content == '' then - return - end + if not content or content == '' then return end -- Safe JSON decoding local ok, data = pcall(vim.json.decode, content) @@ -24,12 +51,13 @@ function M.fix_pio_compile_commands() -- print('PioFix0') -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path local path_map = {} - -- local pio_home = os.getenv('HOME') or os.getenv('USERPROFILE') local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') print('PIO Home ' .. pio_home) if pio_home then + -- Recursively find all binaries in PIO packages - local pio_packages = pio_home .. '/packages/*/bin/*' + -- local pio_packages = pio_home .. '/packages/*/bin/*' + local pio_packages = M.get_pio_packages_dir('packages') .. '/*/bin/*' local found_binaries = vim.fn.glob(pio_packages, false, true) for _, full_path in ipairs(found_binaries) do From db78ad1d866e771c447e606a64fc7aef5af39a65 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 13:02:28 +0300 Subject: [PATCH 0449/1406] update --- lua/platformio/piolsp.lua | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index dc7bcf67..31d1adb6 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -1,5 +1,5 @@ local M = {} -function M.get_pio_packages_dir(envdir) +function M.get_pio_packages_dir(_) -- Run the pio command to dump config in JSON format local cmd = 'pio project config --json-output' local output = vim.fn.system(cmd) @@ -16,15 +16,15 @@ function M.get_pio_packages_dir(envdir) print('Failed to decode JSON from PlatformIO') return nil end - envdir = envdir .. '_dir' + -- envdir = envdir .. '_dir' -- The output is structured by [section], usually under 'platformio' -- or specific environments. We look for the global 'platformio' section. - if config and config.platformio then --and config.platformio.packages_dir - local result = config.platformio[envdir] - if result then - return result - end - -- return config.platformio.packages_dir + if config and config.platformio and config.platformio.packages_dir then + -- local result = config.platformio[envdir] + -- if result then + -- return result + -- end + return config.platformio.packages_dir end return nil @@ -56,8 +56,9 @@ function M.fix_pio_compile_commands() if pio_home then -- Recursively find all binaries in PIO packages - -- local pio_packages = pio_home .. '/packages/*/bin/*' - local pio_packages = M.get_pio_packages_dir('packages') .. '/*/bin/*' + local pio_packages = pio_home .. '/packages/*/bin/*' + print(M.get_pio_packages_dir()) + -- local pio_packages = M.get_pio_packages_dir('packages') .. '/*/bin/*' local found_binaries = vim.fn.glob(pio_packages, false, true) for _, full_path in ipairs(found_binaries) do From 46a10fd817c55302270e5996e533d5ed9231e4d4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 13:36:14 +0300 Subject: [PATCH 0450/1406] update --- lua/platformio/piolsp.lua | 62 ++++++++++++++++++++++++++------------- 1 file changed, 42 insertions(+), 20 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 31d1adb6..6772c7b4 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -1,5 +1,32 @@ local M = {} -function M.get_pio_packages_dir(_) + +-- stylua: ignore +function M.get_packages_dir_from_ini() + local file_path = vim.fn.getcwd() .. '/platformio.ini' + local f = io.open(file_path, 'r') + if not f then return nil end + + local packages_dir = nil + for line in f:lines() do + -- Remove whitespace and look for packages_dir = value + -- The pattern ^%s* matches start of line + optional spaces + -- ([^;%s]+) captures the value, stopping at a comment (;) or space + local match = line:match('^%s*packages_dir%s*=%s*([^;%s]+)') + if match then + packages_dir = match + break + end + end + f:close() + if packages_dir then + print('from ini: ' .. packages_dir) + else + print('from ini: nil') + end + return packages_dir +end + +function M.get_pio_packages_dir() -- Run the pio command to dump config in JSON format local cmd = 'pio project config --json-output' local output = vim.fn.system(cmd) @@ -16,24 +43,16 @@ function M.get_pio_packages_dir(_) print('Failed to decode JSON from PlatformIO') return nil end - -- envdir = envdir .. '_dir' - -- The output is structured by [section], usually under 'platformio' - -- or specific environments. We look for the global 'platformio' section. - if config and config.platformio and config.platformio.packages_dir then - -- local result = config.platformio[envdir] - -- if result then - -- return result - -- end - return config.platformio.packages_dir + local packages_dir = nil + if config and config.platformio then + packages_dir = config.platformio.packages_dir end - - return nil + return packages_dir end -- stylua: ignore function M.fix_pio_compile_commands() - local cwd = vim.fn.getcwd() - local filename = cwd .. '/compile_commands.json' + local filename = vim.fn.getcwd() .. '/compile_commands.json' local file = io.open(filename, 'r') if not file then return end @@ -57,7 +76,15 @@ function M.fix_pio_compile_commands() -- Recursively find all binaries in PIO packages local pio_packages = pio_home .. '/packages/*/bin/*' - print(M.get_pio_packages_dir()) + + local envdir = M.get_packages_dir_from_ini() + if envdir then print('from pio: ' .. envdir) + else print('from pio: nil') end + + envdir = M.get_pio_packages_dir() + if envdir then print('from pio: ' .. envdir) + else print('from pio: nil') end + -- local pio_packages = M.get_pio_packages_dir('packages') .. '/*/bin/*' local found_binaries = vim.fn.glob(pio_packages, false, true) @@ -106,11 +133,6 @@ function M.fix_pio_compile_commands() -- The second argument to vim.fn.system() is the "stdin" passed to the command local formatted_json = vim.fn.system('python -m json.tool', json_str) - -- 2. Write it to a file - -- -- vim.split is used because writefile expects a list of lines - -- local file_path = "config.json" - -- vim.fn.writefile(vim.split(formatted_json, "\n"), file_path) - -- out_file:write(json_str) out_file:write(formatted_json) out_file:close() From 26e1044be495adc9b36d2634ddfe17679892df6b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 13:44:50 +0300 Subject: [PATCH 0451/1406] update --- lua/platformio/piolsp.lua | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 6772c7b4..9463dac8 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -18,11 +18,6 @@ function M.get_packages_dir_from_ini() end end f:close() - if packages_dir then - print('from ini: ' .. packages_dir) - else - print('from ini: nil') - end return packages_dir end @@ -78,8 +73,8 @@ function M.fix_pio_compile_commands() local pio_packages = pio_home .. '/packages/*/bin/*' local envdir = M.get_packages_dir_from_ini() - if envdir then print('from pio: ' .. envdir) - else print('from pio: nil') end + if envdir then print('from ini: ' .. envdir) + else print('from ini: nil') end envdir = M.get_pio_packages_dir() if envdir then print('from pio: ' .. envdir) From a047c13f87c6bdb4d07a7b4d8ca49b324e29fa28 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 14:33:30 +0300 Subject: [PATCH 0452/1406] update --- lua/platformio/piolsp.lua | 109 ++++++++++++++++++++++---------------- 1 file changed, 62 insertions(+), 47 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 9463dac8..1f1b498c 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -1,50 +1,72 @@ local M = {} -- stylua: ignore -function M.get_packages_dir_from_ini() - local file_path = vim.fn.getcwd() .. '/platformio.ini' - local f = io.open(file_path, 'r') - if not f then return nil end - - local packages_dir = nil - for line in f:lines() do - -- Remove whitespace and look for packages_dir = value - -- The pattern ^%s* matches start of line + optional spaces - -- ([^;%s]+) captures the value, stopping at a comment (;) or space - local match = line:match('^%s*packages_dir%s*=%s*([^;%s]+)') - if match then - packages_dir = match - break +function M.get_pio_dir(type) + -- 1. Setup Base Paths + local home = os.getenv('HOME') or os.getenv('USERPROFILE') + local core_dir = os.getenv('PLATFORMIO_CORE_DIR') or (home .. '/.platformio') + + -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) + local map = { + packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, + platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, + } + + local target_config = map[type] + if not target_config then return nil end + + -- 3. Try to get explicit value from platformio.ini + local path = vim.fn.getcwd() .. '/platformio.ini' + local inifile = io.open(path, 'r') + local raw_val = nil + + if inifile then + for line in inifile:lines() do + -- Matches 'key = value', e.g., 'packages_dir = ...' + raw_val = line:match('^%s*' .. target_config.ini .. '%s*=%s*([^;%s]+)') + if raw_val then break end end + inifile:close() end - f:close() - return packages_dir -end -function M.get_pio_packages_dir() - -- Run the pio command to dump config in JSON format - local cmd = 'pio project config --json-output' - local output = vim.fn.system(cmd) + -- 4. Fallback Logic: INI -> Env Var -> Default + local result = raw_val or os.getenv(target_config.env) or (core_dir .. target_config.sub) - -- Check for errors in the command execution - if vim.v.shell_error ~= 0 then - print('Error running pio command: ' .. output) - return nil - end + -- 5. Expand ${platformio.core_dir} + result = result:gsub('%%${platformio.core_dir}', core_dir) - -- Decode the JSON output - local ok, config = pcall(vim.json.decode, output) - if not ok then - print('Failed to decode JSON from PlatformIO') - return nil - end - local packages_dir = nil - if config and config.platformio then - packages_dir = config.platformio.packages_dir - end - return packages_dir + -- 6. Normalize Slashes for Windows + if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end + + return result end + +-- function M.get_pio_packages_dir() +-- -- Run the pio command to dump config in JSON format +-- local cmd = 'pio project config --json-output' +-- local output = vim.fn.system(cmd) +-- +-- -- Check for errors in the command execution +-- if vim.v.shell_error ~= 0 then +-- print('Error running pio command: ' .. output) +-- return nil +-- end +-- +-- -- Decode the JSON output +-- local ok, config = pcall(vim.json.decode, output) +-- if not ok then +-- print('Failed to decode JSON from PlatformIO') +-- return nil +-- end +-- local packages_dir = nil +-- if config and config.platformio then +-- packages_dir = config.platformio.packages_dir +-- end +-- return packages_dir +-- end + + -- stylua: ignore function M.fix_pio_compile_commands() local filename = vim.fn.getcwd() .. '/compile_commands.json' @@ -70,17 +92,10 @@ function M.fix_pio_compile_commands() if pio_home then -- Recursively find all binaries in PIO packages - local pio_packages = pio_home .. '/packages/*/bin/*' - - local envdir = M.get_packages_dir_from_ini() - if envdir then print('from ini: ' .. envdir) - else print('from ini: nil') end - - envdir = M.get_pio_packages_dir() - if envdir then print('from pio: ' .. envdir) - else print('from pio: nil') end + local pio_packages = M.get_pio_dir('packages') .. '/*/bin/*' + -- local pio_packages = pio_home .. '/packages/*/bin/*' + print(pio_packages) - -- local pio_packages = M.get_pio_packages_dir('packages') .. '/*/bin/*' local found_binaries = vim.fn.glob(pio_packages, false, true) for _, full_path in ipairs(found_binaries) do From 3d1f8a85bdd7559cfb83a48a2a4e1bc800517d27 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 14:47:23 +0300 Subject: [PATCH 0453/1406] update --- lua/platformio/piolsp.lua | 50 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 1f1b498c..e23a19a6 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -4,7 +4,8 @@ local M = {} function M.get_pio_dir(type) -- 1. Setup Base Paths local home = os.getenv('HOME') or os.getenv('USERPROFILE') - local core_dir = os.getenv('PLATFORMIO_CORE_DIR') or (home .. '/.platformio') + -- Ensure core_dir itself doesn't have trailing slashes for cleaner joins + local core_dir = (os.getenv('PLATFORMIO_CORE_DIR') or (home .. '/.platformio')):gsub('[\\/]+$', '') -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) local map = { @@ -22,7 +23,6 @@ function M.get_pio_dir(type) if inifile then for line in inifile:lines() do - -- Matches 'key = value', e.g., 'packages_dir = ...' raw_val = line:match('^%s*' .. target_config.ini .. '%s*=%s*([^;%s]+)') if raw_val then break end end @@ -33,13 +33,57 @@ function M.get_pio_dir(type) local result = raw_val or os.getenv(target_config.env) or (core_dir .. target_config.sub) -- 5. Expand ${platformio.core_dir} - result = result:gsub('%%${platformio.core_dir}', core_dir) + if result:find('${platformio.core_dir}', 1, true) then + result = result:gsub('%${platformio.core_dir}', core_dir) + end -- 6. Normalize Slashes for Windows + result = result:gsub('\\', '/'):gsub('//+', '/') if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end return result end +-- stylua: ignore +-- k +-- function M.get_pio_dir(type) +-- -- 1. Setup Base Paths +-- local home = os.getenv('HOME') or os.getenv('USERPROFILE') +-- local core_dir = os.getenv('PLATFORMIO_CORE_DIR') or (home .. '/.platformio') +-- +-- -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) +-- local map = { +-- packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, +-- platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, +-- } +-- +-- local target_config = map[type] +-- if not target_config then return nil end +-- +-- -- 3. Try to get explicit value from platformio.ini +-- local path = vim.fn.getcwd() .. '/platformio.ini' +-- local inifile = io.open(path, 'r') +-- local raw_val = nil +-- +-- if inifile then +-- for line in inifile:lines() do +-- -- Matches 'key = value', e.g., 'packages_dir = ...' +-- raw_val = line:match('^%s*' .. target_config.ini .. '%s*=%s*([^;%s]+)') +-- if raw_val then break end +-- end +-- inifile:close() +-- end +-- +-- -- 4. Fallback Logic: INI -> Env Var -> Default +-- local result = raw_val or os.getenv(target_config.env) or (core_dir .. target_config.sub) +-- +-- -- 5. Expand ${platformio.core_dir} +-- result = result:gsub('%%${platformio.core_dir}', core_dir) +-- +-- -- 6. Normalize Slashes for Windows +-- if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end +-- +-- return result +-- end -- function M.get_pio_packages_dir() From 75b593e6dd077fdf365b13551528fbe1246415c6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 15:04:30 +0300 Subject: [PATCH 0454/1406] update --- lua/platformio/boilerplate.lua | 2 ++ lua/platformio/piolsp.lua | 3 --- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index df0c6f2e..f37d77d7 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -378,6 +378,8 @@ CompileFlags: --target=riscv32-esp-elf, ] Remove: [ + -fno%-fat%-lto%-objects, + -fno%-canonical%-system%-headers, -misc-definitions-in-headers, -fno-tree-switch-conversion, -mtext-section-literals, diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index e23a19a6..194464b2 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -132,13 +132,10 @@ function M.fix_pio_compile_commands() -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path local path_map = {} local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') - print('PIO Home ' .. pio_home) if pio_home then -- Recursively find all binaries in PIO packages local pio_packages = M.get_pio_dir('packages') .. '/*/bin/*' - -- local pio_packages = pio_home .. '/packages/*/bin/*' - print(pio_packages) local found_binaries = vim.fn.glob(pio_packages, false, true) From aab08d63fffdcca600c5ef24b98ab96b01d23726 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 15:08:41 +0300 Subject: [PATCH 0455/1406] update --- lua/platformio/boilerplate.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index f37d77d7..9a6af102 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -378,6 +378,7 @@ CompileFlags: --target=riscv32-esp-elf, ] Remove: [ + -fno-fat-lto-objects -fno%-fat%-lto%-objects, -fno%-canonical%-system%-headers, -misc-definitions-in-headers, From ce6e4663f17904f94c77ed83d5746dd902161c21 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 15:30:04 +0300 Subject: [PATCH 0456/1406] update --- lua/platformio/pioinit.lua | 134 ++++++++++++++++--------------------- lua/platformio/utils.lua | 113 +++++-------------------------- 2 files changed, 74 insertions(+), 173 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index b748ca05..464fd745 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -9,8 +9,6 @@ local entry_display = require('telescope.pickers.entry_display') local make_entry = require('telescope.make_entry') local utils = require('platformio.utils') local previewers = require('telescope.previewers') --- local piolsp = require('platformio.piolsp') --- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local boardentry_maker = function(opts) local displayer = entry_display.create({ @@ -45,89 +43,71 @@ local boardentry_maker = function(opts) end end +-- stylua: ignore local function pick_framework(board_details) local opts = {} - pickers - .new(opts, { - prompt_title = 'frameworks', - finder = finders.new_table({ - results = board_details['frameworks'], - }), - attach_mappings = function(prompt_bufnr, _) - actions.select_default:replace(function() - actions.close(prompt_bufnr) - local selection = action_state.get_selected_entry() - utils.selected_framework = selection[1] + pickers.new(opts, { + prompt_title = 'frameworks', + finder = finders.new_table({ + results = board_details['frameworks'], + }), + attach_mappings = function(prompt_bufnr, _) + actions.select_default:replace(function() + actions.close(prompt_bufnr) + local selection = action_state.get_selected_entry() + utils.selected_framework = selection[1] - utils.run_sequence({ - { - cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. utils.selected_framework .. '"', - cb = utils.handlePioinit, - }, - { - cmd = 'pio run -t compiledb', - cb = utils.handleDb, - }, - }) - - -- local command = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. utils.selected_framework .. '"' - -- -- command = command .. ' && pio run -t compiledb' - -- utils.ToggleTerminal(command, 'float', utils.handlePioinit) - - -- vim.defer_fn(function() - -- vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) - -- piolsp.gitignore_lsp_configs('compile_commands.json') - -- boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') - -- piolsp.lsp_restart('clangd') - -- end, 3000) - -- utils.ToggleTerminal(command, 'float', function() - -- -- require('platformio.piolsp').piolsp() - -- piolsp() - -- boilerplate_gen(selected_framework, vim.fn.getcwd() .. '/src') - -- end) - end) - return true - end, - sorter = telescope_conf.generic_sorter(opts), - }) - :find() + utils.run_sequence({ + { + cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. utils.selected_framework .. '"', + cb = utils.handlePioinit, + }, + { + cmd = 'pio run -t compiledb', + cb = utils.handleDb, + }, + }) + end) + return true + end, + sorter = telescope_conf.generic_sorter(opts), + }):find() end +-- stylua: ignore local function pick_board(json_data) local opts = {} - pickers - .new(opts, { - prompt_title = 'Boards', - finder = finders.new_table({ - results = json_data, - entry_maker = opts.entry_maker or boardentry_maker(opts), - }), - attach_mappings = function(prompt_bufnr, _) - actions.select_default:replace(function() - actions.close(prompt_bufnr) - local selection = action_state.get_selected_entry() - pick_framework(selection['value']['data']) - end) - return true + pickers.new(opts, { + prompt_title = 'Boards', + finder = finders.new_table({ + results = json_data, + entry_maker = opts.entry_maker or boardentry_maker(opts), + }), + attach_mappings = function(prompt_bufnr, _) + actions.select_default:replace(function() + actions.close(prompt_bufnr) + local selection = action_state.get_selected_entry() + pick_framework(selection['value']['data']) + end) + return true + end, + previewer = previewers.new_buffer_previewer({ + title = 'Board Info', + define_preview = function(self, entry, _) + local json = utils.strsplit(vim.inspect(entry['value']['data']), '\n') + local bufnr = self.state.bufnr + vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) + vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function + vim.defer_fn(function() + local win = self.state.winid + vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) + vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) + vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) + end, 0) end, - previewer = previewers.new_buffer_previewer({ - title = 'Board Info', - define_preview = function(self, entry, _) - local json = utils.strsplit(vim.inspect(entry['value']['data']), '\n') - local bufnr = self.state.bufnr - vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) - vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function - vim.defer_fn(function() - local win = self.state.winid - vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) - vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) - vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) - end, 0) - end, - }), - sorter = telescope_conf.generic_sorter(opts), - }) - :find() + }), + sorter = telescope_conf.generic_sorter(opts), + }):find() end function M.pioinit() diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index dd31f992..a7e6aa24 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -17,21 +17,17 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' M.queue = {} local pio_buffer = '' -- Persistent stream buffer --- + -- 1. The Dispatcher (The Brain) ---- stylua: ignore +-- stylua: ignore function M.dispatcher(_, _, data) - if #M.queue == 0 then - return - end + if #M.queue == 0 then return end pio_buffer = pio_buffer .. data[1] -- 2. If the chunk has more than one element, we've encountered newlines if #data > 1 then -- 3. Process any "middle" lines which are guaranteed to be complete - for i = 2, #data - 1 do - pio_buffer = pio_buffer .. data[i] - end + for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end for status in pio_buffer:gmatch('___DONE___:(%a+)') do if status then @@ -39,117 +35,34 @@ function M.dispatcher(_, _, data) -- 4. Store the last element as the new partial buffer for the next call pio_buffer = data[#data] local task = table.remove(M.queue, 1) - if task then - vim.schedule(task) - end + if task then vim.schedule(task) end elseif status == 'FAILED' then M.queue = {} -- Clear queue on any other status (failure) pio_buffer = '' - vim.schedule(function() - vim.notify('PIO Sequence: Aborted', 4) - end) + vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) end break end end - -- - -- for _, line in ipairs(data) do - -- -- 1. Strip ALL whitespace and non-printable control characters (like \r) - -- -- %s is whitespace, %c is control characters - -- local clean_line = line:gsub('[%s%c]', '') - -- - -- -- 2. Look for the pattern in the fully sanitized string - -- -- Regex match: captures 'SUCCESS' or 'FAILED' - -- local status = clean_line:match('^___DONE___:(%a+)') - -- if status then - -- if status == 'SUCCESS' then - -- local task = table.remove(M.queue, 1) - -- if task then - -- vim.schedule(task) - -- end - -- elseif status == 'FAILED' then - -- M.queue = {} -- Clear queue on any other status (failure) - -- vim.schedule(function() - -- vim.notify('PIO Sequence: Aborted', 4) - -- end) - -- end - -- break - -- end - -- end - end - -- Reassemble fragmented chunks into the persistent stream - -- pio_buffer = pio_buffer .. table.concat(data, '') - -- local clean_line = pio_buffer:gsub('[%s%c]', '') - -- local status = clean_line:match('[\r\n]___DONE___:(%a+)') - -- if status then - -- if status == 'SUCCESS' then - -- pio_buffer = '' - -- local task = table.remove(M.queue, 1) - -- if task then vim.schedule(task) end - -- elseif status == 'FAILED' then - -- pio_buffer = '' - -- M.queue = {} -- Clear queue on any other status (failure) - -- vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) - -- end - -- end - -- Safety: Prevent memory leak by capping buffer size - if #pio_buffer > 10000 then - pio_buffer = pio_buffer:sub(-5000) end + if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end end --- Outside the function to persist across multiple stdout calls - -- stylua: ignore --- function M.dispatcher(_, _, data) --- if #M.queue == 0 then return end --- for _, line in ipairs(data) do --- -- 1. Strip ALL whitespace and non-printable control characters (like \r) --- -- %s is whitespace, %c is control characters --- local clean_line = line:gsub('[%s%c]', '') --- --- -- 2. Look for the pattern in the fully sanitized string --- -- Regex match: captures 'SUCCESS' or 'FAILED' --- local status = clean_line:match('^___DONE___:(%a+)') --- if status then --- if status == 'SUCCESS' then --- local task = table.remove(M.queue, 1) --- if task then vim.schedule(task) end --- elseif status == 'FAILED' then --- M.queue = {} -- Clear queue on any other status (failure) --- vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) --- end --- break --- end --- end --- end - --- Improved Runner: Accepts a table of { cmd = "...", cb = function } ---- stylua: ignore M.run_sequence = function(tasks) -- Reset local state for new run M.queue = {} -- pio_buffer = '' local full_cmd = '' - local var = is_windows and '%EMPTY%' or '${EMPTY}' local success = 'echo ___DONE___":"SUCCESS' local failure = 'echo ___DONE___":"FAILED' for _, task in ipairs(tasks) do table.insert(M.queue, task.cb) - - -- Windows CMD/PowerShell specific syntax: - -- No parentheses ensures compatibility with basic 'cmd.exe' - -- Chain: command && success || failure - -- local part = string.format('(%s && %s || %s)', task.cmd, success, failure) local part = string.format('%s && %s', task.cmd, success) - - if full_cmd == '' then - full_cmd = part - else - full_cmd = full_cmd .. ' && ' .. part - end -- Chain multiple commands + if full_cmd == '' then full_cmd = part + else full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands end full_cmd = full_cmd .. ' || ' .. failure M.ToggleTerminal(full_cmd, 'float') @@ -162,10 +75,18 @@ function M.handleDb() piolsp.fix_pio_compile_commands() piolsp.lsp_restart('clangd') end + -- Handle after poioinit execution +-- stylua: ignore function M.handlePioinit() vim.notify('Pioinit: Success', vim.log.levels.INFO) boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') + + -- print('Generating compile_commands.json...') + -- local output = vim.fn.system('pio run -t compiledb') + -- if vim.v.shell_error ~= 0 then + -- vim.notify('PIO Error: fail to generate compiledb' .. output, vim.log.levels.ERROR) + -- end end -- INFO: endDispatcher ------------------------------------------------------ From a41a5208547bab79c9c9609eebf44d0fed2a6105 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 16:45:10 +0300 Subject: [PATCH 0457/1406] update --- lua/platformio/piolib.lua | 103 +++++++++++++++++++++----------------- lua/platformio/utils.lua | 11 ++-- 2 files changed, 61 insertions(+), 53 deletions(-) diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 53a9ad7f..956306da 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -44,58 +44,67 @@ local libentry_maker = function(opts) end end +-- stylua: ignore local function pick_library(json_data) local opts = {} - pickers - .new(opts, { - prompt_title = 'Libraries', - finder = finders.new_table({ - results = json_data['items'], - entry_maker = opts.entry_maker or libentry_maker(opts), - }), - attach_mappings = function(prompt_bufnr, _) - actions.select_default:replace(function() - actions.close(prompt_bufnr) - local selection = action_state.get_selected_entry() - local pkg_name = selection['value']['owner'] .. '/' .. selection['value']['name'] - local command = 'pio pkg install --library "' .. pkg_name .. '"' - command = command .. ' && pio run -t compiledb' + pickers.new(opts, { + prompt_title = 'Libraries', + finder = finders.new_table({ + results = json_data['items'], + entry_maker = opts.entry_maker or libentry_maker(opts), + }), + attach_mappings = function(prompt_bufnr, _) + actions.select_default:replace(function() + actions.close(prompt_bufnr) + local selection = action_state.get_selected_entry() + local pkg_name = selection['value']['owner'] .. '/' .. selection['value']['name'] + -- local command = 'pio pkg install --library "' .. pkg_name .. '"' + -- command = command .. ' && pio run -t compiledb' - utils.ToggleTerminal(command, 'float') - vim.defer_fn(function() - vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) - piolsp.gitignore_lsp_configs('compile_commands.json') - piolsp.lsp_restart('clangd') - end, 900) - -- local command = 'pio pkg install --library "' .. pkg_name .. '" && exit && echo "done"' + utils.run_sequence({ + { + cmd = 'pio pkg install --library "' .. pkg_name .. '"', + cb = utils.handlePiolib, + }, + { + cmd = 'pio run -t compiledb', + cb = utils.handleDb, + }, + }) + -- utils.ToggleTerminal(command, 'float') + -- vim.defer_fn(function() + -- vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) + -- piolsp.gitignore_lsp_configs('compile_commands.json') + -- piolsp.lsp_restart('clangd') + -- end, 900) + -- local command = 'pio pkg install --library "' .. pkg_name .. '" && exit && echo "done"' - -- utils.ToggleTerminal(command, 'float', function() - -- -- require('platformio.piolsp').piolsp() - -- piolsp() - -- end) - -- utils.ToggleTerminal(command, 'float', piolsp) - end) - return true - end, + -- utils.ToggleTerminal(command, 'float', function() + -- -- require('platformio.piolsp').piolsp() + -- piolsp() + -- end) + -- utils.ToggleTerminal(command, 'float', piolsp) + end) + return true + end, - previewer = previewers.new_buffer_previewer({ - title = 'Package Info', - define_preview = function(self, entry, _) - local json = utils.strsplit(vim.inspect(entry['value']['data']), '\n') - local bufnr = self.state.bufnr - vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) - vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function - vim.defer_fn(function() - local win = self.state.winid - vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) - vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) - vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) - end, 0) - end, - }), - sorter = conf.generic_sorter(opts), - }) - :find() + previewer = previewers.new_buffer_previewer({ + title = 'Package Info', + define_preview = function(self, entry, _) + local json = utils.strsplit(vim.inspect(entry['value']['data']), '\n') + local bufnr = self.state.bufnr + vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) + vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function + vim.defer_fn(function() + local win = self.state.winid + vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) + vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) + vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) + end, 0) + end, + }), + sorter = conf.generic_sorter(opts), + }):find() end function M.piolib(lib_arg_list) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index a7e6aa24..f609bed8 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -81,12 +81,11 @@ end function M.handlePioinit() vim.notify('Pioinit: Success', vim.log.levels.INFO) boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') - - -- print('Generating compile_commands.json...') - -- local output = vim.fn.system('pio run -t compiledb') - -- if vim.v.shell_error ~= 0 then - -- vim.notify('PIO Error: fail to generate compiledb' .. output, vim.log.levels.ERROR) - -- end +end +-- Handle after poioinit execution +-- stylua: ignore +function M.handlePiolib() + vim.notify('Piolib: Success', vim.log.levels.INFO) end -- INFO: endDispatcher ------------------------------------------------------ From 524cdf58f2ebdab9773eab8089eed5766f6aee96 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 18:03:26 +0300 Subject: [PATCH 0458/1406] update --- lua/platformio/boilerplate.lua | 26 -- lua/platformio/init.lua | 2 +- .../{lspAttach.lua => llspAttach.lua} | 0 .../{lspClangd.lua => llspClangd.lua} | 2 +- .../{lspKeymaps.lua => llspKeymaps.lua} | 0 lua/platformio/lsp/attach.lua | 125 +++++++ lua/platformio/lsp/clangd.lua | 312 ++++++++++++++++++ lua/platformio/lsp/keymaps.lua | 136 ++++++++ 8 files changed, 575 insertions(+), 28 deletions(-) rename lua/platformio/{lspAttach.lua => llspAttach.lua} (100%) rename lua/platformio/{lspClangd.lua => llspClangd.lua} (96%) rename lua/platformio/{lspKeymaps.lua => llspKeymaps.lua} (100%) create mode 100644 lua/platformio/lsp/attach.lua create mode 100644 lua/platformio/lsp/clangd.lua create mode 100644 lua/platformio/lsp/keymaps.lua diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 9a6af102..84c784e6 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -62,31 +62,8 @@ env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) print(f"Toolchain Inclusion Status: {env.get('COMPILATIONDB_INCLUDE_TOOLCHAIN', 'Not Set')}") print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") ]], - -- content = [[ - -- Import("env") - -- # This must be done in a PRE script to affect the database generation - -- env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) - -- ]], } --- boilerplate['generate_compile_commands.py'] = { --- content = [[ --- # No 'import env' here! --- import subprocess --- from SCons.Script import COMMAND_LINE_TARGETS # Optional: for better IDE support --- --- # This line MUST be here for PIO to provide the environment --- Import("env") --- --- def regenerate_database(source, target, env): --- print("Regenerating...") --- subprocess.run(["pio", "run", "-t", "compiledb"]) --- --- # Use the 'env' object that was imported above --- env.AddPostAction("$BUILD_DIR/${PROGNAME}.elf", regenerate_database) --- ]], --- } - boilerplate['.clangd_cmd'] = { template = [[ clangd @@ -365,12 +342,9 @@ WhitespaceSensitiveMacros: - PP_STRINGIZE - STRINGIZE ... - ]], } --- local home = vim.env.HOME --- print(home) boilerplate['.clangd'] = { content = [[ CompileFlags: diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index 69686ec3..8b6b173a 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -185,7 +185,7 @@ function M.setup(user_config) if M.config.lspClangd.enabled == true then -- vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) - require('platformio.lspClangd') + require('platformio.lsp.clangd') end end diff --git a/lua/platformio/lspAttach.lua b/lua/platformio/llspAttach.lua similarity index 100% rename from lua/platformio/lspAttach.lua rename to lua/platformio/llspAttach.lua diff --git a/lua/platformio/lspClangd.lua b/lua/platformio/llspClangd.lua similarity index 96% rename from lua/platformio/lspClangd.lua rename to lua/platformio/llspClangd.lua index 2a943236..98804f97 100644 --- a/lua/platformio/lspClangd.lua +++ b/lua/platformio/llspClangd.lua @@ -307,6 +307,6 @@ end local config = require('platformio').config if config.lspClangd.attach.enabled then - require('platformio.lspAttach') + require('platformio.lsp.attach') end ---------------------------------------------------------------------------------- diff --git a/lua/platformio/lspKeymaps.lua b/lua/platformio/llspKeymaps.lua similarity index 100% rename from lua/platformio/lspKeymaps.lua rename to lua/platformio/llspKeymaps.lua diff --git a/lua/platformio/lsp/attach.lua b/lua/platformio/lsp/attach.lua new file mode 100644 index 00000000..7d21e24c --- /dev/null +++ b/lua/platformio/lsp/attach.lua @@ -0,0 +1,125 @@ +-- local piolsp = require('platformio.piolsp') --.piolsp +-- INFO: LspAttach autocommand start +vim.api.nvim_create_autocmd('LspAttach', { + group = vim.api.nvim_create_augroup('platformio-lsp-attach', { clear = true }), + callback = function(args) + local client = assert(vim.lsp.get_client_by_id(args.data.client_id)) + local bufnr = args.buf + + if client then + vim.api.nvim_echo({ { 'Attaching ' .. client.name .. ' to buffer ' .. bufnr, 'Info' } }, true, {}) + + ------------------------------------------------------------------ + if client.name == 'clangd' then + vim.api.nvim_buf_create_user_command(0, 'LspClangdSwitchSourceHeader', function() + local method_name = 'textDocument/switchSourceHeader' + local params = vim.lsp.util.make_text_document_params(bufnr) + client.request(method_name, params, function(err, result) + if err then + error(tostring(err)) + end + if not result then + vim.notify('corresponding file cannot be determined') + return + end + vim.cmd.edit(vim.uri_to_fname(result)) + end, bufnr) + end, { desc = 'Switch between source/header' }) + -- piolsp.fix_pio_compile_commands() + end + + -- use lsp completion if no blink + local ok, _ = pcall(require, 'blink.cmp') + if not ok then + if client:supports_method('textDocument/completion') then + vim.opt.completeopt = { 'menu', 'menuone', 'noselect', 'noinsert', 'fuzzy', 'popup' } + + -- Enable native completion for this specific client and buffer + vim.lsp.completion.enable(true, client.id, args.buf, { autotrigger = true }) + vim.keymap.set('i', ' End LspAttach autocommand diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua new file mode 100644 index 00000000..98804f97 --- /dev/null +++ b/lua/platformio/lsp/clangd.lua @@ -0,0 +1,312 @@ +---------------------------------------------------------------------------------------- +-- INFO: create clangd required files +----------------------------------------------------------------------------------------- +local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) + +boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) +-- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) +-- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') + +boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + +boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) + +boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) +-- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) +-- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) +--------------------------------------------------------------------------------- + +local ok, result +ok, result = pcall(require, 'fidget') +if ok then + result.setup({}) +end + +----------------------------------------------------------------------------------------- +ok, result = pcall(require, 'trouble') +if ok then + result.setup({}) +end + +---------------------------------------------------------------------------------------- +-- INFO: setup and install mason packages +----------------------------------------------------------------------------------------- +ok, result = pcall(require, 'mason') +if ok then + result.setup({ + PATH = 'append', + ui = { + border = 'single', + icons = { + package_installed = '✓', + package_pending = '➜', + package_uninstalled = '✗', + }, + }, + }) +end + +-- List of packages you want Mason to ensure are installed +local ensure_installed = { + -- 'clang-format', embeded in clangd + -- 'stylua', +} +-- call mason-registry function to install or ensure formatters/linters are installed +local mr = require('mason-registry') +mr.refresh(function() + for _, tool in ipairs(ensure_installed) do + ok, result = pcall(mr.get_package, tool) + if ok and result then + if not result:is_installed() then + if not result:is_installing() then + result:install({}, function(success, _) + if not success then + vim.defer_fn(function() + vim.notify(tool .. ' failed to install', vim.log.levels.ERROR) + end, 0) + end + end) + else + vim.defer_fn(function() + vim.notify(tool .. ' already installed', vim.log.levels.WARN) + end, 0) + end + end + else + vim.defer_fn(function() + vim.notify('Failed to get package: ' .. tool, vim.log.levels.WARN) + end, 0) + end + end +end) + +---------------------------------------------------------------------------------------- +-- INFO: install clangd using mason-lspconfig +----------------------------------------------------------------------------------------- +local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') +if mok then + mason_lspconfig.setup({ + -- ensure_installed = { 'clangd', 'pyrefly' }, + -- ensure_installed = { 'ccls', 'lua_ls', 'pyrefly', 'yamlls' }, + ensure_installed = { 'clangd', 'lua_ls', 'pyrefly', 'yamlls' }, + automatic_enable = true, -- this will automatically enable LSP servers after lsp.config + }) +end + +local capabilities = vim.lsp.protocol.make_client_capabilities({ + textDocument = { + -- Folding capabilities for nvim-ufo + foldingRange = { + dynamicRegistration = false, + lineFoldingOnly = true, + }, + }, +}) +local bok, blink = pcall(require, 'blink.cmp') +if bok then + -- capabilities = vim.tbl_deep_extend('force', capabilities, blink.get_lsp_capabilities({}, false)) + capabilities = blink.get_lsp_capabilities(capabilities) +end + +-- INFO: 1 +vim.lsp.config('*', { + capabilities = capabilities, + root_markers = { '.git' }, + workspace_required = false, +}) + +---------------------------------------------------------------------------------------- +-- INFO: configure ccls lsp server +----------------------------------------------------------------------------------------- +-- vim.lsp.config('ccls', { +-- filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, +-- root_markers = { +-- 'CMakeLists.txt', +-- '.clangd', +-- '.clang-tidy', +-- '.clang-format', +-- 'compile_commands.json', +-- 'compile_flags.txt', +-- 'configure.ac', +-- '.git', +-- vim.uv.cwd(), +-- }, +-- init_options = { +-- diagnostics = { +-- onChange = 100, +-- }, +-- }, +-- }) +-- vim.lsp.enable('ccls') + +---------------------------------------------------------------------------------------- +-- INFO: configure clangd lsp server +----------------------------------------------------------------------------------------- +local cmd = { 'clangd' } +local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) +-- if vim.fn.filereadable(fname) == 1 then +if vim.uv.fs_stat(fname) then + ok, result = pcall(vim.fn.readfile, fname) + if ok then + cmd = result + -- print(vim.inspect(cmd)) + end +end + +local clangd = { + cmd = cmd, + filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, + root_markers = { + 'CMakeLists.txt', + '.clangd', + '.clang-tidy', + '.clang-format', + 'compile_commands.json', + 'compile_flags.txt', + 'configure.ac', + '.git', + vim.uv.cwd(), + }, + workspace_required = true, + single_file_support = true, + init_options = { + usePlaceholders = true, + completeUnimported = true, + fallback_flags = { '-std=c++17' }, + clangdFileStatus = true, + compilationDatabasePath = vim.fn.getcwd(), + }, +} +vim.lsp.config('clangd', clangd) + +---------------------------------------------------------------------------------------- +-- INFO: configure clangd lsp server +----------------------------------------------------------------------------------------- +local lua_ls = { + cmd = { 'lua-language-server' }, + filetypes = { 'lua' }, + root_markers = { + '.luarc.json', + '.luarc.jsonc', + '.luacheckrc', + '.stylua.toml', + 'selene.toml', + 'selene.yml', + '.git', + }, + settings = { + Lua = { + hint = { + enable = true, + arrayIndex = 'Enable', + await = true, + paramName = 'All', + paramType = true, + semicolon = 'Disable', + setType = true, + }, + telemetry = { enable = false }, + diagnostics = { globals = { 'vim' } }, + runtime = { + -- Specify LuaJIT for Neovim + version = 'LuaJIT', + -- Include Neovim runtime files + path = vim.split(package.path, ';'), + }, + workspace = { + checkThirdParty = false, + library = { + vim.env.VIMRUNTIME, + '${3rd}/luv/library', + './lua', + vim.api.nvim_get_runtime_file('', true), + -- Depending on the usage, you might want to add additional paths here. + -- "${3rd}/busted/library", + }, + }, + }, + }, +} +vim.lsp.config('lua_ls', lua_ls) + +local yamlls = { + -- on_attach = opts.on_attach, + cmd = { 'yaml-language-server', '--stdio' }, + filetypes = { 'yaml', 'yaml.docker-compose', 'yaml.gitlab' }, + settings = { + yaml = { + hover = true, + validate = false, + completion = true, + keyOrdering = false, + format = { enabled = false }, + redhat = { + telemetry = { enabled = false }, + }, + schemaStore = { + enable = true, + url = 'https://www.schemastore.org/api/json/catalog.json', + }, + schemas = { + kubernetes = '*.yaml', + ['http://json.schemastore.org/github-workflow'] = '.github/workflows/*', + ['http://json.schemastore.org/github-action'] = '.github/action.{yml,yaml}', + ['https://raw.githubusercontent.com/microsoft/azure-pipelines-vscode/master/service-schema.json'] = 'azure-pipelines.yml', + ['http://json.schemastore.org/ansible-stable-2.9'] = 'roles/tasks/*.{yml,yaml}', + ['http://json.schemastore.org/prettierrc'] = '.prettierrc.{yml,yaml}', + ['http://json.schemastore.org/kustomization'] = 'kustomization.{yml,yaml}', + ['http://json.schemastore.org/ansible-playbook'] = '*play*.{yml,yaml}', + ['http://json.schemastore.org/chart'] = 'Chart.{yml,yaml}', + ['https://json.schemastore.org/dependabot-v2'] = '.github/dependabot.{yml,yaml}', + ['https://gitlab.com/gitlab-org/gitlab/-/raw/master/app/assets/javascripts/editor/schema/ci.json'] = '*gitlab-ci*.{yml,yaml}', + ['https://raw.githubusercontent.com/OAI/OpenAPI-Specification/main/schemas/v3.1/schema.json'] = '*api*.{yml,yaml}', + ['https://raw.githubusercontent.com/compose-spec/compose-spec/master/schema/compose-spec.json'] = '*docker-compose*.{yml,yaml}', + ['https://raw.githubusercontent.com/argoproj/argo-workflows/master/api/jsonschema/schema.json'] = '*flow*.{yml,yaml}', + ['https://raw.githubusercontent.com/yannh/kubernetes-json-schema/refs/heads/master/v1.32.1-standalone-strict/all.json'] = '/*.k8s.yaml', + }, + }, + }, +} +vim.lsp.config('yamlls', yamlls) + +-- local stylua = { +-- cmd = { 'stylua', '--search-parent-directories', '--stdin-filepath', '$FILENAME', '-' }, +-- filetypes = { 'lua' }, +-- root_markers = { 'stylua.toml', '.stylua.toml', '.git' }, +-- } +-- vim.lsp.config('stylua', stylua) +-- vim.lsp.enable('stylua') + +local pyrefly = { + name = 'pyrefly', + cmd = { 'pyrefly', 'lsp' }, + filetypes = { 'python' }, + root_markers = { 'pyrefly.toml', 'pyproject.toml', 'setup.py', 'setup.cfg', 'requirements.txt', 'Pipfile', '.git' }, + settings = { + python = { + pyrefly = { + displayTypeErrors = 'force-on', + }, + -- pythonPath = vim.env.VIRTUAL_ENV, + venvPath = vim.env.VIRTUAL_ENV, + }, + }, +} +vim.lsp.config('pyrefly', pyrefly) + +-- require('platformio.piolsp').piolsp() +if vim.fn.has('nvim-0.12') then + if #vim.lsp.get_clients() > 0 then + vim.cmd('lsp restart') + end +else + vim.cmd('LspRestart') +end + +local config = require('platformio').config +if config.lspClangd.attach.enabled then + require('platformio.lsp.attach') +end +---------------------------------------------------------------------------------- diff --git a/lua/platformio/lsp/keymaps.lua b/lua/platformio/lsp/keymaps.lua new file mode 100644 index 00000000..cb58c3ba --- /dev/null +++ b/lua/platformio/lsp/keymaps.lua @@ -0,0 +1,136 @@ +local K = {} +--Lua functions in combination with the option expr = true handles keycodes automatically +function K.lspKeymaps(client, bufnr) + local bufkeymap = function(mode, lhs, rhs, desc) + vim.keymap.set(mode, lhs, rhs, { buffer = bufnr, silent = true, desc = desc }) -- noremap by default + end + -- Disable defaults + pcall(vim.keymap.del, 'n', 'gra') + pcall(vim.keymap.del, 'n', 'gri') + pcall(vim.keymap.del, 'n', 'grn') + pcall(vim.keymap.del, 'n', 'grr') + pcall(vim.keymap.del, 'n', 'gO') + pcall(vim.keymap.del, 'n', 'K') + -- + -- Quickfix list + bufkeymap('n', '[q', vim.cmd.cprev, 'Previous quickfix item') + bufkeymap('n', ']q', vim.cmd.cnext, 'Next quickfix item') + + -- Diagnostic keymaps + bufkeymap('n', '[d', 'vim.diagnostic.goto_prev()', 'Go to previous [d]iagnostic message') + bufkeymap('n', ']d', 'vim.diagnostic.goto_next()', 'Go to next [d]iagnostic message') + bufkeymap('n', 'gle', vim.diagnostic.open_float, 'Show diagnostic [e]rror messages') + -- bufkeymap('n', 'gle', 'Telescope diagnostics', 'Show diagnostic [e]rror messages') + bufkeymap('n', 'glq', vim.diagnostic.setloclist, 'Open diagnostic [q]uickfix list') + -- + -- stylua: ignore start + -- << local trouble = require("trouble").toggle + -- << bufkeymap('n', "tt", function() trouble() end, "Toggle Trouble") + -- << bufkeymap('n', "tq", function() trouble("quickfix") end, "Quickfix List") + -- << bufkeymap('n', "dr", function() trouble("lsp_references") end, "References") + -- << bufkeymap('n', "dd", function() trouble("document_diagnostics") end, "Document Diagnostics") + -- << bufkeymap('n', "dw", function() trouble("workspace_diagnostics") end, "Workspace Diagnostics") + -- stylua: ignore end + -- + if client.server_capabilities.hoverProvider then + bufkeymap('n', 'glk', vim.lsp.buf.hover, 'Hover Documentation') + end + if client.server_capabilities.signatureHelpProvider then + bufkeymap({ 'i', 'n' }, 'gls', vim.lsp.buf.signature_help, 'Show signature') + end + if client.server_capabilities.declarationProvider then + bufkeymap('n', 'glD', vim.lsp.buf.declaration, 'Goto [D]eclaration') + end + if client.server_capabilities.definitionProvider then + bufkeymap('n', 'gld', vim.lsp.buf.definition, 'Go to [d]efinition') + -- bufkeymap('n', 'gld', 'Telescope lsp_definitions', '[G]oto [D]efinition') + end + if client.server_capabilities.typeDefinitionProvider then + bufkeymap('n', 'glt', vim.lsp.buf.type_definition, 'Goto [t]ype definition') + -- bufkeymap('n', 'glt', 'Telescope lsp_type_definitions', 'Goto [t]ype definition') + end + if client.server_capabilities.implementationProvider then + bufkeymap('n', 'gli', vim.lsp.buf.implementation, 'Goto [i]mplementation') + -- bufkeymap('n', 'gli', 'Telescope lsp_implementations', 'Goto [i]mplementation') + end + + -- bufkeymap('n', 'glr', '(CodeAction, implementation, rename, references)', 'CodeAction, implementation, rename, references') + if client.server_capabilities.referencesProvider then + -- bufkeymap('n', 'gr', vim.lsp.buf.references, 'List references') + bufkeymap('n', 'glr', 'Telescope lsp_references', 'Goto [r]eferences') + -- bufkeymap('n', 'glr', 'Telescope lsp_references', '[G]oto [R]eferences') + end + if client.server_capabilities.renameProvider then + -- bufkeymap('n', '', vim.lsp.buf.rename, 'Rename symbol') + bufkeymap('n', 'glR', vim.lsp.buf.rename, '[R]ename') + end + if client.server_capabilities.codeActionProvider then + bufkeymap('n', 'gla', vim.lsp.buf.code_action, 'Code [a]ction') + end + + if client.server_capabilities.documentSymbolProvider then + bufkeymap('n', 'glwd', vim.lsp.buf.document_symbol, '[D]ocument symbols') + -- bufkeymap('n', 'glwd', Telescope lsp_document_symbols, '[D]ocument [S]ymbols') + end + if client:supports_method('workspace/symbol') then + -- if client.server_capabilities.workspaceSymbolProvider then + bufkeymap('n', 'glww', vim.lsp.buf.workspace_symbol, 'List [w]orkspace symbols') + -- bufkeymap('n', 'glww', require('telescope.builtin').lsp_dynamic_workspace_symbols, '[W]orkspace [S]ymbols') + end + if client.server_capabilities.workspace then + bufkeymap('n', 'glwa', vim.lsp.buf.add_workspace_folder, 'Workspace [a]dd folder') + bufkeymap('n', 'glwr', vim.lsp.buf.remove_workspace_folder, 'Workspace [r]emove folder') + bufkeymap('n', 'glwl', function() + print(vim.inspect(vim.lsp.buf.list_workspace_folders())) + end, '[W]orkspace [L]ist folders') + end + -- + if client:supports_method('textDocument/switchSourceHeader') then + bufkeymap('n', 'glws', 'LspClangdSwitchSourceHeader', '[S]witch Source/Header (C/C++)') + end + + if client:supports_method('textDocument/formatting') then + -- if client.server_capabilities.documentFormattingProvider then + bufkeymap({ 'n', 'x' }, 'glf', function() + vim.lsp.buf.format({ bufnr = bufnr, async = true }) + -- require('conform').format({ bufnr = bufnr, async = true }) + end, '[f]ormat buffer') + + -- LSP format the current buffer on save + local fmt_group = vim.api.nvim_create_augroup('autoformat_cmds', { clear = true }) + vim.api.nvim_create_autocmd('BufWritePre', { + buffer = bufnr, + group = fmt_group, + desc = 'Fromat current buffer', + callback = function(args) + -- if (client.name == 'lua_ls') and (vim.fn.executable('stylua') == 1) then + -- -- if (client.name == 'stylua') and (vim.fn.executable('stylua') == 1) then + -- -- vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(bufnr) }) + -- vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(args.buf) }) + -- vim.cmd('checktime') + -- print('stylua formatting') + -- else + vim.lsp.buf.format({ + bufnr = bufnr, + async = false, + timeout_ms = 10000, + id = client.id, + filter = function(c) + return c.id == client.id + end, + }) + print('lsp formatting') + -- end + end, + }) + end + -- + if client.server_capabilities.inlayHintProvider and vim.lsp.inlay_hint then + bufkeymap('n', 'glh', function() + vim.lsp.inlay_hint.enable(not vim.lsp.inlay_hint.is_enabled({ bufnr = bufnr }), { bufnr = bufnr }) + end, '[h]ints toggle') + ------------------------------------------------------------------------------ + end +end + +return K From 2a8ea3ecc5a40d7075cb89a2d09cdc090b0a529f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 18:11:51 +0300 Subject: [PATCH 0459/1406] update --- lua/platformio/lsp/attach.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lsp/attach.lua b/lua/platformio/lsp/attach.lua index 7d21e24c..3f7df327 100644 --- a/lua/platformio/lsp/attach.lua +++ b/lua/platformio/lsp/attach.lua @@ -85,7 +85,7 @@ vim.api.nvim_create_autocmd('LspAttach', { ------------------------------------------------------------------ local config = require('platformio').config if config.lspClangd.attach.keymaps then - local lspkeymaps = require('platformio.lspKeymaps') + local lspkeymaps = require('platformio.lsp.keymaps') lspkeymaps.lspKeymaps(client, bufnr) end end From 9de2eb471792b9fd057d6b00caaed2b3e7e00087 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 18:47:48 +0300 Subject: [PATCH 0460/1406] update --- lua/platformio/boilerplate.lua | 1 + lua/platformio/piolsp.lua | 103 +++++++-------------------------- 2 files changed, 23 insertions(+), 81 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 84c784e6..f6e66fe2 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -86,6 +86,7 @@ clangd --query-driver=**/*riscv32-esp-elf-*,**/*gcc*,**/*g++* ]], content = function(self) + localjjjj return string.format(self.template, vim.env.HOME) end, --query-driver=%s/.platformio/packages/*/bin/riscv32-esp-elf-* diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 194464b2..c3c9f4e7 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -33,9 +33,7 @@ function M.get_pio_dir(type) local result = raw_val or os.getenv(target_config.env) or (core_dir .. target_config.sub) -- 5. Expand ${platformio.core_dir} - if result:find('${platformio.core_dir}', 1, true) then - result = result:gsub('%${platformio.core_dir}', core_dir) - end + if result:find('${platformio.core_dir}', 1, true) then result = result:gsub('%${platformio.core_dir}', core_dir) end -- 6. Normalize Slashes for Windows result = result:gsub('\\', '/'):gsub('//+', '/') @@ -43,73 +41,6 @@ function M.get_pio_dir(type) return result end --- stylua: ignore --- k --- function M.get_pio_dir(type) --- -- 1. Setup Base Paths --- local home = os.getenv('HOME') or os.getenv('USERPROFILE') --- local core_dir = os.getenv('PLATFORMIO_CORE_DIR') or (home .. '/.platformio') --- --- -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) --- local map = { --- packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, --- platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, --- } --- --- local target_config = map[type] --- if not target_config then return nil end --- --- -- 3. Try to get explicit value from platformio.ini --- local path = vim.fn.getcwd() .. '/platformio.ini' --- local inifile = io.open(path, 'r') --- local raw_val = nil --- --- if inifile then --- for line in inifile:lines() do --- -- Matches 'key = value', e.g., 'packages_dir = ...' --- raw_val = line:match('^%s*' .. target_config.ini .. '%s*=%s*([^;%s]+)') --- if raw_val then break end --- end --- inifile:close() --- end --- --- -- 4. Fallback Logic: INI -> Env Var -> Default --- local result = raw_val or os.getenv(target_config.env) or (core_dir .. target_config.sub) --- --- -- 5. Expand ${platformio.core_dir} --- result = result:gsub('%%${platformio.core_dir}', core_dir) --- --- -- 6. Normalize Slashes for Windows --- if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end --- --- return result --- end - - --- function M.get_pio_packages_dir() --- -- Run the pio command to dump config in JSON format --- local cmd = 'pio project config --json-output' --- local output = vim.fn.system(cmd) --- --- -- Check for errors in the command execution --- if vim.v.shell_error ~= 0 then --- print('Error running pio command: ' .. output) --- return nil --- end --- --- -- Decode the JSON output --- local ok, config = pcall(vim.json.decode, output) --- if not ok then --- print('Failed to decode JSON from PlatformIO') --- return nil --- end --- local packages_dir = nil --- if config and config.platformio then --- packages_dir = config.platformio.packages_dir --- end --- return packages_dir --- end - -- stylua: ignore function M.fix_pio_compile_commands() @@ -226,25 +157,35 @@ function M.lsp_restarti(name) end end --- stylua: ignore +--- stylua: ignore function M.lsp_restart(name) if vim.fn.has('nvim-0.12') == 1 then -- local clients = vim.lsp.get_clients({ name = name }) local clangd = vim.lsp.get_clients({ name = name })[1] if clangd then local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) - if not ok then vim.notify('LSP ' .. name .. ' restart failed: ' .. err) - else vim.notify('LSP ' .. name .. ' restarted' .. err) end + if not ok then + vim.notify('LSP ' .. name .. ' restart failed: ' .. err) + else + vim.notify('LSP ' .. name .. ' restarted' .. err) + end end else - local client_name = 'clangd' - local clients = vim.lsp.get_clients({ name = client_name }) - -- 1. Stop the specific client - for _, client in ipairs(clients) do client:stop() end - - -- 2. Reload all loaded buffers to trigger re-attachment for that client - -- (Note: 'checktime' is safer than 'bufdo edit' as it respects unsaved changes) - vim.cmd('checktime') + local clients = vim.lsp.get_clients({ name = name }) + for _, c in ipairs(clients) do + local configc = c.config + c:stop(true) + vim.defer_fn(function() + vim.lsp.config(name, configc) + vim.lsp.enable(name) + end, 600) + end + -- -- 1. Stop the specific client + -- for _, client in ipairs(clients) do client:stop() end + -- + -- -- 2. Reload all loaded buffers to trigger re-attachment for that client + -- -- (Note: 'checktime' is safer than 'bufdo edit' as it respects unsaved changes) + -- vim.cmd('checktime') end end From 3ab2b134d311e0cbb304dceacbebaf0bd094b578 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 18:53:57 +0300 Subject: [PATCH 0461/1406] update --- lua/platformio/piolsp.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index c3c9f4e7..a10a0dc7 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -176,8 +176,9 @@ function M.lsp_restart(name) local configc = c.config c:stop(true) vim.defer_fn(function() - vim.lsp.config(name, configc) + -- vim.lsp.config(name, configc) vim.lsp.enable(name) + vim.cmd('checktime') end, 600) end -- -- 1. Stop the specific client From ce789633a9175e705051c1a7fe7a6ac7d2191eca Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 19:00:28 +0300 Subject: [PATCH 0462/1406] update --- lua/platformio/boilerplate.lua | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index f6e66fe2..2d688bb5 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -83,16 +83,15 @@ clangd --pch-storage=memory --pretty --ranking-model=decision_forest ---query-driver=**/*riscv32-esp-elf-*,**/*gcc*,**/*g++* +--query-driver=%s/toolchain-*/**/bin/* ]], content = function(self) - localjjjj - return string.format(self.template, vim.env.HOME) + return string.format(self.template, require('platformio.piolsp').get_pio_dir('packages')) end, --query-driver=%s/.platformio/packages/*/bin/riscv32-esp-elf-* --query-driver=%s/.platformio/**/packages/toolchain-*/**/bin/* --query-driver = [[clangd --query-driver=]] .. vim.env.HOME .. [[/.platformio/packages/*]] - --query-driver=** + --query-driver=**/*riscv32-esp-elf-*,**/*gcc*,**/*g++* --query-driver=**/.platformio/packages/toolchain*/**/bin/*gcc* } From 412ca00aec55e59f46a9ac0b438d10b28b393ff3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 19:09:56 +0300 Subject: [PATCH 0463/1406] update --- lua/platformio/boilerplate.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 2d688bb5..833a1cd1 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -86,7 +86,8 @@ clangd --query-driver=%s/toolchain-*/**/bin/* ]], content = function(self) - return string.format(self.template, require('platformio.piolsp').get_pio_dir('packages')) + local packages = require('platformio.piolsp') + return string.format(self.template, packages().get_pio_dir('packages')) end, --query-driver=%s/.platformio/packages/*/bin/riscv32-esp-elf-* --query-driver=%s/.platformio/**/packages/toolchain-*/**/bin/* From 076f4c7ab3d5cb9c5c89516c99f269a61dc3a6a9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 19:40:32 +0300 Subject: [PATCH 0464/1406] update --- lua/platformio/boilerplate.lua | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 833a1cd1..562e5969 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -5,7 +5,6 @@ local boilerplate = {} --- stylua: ignore boilerplate['arduino'] = { - -- filename = 'main.cpp', content = [[ #include @@ -42,9 +41,6 @@ monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dt lib_ldf_mode = chain+ ;Library dependencies Finder ldf ]], - -- content = function() - -- return string.format(boilerplate['platformio.ini'].template, vim.env.PLATFORMIO_CORE_DIR) - -- end, content = function(self) return string.format(self.template, vim.env.PLATFORMIO_CORE_DIR) end, @@ -87,7 +83,7 @@ clangd ]], content = function(self) local packages = require('platformio.piolsp') - return string.format(self.template, packages().get_pio_dir('packages')) + return string.format(self.template, packages.get_pio_dir('packages')) end, --query-driver=%s/.platformio/packages/*/bin/riscv32-esp-elf-* --query-driver=%s/.platformio/**/packages/toolchain-*/**/bin/* From 638fc0102e0c19e20bdd454d046ff6ef0b29588b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 19:43:50 +0300 Subject: [PATCH 0465/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 562e5969..67f37602 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -83,7 +83,7 @@ clangd ]], content = function(self) local packages = require('platformio.piolsp') - return string.format(self.template, packages.get_pio_dir('packages')) + return string.format(self.template, packages.get_pio_dir('packages') or '**') end, --query-driver=%s/.platformio/packages/*/bin/riscv32-esp-elf-* --query-driver=%s/.platformio/**/packages/toolchain-*/**/bin/* From 232f8c50348a276dae853224c11911e7249548d8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 21:06:00 +0300 Subject: [PATCH 0466/1406] update --- lua/platformio/piolsp.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index a10a0dc7..ba2b3f33 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -59,7 +59,7 @@ function M.fix_pio_compile_commands() return end - -- print('PioFix0') + print('PioFix0') -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path local path_map = {} local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') @@ -74,7 +74,7 @@ function M.fix_pio_compile_commands() -- Extract filename (e.g., riscv32-esp-elf-gcc) local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = full_path - -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) + print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) end end From 595fe7e8e447cf78fc32358b27848a0651857ce3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 21:52:11 +0300 Subject: [PATCH 0467/1406] update --- lua/platformio/piolsp.lua | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index ba2b3f33..f32052fc 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -4,11 +4,10 @@ local M = {} function M.get_pio_dir(type) -- 1. Setup Base Paths local home = os.getenv('HOME') or os.getenv('USERPROFILE') - -- Ensure core_dir itself doesn't have trailing slashes for cleaner joins - local core_dir = (os.getenv('PLATFORMIO_CORE_DIR') or (home .. '/.platformio')):gsub('[\\/]+$', '') -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) local map = { + core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, } @@ -19,26 +18,31 @@ function M.get_pio_dir(type) -- 3. Try to get explicit value from platformio.ini local path = vim.fn.getcwd() .. '/platformio.ini' local inifile = io.open(path, 'r') - local raw_val = nil + local ini_val = nil + local core_val = nil if inifile then for line in inifile:lines() do - raw_val = line:match('^%s*' .. target_config.ini .. '%s*=%s*([^;%s]+)') - if raw_val then break end + if ~core_val then core_val = line:match('^%s*' .. map['core'].ini .. '%s*=%s*([^;%s]+)') end + if ~ini_val then ini_val = line:match('^%s*' .. target_config.ini .. '%s*=%s*([^;%s]+)') + if ini_val and core_val then break end end inifile:close() end + local core_dir = core_val or os.getenv('PLATFORMIO_CORE_DIR' or (home .. map['core'].sub)):gsub('[\\/]+$', '') + if type == 'core' then return core_val end -- 4. Fallback Logic: INI -> Env Var -> Default - local result = raw_val or os.getenv(target_config.env) or (core_dir .. target_config.sub) + local result = ini_val or os.getenv(target_config.env) or (core_dir .. target_config.sub) -- 5. Expand ${platformio.core_dir} if result:find('${platformio.core_dir}', 1, true) then result = result:gsub('%${platformio.core_dir}', core_dir) end -- 6. Normalize Slashes for Windows result = result:gsub('\\', '/'):gsub('//+', '/') - if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end + -- if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end + -- Ensure core_dir itself doesn't have trailing slashes for cleaner joins return result end From c44dbe304e1938b7f3e9756f2b0cef798c6d5b77 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 22:01:57 +0300 Subject: [PATCH 0468/1406] update --- lua/platformio/piolsp.lua | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index f32052fc..7507a0a8 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -23,16 +23,20 @@ function M.get_pio_dir(type) if inifile then for line in inifile:lines() do - if ~core_val then core_val = line:match('^%s*' .. map['core'].ini .. '%s*=%s*([^;%s]+)') end - if ~ini_val then ini_val = line:match('^%s*' .. target_config.ini .. '%s*=%s*([^;%s]+)') + if core_val ~= nil then core_val = line:match('^%s*' .. map['core'].ini .. '%s*=%s*([^;%s]+)') end + if ini_val ~= nil then ini_val = line:match('^%s*' .. target_config.ini .. '%s*=%s*([^;%s]+)') end if ini_val and core_val then break end end inifile:close() end + + -- 4.0 Fallback Logic: INI -> Env Var -> Default local core_dir = core_val or os.getenv('PLATFORMIO_CORE_DIR' or (home .. map['core'].sub)):gsub('[\\/]+$', '') - if type == 'core' then return core_val end + core_dir = core_dir:gsub('\\', '/'):gsub('//+', '/') + if vim.fn.has('win32') == 1 then core_dir = core_dir():gsub('/', '\\') end + if type == 'core' then return core_dir end - -- 4. Fallback Logic: INI -> Env Var -> Default + -- 4.1 Fallback Logic: INI -> Env Var -> Default local result = ini_val or os.getenv(target_config.env) or (core_dir .. target_config.sub) -- 5. Expand ${platformio.core_dir} @@ -40,7 +44,7 @@ function M.get_pio_dir(type) -- 6. Normalize Slashes for Windows result = result:gsub('\\', '/'):gsub('//+', '/') - -- if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end + if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end -- Ensure core_dir itself doesn't have trailing slashes for cleaner joins return result From 66bdf74b420f1d63b4b3b36395323a315e7c28a2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 22:05:38 +0300 Subject: [PATCH 0469/1406] update --- lua/platformio/piolsp.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 7507a0a8..4ee38f43 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -23,8 +23,8 @@ function M.get_pio_dir(type) if inifile then for line in inifile:lines() do - if core_val ~= nil then core_val = line:match('^%s*' .. map['core'].ini .. '%s*=%s*([^;%s]+)') end - if ini_val ~= nil then ini_val = line:match('^%s*' .. target_config.ini .. '%s*=%s*([^;%s]+)') end + if core_val == nil then core_val = line:match('^%s*' .. map['core'].ini .. '%s*=%s*([^;%s]+)') end + if ini_val == nil then ini_val = line:match('^%s*' .. target_config.ini .. '%s*=%s*([^;%s]+)') end if ini_val and core_val then break end end inifile:close() From 085a0370a8be2b574647e4249b344d5c0c78efcc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 22:10:12 +0300 Subject: [PATCH 0470/1406] update --- lua/platformio/piolsp.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index 4ee38f43..d224f631 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -33,7 +33,7 @@ function M.get_pio_dir(type) -- 4.0 Fallback Logic: INI -> Env Var -> Default local core_dir = core_val or os.getenv('PLATFORMIO_CORE_DIR' or (home .. map['core'].sub)):gsub('[\\/]+$', '') core_dir = core_dir:gsub('\\', '/'):gsub('//+', '/') - if vim.fn.has('win32') == 1 then core_dir = core_dir():gsub('/', '\\') end + if vim.fn.has('win32') == 1 then core_dir = core_dir:gsub('/', '\\') end if type == 'core' then return core_dir end -- 4.1 Fallback Logic: INI -> Env Var -> Default From 28bb8e322e10eb95546b18d2d2cc14a0e0566d05 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 22:19:06 +0300 Subject: [PATCH 0471/1406] update --- lua/platformio/piolsp.lua | 4 ++-- mini_nvimPlatformio.lua | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index d224f631..911e4a53 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -33,7 +33,7 @@ function M.get_pio_dir(type) -- 4.0 Fallback Logic: INI -> Env Var -> Default local core_dir = core_val or os.getenv('PLATFORMIO_CORE_DIR' or (home .. map['core'].sub)):gsub('[\\/]+$', '') core_dir = core_dir:gsub('\\', '/'):gsub('//+', '/') - if vim.fn.has('win32') == 1 then core_dir = core_dir:gsub('/', '\\') end + -- if vim.fn.has('win32') == 1 then core_dir = core_dir:gsub('/', '\\') end if type == 'core' then return core_dir end -- 4.1 Fallback Logic: INI -> Env Var -> Default @@ -44,7 +44,7 @@ function M.get_pio_dir(type) -- 6. Normalize Slashes for Windows result = result:gsub('\\', '/'):gsub('//+', '/') - if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end + -- if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end -- Ensure core_dir itself doesn't have trailing slashes for cleaner joins return result diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 144519f1..ab08d93f 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -317,11 +317,11 @@ vim.api.nvim_create_autocmd('User', { -- INFO: set up python nvim venv (virtual environment 'nenv'), activaten. local platformio_core_dir, pynvim_env, pynvim_python, pynvim_lib, pynvim_bin, pynvim_activate if isWindows then - platformio_core_dir = vim.env.HOME .. '\\.platformio' - pynvim_env = platformio_core_dir .. '\\nenv' - pynvim_bin = pynvim_env .. '\\Scripts' - pynvim_python = pynvim_bin .. '\\python.exe' - pynvim_activate = pynvim_bin .. '\\Activate.ps1' + platformio_core_dir = vim.env.HOME .. '/.platformio' + pynvim_env = platformio_core_dir .. '/nenv' + pynvim_bin = pynvim_env .. '/Scripts' + pynvim_python = pynvim_bin .. '/python.exe' + pynvim_activate = pynvim_bin .. '/Activate.ps1' else platformio_core_dir = vim.env.HOME .. '/.platformio' pynvim_env = platformio_core_dir .. '/nenv' From 6c23a0cce02c6826e4b65f51d7209bd111d8c673 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 9 Apr 2026 23:09:23 +0300 Subject: [PATCH 0472/1406] update --- lua/platformio/boilerplate.lua | 6 +- lua/platformio/lpiolsp.lua | 209 +++++++++ lua/platformio/lsp/piolsp.lua | 76 ++++ lua/platformio/pioinit.lua | 11 +- lua/platformio/piolib.lua | 9 +- lua/platformio/utils.lua | 160 +++---- lua/platformio/utils/misc.lua | 0 lua/platformio/{piolsp.lua => utils/pio.lua} | 426 ++++++++++--------- plugin/platformio.lua | 13 +- 9 files changed, 606 insertions(+), 304 deletions(-) create mode 100644 lua/platformio/lpiolsp.lua create mode 100644 lua/platformio/lsp/piolsp.lua create mode 100644 lua/platformio/utils/misc.lua rename lua/platformio/{piolsp.lua => utils/pio.lua} (64%) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 67f37602..8a16f2c3 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -1,3 +1,4 @@ +local pio = require('platformio.utils.pio') local M = {} local uv = vim.loop @@ -42,7 +43,7 @@ monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dt lib_ldf_mode = chain+ ;Library dependencies Finder ldf ]], content = function(self) - return string.format(self.template, vim.env.PLATFORMIO_CORE_DIR) + return string.format(self.template, pio.get_pio_dir('core')) end, } @@ -82,8 +83,7 @@ clangd --query-driver=%s/toolchain-*/**/bin/* ]], content = function(self) - local packages = require('platformio.piolsp') - return string.format(self.template, packages.get_pio_dir('packages') or '**') + return string.format(self.template, pio.get_pio_dir('packages') or '**') end, --query-driver=%s/.platformio/packages/*/bin/riscv32-esp-elf-* --query-driver=%s/.platformio/**/packages/toolchain-*/**/bin/* diff --git a/lua/platformio/lpiolsp.lua b/lua/platformio/lpiolsp.lua new file mode 100644 index 00000000..bbe0c470 --- /dev/null +++ b/lua/platformio/lpiolsp.lua @@ -0,0 +1,209 @@ +local M = {} + +-- -- stylua: ignore +-- function M.get_pio_dir(type) +-- -- 1. Setup Base Paths +-- local home = os.getenv('HOME') or os.getenv('USERPROFILE') +-- +-- -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) +-- local map = { +-- core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, +-- packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, +-- platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, +-- } +-- +-- local target_config = map[type] +-- if not target_config then return nil end +-- +-- -- 3. Try to get explicit value from platformio.ini +-- local path = vim.fn.getcwd() .. '/platformio.ini' +-- local inifile = io.open(path, 'r') +-- local ini_val = nil +-- local core_val = nil +-- +-- if inifile then +-- for line in inifile:lines() do +-- if core_val == nil then core_val = line:match('^%s*' .. map['core'].ini .. '%s*=%s*([^;%s]+)') end +-- if ini_val == nil then ini_val = line:match('^%s*' .. target_config.ini .. '%s*=%s*([^;%s]+)') end +-- if ini_val and core_val then break end +-- end +-- inifile:close() +-- end +-- +-- -- 4.0 Fallback Logic: INI -> Env Var -> Default +-- local core_dir = core_val or os.getenv('PLATFORMIO_CORE_DIR' or (home .. map['core'].sub)):gsub('[\\/]+$', '') +-- core_dir = core_dir:gsub('\\', '/'):gsub('//+', '/') +-- -- if vim.fn.has('win32') == 1 then core_dir = core_dir:gsub('/', '\\') end +-- if type == 'core' then return core_dir end +-- +-- -- 4.1 Fallback Logic: INI -> Env Var -> Default +-- local result = ini_val or os.getenv(target_config.env) or (core_dir .. target_config.sub) +-- +-- -- 5. Expand ${platformio.core_dir} +-- if result:find('${platformio.core_dir}', 1, true) then result = result:gsub('%${platformio.core_dir}', core_dir) end +-- +-- -- 6. Normalize Slashes for Windows +-- result = result:gsub('\\', '/'):gsub('//+', '/') +-- -- if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end +-- +-- -- Ensure core_dir itself doesn't have trailing slashes for cleaner joins +-- return result +-- end +-- +-- -- stylua: ignore +-- function M.fix_pio_compile_commands() +-- local filename = vim.fn.getcwd() .. '/compile_commands.json' +-- local file = io.open(filename, 'r') +-- if not file then return end +-- +-- local content = file:read('*a') +-- file:close() +-- if not content or content == '' then return end +-- +-- -- Safe JSON decoding +-- local ok, data = pcall(vim.json.decode, content) +-- if not ok or type(data) ~= 'table' then +-- vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) +-- return +-- end +-- +-- print('PioFix0') +-- -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path +-- local path_map = {} +-- local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') +-- if pio_home then +-- +-- -- Recursively find all binaries in PIO packages +-- local pio_packages = M.get_pio_dir('packages') .. '/*/bin/*' +-- +-- local found_binaries = vim.fn.glob(pio_packages, false, true) +-- +-- for _, full_path in ipairs(found_binaries) do +-- -- Extract filename (e.g., riscv32-esp-elf-gcc) +-- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') +-- path_map[name] = full_path +-- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) +-- end +-- end +-- +-- -- PHASE 2: Update JSON using the Map +-- local modified = 0 +-- for _, entry in ipairs(data) do +-- if type(entry.command) == 'string' then +-- local cmd_parts = vim.split(entry.command, ' ') +-- local first_token = cmd_parts[1] +-- +-- if first_token then +-- -- Check if it's already a short name (not an absolute path) +-- local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') +-- +-- if not is_abs then +-- local short_name = first_token:gsub('%.exe$', '') +-- -- print('PioFix2: short_name=' .. short_name) +-- -- Direct Query: Does this name exist in our discovered list? +-- if path_map[short_name] then +-- cmd_parts[1] = path_map[short_name] +-- -- print('PioFix3: full_name=' .. cmd_parts[1]) +-- entry.command = table.concat(cmd_parts, ' ') +-- modified = modified + 1 +-- end +-- end +-- end +-- end +-- end +-- +-- -- PHASE 3: Save and Refresh +-- -- Safe JSON encoding +-- if modified > 0 then +-- local out_file = io.open(filename, 'w') +-- if out_file then +-- local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) +-- if encode_ok and json_str then +-- -- 1. Format the string using python's json.tool +-- -- The second argument to vim.fn.system() is the "stdin" passed to the command +-- local formatted_json = vim.fn.system('python -m json.tool', json_str) +-- +-- -- out_file:write(json_str) +-- out_file:write(formatted_json) +-- out_file:close() +-- vim.notify('compiledb: fixed', vim.log.levels.INFO) +-- M.lsp_restart('clangd') +-- end +-- end +-- end +-- end + +function M.gitignore_lsp_configs(config_file) + local gitignore_path = vim.fs.joinpath(vim.g.platformioRootDir, '.gitignore') + local file = io.open(gitignore_path, 'r') + local pattern = '^%s*' .. vim.pesc(config_file) .. '%s*$' + + if file then + for line in file:lines() do + if line:match(pattern) then + file:close() + return + end + end + file:close() + end + + file = io.open(gitignore_path, 'a') + if file then + file:write(config_file .. '\n') + file:close() + end +end + +-- stylua: ignore +function M.lsp_restarti(name) + local clients = vim.lsp.get_clients({ name = name }) + for _, c in ipairs(clients) do + local configc = c.config + c:stop(true) + vim.defer_fn(function() vim.lsp.config(name, configc) vim.lsp.enable(name) end, 600) + end +end + +--- stylua: ignore +function M.lsp_restart(name) + if vim.fn.has('nvim-0.12') == 1 then + -- local clients = vim.lsp.get_clients({ name = name }) + local clangd = vim.lsp.get_clients({ name = name })[1] + if clangd then + local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) + if not ok then + vim.notify('LSP ' .. name .. ' restart failed: ' .. err) + else + vim.notify('LSP ' .. name .. ' restarted' .. err) + end + end + else + local clients = vim.lsp.get_clients({ name = name }) + for _, c in ipairs(clients) do + local configc = c.config + c:stop(true) + vim.defer_fn(function() + -- vim.lsp.config(name, configc) + vim.lsp.enable(name) + vim.cmd('checktime') + end, 600) + end + -- -- 1. Stop the specific client + -- for _, client in ipairs(clients) do client:stop() end + -- + -- -- 2. Reload all loaded buffers to trigger re-attachment for that client + -- -- (Note: 'checktime' is safer than 'bufdo edit' as it respects unsaved changes) + -- vim.cmd('checktime') + end +end + +-- stylua: ignore +function M.piolsp() + local ok, err = pcall(vim.cmd.lsp, { args = { 'restart' } }) + if ok then vim.notify('LSP restarted' .. err) + else vim.notify('LSP restart failed: ' .. err) end + -- M.fix_pio_compile_commands() +end + +return M diff --git a/lua/platformio/lsp/piolsp.lua b/lua/platformio/lsp/piolsp.lua new file mode 100644 index 00000000..51c395a1 --- /dev/null +++ b/lua/platformio/lsp/piolsp.lua @@ -0,0 +1,76 @@ +local M = {} + +function M.gitignore_lsp_configs(config_file) + local gitignore_path = vim.fs.joinpath(vim.g.platformioRootDir, '.gitignore') + local file = io.open(gitignore_path, 'r') + local pattern = '^%s*' .. vim.pesc(config_file) .. '%s*$' + + if file then + for line in file:lines() do + if line:match(pattern) then + file:close() + return + end + end + file:close() + end + + file = io.open(gitignore_path, 'a') + if file then + file:write(config_file .. '\n') + file:close() + end +end + +-- stylua: ignore +function M.lsp_restarti(name) + local clients = vim.lsp.get_clients({ name = name }) + for _, c in ipairs(clients) do + local configc = c.config + c:stop(true) + vim.defer_fn(function() vim.lsp.config(name, configc) vim.lsp.enable(name) end, 600) + end +end + +--- stylua: ignore +function M.lsp_restart(name) + if vim.fn.has('nvim-0.12') == 1 then + -- local clients = vim.lsp.get_clients({ name = name }) + local clangd = vim.lsp.get_clients({ name = name })[1] + if clangd then + local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) + if not ok then + vim.notify('LSP ' .. name .. ' restart failed: ' .. err) + else + vim.notify('LSP ' .. name .. ' restarted' .. err) + end + end + else + local clients = vim.lsp.get_clients({ name = name }) + for _, c in ipairs(clients) do + local configc = c.config + c:stop(true) + vim.defer_fn(function() + -- vim.lsp.config(name, configc) + vim.lsp.enable(name) + vim.cmd('checktime') + end, 600) + end + -- -- 1. Stop the specific client + -- for _, client in ipairs(clients) do client:stop() end + -- + -- -- 2. Reload all loaded buffers to trigger re-attachment for that client + -- -- (Note: 'checktime' is safer than 'bufdo edit' as it respects unsaved changes) + -- vim.cmd('checktime') + end +end + +-- stylua: ignore +function M.piolsp() + local ok, err = pcall(vim.cmd.lsp, { args = { 'restart' } }) + if ok then vim.notify('LSP restarted' .. err) + else vim.notify('LSP restart failed: ' .. err) end + -- M.fix_pio_compile_commands() +end + +return M diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 464fd745..1e0bfece 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -8,6 +8,7 @@ local action_state = require('telescope.actions.state') local entry_display = require('telescope.pickers.entry_display') local make_entry = require('telescope.make_entry') local utils = require('platformio.utils') +local pio = require('platformio.utils.pio') local previewers = require('telescope.previewers') local boardentry_maker = function(opts) @@ -55,16 +56,16 @@ local function pick_framework(board_details) actions.select_default:replace(function() actions.close(prompt_bufnr) local selection = action_state.get_selected_entry() - utils.selected_framework = selection[1] + pio.selected_framework = selection[1] - utils.run_sequence({ + pio.run_sequence({ { - cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. utils.selected_framework .. '"', - cb = utils.handlePioinit, + cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', + cb = pio.handlePioinit, }, { cmd = 'pio run -t compiledb', - cb = utils.handleDb, + cb = pio.handleDb, }, }) end) diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 956306da..60c8df21 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -9,8 +9,9 @@ local conf = require('telescope.config').values local actions = require('telescope.actions') local action_state = require('telescope.actions.state') local utils = require('platformio.utils') +local pio = require('platformio.utils.pio') local previewers = require('telescope.previewers') -local piolsp = require('platformio.piolsp') --.piolsp +-- local piolsp = require('platformio.piolsp') --.piolsp local libentry_maker = function(opts) local displayer = entry_display.create({ @@ -61,14 +62,14 @@ local function pick_library(json_data) -- local command = 'pio pkg install --library "' .. pkg_name .. '"' -- command = command .. ' && pio run -t compiledb' - utils.run_sequence({ + pio.run_sequence({ { cmd = 'pio pkg install --library "' .. pkg_name .. '"', - cb = utils.handlePiolib, + cb = pio.handlePiolib, }, { cmd = 'pio run -t compiledb', - cb = utils.handleDb, + cb = pio.handleDb, }, }) -- utils.ToggleTerminal(command, 'float') diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index f609bed8..07006c23 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -1,6 +1,6 @@ local config = require('platformio').config -local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -local piolsp = require('platformio.piolsp') --.piolsp +-- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +local pio = require('platformio.utils.pio') --.piolsp local is_windows = jit.os == 'Windows' -- local pioinit = require('platformio.pioinit') @@ -12,83 +12,83 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' ------------------------------------------------------- --- INFO: Dispatcher - -M.queue = {} -local pio_buffer = '' -- Persistent stream buffer - --- 1. The Dispatcher (The Brain) --- stylua: ignore -function M.dispatcher(_, _, data) - if #M.queue == 0 then return end - - pio_buffer = pio_buffer .. data[1] - -- 2. If the chunk has more than one element, we've encountered newlines - if #data > 1 then - -- 3. Process any "middle" lines which are guaranteed to be complete - for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end - - for status in pio_buffer:gmatch('___DONE___:(%a+)') do - if status then - if status == 'SUCCESS' then - -- 4. Store the last element as the new partial buffer for the next call - pio_buffer = data[#data] - local task = table.remove(M.queue, 1) - if task then vim.schedule(task) end - elseif status == 'FAILED' then - M.queue = {} -- Clear queue on any other status (failure) - pio_buffer = '' - vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) - end - break - end - end - end - if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end -end - --- stylua: ignore -M.run_sequence = function(tasks) - -- Reset local state for new run - M.queue = {} - -- pio_buffer = '' - local full_cmd = '' - - local success = 'echo ___DONE___":"SUCCESS' - local failure = 'echo ___DONE___":"FAILED' - - for _, task in ipairs(tasks) do - table.insert(M.queue, task.cb) - local part = string.format('%s && %s', task.cmd, success) - if full_cmd == '' then full_cmd = part - else full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands - end - full_cmd = full_cmd .. ' || ' .. failure - M.ToggleTerminal(full_cmd, 'float') -end - --- Handle after 'pio run -t compiledb' execution -function M.handleDb() - vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) - piolsp.gitignore_lsp_configs('compile_commands.json') - piolsp.fix_pio_compile_commands() - piolsp.lsp_restart('clangd') -end - --- Handle after poioinit execution --- stylua: ignore -function M.handlePioinit() - vim.notify('Pioinit: Success', vim.log.levels.INFO) - boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') -end --- Handle after poioinit execution --- stylua: ignore -function M.handlePiolib() - vim.notify('Piolib: Success', vim.log.levels.INFO) -end --- INFO: endDispatcher ------------------------------------------------------- +-- ------------------------------------------------------ +-- -- INFO: Dispatcher +-- +-- M.queue = {} +-- local pio_buffer = '' -- Persistent stream buffer +-- +-- -- 1. The Dispatcher (The Brain) +-- -- stylua: ignore +-- function M.dispatcher(_, _, data) +-- if #M.queue == 0 then return end +-- +-- pio_buffer = pio_buffer .. data[1] +-- -- 2. If the chunk has more than one element, we've encountered newlines +-- if #data > 1 then +-- -- 3. Process any "middle" lines which are guaranteed to be complete +-- for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end +-- +-- for status in pio_buffer:gmatch('___DONE___:(%a+)') do +-- if status then +-- if status == 'SUCCESS' then +-- -- 4. Store the last element as the new partial buffer for the next call +-- pio_buffer = data[#data] +-- local task = table.remove(M.queue, 1) +-- if task then vim.schedule(task) end +-- elseif status == 'FAILED' then +-- M.queue = {} -- Clear queue on any other status (failure) +-- pio_buffer = '' +-- vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) +-- end +-- break +-- end +-- end +-- end +-- if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end +-- end +-- +-- -- stylua: ignore +-- M.run_sequence = function(tasks) +-- -- Reset local state for new run +-- M.queue = {} +-- -- pio_buffer = '' +-- local full_cmd = '' +-- +-- local success = 'echo ___DONE___":"SUCCESS' +-- local failure = 'echo ___DONE___":"FAILED' +-- +-- for _, task in ipairs(tasks) do +-- table.insert(M.queue, task.cb) +-- local part = string.format('%s && %s', task.cmd, success) +-- if full_cmd == '' then full_cmd = part +-- else full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands +-- end +-- full_cmd = full_cmd .. ' || ' .. failure +-- M.ToggleTerminal(full_cmd, 'float') +-- end +-- +-- -- Handle after 'pio run -t compiledb' execution +-- function M.handleDb() +-- vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) +-- piolsp.gitignore_lsp_configs('compile_commands.json') +-- piolsp.fix_pio_compile_commands() +-- piolsp.lsp_restart('clangd') +-- end +-- +-- -- Handle after poioinit execution +-- -- stylua: ignore +-- function M.handlePioinit() +-- vim.notify('Pioinit: Success', vim.log.levels.INFO) +-- boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') +-- end +-- -- Handle after poioinit execution +-- -- stylua: ignore +-- function M.handlePiolib() +-- vim.notify('Piolib: Success', vim.log.levels.INFO) +-- end +-- -- INFO: endDispatcher +-- ------------------------------------------------------ ------------------------------------------------------ function M.strsplit(inputstr, del) @@ -327,7 +327,7 @@ function M.ToggleTerminal(command, direction) -- INFO: on_stdout -- on_stdout = stdout_callback, - on_stdout = M.dispatcher, + on_stdout = pio.dispatcher, -- INFO: on_create() { on_create = function(t) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua new file mode 100644 index 00000000..e69de29b diff --git a/lua/platformio/piolsp.lua b/lua/platformio/utils/pio.lua similarity index 64% rename from lua/platformio/piolsp.lua rename to lua/platformio/utils/pio.lua index 911e4a53..c5522995 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/utils/pio.lua @@ -1,209 +1,217 @@ -local M = {} - --- stylua: ignore -function M.get_pio_dir(type) - -- 1. Setup Base Paths - local home = os.getenv('HOME') or os.getenv('USERPROFILE') - - -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) - local map = { - core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, - packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, - platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, - } - - local target_config = map[type] - if not target_config then return nil end - - -- 3. Try to get explicit value from platformio.ini - local path = vim.fn.getcwd() .. '/platformio.ini' - local inifile = io.open(path, 'r') - local ini_val = nil - local core_val = nil - - if inifile then - for line in inifile:lines() do - if core_val == nil then core_val = line:match('^%s*' .. map['core'].ini .. '%s*=%s*([^;%s]+)') end - if ini_val == nil then ini_val = line:match('^%s*' .. target_config.ini .. '%s*=%s*([^;%s]+)') end - if ini_val and core_val then break end - end - inifile:close() - end - - -- 4.0 Fallback Logic: INI -> Env Var -> Default - local core_dir = core_val or os.getenv('PLATFORMIO_CORE_DIR' or (home .. map['core'].sub)):gsub('[\\/]+$', '') - core_dir = core_dir:gsub('\\', '/'):gsub('//+', '/') - -- if vim.fn.has('win32') == 1 then core_dir = core_dir:gsub('/', '\\') end - if type == 'core' then return core_dir end - - -- 4.1 Fallback Logic: INI -> Env Var -> Default - local result = ini_val or os.getenv(target_config.env) or (core_dir .. target_config.sub) - - -- 5. Expand ${platformio.core_dir} - if result:find('${platformio.core_dir}', 1, true) then result = result:gsub('%${platformio.core_dir}', core_dir) end - - -- 6. Normalize Slashes for Windows - result = result:gsub('\\', '/'):gsub('//+', '/') - -- if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end - - -- Ensure core_dir itself doesn't have trailing slashes for cleaner joins - return result -end - --- stylua: ignore -function M.fix_pio_compile_commands() - local filename = vim.fn.getcwd() .. '/compile_commands.json' - local file = io.open(filename, 'r') - if not file then return end - - local content = file:read('*a') - file:close() - if not content or content == '' then return end - - -- Safe JSON decoding - local ok, data = pcall(vim.json.decode, content) - if not ok or type(data) ~= 'table' then - vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) - return - end - - print('PioFix0') - -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path - local path_map = {} - local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') - if pio_home then - - -- Recursively find all binaries in PIO packages - local pio_packages = M.get_pio_dir('packages') .. '/*/bin/*' - - local found_binaries = vim.fn.glob(pio_packages, false, true) - - for _, full_path in ipairs(found_binaries) do - -- Extract filename (e.g., riscv32-esp-elf-gcc) - local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') - path_map[name] = full_path - print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) - end - end - - -- PHASE 2: Update JSON using the Map - local modified = 0 - for _, entry in ipairs(data) do - if type(entry.command) == 'string' then - local cmd_parts = vim.split(entry.command, ' ') - local first_token = cmd_parts[1] - - if first_token then - -- Check if it's already a short name (not an absolute path) - local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') - - if not is_abs then - local short_name = first_token:gsub('%.exe$', '') - -- print('PioFix2: short_name=' .. short_name) - -- Direct Query: Does this name exist in our discovered list? - if path_map[short_name] then - cmd_parts[1] = path_map[short_name] - -- print('PioFix3: full_name=' .. cmd_parts[1]) - entry.command = table.concat(cmd_parts, ' ') - modified = modified + 1 - end - end - end - end - end - - -- PHASE 3: Save and Refresh - -- Safe JSON encoding - if modified > 0 then - local out_file = io.open(filename, 'w') - if out_file then - local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) - if encode_ok and json_str then - -- 1. Format the string using python's json.tool - -- The second argument to vim.fn.system() is the "stdin" passed to the command - local formatted_json = vim.fn.system('python -m json.tool', json_str) - - -- out_file:write(json_str) - out_file:write(formatted_json) - out_file:close() - vim.notify('compiledb: fixed', vim.log.levels.INFO) - M.lsp_restart('clangd') - end - end - end -end - -function M.gitignore_lsp_configs(config_file) - local gitignore_path = vim.fs.joinpath(vim.g.platformioRootDir, '.gitignore') - local file = io.open(gitignore_path, 'r') - local pattern = '^%s*' .. vim.pesc(config_file) .. '%s*$' - - if file then - for line in file:lines() do - if line:match(pattern) then - file:close() - return - end - end - file:close() - end - - file = io.open(gitignore_path, 'a') - if file then - file:write(config_file .. '\n') - file:close() - end -end - --- stylua: ignore -function M.lsp_restarti(name) - local clients = vim.lsp.get_clients({ name = name }) - for _, c in ipairs(clients) do - local configc = c.config - c:stop(true) - vim.defer_fn(function() vim.lsp.config(name, configc) vim.lsp.enable(name) end, 600) - end -end - ---- stylua: ignore -function M.lsp_restart(name) - if vim.fn.has('nvim-0.12') == 1 then - -- local clients = vim.lsp.get_clients({ name = name }) - local clangd = vim.lsp.get_clients({ name = name })[1] - if clangd then - local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) - if not ok then - vim.notify('LSP ' .. name .. ' restart failed: ' .. err) - else - vim.notify('LSP ' .. name .. ' restarted' .. err) - end - end - else - local clients = vim.lsp.get_clients({ name = name }) - for _, c in ipairs(clients) do - local configc = c.config - c:stop(true) - vim.defer_fn(function() - -- vim.lsp.config(name, configc) - vim.lsp.enable(name) - vim.cmd('checktime') - end, 600) - end - -- -- 1. Stop the specific client - -- for _, client in ipairs(clients) do client:stop() end - -- - -- -- 2. Reload all loaded buffers to trigger re-attachment for that client - -- -- (Note: 'checktime' is safer than 'bufdo edit' as it respects unsaved changes) - -- vim.cmd('checktime') - end -end - --- stylua: ignore -function M.piolsp() - local ok, err = pcall(vim.cmd.lsp, { args = { 'restart' } }) - if ok then vim.notify('LSP restarted' .. err) - else vim.notify('LSP restart failed: ' .. err) end - -- M.fix_pio_compile_commands() -end - -return M +local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +local pio = require('platformio.utils.piolsp') +local M = {} + +M.selected_framework = '' + +-- stylua: ignore +function M.get_pio_dir(type) + -- 1. Setup Base Paths + local home = os.getenv('HOME') or os.getenv('USERPROFILE') + + -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) + local map = { + core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, + packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, + platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, + } + + local target_config = map[type] + if not target_config then return nil end + + -- 3. Try to get explicit value from platformio.ini + local path = vim.fn.getcwd() .. '/platformio.ini' + local inifile = io.open(path, 'r') + local ini_val = nil + local core_val = nil + + if inifile then + for line in inifile:lines() do + if core_val == nil then core_val = line:match('^%s*' .. map['core'].ini .. '%s*=%s*([^;%s]+)') end + if ini_val == nil then ini_val = line:match('^%s*' .. target_config.ini .. '%s*=%s*([^;%s]+)') end + if ini_val and core_val then break end + end + inifile:close() + end + + -- 4.0 Fallback Logic: INI -> Env Var -> Default + local core_dir = core_val or os.getenv('PLATFORMIO_CORE_DIR' or (home .. map['core'].sub)):gsub('[\\/]+$', '') + core_dir = core_dir:gsub('\\', '/'):gsub('//+', '/') + -- if vim.fn.has('win32') == 1 then core_dir = core_dir:gsub('/', '\\') end + if type == 'core' then return core_dir end + + -- 4.1 Fallback Logic: INI -> Env Var -> Default + local result = ini_val or os.getenv(target_config.env) or (core_dir .. target_config.sub) + + -- 5. Expand ${platformio.core_dir} + if result:find('${platformio.core_dir}', 1, true) then result = result:gsub('%${platformio.core_dir}', core_dir) end + + -- 6. Normalize Slashes for Windows + result = result:gsub('\\', '/'):gsub('//+', '/') + -- if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end + + -- Ensure core_dir itself doesn't have trailing slashes for cleaner joins + return result +end + +-- stylua: ignore +function M.fix_pio_compile_commands() + local filename = vim.fn.getcwd() .. '/compile_commands.json' + local file = io.open(filename, 'r') + if not file then return end + + local content = file:read('*a') + file:close() + if not content or content == '' then return end + + -- Safe JSON decoding + local ok, data = pcall(vim.json.decode, content) + if not ok or type(data) ~= 'table' then + vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) + return + end + + print('PioFix0') + -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path + local path_map = {} + local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') + if pio_home then + + -- Recursively find all binaries in PIO packages + local pio_packages = M.get_pio_dir('packages') .. '/*/bin/*' + + local found_binaries = vim.fn.glob(pio_packages, false, true) + + for _, full_path in ipairs(found_binaries) do + -- Extract filename (e.g., riscv32-esp-elf-gcc) + local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') + path_map[name] = full_path + print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) + end + end + + -- PHASE 2: Update JSON using the Map + local modified = 0 + for _, entry in ipairs(data) do + if type(entry.command) == 'string' then + local cmd_parts = vim.split(entry.command, ' ') + local first_token = cmd_parts[1] + + if first_token then + -- Check if it's already a short name (not an absolute path) + local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') + + if not is_abs then + local short_name = first_token:gsub('%.exe$', '') + -- print('PioFix2: short_name=' .. short_name) + -- Direct Query: Does this name exist in our discovered list? + if path_map[short_name] then + cmd_parts[1] = path_map[short_name] + -- print('PioFix3: full_name=' .. cmd_parts[1]) + entry.command = table.concat(cmd_parts, ' ') + modified = modified + 1 + end + end + end + end + end + + -- PHASE 3: Save and Refresh + -- Safe JSON encoding + if modified > 0 then + local out_file = io.open(filename, 'w') + if out_file then + local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) + if encode_ok and json_str then + -- 1. Format the string using python's json.tool + -- The second argument to vim.fn.system() is the "stdin" passed to the command + local formatted_json = vim.fn.system('python -m json.tool', json_str) + + -- out_file:write(json_str) + out_file:write(formatted_json) + out_file:close() + vim.notify('compiledb: fixed', vim.log.levels.INFO) + M.lsp_restart('clangd') + end + end + end +end + +------------------------------------------------------ +-- INFO: Dispatcher + +M.queue = {} +local pio_buffer = '' -- Persistent stream buffer + +-- 1. The Dispatcher (The Brain) +-- stylua: ignore +function M.dispatcher(_, _, data) + if #M.queue == 0 then return end + + pio_buffer = pio_buffer .. data[1] + -- 2. If the chunk has more than one element, we've encountered newlines + if #data > 1 then + -- 3. Process any "middle" lines which are guaranteed to be complete + for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end + + for status in pio_buffer:gmatch('___DONE___:(%a+)') do + if status then + if status == 'SUCCESS' then + -- 4. Store the last element as the new partial buffer for the next call + pio_buffer = data[#data] + local task = table.remove(M.queue, 1) + if task then vim.schedule(task) end + elseif status == 'FAILED' then + M.queue = {} -- Clear queue on any other status (failure) + pio_buffer = '' + vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) + end + break + end + end + end + if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end +end + +-- stylua: ignore +M.run_sequence = function(tasks) + -- Reset local state for new run + M.queue = {} + -- pio_buffer = '' + local full_cmd = '' + + local success = 'echo ___DONE___":"SUCCESS' + local failure = 'echo ___DONE___":"FAILED' + + for _, task in ipairs(tasks) do + table.insert(M.queue, task.cb) + local part = string.format('%s && %s', task.cmd, success) + if full_cmd == '' then full_cmd = part + else full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands + end + full_cmd = full_cmd .. ' || ' .. failure + M.ToggleTerminal(full_cmd, 'float') +end + +-- Handle after 'pio run -t compiledb' execution +function M.handleDb() + vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) + pio.gitignore_lsp_configs('compile_commands.json') + pio.fix_pio_compile_commands() + pio.lsp_restart('clangd') +end + +-- Handle after poioinit execution +-- stylua: ignore +function M.handlePioinit() + vim.notify('Pioinit: Success', vim.log.levels.INFO) + boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') +end +-- Handle after poioinit execution +-- stylua: ignore +function M.handlePiolib() + vim.notify('Piolib: Success', vim.log.levels.INFO) +end +-- INFO: endDispatcher +------------------------------------------------------ +return M diff --git a/plugin/platformio.lua b/plugin/platformio.lua index e067c8a5..f7f88c32 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -7,6 +7,7 @@ -- -1: Zero or one argument (like ?, explicitly). local utils = require('platformio.utils') +local pio = require('platformio.utils.pio') local piolsserial = require('platformio.piolsserial') -- Pioinit @@ -17,7 +18,7 @@ end, { force = true }) -- Piolsp vim.api.nvim_create_user_command('PioLSP', function() vim.schedule(function() - require('platformio.piolsp').piolsp() + require('platformio.lsp.piolsp').piolsp() end) end, {}) @@ -96,8 +97,14 @@ end, {}) -- INFO: fix paths in compile_commands.json -- vim.api.nvim_create_user_command('PioFixPaths', require('platformio.piolsp').fix_pio_compile_commands, {}) vim.api.nvim_create_user_command('PioFixPaths', function() - local command = 'pio run -t compiledb' - utils.ToggleTerminal(command, 'float', require('platformio.piolsp').fix_pio_compile_commands) + pio.run_sequence({ + { + cmd = 'pio run -t compiledb', + cb = pio.handleDb, + }, + }) + -- local command = 'pio run -t compiledb' + -- utils.ToggleTerminal(command, 'float') end, {}) ------------------------------------------------------ From 6db4c78cb3054ed9df82fb194a8469e231097bdf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 04:50:22 +0300 Subject: [PATCH 0473/1406] update --- lua/platformio/lsp/clangd.lua | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua index 98804f97..47a53e14 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -1,19 +1,19 @@ ---------------------------------------------------------------------------------------- -- INFO: create clangd required files ----------------------------------------------------------------------------------------- -local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) +local boiler = require('platformio.boilerplate') +boiler.boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) -boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) +boiler.boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +boiler.boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') -boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) +boiler.boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) -boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) +boiler.boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) -boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) +boiler.boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) -- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) -- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) --------------------------------------------------------------------------------- From 4bcc536b8169a93dbaee6b90cb1136afaaaf0924 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 04:55:33 +0300 Subject: [PATCH 0474/1406] update --- lua/platformio/boilerplate.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 8a16f2c3..bc50a63b 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -1,4 +1,3 @@ -local pio = require('platformio.utils.pio') local M = {} local uv = vim.loop @@ -43,6 +42,7 @@ monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dt lib_ldf_mode = chain+ ;Library dependencies Finder ldf ]], content = function(self) + local pio = require('platformio.utils.pio') return string.format(self.template, pio.get_pio_dir('core')) end, } @@ -83,6 +83,7 @@ clangd --query-driver=%s/toolchain-*/**/bin/* ]], content = function(self) + local pio = require('platformio.utils.pio') return string.format(self.template, pio.get_pio_dir('packages') or '**') end, --query-driver=%s/.platformio/packages/*/bin/riscv32-esp-elf-* From 2ddb3184c9396fb2e4efe1bc7712a03294b1109d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 05:41:56 +0300 Subject: [PATCH 0475/1406] update --- lua/platformio/boilerplate.lua | 3 +- lua/platformio/lpiolsp.lua | 209 --------------------------------- lua/platformio/lsp/piolsp.lua | 76 ------------ lua/platformio/piolib.lua | 13 -- lua/platformio/piolsp.lua | 13 ++ lua/platformio/utils.lua | 78 ------------ lua/platformio/utils/misc.lua | 58 +++++++++ lua/platformio/utils/pio.lua | 18 ++- plugin/platformio.lua | 2 +- 9 files changed, 85 insertions(+), 385 deletions(-) delete mode 100644 lua/platformio/lpiolsp.lua delete mode 100644 lua/platformio/lsp/piolsp.lua create mode 100644 lua/platformio/piolsp.lua diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index bc50a63b..8a16f2c3 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -1,3 +1,4 @@ +local pio = require('platformio.utils.pio') local M = {} local uv = vim.loop @@ -42,7 +43,6 @@ monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dt lib_ldf_mode = chain+ ;Library dependencies Finder ldf ]], content = function(self) - local pio = require('platformio.utils.pio') return string.format(self.template, pio.get_pio_dir('core')) end, } @@ -83,7 +83,6 @@ clangd --query-driver=%s/toolchain-*/**/bin/* ]], content = function(self) - local pio = require('platformio.utils.pio') return string.format(self.template, pio.get_pio_dir('packages') or '**') end, --query-driver=%s/.platformio/packages/*/bin/riscv32-esp-elf-* diff --git a/lua/platformio/lpiolsp.lua b/lua/platformio/lpiolsp.lua deleted file mode 100644 index bbe0c470..00000000 --- a/lua/platformio/lpiolsp.lua +++ /dev/null @@ -1,209 +0,0 @@ -local M = {} - --- -- stylua: ignore --- function M.get_pio_dir(type) --- -- 1. Setup Base Paths --- local home = os.getenv('HOME') or os.getenv('USERPROFILE') --- --- -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) --- local map = { --- core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, --- packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, --- platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, --- } --- --- local target_config = map[type] --- if not target_config then return nil end --- --- -- 3. Try to get explicit value from platformio.ini --- local path = vim.fn.getcwd() .. '/platformio.ini' --- local inifile = io.open(path, 'r') --- local ini_val = nil --- local core_val = nil --- --- if inifile then --- for line in inifile:lines() do --- if core_val == nil then core_val = line:match('^%s*' .. map['core'].ini .. '%s*=%s*([^;%s]+)') end --- if ini_val == nil then ini_val = line:match('^%s*' .. target_config.ini .. '%s*=%s*([^;%s]+)') end --- if ini_val and core_val then break end --- end --- inifile:close() --- end --- --- -- 4.0 Fallback Logic: INI -> Env Var -> Default --- local core_dir = core_val or os.getenv('PLATFORMIO_CORE_DIR' or (home .. map['core'].sub)):gsub('[\\/]+$', '') --- core_dir = core_dir:gsub('\\', '/'):gsub('//+', '/') --- -- if vim.fn.has('win32') == 1 then core_dir = core_dir:gsub('/', '\\') end --- if type == 'core' then return core_dir end --- --- -- 4.1 Fallback Logic: INI -> Env Var -> Default --- local result = ini_val or os.getenv(target_config.env) or (core_dir .. target_config.sub) --- --- -- 5. Expand ${platformio.core_dir} --- if result:find('${platformio.core_dir}', 1, true) then result = result:gsub('%${platformio.core_dir}', core_dir) end --- --- -- 6. Normalize Slashes for Windows --- result = result:gsub('\\', '/'):gsub('//+', '/') --- -- if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end --- --- -- Ensure core_dir itself doesn't have trailing slashes for cleaner joins --- return result --- end --- --- -- stylua: ignore --- function M.fix_pio_compile_commands() --- local filename = vim.fn.getcwd() .. '/compile_commands.json' --- local file = io.open(filename, 'r') --- if not file then return end --- --- local content = file:read('*a') --- file:close() --- if not content or content == '' then return end --- --- -- Safe JSON decoding --- local ok, data = pcall(vim.json.decode, content) --- if not ok or type(data) ~= 'table' then --- vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) --- return --- end --- --- print('PioFix0') --- -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path --- local path_map = {} --- local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') --- if pio_home then --- --- -- Recursively find all binaries in PIO packages --- local pio_packages = M.get_pio_dir('packages') .. '/*/bin/*' --- --- local found_binaries = vim.fn.glob(pio_packages, false, true) --- --- for _, full_path in ipairs(found_binaries) do --- -- Extract filename (e.g., riscv32-esp-elf-gcc) --- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') --- path_map[name] = full_path --- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) --- end --- end --- --- -- PHASE 2: Update JSON using the Map --- local modified = 0 --- for _, entry in ipairs(data) do --- if type(entry.command) == 'string' then --- local cmd_parts = vim.split(entry.command, ' ') --- local first_token = cmd_parts[1] --- --- if first_token then --- -- Check if it's already a short name (not an absolute path) --- local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') --- --- if not is_abs then --- local short_name = first_token:gsub('%.exe$', '') --- -- print('PioFix2: short_name=' .. short_name) --- -- Direct Query: Does this name exist in our discovered list? --- if path_map[short_name] then --- cmd_parts[1] = path_map[short_name] --- -- print('PioFix3: full_name=' .. cmd_parts[1]) --- entry.command = table.concat(cmd_parts, ' ') --- modified = modified + 1 --- end --- end --- end --- end --- end --- --- -- PHASE 3: Save and Refresh --- -- Safe JSON encoding --- if modified > 0 then --- local out_file = io.open(filename, 'w') --- if out_file then --- local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) --- if encode_ok and json_str then --- -- 1. Format the string using python's json.tool --- -- The second argument to vim.fn.system() is the "stdin" passed to the command --- local formatted_json = vim.fn.system('python -m json.tool', json_str) --- --- -- out_file:write(json_str) --- out_file:write(formatted_json) --- out_file:close() --- vim.notify('compiledb: fixed', vim.log.levels.INFO) --- M.lsp_restart('clangd') --- end --- end --- end --- end - -function M.gitignore_lsp_configs(config_file) - local gitignore_path = vim.fs.joinpath(vim.g.platformioRootDir, '.gitignore') - local file = io.open(gitignore_path, 'r') - local pattern = '^%s*' .. vim.pesc(config_file) .. '%s*$' - - if file then - for line in file:lines() do - if line:match(pattern) then - file:close() - return - end - end - file:close() - end - - file = io.open(gitignore_path, 'a') - if file then - file:write(config_file .. '\n') - file:close() - end -end - --- stylua: ignore -function M.lsp_restarti(name) - local clients = vim.lsp.get_clients({ name = name }) - for _, c in ipairs(clients) do - local configc = c.config - c:stop(true) - vim.defer_fn(function() vim.lsp.config(name, configc) vim.lsp.enable(name) end, 600) - end -end - ---- stylua: ignore -function M.lsp_restart(name) - if vim.fn.has('nvim-0.12') == 1 then - -- local clients = vim.lsp.get_clients({ name = name }) - local clangd = vim.lsp.get_clients({ name = name })[1] - if clangd then - local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) - if not ok then - vim.notify('LSP ' .. name .. ' restart failed: ' .. err) - else - vim.notify('LSP ' .. name .. ' restarted' .. err) - end - end - else - local clients = vim.lsp.get_clients({ name = name }) - for _, c in ipairs(clients) do - local configc = c.config - c:stop(true) - vim.defer_fn(function() - -- vim.lsp.config(name, configc) - vim.lsp.enable(name) - vim.cmd('checktime') - end, 600) - end - -- -- 1. Stop the specific client - -- for _, client in ipairs(clients) do client:stop() end - -- - -- -- 2. Reload all loaded buffers to trigger re-attachment for that client - -- -- (Note: 'checktime' is safer than 'bufdo edit' as it respects unsaved changes) - -- vim.cmd('checktime') - end -end - --- stylua: ignore -function M.piolsp() - local ok, err = pcall(vim.cmd.lsp, { args = { 'restart' } }) - if ok then vim.notify('LSP restarted' .. err) - else vim.notify('LSP restart failed: ' .. err) end - -- M.fix_pio_compile_commands() -end - -return M diff --git a/lua/platformio/lsp/piolsp.lua b/lua/platformio/lsp/piolsp.lua deleted file mode 100644 index 51c395a1..00000000 --- a/lua/platformio/lsp/piolsp.lua +++ /dev/null @@ -1,76 +0,0 @@ -local M = {} - -function M.gitignore_lsp_configs(config_file) - local gitignore_path = vim.fs.joinpath(vim.g.platformioRootDir, '.gitignore') - local file = io.open(gitignore_path, 'r') - local pattern = '^%s*' .. vim.pesc(config_file) .. '%s*$' - - if file then - for line in file:lines() do - if line:match(pattern) then - file:close() - return - end - end - file:close() - end - - file = io.open(gitignore_path, 'a') - if file then - file:write(config_file .. '\n') - file:close() - end -end - --- stylua: ignore -function M.lsp_restarti(name) - local clients = vim.lsp.get_clients({ name = name }) - for _, c in ipairs(clients) do - local configc = c.config - c:stop(true) - vim.defer_fn(function() vim.lsp.config(name, configc) vim.lsp.enable(name) end, 600) - end -end - ---- stylua: ignore -function M.lsp_restart(name) - if vim.fn.has('nvim-0.12') == 1 then - -- local clients = vim.lsp.get_clients({ name = name }) - local clangd = vim.lsp.get_clients({ name = name })[1] - if clangd then - local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) - if not ok then - vim.notify('LSP ' .. name .. ' restart failed: ' .. err) - else - vim.notify('LSP ' .. name .. ' restarted' .. err) - end - end - else - local clients = vim.lsp.get_clients({ name = name }) - for _, c in ipairs(clients) do - local configc = c.config - c:stop(true) - vim.defer_fn(function() - -- vim.lsp.config(name, configc) - vim.lsp.enable(name) - vim.cmd('checktime') - end, 600) - end - -- -- 1. Stop the specific client - -- for _, client in ipairs(clients) do client:stop() end - -- - -- -- 2. Reload all loaded buffers to trigger re-attachment for that client - -- -- (Note: 'checktime' is safer than 'bufdo edit' as it respects unsaved changes) - -- vim.cmd('checktime') - end -end - --- stylua: ignore -function M.piolsp() - local ok, err = pcall(vim.cmd.lsp, { args = { 'restart' } }) - if ok then vim.notify('LSP restarted' .. err) - else vim.notify('LSP restart failed: ' .. err) end - -- M.fix_pio_compile_commands() -end - -return M diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 60c8df21..0a5bf87c 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -72,19 +72,6 @@ local function pick_library(json_data) cb = pio.handleDb, }, }) - -- utils.ToggleTerminal(command, 'float') - -- vim.defer_fn(function() - -- vim.notify('LSP: compile_commands.json generation/update completed!', vim.log.levels.INFO) - -- piolsp.gitignore_lsp_configs('compile_commands.json') - -- piolsp.lsp_restart('clangd') - -- end, 900) - -- local command = 'pio pkg install --library "' .. pkg_name .. '" && exit && echo "done"' - - -- utils.ToggleTerminal(command, 'float', function() - -- -- require('platformio.piolsp').piolsp() - -- piolsp() - -- end) - -- utils.ToggleTerminal(command, 'float', piolsp) end) return true end, diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua new file mode 100644 index 00000000..f6a54301 --- /dev/null +++ b/lua/platformio/piolsp.lua @@ -0,0 +1,13 @@ +local misc = require('platformio.utils.misc') +local M = {} + +-- stylua: ignore +function M.piolsp() + misc.lsp_restart() + -- local ok, err = pcall(vim.cmd.lsp, { args = { 'restart' } }) + -- if ok then vim.notify('LSP restarted' .. err) + -- else vim.notify('LSP restart failed: ' .. err) end + -- M.fix_pio_compile_commands() +end + +return M diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 07006c23..48f9a18d 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -12,84 +12,6 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' --- ------------------------------------------------------ --- -- INFO: Dispatcher --- --- M.queue = {} --- local pio_buffer = '' -- Persistent stream buffer --- --- -- 1. The Dispatcher (The Brain) --- -- stylua: ignore --- function M.dispatcher(_, _, data) --- if #M.queue == 0 then return end --- --- pio_buffer = pio_buffer .. data[1] --- -- 2. If the chunk has more than one element, we've encountered newlines --- if #data > 1 then --- -- 3. Process any "middle" lines which are guaranteed to be complete --- for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end --- --- for status in pio_buffer:gmatch('___DONE___:(%a+)') do --- if status then --- if status == 'SUCCESS' then --- -- 4. Store the last element as the new partial buffer for the next call --- pio_buffer = data[#data] --- local task = table.remove(M.queue, 1) --- if task then vim.schedule(task) end --- elseif status == 'FAILED' then --- M.queue = {} -- Clear queue on any other status (failure) --- pio_buffer = '' --- vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) --- end --- break --- end --- end --- end --- if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end --- end --- --- -- stylua: ignore --- M.run_sequence = function(tasks) --- -- Reset local state for new run --- M.queue = {} --- -- pio_buffer = '' --- local full_cmd = '' --- --- local success = 'echo ___DONE___":"SUCCESS' --- local failure = 'echo ___DONE___":"FAILED' --- --- for _, task in ipairs(tasks) do --- table.insert(M.queue, task.cb) --- local part = string.format('%s && %s', task.cmd, success) --- if full_cmd == '' then full_cmd = part --- else full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands --- end --- full_cmd = full_cmd .. ' || ' .. failure --- M.ToggleTerminal(full_cmd, 'float') --- end --- --- -- Handle after 'pio run -t compiledb' execution --- function M.handleDb() --- vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) --- piolsp.gitignore_lsp_configs('compile_commands.json') --- piolsp.fix_pio_compile_commands() --- piolsp.lsp_restart('clangd') --- end --- --- -- Handle after poioinit execution --- -- stylua: ignore --- function M.handlePioinit() --- vim.notify('Pioinit: Success', vim.log.levels.INFO) --- boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') --- end --- -- Handle after poioinit execution --- -- stylua: ignore --- function M.handlePiolib() --- vim.notify('Piolib: Success', vim.log.levels.INFO) --- end --- -- INFO: endDispatcher --- ------------------------------------------------------ - ------------------------------------------------------ function M.strsplit(inputstr, del) local t = {} diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index e69de29b..0a3b1856 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -0,0 +1,58 @@ +local M = {} + +--- stylua: ignore +function M.lsp_restart(name) + if vim.fn.has('nvim-0.12') == 1 then + -- local clients = vim.lsp.get_clients({ name = name }) + local clangd = vim.lsp.get_clients({ name = name })[1] + if clangd then + local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) + if not ok then + vim.notify('LSP ' .. name .. ' restart failed: ' .. err) + else + vim.notify('LSP ' .. name .. ' restarted' .. err) + end + end + else + local clients = vim.lsp.get_clients({ name = name }) + for _, c in ipairs(clients) do + local configc = c.config + c:stop(true) + vim.defer_fn(function() + vim.lsp.config(name, configc) + vim.lsp.enable(name) + vim.cmd('checktime') + end, 600) + end + -- -- 1. Stop the specific client + -- for _, client in ipairs(clients) do client:stop() end + -- + -- -- 2. Reload all loaded buffers to trigger re-attachment for that client + -- -- (Note: 'checktime' is safer than 'bufdo edit' as it respects unsaved changes) + -- vim.cmd('checktime') + end +end + +function M.gitignore_lsp_configs(config_file) + local gitignore_path = vim.fs.joinpath(vim.g.platformioRootDir, '.gitignore') + local file = io.open(gitignore_path, 'r') + local pattern = '^%s*' .. vim.pesc(config_file) .. '%s*$' + + if file then + for line in file:lines() do + if line:match(pattern) then + file:close() + return + end + end + file:close() + end + + file = io.open(gitignore_path, 'a') + if file then + file:write(config_file .. '\n') + file:close() + end +end + +return M diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index c5522995..732e44e9 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -1,9 +1,10 @@ -local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -local pio = require('platformio.utils.piolsp') +-- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +local misc = require('platformio.utils.misc') local M = {} M.selected_framework = '' +------------------------------------------------------ -- stylua: ignore function M.get_pio_dir(type) -- 1. Setup Base Paths @@ -54,6 +55,7 @@ function M.get_pio_dir(type) return result end +------------------------------------------------------ -- stylua: ignore function M.fix_pio_compile_commands() local filename = vim.fn.getcwd() .. '/compile_commands.json' @@ -143,6 +145,7 @@ end M.queue = {} local pio_buffer = '' -- Persistent stream buffer +------------------------------------------------------ -- 1. The Dispatcher (The Brain) -- stylua: ignore function M.dispatcher(_, _, data) @@ -173,6 +176,7 @@ function M.dispatcher(_, _, data) if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end end +------------------------------------------------------ -- stylua: ignore M.run_sequence = function(tasks) -- Reset local state for new run @@ -193,19 +197,21 @@ M.run_sequence = function(tasks) M.ToggleTerminal(full_cmd, 'float') end +------------------------------------------------------ -- Handle after 'pio run -t compiledb' execution function M.handleDb() vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) - pio.gitignore_lsp_configs('compile_commands.json') - pio.fix_pio_compile_commands() - pio.lsp_restart('clangd') + misc.gitignore_lsp_configs('compile_commands.json') + M.fix_pio_compile_commands() + misc.lsp_restart('clangd') end +------------------------------------------------------ -- Handle after poioinit execution -- stylua: ignore function M.handlePioinit() vim.notify('Pioinit: Success', vim.log.levels.INFO) - boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') + require('platformio.boilerplate').boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') end -- Handle after poioinit execution -- stylua: ignore diff --git a/plugin/platformio.lua b/plugin/platformio.lua index f7f88c32..334f4478 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -18,7 +18,7 @@ end, { force = true }) -- Piolsp vim.api.nvim_create_user_command('PioLSP', function() vim.schedule(function() - require('platformio.lsp.piolsp').piolsp() + require('platformio.piolsp').piolsp() end) end, {}) From d787c0064311ce9835107b29ec35423436a45544 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 05:45:16 +0300 Subject: [PATCH 0476/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 732e44e9..bcf83d1e 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -211,7 +211,7 @@ end -- stylua: ignore function M.handlePioinit() vim.notify('Pioinit: Success', vim.log.levels.INFO) - require('platformio.boilerplate').boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') + -- require('platformio.boilerplate').boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') end -- Handle after poioinit execution -- stylua: ignore From 46b8b7c4bc6536411065c3c6326837b9c1c5c3fa Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 05:58:49 +0300 Subject: [PATCH 0477/1406] update --- lua/platformio/boilerplate.lua | 3 ++- lua/platformio/piolsp.lua | 3 ++- lua/platformio/utils/pio.lua | 5 +++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 8a16f2c3..b16a903d 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -1,5 +1,6 @@ -local pio = require('platformio.utils.pio') local M = {} + +local pio = require('platformio.utils.pio') local uv = vim.loop local boilerplate = {} diff --git a/lua/platformio/piolsp.lua b/lua/platformio/piolsp.lua index f6a54301..15c213a4 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/piolsp.lua @@ -1,6 +1,7 @@ -local misc = require('platformio.utils.misc') local M = {} +local misc = require('platformio.utils.misc') + -- stylua: ignore function M.piolsp() misc.lsp_restart() diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index bcf83d1e..360d44a4 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -1,9 +1,10 @@ -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -local misc = require('platformio.utils.misc') local M = {} M.selected_framework = '' +local misc = require('platformio.utils.misc') + ------------------------------------------------------ -- stylua: ignore function M.get_pio_dir(type) @@ -211,7 +212,7 @@ end -- stylua: ignore function M.handlePioinit() vim.notify('Pioinit: Success', vim.log.levels.INFO) - -- require('platformio.boilerplate').boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') + require('platformio.boilerplate').boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') end -- Handle after poioinit execution -- stylua: ignore From 38a338f6e755168058857ac0d017b1b91b4c5827 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 06:15:14 +0300 Subject: [PATCH 0478/1406] update --- lua/platformio/boilerplate.lua | 3 ++- lua/platformio/lsp/clangd.lua | 15 ++++++++------- lua/platformio/utils/pio.lua | 4 ++-- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index b16a903d..aa10dd1a 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -1,6 +1,5 @@ local M = {} -local pio = require('platformio.utils.pio') local uv = vim.loop local boilerplate = {} @@ -44,6 +43,7 @@ monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dt lib_ldf_mode = chain+ ;Library dependencies Finder ldf ]], content = function(self) + local pio = require('platformio.utils.pio') return string.format(self.template, pio.get_pio_dir('core')) end, } @@ -84,6 +84,7 @@ clangd --query-driver=%s/toolchain-*/**/bin/* ]], content = function(self) + local pio = require('platformio.utils.pio') return string.format(self.template, pio.get_pio_dir('packages') or '**') end, --query-driver=%s/.platformio/packages/*/bin/riscv32-esp-elf-* diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua index 47a53e14..f5840728 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -1,19 +1,20 @@ ---------------------------------------------------------------------------------------- -- INFO: create clangd required files ----------------------------------------------------------------------------------------- -local boiler = require('platformio.boilerplate') -boiler.boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) +local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) -boiler.boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -boiler.boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) +boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +-- local pio = require('platformio.utils.pio') +boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') -boiler.boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) +boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) -boiler.boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) +boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) -boiler.boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) +boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) -- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) -- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) --------------------------------------------------------------------------------- diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 360d44a4..bb34f1b3 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -1,4 +1,3 @@ --- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local M = {} M.selected_framework = '' @@ -212,7 +211,8 @@ end -- stylua: ignore function M.handlePioinit() vim.notify('Pioinit: Success', vim.log.levels.INFO) - require('platformio.boilerplate').boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') end -- Handle after poioinit execution -- stylua: ignore From 144e1154a49904e56e5eb3080563201dc0e12af7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 06:23:40 +0300 Subject: [PATCH 0479/1406] update --- lua/platformio/utils.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 48f9a18d..534800d4 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -6,7 +6,6 @@ local is_windows = jit.os == 'Windows' local M = {} -M.selected_framework = '' M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' From 62e86ca0807b57f08324e746f16dc1188f0cd59f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 06:34:42 +0300 Subject: [PATCH 0480/1406] update --- lua/platformio/utils.lua | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 534800d4..a17b0684 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -1,16 +1,13 @@ -local config = require('platformio').config --- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -local pio = require('platformio.utils.pio') --.piolsp -local is_windows = jit.os == 'Windows' --- local pioinit = require('platformio.pioinit') - local M = {} +local is_windows = jit.os == 'Windows' M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' - -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' +local config = require('platformio').config +-- local pio = require('platformio.utils.pio') --.piolsp + ------------------------------------------------------ function M.strsplit(inputstr, del) local t = {} @@ -248,7 +245,7 @@ function M.ToggleTerminal(command, direction) -- INFO: on_stdout -- on_stdout = stdout_callback, - on_stdout = pio.dispatcher, + on_stdout = require('platformio.utils.pio').dispatcher, -- INFO: on_create() { on_create = function(t) From 0abeb8257d32189861fccc8d05b1e0f4fdd54408 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 11:12:13 +0300 Subject: [PATCH 0481/1406] update --- lua/platformio/pioinit.lua | 1 + lua/platformio/utils/pio.lua | 6 ++++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 1e0bfece..3b8f5d89 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -58,6 +58,7 @@ local function pick_framework(board_details) local selection = action_state.get_selected_entry() pio.selected_framework = selection[1] + print(pio.selected_framework) pio.run_sequence({ { cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index bb34f1b3..fcbbbf49 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -73,7 +73,7 @@ function M.fix_pio_compile_commands() return end - print('PioFix0') + -- print('PioFix0') -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path local path_map = {} local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') @@ -194,7 +194,9 @@ M.run_sequence = function(tasks) else full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands end full_cmd = full_cmd .. ' || ' .. failure - M.ToggleTerminal(full_cmd, 'float') + print(full_cmd) + print(M.selected_framework) + -- M.ToggleTerminal(full_cmd, 'float') end ------------------------------------------------------ From 55b9344286f9dd829ef0767f0bce100ea932138e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 11:17:55 +0300 Subject: [PATCH 0482/1406] update --- lua/platformio/pioinit.lua | 1 - lua/platformio/utils.lua | 2 +- lua/platformio/utils/pio.lua | 4 +--- 3 files changed, 2 insertions(+), 5 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 3b8f5d89..1e0bfece 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -58,7 +58,6 @@ local function pick_framework(board_details) local selection = action_state.get_selected_entry() pio.selected_framework = selection[1] - print(pio.selected_framework) pio.run_sequence({ { cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index a17b0684..308b7b5c 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -245,7 +245,7 @@ function M.ToggleTerminal(command, direction) -- INFO: on_stdout -- on_stdout = stdout_callback, - on_stdout = require('platformio.utils.pio').dispatcher, + on_stdout = nil, --require('platformio.utils.pio').dispatcher, -- INFO: on_create() { on_create = function(t) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index fcbbbf49..b2a74052 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -194,9 +194,7 @@ M.run_sequence = function(tasks) else full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands end full_cmd = full_cmd .. ' || ' .. failure - print(full_cmd) - print(M.selected_framework) - -- M.ToggleTerminal(full_cmd, 'float') + M.ToggleTerminal(full_cmd, 'float') end ------------------------------------------------------ From 274516d3e804d4b2739fa880fae7c561db03d4fe Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 12:26:47 +0300 Subject: [PATCH 0483/1406] update --- lua/platformio/utils.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils.lua b/lua/platformio/utils.lua index 308b7b5c..a17b0684 100644 --- a/lua/platformio/utils.lua +++ b/lua/platformio/utils.lua @@ -245,7 +245,7 @@ function M.ToggleTerminal(command, direction) -- INFO: on_stdout -- on_stdout = stdout_callback, - on_stdout = nil, --require('platformio.utils.pio').dispatcher, + on_stdout = require('platformio.utils.pio').dispatcher, -- INFO: on_create() { on_create = function(t) From 7ce01b7ff8752ce1442c81c36b111a9c1986b351 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 14:32:20 +0300 Subject: [PATCH 0484/1406] update --- lua/platformio/init.lua | 2 +- lua/platformio/{lsp => lspConfig}/attach.lua | 2 +- lua/platformio/{lsp => lspConfig}/clangd.lua | 3 +- lua/platformio/{lsp => lspConfig}/keymaps.lua | 0 lua/platformio/{ => old}/llspAttach.lua | 0 lua/platformio/{ => old}/llspClangd.lua | 2 +- lua/platformio/{ => old}/llspKeymaps.lua | 0 .../{piocmd.lua => old/lpiocmd.lua} | 0 .../{piodebug.lua => old/lpiodebug.lua} | 0 .../{piolsp.lua => old/lpiolsp.lua} | 4 +- .../{piomon.lua => old/lpiomon.lua} | 0 lua/platformio/{utils.lua => old/lutils.lua} | 0 lua/platformio/old/utils.lua | 104 ++++++ lua/platformio/pioCommands.lua | 71 ++++ lua/platformio/pioinit.lua | 11 +- lua/platformio/piolib.lua | 8 +- lua/platformio/piolsserial.lua | 6 +- lua/platformio/piorun.lua | 21 +- lua/platformio/utils/lsp.lua | 36 ++ lua/platformio/utils/misc.lua | 122 +++++-- lua/platformio/utils/pio.lua | 8 +- lua/platformio/utils/term.lua | 321 ++++++++++++++++++ plugin/platformio.lua | 12 +- 23 files changed, 667 insertions(+), 66 deletions(-) rename lua/platformio/{lsp => lspConfig}/attach.lua (96%) rename lua/platformio/{lsp => lspConfig}/clangd.lua (96%) rename lua/platformio/{lsp => lspConfig}/keymaps.lua (100%) rename lua/platformio/{ => old}/llspAttach.lua (100%) rename lua/platformio/{ => old}/llspClangd.lua (96%) rename lua/platformio/{ => old}/llspKeymaps.lua (100%) rename lua/platformio/{piocmd.lua => old/lpiocmd.lua} (100%) rename lua/platformio/{piodebug.lua => old/lpiodebug.lua} (100%) rename lua/platformio/{piolsp.lua => old/lpiolsp.lua} (80%) rename lua/platformio/{piomon.lua => old/lpiomon.lua} (100%) rename lua/platformio/{utils.lua => old/lutils.lua} (100%) create mode 100644 lua/platformio/old/utils.lua create mode 100644 lua/platformio/pioCommands.lua create mode 100644 lua/platformio/utils/lsp.lua create mode 100644 lua/platformio/utils/term.lua diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index 8b6b173a..43815194 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -185,7 +185,7 @@ function M.setup(user_config) if M.config.lspClangd.enabled == true then -- vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) - require('platformio.lsp.clangd') + require('platformio.lspConfig.clangd') end end diff --git a/lua/platformio/lsp/attach.lua b/lua/platformio/lspConfig/attach.lua similarity index 96% rename from lua/platformio/lsp/attach.lua rename to lua/platformio/lspConfig/attach.lua index 3f7df327..fc8aa51a 100644 --- a/lua/platformio/lsp/attach.lua +++ b/lua/platformio/lspConfig/attach.lua @@ -85,7 +85,7 @@ vim.api.nvim_create_autocmd('LspAttach', { ------------------------------------------------------------------ local config = require('platformio').config if config.lspClangd.attach.keymaps then - local lspkeymaps = require('platformio.lsp.keymaps') + local lspkeymaps = require('platformio.lspConfig.keymaps') lspkeymaps.lspKeymaps(client, bufnr) end end diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lspConfig/clangd.lua similarity index 96% rename from lua/platformio/lsp/clangd.lua rename to lua/platformio/lspConfig/clangd.lua index f5840728..791d92d0 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -5,7 +5,6 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.g.platformioRootDir) --- local pio = require('platformio.utils.pio') boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') @@ -308,6 +307,6 @@ end local config = require('platformio').config if config.lspClangd.attach.enabled then - require('platformio.lsp.attach') + require('platformio.lspConfig.attach') end ---------------------------------------------------------------------------------- diff --git a/lua/platformio/lsp/keymaps.lua b/lua/platformio/lspConfig/keymaps.lua similarity index 100% rename from lua/platformio/lsp/keymaps.lua rename to lua/platformio/lspConfig/keymaps.lua diff --git a/lua/platformio/llspAttach.lua b/lua/platformio/old/llspAttach.lua similarity index 100% rename from lua/platformio/llspAttach.lua rename to lua/platformio/old/llspAttach.lua diff --git a/lua/platformio/llspClangd.lua b/lua/platformio/old/llspClangd.lua similarity index 96% rename from lua/platformio/llspClangd.lua rename to lua/platformio/old/llspClangd.lua index 98804f97..dad10391 100644 --- a/lua/platformio/llspClangd.lua +++ b/lua/platformio/old/llspClangd.lua @@ -307,6 +307,6 @@ end local config = require('platformio').config if config.lspClangd.attach.enabled then - require('platformio.lsp.attach') + require('platformio.lspConfig.attach') end ---------------------------------------------------------------------------------- diff --git a/lua/platformio/llspKeymaps.lua b/lua/platformio/old/llspKeymaps.lua similarity index 100% rename from lua/platformio/llspKeymaps.lua rename to lua/platformio/old/llspKeymaps.lua diff --git a/lua/platformio/piocmd.lua b/lua/platformio/old/lpiocmd.lua similarity index 100% rename from lua/platformio/piocmd.lua rename to lua/platformio/old/lpiocmd.lua diff --git a/lua/platformio/piodebug.lua b/lua/platformio/old/lpiodebug.lua similarity index 100% rename from lua/platformio/piodebug.lua rename to lua/platformio/old/lpiodebug.lua diff --git a/lua/platformio/piolsp.lua b/lua/platformio/old/lpiolsp.lua similarity index 80% rename from lua/platformio/piolsp.lua rename to lua/platformio/old/lpiolsp.lua index 15c213a4..c0c10560 100644 --- a/lua/platformio/piolsp.lua +++ b/lua/platformio/old/lpiolsp.lua @@ -1,10 +1,10 @@ local M = {} -local misc = require('platformio.utils.misc') +local lsp = require('platformio.utils.lsp') -- stylua: ignore function M.piolsp() - misc.lsp_restart() + lsp.lsp_restart() -- local ok, err = pcall(vim.cmd.lsp, { args = { 'restart' } }) -- if ok then vim.notify('LSP restarted' .. err) -- else vim.notify('LSP restart failed: ' .. err) end diff --git a/lua/platformio/piomon.lua b/lua/platformio/old/lpiomon.lua similarity index 100% rename from lua/platformio/piomon.lua rename to lua/platformio/old/lpiomon.lua diff --git a/lua/platformio/utils.lua b/lua/platformio/old/lutils.lua similarity index 100% rename from lua/platformio/utils.lua rename to lua/platformio/old/lutils.lua diff --git a/lua/platformio/old/utils.lua b/lua/platformio/old/utils.lua new file mode 100644 index 00000000..b6499dc8 --- /dev/null +++ b/lua/platformio/old/utils.lua @@ -0,0 +1,104 @@ +local M = {} + +local is_windows = jit.os == 'Windows' +M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' +-- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' +-- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' + +------------------------------------------------------ +function M.strsplit(inputstr, del) + local t = {} + if type(inputstr) == 'string' and inputstr and inputstr ~= '' then + for str in string.gmatch(inputstr, '([^' .. del .. ']+)') do + table.insert(t, str) + end + end + return t +end + +function M.check_prefix(str, prefix) + return str:sub(1, #prefix) == prefix +end + +local function pathmul(n) + return '..' .. string.rep('/..', n) +end + +local paths = { '.', '..', pathmul(1), pathmul(2), pathmul(3), pathmul(4), pathmul(5) } + +function M.file_exists(name) + local f = io.open(name, 'r') + if f ~= nil then + io.close(f) + return true + else + return false + end +end + +function M.set_platformioRootDir() + if vim.g.platformioRootDir ~= nil then + return + end + for _, path in pairs(paths) do + if M.file_exists(path .. '/platformio.ini') then + vim.g.platformioRootDir = path + return + end + end + vim.notify('Could not find platformio.ini, run :Pioinit to create a new project', vim.log.levels.ERROR) +end + +function M.cd_pioini() + M.set_platformioRootDir() + vim.cmd('cd ' .. vim.g.platformioRootDir) +end + +function M.pio_install_check() + local handel = (jit.os == 'Windows') and assert(io.popen('where.exe pio 2>./nul')) or assert(io.popen('which pio 2>/dev/null')) + local pio_path = assert(handel:read('*a')) + handel:close() + + if #pio_path == 0 then + vim.notify('Platformio not found in the path', vim.log.levels.ERROR) + return false + end + return true +end + +function M.async_shell_cmd(cmd, callback) + local output = {} + + vim.fn.jobstart(cmd, { + stdout_buffered = true, + stderr_buffered = false, + + on_stdout = function(_, data) + if data then + for _, line in ipairs(data) do + if line ~= '' then + table.insert(output, line) + end + end + end + end, + + on_exit = function(_, code) + callback(output, code) + end, + }) +end + +function M.shell_cmd_blocking(command) + local handle = io.popen(command, 'r') + if not handle then + return nil, 'failed to run command' + end + + local result = handle:read('*a') + handle:close() + + return result +end + +return M diff --git a/lua/platformio/pioCommands.lua b/lua/platformio/pioCommands.lua new file mode 100644 index 00000000..2f0ef23f --- /dev/null +++ b/lua/platformio/pioCommands.lua @@ -0,0 +1,71 @@ +local M = {} + +local misc = require('platformio.utils.misc') +local ToggleTerminal = require('platformio.utils.term').ToggleTerminal + +-- stylua: ignore +function M.piolsp() + require('platformio.utils.lsp').lsp_restart() + -- local ok, err = pcall(vim.cmd.lsp, { args = { 'restart' } }) + -- if ok then vim.notify('LSP restarted' .. err) + -- else vim.notify('LSP restart failed: ' .. err) end + -- M.fix_pio_compile_commands() +end + +function M.piocmd(cmd_table, direction) + if not misc.pio_install_check() then + return + end + + misc.cd_pioini() + + if cmd_table[1] == '' then + ToggleTerminal('', direction) + else + local cmd = 'pio ' + for _, v in pairs(cmd_table) do + cmd = cmd .. ' ' .. v + end + ToggleTerminal(cmd, direction) + end +end + +function M.piodebug(args_table) + if not misc.pio_install_check() then + return + end + + misc.cd_pioini() + + local command = 'pio debug --interface=gdb -- -x .pioinit' + -- local command = string.format('pio debug --interface=gdb -- -x .pioinit %s', utils.extra) + ToggleTerminal(command, 'float') +end + +function M.piomon(args_table) + if not misc.pio_install_check() then + return + end + + misc.cd_pioini() + + local command = nil + if #args_table == 0 then + command = 'pio device monitor' + elseif #args_table == 1 then + local baud_rate = args_table[1] + command = string.format('pio device monitor -b %s', baud_rate) + elseif #args_table == 2 then + local baud_rate = args_table[1] + local port = args_table[2] + command = string.format('pio device monitor -b %s -p %s', baud_rate, port) + end + + if command == nil then + vim.notify('Usage: Piomon ', vim.log.levels.ERROR) + else + ToggleTerminal(command, 'horizontal') + end +end + +return M diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 1e0bfece..7b4c13cf 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -7,8 +7,7 @@ local actions = require('telescope.actions') local action_state = require('telescope.actions.state') local entry_display = require('telescope.pickers.entry_display') local make_entry = require('telescope.make_entry') -local utils = require('platformio.utils') -local pio = require('platformio.utils.pio') +local misc = require('platformio.utils.misc') local previewers = require('telescope.previewers') local boardentry_maker = function(opts) @@ -56,6 +55,8 @@ local function pick_framework(board_details) actions.select_default:replace(function() actions.close(prompt_bufnr) local selection = action_state.get_selected_entry() + + local pio = require('platformio.utils.pio') pio.selected_framework = selection[1] pio.run_sequence({ @@ -95,7 +96,7 @@ local function pick_board(json_data) previewer = previewers.new_buffer_previewer({ title = 'Board Info', define_preview = function(self, entry, _) - local json = utils.strsplit(vim.inspect(entry['value']['data']), '\n') + local json = misc.strsplit(vim.inspect(entry['value']['data']), '\n') local bufnr = self.state.bufnr vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function @@ -112,13 +113,13 @@ local function pick_board(json_data) end function M.pioinit() - if not utils.pio_install_check() then + if not misc.pio_install_check() then return end -- Read stdout local command = 'pio boards --json-output' - local handel = io.popen(command .. utils.devNul) + local handel = io.popen(command .. misc.devNul) if not handel then return end diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 0a5bf87c..557e1f0c 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -8,8 +8,7 @@ local make_entry = require('telescope.make_entry') local conf = require('telescope.config').values local actions = require('telescope.actions') local action_state = require('telescope.actions.state') -local utils = require('platformio.utils') -local pio = require('platformio.utils.pio') +local misc = require('platformio.utils.misc') local previewers = require('telescope.previewers') -- local piolsp = require('platformio.piolsp') --.piolsp @@ -62,6 +61,7 @@ local function pick_library(json_data) -- local command = 'pio pkg install --library "' .. pkg_name .. '"' -- command = command .. ' && pio run -t compiledb' + local pio = require('platformio.utils.pio') pio.run_sequence({ { cmd = 'pio pkg install --library "' .. pkg_name .. '"', @@ -79,7 +79,7 @@ local function pick_library(json_data) previewer = previewers.new_buffer_previewer({ title = 'Package Info', define_preview = function(self, entry, _) - local json = utils.strsplit(vim.inspect(entry['value']['data']), '\n') + local json = misc.strsplit(vim.inspect(entry['value']['data']), '\n') local bufnr = self.state.bufnr vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function @@ -96,7 +96,7 @@ local function pick_library(json_data) end function M.piolib(lib_arg_list) - if not utils.pio_install_check() then + if not misc.pio_install_check() then return end diff --git a/lua/platformio/piolsserial.lua b/lua/platformio/piolsserial.lua index 2ff7dede..d045e3b2 100644 --- a/lua/platformio/piolsserial.lua +++ b/lua/platformio/piolsserial.lua @@ -1,5 +1,5 @@ local M = {} -local utils = require('platformio.utils') +local misc = require('platformio.utils.misc') M.tty_list = {} @@ -16,14 +16,14 @@ function M.parse_tty(lines) end function M.sync_ttylist() - utils.async_shell_cmd({ 'platformio', 'device', 'list', '--json-output' }, M.parse_tty) + misc.async_shell_cmd({ 'platformio', 'device', 'list', '--json-output' }, M.parse_tty) end function M.sync_ttylist_await() local done = false local result = nil - utils.async_shell_cmd({ 'platformio', 'device', 'list', '--json-output' }, function(lines, code) + misc.async_shell_cmd({ 'platformio', 'device', 'list', '--json-output' }, function(lines, code) result = { lines = lines, code = code } done = true end) diff --git a/lua/platformio/piorun.lua b/lua/platformio/piorun.lua index 89020f20..aae85f15 100644 --- a/lua/platformio/piorun.lua +++ b/lua/platformio/piorun.lua @@ -1,33 +1,34 @@ local M = {} -local utils = require('platformio.utils') +local misc = require('platformio.utils.misc') +local ToggleTerminal = require('platformio.utils.term').ToggleTerminal function M.piobuild() - utils.cd_pioini() + misc.cd_pioini() local command = 'pio run' -- .. utils.extra - utils.ToggleTerminal(command, 'float') + ToggleTerminal(command, 'float') end function M.pioupload() - utils.cd_pioini() + misc.cd_pioini() local command = 'pio run --target upload' -- .. utils.extra - utils.ToggleTerminal(command, 'float') + ToggleTerminal(command, 'float') end function M.piouploadfs() - utils.cd_pioini() + misc.cd_pioini() local command = 'pio run --target uploadfs' -- .. utils.extra - utils.ToggleTerminal(command, 'float') + ToggleTerminal(command, 'float') end function M.pioclean() - utils.cd_pioini() + misc.cd_pioini() local command = 'pio run --target clean' -- .. utils.extra - utils.ToggleTerminal(command, 'float') + ToggleTerminal(command, 'float') end function M.piorun(arg_table) - if not utils.pio_install_check() then + if not misc.pio_install_check() then return end if arg_table[1] == '' then diff --git a/lua/platformio/utils/lsp.lua b/lua/platformio/utils/lsp.lua new file mode 100644 index 00000000..f85c1694 --- /dev/null +++ b/lua/platformio/utils/lsp.lua @@ -0,0 +1,36 @@ +local M = {} + +--- stylua: ignore +function M.lsp_restart(name) + if vim.fn.has('nvim-0.12') == 1 then + -- local clients = vim.lsp.get_clients({ name = name }) + local clangd = vim.lsp.get_clients({ name = name })[1] + if clangd then + local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) + if not ok then + vim.notify('LSP ' .. name .. ' restart failed: ' .. err) + else + vim.notify('LSP ' .. name .. ' restarted' .. err) + end + end + else + local clients = vim.lsp.get_clients({ name = name }) + for _, c in ipairs(clients) do + local configc = c.config + c:stop(true) + vim.defer_fn(function() + vim.lsp.config(name, configc) + vim.lsp.enable(name) + vim.cmd('checktime') + end, 600) + end + -- -- 1. Stop the specific client + -- for _, client in ipairs(clients) do client:stop() end + -- + -- -- 2. Reload all loaded buffers to trigger re-attachment for that client + -- -- (Note: 'checktime' is safer than 'bufdo edit' as it respects unsaved changes) + -- vim.cmd('checktime') + end +end + +return M diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 0a3b1856..0e587c6a 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -1,36 +1,104 @@ local M = {} ---- stylua: ignore -function M.lsp_restart(name) - if vim.fn.has('nvim-0.12') == 1 then - -- local clients = vim.lsp.get_clients({ name = name }) - local clangd = vim.lsp.get_clients({ name = name })[1] - if clangd then - local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) - if not ok then - vim.notify('LSP ' .. name .. ' restart failed: ' .. err) - else - vim.notify('LSP ' .. name .. ' restarted' .. err) - end +local is_windows = jit.os == 'Windows' +M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' +-- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' +-- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' + +------------------------------------------------------ +function M.strsplit(inputstr, del) + local t = {} + if type(inputstr) == 'string' and inputstr and inputstr ~= '' then + for str in string.gmatch(inputstr, '([^' .. del .. ']+)') do + table.insert(t, str) end + end + return t +end + +function M.check_prefix(str, prefix) + return str:sub(1, #prefix) == prefix +end + +local function pathmul(n) + return '..' .. string.rep('/..', n) +end + +local paths = { '.', '..', pathmul(1), pathmul(2), pathmul(3), pathmul(4), pathmul(5) } + +function M.file_exists(name) + local f = io.open(name, 'r') + if f ~= nil then + io.close(f) + return true else - local clients = vim.lsp.get_clients({ name = name }) - for _, c in ipairs(clients) do - local configc = c.config - c:stop(true) - vim.defer_fn(function() - vim.lsp.config(name, configc) - vim.lsp.enable(name) - vim.cmd('checktime') - end, 600) + return false + end +end + +function M.set_platformioRootDir() + if vim.g.platformioRootDir ~= nil then + return + end + for _, path in pairs(paths) do + if M.file_exists(path .. '/platformio.ini') then + vim.g.platformioRootDir = path + return end - -- -- 1. Stop the specific client - -- for _, client in ipairs(clients) do client:stop() end - -- - -- -- 2. Reload all loaded buffers to trigger re-attachment for that client - -- -- (Note: 'checktime' is safer than 'bufdo edit' as it respects unsaved changes) - -- vim.cmd('checktime') end + vim.notify('Could not find platformio.ini, run :Pioinit to create a new project', vim.log.levels.ERROR) +end + +function M.cd_pioini() + M.set_platformioRootDir() + vim.cmd('cd ' .. vim.g.platformioRootDir) +end + +function M.pio_install_check() + local handel = (jit.os == 'Windows') and assert(io.popen('where.exe pio 2>./nul')) or assert(io.popen('which pio 2>/dev/null')) + local pio_path = assert(handel:read('*a')) + handel:close() + + if #pio_path == 0 then + vim.notify('Platformio not found in the path', vim.log.levels.ERROR) + return false + end + return true +end + +function M.async_shell_cmd(cmd, callback) + local output = {} + + vim.fn.jobstart(cmd, { + stdout_buffered = true, + stderr_buffered = false, + + on_stdout = function(_, data) + if data then + for _, line in ipairs(data) do + if line ~= '' then + table.insert(output, line) + end + end + end + end, + + on_exit = function(_, code) + callback(output, code) + end, + }) +end + +function M.shell_cmd_blocking(command) + local handle = io.popen(command, 'r') + if not handle then + return nil, 'failed to run command' + end + + local result = handle:read('*a') + handle:close() + + return result end function M.gitignore_lsp_configs(config_file) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index b2a74052..5807c62a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -3,6 +3,7 @@ local M = {} M.selected_framework = '' local misc = require('platformio.utils.misc') +local lsp = require('platformio.utils.lsp') ------------------------------------------------------ -- stylua: ignore @@ -133,7 +134,7 @@ function M.fix_pio_compile_commands() out_file:write(formatted_json) out_file:close() vim.notify('compiledb: fixed', vim.log.levels.INFO) - M.lsp_restart('clangd') + lsp.lsp_restart('clangd') end end end @@ -194,7 +195,8 @@ M.run_sequence = function(tasks) else full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands end full_cmd = full_cmd .. ' || ' .. failure - M.ToggleTerminal(full_cmd, 'float') + local ToggleTerminal = require('platformio.utils.term').ToggleTerminal + ToggleTerminal(full_cmd, 'float') end ------------------------------------------------------ @@ -203,7 +205,7 @@ function M.handleDb() vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) misc.gitignore_lsp_configs('compile_commands.json') M.fix_pio_compile_commands() - misc.lsp_restart('clangd') + lsp.lsp_restart('clangd') end ------------------------------------------------------ diff --git a/lua/platformio/utils/term.lua b/lua/platformio/utils/term.lua new file mode 100644 index 00000000..7a8d8981 --- /dev/null +++ b/lua/platformio/utils/term.lua @@ -0,0 +1,321 @@ +local M = {} + +local is_windows = jit.os == 'Windows' +M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' +-- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' +-- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' + +local config = require('platformio').config +local pio = require('platformio.utils.pio') + +------------------------------------------------------ +function M.strsplit(inputstr, del) + local t = {} + if type(inputstr) == 'string' and inputstr and inputstr ~= '' then + for str in string.gmatch(inputstr, '([^' .. del .. ']+)') do + table.insert(t, str) + end + end + return t +end + +function M.check_prefix(str, prefix) + return str:sub(1, #prefix) == prefix +end + +local function pathmul(n) + return '..' .. string.rep('/..', n) +end + +------------------------------------------------------ + +-- INFO: get current OS enter +function M.enter() + local shell = vim.o.shell + if is_windows then + return vim.fn.executable('pwsh') and '\r' or '\r\n' + elseif shell:find('nu') then + return '\r' + else + return '\n' + end +end + +-- INFO: get previous window +local function getPreviousWindow(orig_window) + local prev = { + orig_window = orig_window, + term = nil, --active terminal + cli = nil, --cli terminal + mon = nil, --mon terminal + float = false, --is active terminal direction float + } + local terms = require('toggleterm.terminal').get_all(true) + if #terms ~= 0 then + for i = 1, #terms do + if terms[i].display_name and terms[i].display_name ~= '' and terms[i].display_name:find('pio', 1) then + local name_splt = M.strsplit(terms[i].display_name, ':') + if name_splt[1] == 'piocli' then + prev.cli = terms[i] + if terms[i].window == orig_window then + ---@diagnostic disable-next-line: cast-local-type + prev.orig_window = tonumber(name_splt[2]) -- set orig_window to the previous terminal onrig_window + prev.term = terms[i] + end + if terms[i].direction == 'float' then + prev.float = true + end + elseif name_splt[1] == 'piomon' then + prev.mon = terms[i] + if terms[i].window == orig_window then + ---@diagnostic disable-next-line: cast-local-type + prev.orig_window = tonumber(name_splt[2]) -- set orig_window to the previous terminal onrig_window + prev.term = terms[i] + end + if terms[i].direction == 'float' then + prev.float = true + end + end + end + end + end + return prev +end + +------------------------------------------------------ +-- INFO: Send command +local function send(term, cmd) + vim.fn.chansend(term.job_id, cmd .. M.enter()) + if vim.api.nvim_buf_is_loaded(term.bufnr) and vim.api.nvim_buf_is_valid(term.bufnr) then + if term.window and vim.api.nvim_win_is_valid(term.window) then --vim.ui.term_has_open_win(term) then + vim.api.nvim_set_current_win(term.window) -- terminal focus + vim.api.nvim_buf_call(term.bufnr, function() + local mode = vim.api.nvim_get_mode().mode + if mode == 'n' or mode == 'nt' then + vim.cmd('normal! G') -- normal command to Goto bottom of buffer (scroll) + end + end) + end + end +end + +------------------------------------------------------ +-- INFO: PioTermClose +local function PioTermClose(t) + local orig_window = tonumber(M.strsplit(t.display_name, ':')[2]) + -- close terminal window + vim.api.nvim_win_close(t.window, true) + + -- go back to previous window + if orig_window and vim.api.nvim_win_is_valid(orig_window) then + vim.api.nvim_set_current_win(orig_window) + else + vim.api.nvim_set_current_win(0) + end +end + +------------------------------------------------------ +-- INFO: ToggleTerminal +function M.ToggleTerminal(command, direction) + local status_ok, _ = pcall(require, 'toggleterm') + if not status_ok then + vim.api.nvim_echo({ { 'toggleterm not found!', 'ErrorMsg' } }, true, {}) + return + end + + local title = '' + local pioOpts = {} + + -- INFO: set orig_window to current window, or if available get current toggleterm previous window + local prev = getPreviousWindow(vim.api.nvim_get_current_win()) + local orig_window = prev.orig_window + + if string.find(command, ' monitor') then + if prev.mon then -- INFO: if previous monitor terminal already opened ==> reopen + prev.mon.display_name = 'piomon:' .. orig_window + local win_type = vim.fn.win_gettype(prev.mon.window) + local win_open = win_type == '' or win_type == 'popup' + if prev.mon.window and (win_open and vim.api.nvim_win_get_buf(prev.mon.window) == prev.mon.bufnr) then + vim.api.nvim_set_current_win(prev.mon.window) + else + prev.mon:open() + end + return + end + title = 'Pio Monitor: [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' + pioOpts.display_name = 'piomon:' .. orig_window + else -- INFO: if previous cli terminal already opened ==> reopen + if prev.cli then + prev.cli.display_name = 'piocli:' .. orig_window + local win_type = vim.fn.win_gettype(prev.cli.window) + local win_open = win_type == '' or win_type == 'popup' + if prev.cli.window and (win_open and vim.api.nvim_win_get_buf(prev.cli.window) == prev.cli.bufnr) then + vim.api.nvim_set_current_win(prev.cli.window) + else + prev.cli:open() + end + vim.defer_fn(function() + if command and command ~= '' then + send(prev.cli, command) + end + end, 50) -- 50ms delay, adjust as needed + return + end + title = 'Pio CLI> [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' + pioOpts.display_name = 'piocli:' .. orig_window + end + pioOpts.direction = direction + ------------------------------------------------------ + + -- INFO: termConfig table start + local termConfig = { + hidden = true, -- Start hidden, we'll open it explicitly + hide_numbers = true, + float_opts = { + winblend = 0, + width = function() + return math.ceil(vim.o.columns * 0.85) + end, + height = function() + return math.ceil(vim.o.lines * 0.85) + end, + -- shell = vim.o.shell, + shell = vim.o.shell, + highlights = { + border = 'FloatBorder', + background = 'NormalFloat', + }, + }, + close_on_exit = false, --closeOnexit, + + -- INFO: on_open() + on_open = function(t) + -- Get properties of the 'Normal' highlight group (background of main editor) + -- local hl = vim.api.nvim_get_hl(0, { name = 'PmenuSel' }) + -- local hl = { bg = '#e4cf0e', fg = '#0012d9' } + local hl = { bg = '#80a3d4', fg = '#000000' } + + if hl then + vim.api.nvim_set_hl(0, 'MyWinBar', { bg = hl.bg, fg = hl.fg }) + + local winBartitle = '%#MyWinBar#' .. title .. '%*' + vim.api.nvim_set_option_value('winbar', winBartitle, { scope = 'local', win = t.window }) + + -- Following necessary to solve that some time winbar not showing + vim.schedule(function() + vim.api.nvim_set_option_value('winbar', winBartitle, { scope = 'local', win = t.window }) + end) + end + vim.keymap.set('t', '', [[k]], { buffer = t.bufnr }) + vim.keymap.set('n', '', [[a]], { buffer = t.bufnr }) + + vim.keymap.set('n', 'q', function() + PioTermClose(t) + end, { desc = 'PioTermClose', buffer = t.bufnr }) + + if config.debug then + local name_splt = M.strsplit(t.display_name, ':') + vim.api.nvim_echo({ + { 'ToggleTerm ', 'MoreMsg' }, + { '(Term name: ' .. name_splt[1] .. ')', 'MoreMsg' }, + { '(Prev win ID: ' .. name_splt[2] .. ')', 'MoreMsg' }, + { '(Term Win ID: ' .. t.window .. ')', 'MoreMsg' }, + { '(Term Buffer#: ' .. t.bufnr .. ')', 'MoreMsg' }, + { '(Term id: ' .. t.id .. ')', 'MoreMsg' }, + { '(Job ID: ' .. t.job_id .. ')', 'MoreMsg' }, + }, true, {}) + end + end, + + -- INFO: on_close() + on_close = function(t) + orig_window = tonumber(M.strsplit(t.display_name, ':')[2]) + ---@diagnostic disable-next-line: param-type-mismatch + if orig_window and vim.api.nvim_win_is_valid(orig_window) then + vim.api.nvim_set_current_win(orig_window) + else + vim.api.nvim_set_current_win(0) + end + end, + + -- -- INFO: on_exit() + -- on_exit = function(_) + -- exit_callback() + -- end, + + -- INFO: on_stdout + -- on_stdout = stdout_callback, + on_stdout = pio.dispatcher, + + -- INFO: on_create() { + on_create = function(t) + local platformio = vim.api.nvim_create_augroup(M.strsplit(t.display_name, ':')[1], { clear = true }) + + -- INFO: CmdlineLeave + vim.api.nvim_create_autocmd('CmdlineLeave', { + group = platformio, + -- pattern = ':', + buffer = t.bufnr, + callback = function() + if vim.v.event and not vim.v.event.abort and vim.v.event.cmdtype == ':' then + local quit = vim.fn.getcmdline() == 'q' + local quitbang = vim.fn.getcmdline() == 'q!' + if quitbang or quit then + local name_splt = M.strsplit(t.display_name, ':') + if quitbang then + if name_splt[1] == 'piomon' then -- monitor terminal + local exit = vim.api.nvim_replace_termcodes('exit', true, true, true) + send(t, exit) + else -- cli terminal + send(t, 'exit') + end + end + + orig_window = tonumber(name_splt[2]) + vim.schedule(function() + -- go back to previous window + if orig_window and vim.api.nvim_win_is_valid(orig_window) then + vim.api.nvim_set_current_win(orig_window) + else + vim.api.nvim_set_current_win(0) + end + end) + end + end + end, + }) + + -- INFO: BufUnload + vim.api.nvim_create_autocmd('BufUnload', { + group = platformio, + desc = 'toggleterm buffer unloaded', + buffer = t.bufnr, + callback = function(args) + vim.keymap.del('t', '', { buffer = args.buf }) + vim.keymap.del('n', '', { buffer = args.buf }) + + -- clear autommmand when quit + vim.api.nvim_clear_autocmds({ group = M.strsplit(t.display_name, ':')[1] }) + end, + }) + end, + } + -- INFO: termConfig table end + + termConfig = vim.tbl_deep_extend('force', termConfig, pioOpts or {}) + + -- INFO: create new terminal + local terminal = require('toggleterm.terminal').Terminal:new(termConfig) + if prev.term and prev.float then + prev.term:close() + end + terminal:toggle() + vim.defer_fn(function() + if command and command ~= '' then + send(terminal, command) + end + end, 50) -- 50ms delay, adjust as needed sgget +end + +return M +---------------------------------------------------------------------------------------- diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 334f4478..dc595517 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -18,7 +18,7 @@ end, { force = true }) -- Piolsp vim.api.nvim_create_user_command('PioLSP', function() vim.schedule(function() - require('platformio.piolsp').piolsp() + require('platformio.pioCommands').piolsp() end) end, {}) @@ -37,7 +37,7 @@ end, { -- piolsserial.sync_ttylist() vim.api.nvim_create_user_command('Piomon', function(opts) local args = opts.fargs - require('platformio.piomon').piomon(args) + require('platformio.pioCommands').piomon(args) end, { nargs = '*', @@ -74,7 +74,7 @@ end, { -- Piocmdh Piocmd horizontal terminal vim.api.nvim_create_user_command('Piocmdh', function(opts) local cmd_table = vim.split(opts.args, ' ') - require('platformio.piocmd').piocmd(cmd_table, 'horizontal') + require('platformio.pioCommands').piocmd(cmd_table, 'horizontal') end, { nargs = '*', }) @@ -82,14 +82,14 @@ end, { -- Piocmdf Piocmd float terminal vim.api.nvim_create_user_command('Piocmdf', function(opts) local cmd_table = vim.split(opts.args, ' ') - require('platformio.piocmd').piocmd(cmd_table, 'float') + require('platformio.pioCommands').piocmd(cmd_table, 'float') end, { nargs = '*', }) -- Piodebug vim.api.nvim_create_user_command('Piodebug', function() - require('platformio.piodebug').piodebug() + require('platformio.pioCommands').piodebug() end, {}) ------------------------------------------------------ @@ -103,8 +103,6 @@ vim.api.nvim_create_user_command('PioFixPaths', function() cb = pio.handleDb, }, }) - -- local command = 'pio run -t compiledb' - -- utils.ToggleTerminal(command, 'float') end, {}) ------------------------------------------------------ From 35e137372ea306768cd04810bb1c0df1bc214fb5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 14:39:36 +0300 Subject: [PATCH 0485/1406] update --- lua/platformio/pioinit.lua | 16 ++++++++-------- lua/platformio/utils/misc.lua | 6 +++--- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 7b4c13cf..c1d3d911 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -119,21 +119,21 @@ function M.pioinit() -- Read stdout local command = 'pio boards --json-output' - local handel = io.popen(command .. misc.devNul) - if not handel then + local handle = io.popen(command .. misc.devNul) + if not handle then return end - local json_str = handel:read('*a') - handel:close() + local json_str = handle:read('*a') + handle:close() if #json_str == 0 then -- read stderr - handel = io.popen(command .. ' 2>&1') - if not handel then + handle = io.popen(command .. ' 2>&1') + if not handle then return end - local command_output = handel:read('*a') - handel:close() + local command_output = handle:read('*a') + handle:close() vim.notify('Some error occured while executing `' .. command .. "`', command output: \n", vim.log.levels.WARN) print(command_output) return diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 0e587c6a..b226ba37 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -55,9 +55,9 @@ function M.cd_pioini() end function M.pio_install_check() - local handel = (jit.os == 'Windows') and assert(io.popen('where.exe pio 2>./nul')) or assert(io.popen('which pio 2>/dev/null')) - local pio_path = assert(handel:read('*a')) - handel:close() + local handle = (jit.os == 'Windows') and assert(io.popen('where.exe pio 2>./nul')) or assert(io.popen('which pio 2>/dev/null')) + local pio_path = assert(handle():read('*a')) + handle():close() if #pio_path == 0 then vim.notify('Platformio not found in the path', vim.log.levels.ERROR) From 7b527b0314416b0c4f551665f4113e420ad9808e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 14:42:55 +0300 Subject: [PATCH 0486/1406] update --- plugin/platformio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugin/platformio.lua b/plugin/platformio.lua index dc595517..8b8774a5 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -6,7 +6,7 @@ -- +: At least one argument. -- -1: Zero or one argument (like ?, explicitly). -local utils = require('platformio.utils') +local misc = require('platformio.utils.misc') local pio = require('platformio.utils.pio') local piolsserial = require('platformio.piolsserial') @@ -142,7 +142,7 @@ vim.api.nvim_create_user_command('PioTermList', function() if #terms ~= 0 then for i = 1, #terms do if terms[i].display_name and terms[i].display_name ~= '' and terms[i].display_name:find('pio', 1) then - local termtype = utils.strsplit(terms[i].display_name, ':')[1] + local termtype = misc.strsplit(terms[i].display_name, ':')[1] table.insert(toggleterm_list, { term = terms[i], termtype = termtype, -- Store the terminal type [piomon or piocli] From 99c819b8557f034618458c4a0b2a5d6d9e0b2e7b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 14:47:08 +0300 Subject: [PATCH 0487/1406] update --- lua/platformio/utils/misc.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index b226ba37..8eea81aa 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -56,8 +56,8 @@ end function M.pio_install_check() local handle = (jit.os == 'Windows') and assert(io.popen('where.exe pio 2>./nul')) or assert(io.popen('which pio 2>/dev/null')) - local pio_path = assert(handle():read('*a')) - handle():close() + local pio_path = assert(handle:read('*a')) + handle:close() if #pio_path == 0 then vim.notify('Platformio not found in the path', vim.log.levels.ERROR) From 45e07aea167866d5d6d70910aaf051b03c1c54b9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 14:52:51 +0300 Subject: [PATCH 0488/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 5807c62a..28ea650f 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -182,7 +182,7 @@ end M.run_sequence = function(tasks) -- Reset local state for new run M.queue = {} - -- pio_buffer = '' + pio_buffer = '' local full_cmd = '' local success = 'echo ___DONE___":"SUCCESS' From ca0ed1d6c721b015061e78578a440fa0d59f6fdd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 15:20:08 +0300 Subject: [PATCH 0489/1406] update --- .../{old/lpiocmd.lua => archived/piocmd.lua} | 0 .../lpiodebug.lua => archived/piodebug.lua} | 0 .../{old/lpiolsp.lua => archived/piolsp.lua} | 0 .../{old/lpiomon.lua => archived/piomon.lua} | 0 .../{old/lutils.lua => archived/utils.lua} | 0 lua/platformio/old/llspAttach.lua | 125 ------- lua/platformio/old/llspClangd.lua | 312 ------------------ lua/platformio/old/llspKeymaps.lua | 136 -------- lua/platformio/old/utils.lua | 104 ------ lua/platformio/piolsserial.lua | 2 +- lua/platformio/utils/pio.lua | 9 +- 11 files changed, 4 insertions(+), 684 deletions(-) rename lua/platformio/{old/lpiocmd.lua => archived/piocmd.lua} (100%) rename lua/platformio/{old/lpiodebug.lua => archived/piodebug.lua} (100%) rename lua/platformio/{old/lpiolsp.lua => archived/piolsp.lua} (100%) rename lua/platformio/{old/lpiomon.lua => archived/piomon.lua} (100%) rename lua/platformio/{old/lutils.lua => archived/utils.lua} (100%) delete mode 100644 lua/platformio/old/llspAttach.lua delete mode 100644 lua/platformio/old/llspClangd.lua delete mode 100644 lua/platformio/old/llspKeymaps.lua delete mode 100644 lua/platformio/old/utils.lua diff --git a/lua/platformio/old/lpiocmd.lua b/lua/platformio/archived/piocmd.lua similarity index 100% rename from lua/platformio/old/lpiocmd.lua rename to lua/platformio/archived/piocmd.lua diff --git a/lua/platformio/old/lpiodebug.lua b/lua/platformio/archived/piodebug.lua similarity index 100% rename from lua/platformio/old/lpiodebug.lua rename to lua/platformio/archived/piodebug.lua diff --git a/lua/platformio/old/lpiolsp.lua b/lua/platformio/archived/piolsp.lua similarity index 100% rename from lua/platformio/old/lpiolsp.lua rename to lua/platformio/archived/piolsp.lua diff --git a/lua/platformio/old/lpiomon.lua b/lua/platformio/archived/piomon.lua similarity index 100% rename from lua/platformio/old/lpiomon.lua rename to lua/platformio/archived/piomon.lua diff --git a/lua/platformio/old/lutils.lua b/lua/platformio/archived/utils.lua similarity index 100% rename from lua/platformio/old/lutils.lua rename to lua/platformio/archived/utils.lua diff --git a/lua/platformio/old/llspAttach.lua b/lua/platformio/old/llspAttach.lua deleted file mode 100644 index 7d21e24c..00000000 --- a/lua/platformio/old/llspAttach.lua +++ /dev/null @@ -1,125 +0,0 @@ --- local piolsp = require('platformio.piolsp') --.piolsp --- INFO: LspAttach autocommand start -vim.api.nvim_create_autocmd('LspAttach', { - group = vim.api.nvim_create_augroup('platformio-lsp-attach', { clear = true }), - callback = function(args) - local client = assert(vim.lsp.get_client_by_id(args.data.client_id)) - local bufnr = args.buf - - if client then - vim.api.nvim_echo({ { 'Attaching ' .. client.name .. ' to buffer ' .. bufnr, 'Info' } }, true, {}) - - ------------------------------------------------------------------ - if client.name == 'clangd' then - vim.api.nvim_buf_create_user_command(0, 'LspClangdSwitchSourceHeader', function() - local method_name = 'textDocument/switchSourceHeader' - local params = vim.lsp.util.make_text_document_params(bufnr) - client.request(method_name, params, function(err, result) - if err then - error(tostring(err)) - end - if not result then - vim.notify('corresponding file cannot be determined') - return - end - vim.cmd.edit(vim.uri_to_fname(result)) - end, bufnr) - end, { desc = 'Switch between source/header' }) - -- piolsp.fix_pio_compile_commands() - end - - -- use lsp completion if no blink - local ok, _ = pcall(require, 'blink.cmp') - if not ok then - if client:supports_method('textDocument/completion') then - vim.opt.completeopt = { 'menu', 'menuone', 'noselect', 'noinsert', 'fuzzy', 'popup' } - - -- Enable native completion for this specific client and buffer - vim.lsp.completion.enable(true, client.id, args.buf, { autotrigger = true }) - vim.keymap.set('i', ' End LspAttach autocommand diff --git a/lua/platformio/old/llspClangd.lua b/lua/platformio/old/llspClangd.lua deleted file mode 100644 index dad10391..00000000 --- a/lua/platformio/old/llspClangd.lua +++ /dev/null @@ -1,312 +0,0 @@ ----------------------------------------------------------------------------------------- --- INFO: create clangd required files ------------------------------------------------------------------------------------------ -local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) - -boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -boilerplate_gen([[.clangd]], vim.env.PLATFORMIO_CORE_DIR) --- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) --- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') - -boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - -boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) - -boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) --- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) --- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) ---------------------------------------------------------------------------------- - -local ok, result -ok, result = pcall(require, 'fidget') -if ok then - result.setup({}) -end - ------------------------------------------------------------------------------------------ -ok, result = pcall(require, 'trouble') -if ok then - result.setup({}) -end - ----------------------------------------------------------------------------------------- --- INFO: setup and install mason packages ------------------------------------------------------------------------------------------ -ok, result = pcall(require, 'mason') -if ok then - result.setup({ - PATH = 'append', - ui = { - border = 'single', - icons = { - package_installed = '✓', - package_pending = '➜', - package_uninstalled = '✗', - }, - }, - }) -end - --- List of packages you want Mason to ensure are installed -local ensure_installed = { - -- 'clang-format', embeded in clangd - -- 'stylua', -} --- call mason-registry function to install or ensure formatters/linters are installed -local mr = require('mason-registry') -mr.refresh(function() - for _, tool in ipairs(ensure_installed) do - ok, result = pcall(mr.get_package, tool) - if ok and result then - if not result:is_installed() then - if not result:is_installing() then - result:install({}, function(success, _) - if not success then - vim.defer_fn(function() - vim.notify(tool .. ' failed to install', vim.log.levels.ERROR) - end, 0) - end - end) - else - vim.defer_fn(function() - vim.notify(tool .. ' already installed', vim.log.levels.WARN) - end, 0) - end - end - else - vim.defer_fn(function() - vim.notify('Failed to get package: ' .. tool, vim.log.levels.WARN) - end, 0) - end - end -end) - ----------------------------------------------------------------------------------------- --- INFO: install clangd using mason-lspconfig ------------------------------------------------------------------------------------------ -local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') -if mok then - mason_lspconfig.setup({ - -- ensure_installed = { 'clangd', 'pyrefly' }, - -- ensure_installed = { 'ccls', 'lua_ls', 'pyrefly', 'yamlls' }, - ensure_installed = { 'clangd', 'lua_ls', 'pyrefly', 'yamlls' }, - automatic_enable = true, -- this will automatically enable LSP servers after lsp.config - }) -end - -local capabilities = vim.lsp.protocol.make_client_capabilities({ - textDocument = { - -- Folding capabilities for nvim-ufo - foldingRange = { - dynamicRegistration = false, - lineFoldingOnly = true, - }, - }, -}) -local bok, blink = pcall(require, 'blink.cmp') -if bok then - -- capabilities = vim.tbl_deep_extend('force', capabilities, blink.get_lsp_capabilities({}, false)) - capabilities = blink.get_lsp_capabilities(capabilities) -end - --- INFO: 1 -vim.lsp.config('*', { - capabilities = capabilities, - root_markers = { '.git' }, - workspace_required = false, -}) - ----------------------------------------------------------------------------------------- --- INFO: configure ccls lsp server ------------------------------------------------------------------------------------------ --- vim.lsp.config('ccls', { --- filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, --- root_markers = { --- 'CMakeLists.txt', --- '.clangd', --- '.clang-tidy', --- '.clang-format', --- 'compile_commands.json', --- 'compile_flags.txt', --- 'configure.ac', --- '.git', --- vim.uv.cwd(), --- }, --- init_options = { --- diagnostics = { --- onChange = 100, --- }, --- }, --- }) --- vim.lsp.enable('ccls') - ----------------------------------------------------------------------------------------- --- INFO: configure clangd lsp server ------------------------------------------------------------------------------------------ -local cmd = { 'clangd' } -local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) --- if vim.fn.filereadable(fname) == 1 then -if vim.uv.fs_stat(fname) then - ok, result = pcall(vim.fn.readfile, fname) - if ok then - cmd = result - -- print(vim.inspect(cmd)) - end -end - -local clangd = { - cmd = cmd, - filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, - root_markers = { - 'CMakeLists.txt', - '.clangd', - '.clang-tidy', - '.clang-format', - 'compile_commands.json', - 'compile_flags.txt', - 'configure.ac', - '.git', - vim.uv.cwd(), - }, - workspace_required = true, - single_file_support = true, - init_options = { - usePlaceholders = true, - completeUnimported = true, - fallback_flags = { '-std=c++17' }, - clangdFileStatus = true, - compilationDatabasePath = vim.fn.getcwd(), - }, -} -vim.lsp.config('clangd', clangd) - ----------------------------------------------------------------------------------------- --- INFO: configure clangd lsp server ------------------------------------------------------------------------------------------ -local lua_ls = { - cmd = { 'lua-language-server' }, - filetypes = { 'lua' }, - root_markers = { - '.luarc.json', - '.luarc.jsonc', - '.luacheckrc', - '.stylua.toml', - 'selene.toml', - 'selene.yml', - '.git', - }, - settings = { - Lua = { - hint = { - enable = true, - arrayIndex = 'Enable', - await = true, - paramName = 'All', - paramType = true, - semicolon = 'Disable', - setType = true, - }, - telemetry = { enable = false }, - diagnostics = { globals = { 'vim' } }, - runtime = { - -- Specify LuaJIT for Neovim - version = 'LuaJIT', - -- Include Neovim runtime files - path = vim.split(package.path, ';'), - }, - workspace = { - checkThirdParty = false, - library = { - vim.env.VIMRUNTIME, - '${3rd}/luv/library', - './lua', - vim.api.nvim_get_runtime_file('', true), - -- Depending on the usage, you might want to add additional paths here. - -- "${3rd}/busted/library", - }, - }, - }, - }, -} -vim.lsp.config('lua_ls', lua_ls) - -local yamlls = { - -- on_attach = opts.on_attach, - cmd = { 'yaml-language-server', '--stdio' }, - filetypes = { 'yaml', 'yaml.docker-compose', 'yaml.gitlab' }, - settings = { - yaml = { - hover = true, - validate = false, - completion = true, - keyOrdering = false, - format = { enabled = false }, - redhat = { - telemetry = { enabled = false }, - }, - schemaStore = { - enable = true, - url = 'https://www.schemastore.org/api/json/catalog.json', - }, - schemas = { - kubernetes = '*.yaml', - ['http://json.schemastore.org/github-workflow'] = '.github/workflows/*', - ['http://json.schemastore.org/github-action'] = '.github/action.{yml,yaml}', - ['https://raw.githubusercontent.com/microsoft/azure-pipelines-vscode/master/service-schema.json'] = 'azure-pipelines.yml', - ['http://json.schemastore.org/ansible-stable-2.9'] = 'roles/tasks/*.{yml,yaml}', - ['http://json.schemastore.org/prettierrc'] = '.prettierrc.{yml,yaml}', - ['http://json.schemastore.org/kustomization'] = 'kustomization.{yml,yaml}', - ['http://json.schemastore.org/ansible-playbook'] = '*play*.{yml,yaml}', - ['http://json.schemastore.org/chart'] = 'Chart.{yml,yaml}', - ['https://json.schemastore.org/dependabot-v2'] = '.github/dependabot.{yml,yaml}', - ['https://gitlab.com/gitlab-org/gitlab/-/raw/master/app/assets/javascripts/editor/schema/ci.json'] = '*gitlab-ci*.{yml,yaml}', - ['https://raw.githubusercontent.com/OAI/OpenAPI-Specification/main/schemas/v3.1/schema.json'] = '*api*.{yml,yaml}', - ['https://raw.githubusercontent.com/compose-spec/compose-spec/master/schema/compose-spec.json'] = '*docker-compose*.{yml,yaml}', - ['https://raw.githubusercontent.com/argoproj/argo-workflows/master/api/jsonschema/schema.json'] = '*flow*.{yml,yaml}', - ['https://raw.githubusercontent.com/yannh/kubernetes-json-schema/refs/heads/master/v1.32.1-standalone-strict/all.json'] = '/*.k8s.yaml', - }, - }, - }, -} -vim.lsp.config('yamlls', yamlls) - --- local stylua = { --- cmd = { 'stylua', '--search-parent-directories', '--stdin-filepath', '$FILENAME', '-' }, --- filetypes = { 'lua' }, --- root_markers = { 'stylua.toml', '.stylua.toml', '.git' }, --- } --- vim.lsp.config('stylua', stylua) --- vim.lsp.enable('stylua') - -local pyrefly = { - name = 'pyrefly', - cmd = { 'pyrefly', 'lsp' }, - filetypes = { 'python' }, - root_markers = { 'pyrefly.toml', 'pyproject.toml', 'setup.py', 'setup.cfg', 'requirements.txt', 'Pipfile', '.git' }, - settings = { - python = { - pyrefly = { - displayTypeErrors = 'force-on', - }, - -- pythonPath = vim.env.VIRTUAL_ENV, - venvPath = vim.env.VIRTUAL_ENV, - }, - }, -} -vim.lsp.config('pyrefly', pyrefly) - --- require('platformio.piolsp').piolsp() -if vim.fn.has('nvim-0.12') then - if #vim.lsp.get_clients() > 0 then - vim.cmd('lsp restart') - end -else - vim.cmd('LspRestart') -end - -local config = require('platformio').config -if config.lspClangd.attach.enabled then - require('platformio.lspConfig.attach') -end ----------------------------------------------------------------------------------- diff --git a/lua/platformio/old/llspKeymaps.lua b/lua/platformio/old/llspKeymaps.lua deleted file mode 100644 index cb58c3ba..00000000 --- a/lua/platformio/old/llspKeymaps.lua +++ /dev/null @@ -1,136 +0,0 @@ -local K = {} ---Lua functions in combination with the option expr = true handles keycodes automatically -function K.lspKeymaps(client, bufnr) - local bufkeymap = function(mode, lhs, rhs, desc) - vim.keymap.set(mode, lhs, rhs, { buffer = bufnr, silent = true, desc = desc }) -- noremap by default - end - -- Disable defaults - pcall(vim.keymap.del, 'n', 'gra') - pcall(vim.keymap.del, 'n', 'gri') - pcall(vim.keymap.del, 'n', 'grn') - pcall(vim.keymap.del, 'n', 'grr') - pcall(vim.keymap.del, 'n', 'gO') - pcall(vim.keymap.del, 'n', 'K') - -- - -- Quickfix list - bufkeymap('n', '[q', vim.cmd.cprev, 'Previous quickfix item') - bufkeymap('n', ']q', vim.cmd.cnext, 'Next quickfix item') - - -- Diagnostic keymaps - bufkeymap('n', '[d', 'vim.diagnostic.goto_prev()', 'Go to previous [d]iagnostic message') - bufkeymap('n', ']d', 'vim.diagnostic.goto_next()', 'Go to next [d]iagnostic message') - bufkeymap('n', 'gle', vim.diagnostic.open_float, 'Show diagnostic [e]rror messages') - -- bufkeymap('n', 'gle', 'Telescope diagnostics', 'Show diagnostic [e]rror messages') - bufkeymap('n', 'glq', vim.diagnostic.setloclist, 'Open diagnostic [q]uickfix list') - -- - -- stylua: ignore start - -- << local trouble = require("trouble").toggle - -- << bufkeymap('n', "tt", function() trouble() end, "Toggle Trouble") - -- << bufkeymap('n', "tq", function() trouble("quickfix") end, "Quickfix List") - -- << bufkeymap('n', "dr", function() trouble("lsp_references") end, "References") - -- << bufkeymap('n', "dd", function() trouble("document_diagnostics") end, "Document Diagnostics") - -- << bufkeymap('n', "dw", function() trouble("workspace_diagnostics") end, "Workspace Diagnostics") - -- stylua: ignore end - -- - if client.server_capabilities.hoverProvider then - bufkeymap('n', 'glk', vim.lsp.buf.hover, 'Hover Documentation') - end - if client.server_capabilities.signatureHelpProvider then - bufkeymap({ 'i', 'n' }, 'gls', vim.lsp.buf.signature_help, 'Show signature') - end - if client.server_capabilities.declarationProvider then - bufkeymap('n', 'glD', vim.lsp.buf.declaration, 'Goto [D]eclaration') - end - if client.server_capabilities.definitionProvider then - bufkeymap('n', 'gld', vim.lsp.buf.definition, 'Go to [d]efinition') - -- bufkeymap('n', 'gld', 'Telescope lsp_definitions', '[G]oto [D]efinition') - end - if client.server_capabilities.typeDefinitionProvider then - bufkeymap('n', 'glt', vim.lsp.buf.type_definition, 'Goto [t]ype definition') - -- bufkeymap('n', 'glt', 'Telescope lsp_type_definitions', 'Goto [t]ype definition') - end - if client.server_capabilities.implementationProvider then - bufkeymap('n', 'gli', vim.lsp.buf.implementation, 'Goto [i]mplementation') - -- bufkeymap('n', 'gli', 'Telescope lsp_implementations', 'Goto [i]mplementation') - end - - -- bufkeymap('n', 'glr', '(CodeAction, implementation, rename, references)', 'CodeAction, implementation, rename, references') - if client.server_capabilities.referencesProvider then - -- bufkeymap('n', 'gr', vim.lsp.buf.references, 'List references') - bufkeymap('n', 'glr', 'Telescope lsp_references', 'Goto [r]eferences') - -- bufkeymap('n', 'glr', 'Telescope lsp_references', '[G]oto [R]eferences') - end - if client.server_capabilities.renameProvider then - -- bufkeymap('n', '', vim.lsp.buf.rename, 'Rename symbol') - bufkeymap('n', 'glR', vim.lsp.buf.rename, '[R]ename') - end - if client.server_capabilities.codeActionProvider then - bufkeymap('n', 'gla', vim.lsp.buf.code_action, 'Code [a]ction') - end - - if client.server_capabilities.documentSymbolProvider then - bufkeymap('n', 'glwd', vim.lsp.buf.document_symbol, '[D]ocument symbols') - -- bufkeymap('n', 'glwd', Telescope lsp_document_symbols, '[D]ocument [S]ymbols') - end - if client:supports_method('workspace/symbol') then - -- if client.server_capabilities.workspaceSymbolProvider then - bufkeymap('n', 'glww', vim.lsp.buf.workspace_symbol, 'List [w]orkspace symbols') - -- bufkeymap('n', 'glww', require('telescope.builtin').lsp_dynamic_workspace_symbols, '[W]orkspace [S]ymbols') - end - if client.server_capabilities.workspace then - bufkeymap('n', 'glwa', vim.lsp.buf.add_workspace_folder, 'Workspace [a]dd folder') - bufkeymap('n', 'glwr', vim.lsp.buf.remove_workspace_folder, 'Workspace [r]emove folder') - bufkeymap('n', 'glwl', function() - print(vim.inspect(vim.lsp.buf.list_workspace_folders())) - end, '[W]orkspace [L]ist folders') - end - -- - if client:supports_method('textDocument/switchSourceHeader') then - bufkeymap('n', 'glws', 'LspClangdSwitchSourceHeader', '[S]witch Source/Header (C/C++)') - end - - if client:supports_method('textDocument/formatting') then - -- if client.server_capabilities.documentFormattingProvider then - bufkeymap({ 'n', 'x' }, 'glf', function() - vim.lsp.buf.format({ bufnr = bufnr, async = true }) - -- require('conform').format({ bufnr = bufnr, async = true }) - end, '[f]ormat buffer') - - -- LSP format the current buffer on save - local fmt_group = vim.api.nvim_create_augroup('autoformat_cmds', { clear = true }) - vim.api.nvim_create_autocmd('BufWritePre', { - buffer = bufnr, - group = fmt_group, - desc = 'Fromat current buffer', - callback = function(args) - -- if (client.name == 'lua_ls') and (vim.fn.executable('stylua') == 1) then - -- -- if (client.name == 'stylua') and (vim.fn.executable('stylua') == 1) then - -- -- vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(bufnr) }) - -- vim.fn.system({ 'stylua', vim.api.nvim_buf_get_name(args.buf) }) - -- vim.cmd('checktime') - -- print('stylua formatting') - -- else - vim.lsp.buf.format({ - bufnr = bufnr, - async = false, - timeout_ms = 10000, - id = client.id, - filter = function(c) - return c.id == client.id - end, - }) - print('lsp formatting') - -- end - end, - }) - end - -- - if client.server_capabilities.inlayHintProvider and vim.lsp.inlay_hint then - bufkeymap('n', 'glh', function() - vim.lsp.inlay_hint.enable(not vim.lsp.inlay_hint.is_enabled({ bufnr = bufnr }), { bufnr = bufnr }) - end, '[h]ints toggle') - ------------------------------------------------------------------------------ - end -end - -return K diff --git a/lua/platformio/old/utils.lua b/lua/platformio/old/utils.lua deleted file mode 100644 index b6499dc8..00000000 --- a/lua/platformio/old/utils.lua +++ /dev/null @@ -1,104 +0,0 @@ -local M = {} - -local is_windows = jit.os == 'Windows' -M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' --- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' --- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' - ------------------------------------------------------- -function M.strsplit(inputstr, del) - local t = {} - if type(inputstr) == 'string' and inputstr and inputstr ~= '' then - for str in string.gmatch(inputstr, '([^' .. del .. ']+)') do - table.insert(t, str) - end - end - return t -end - -function M.check_prefix(str, prefix) - return str:sub(1, #prefix) == prefix -end - -local function pathmul(n) - return '..' .. string.rep('/..', n) -end - -local paths = { '.', '..', pathmul(1), pathmul(2), pathmul(3), pathmul(4), pathmul(5) } - -function M.file_exists(name) - local f = io.open(name, 'r') - if f ~= nil then - io.close(f) - return true - else - return false - end -end - -function M.set_platformioRootDir() - if vim.g.platformioRootDir ~= nil then - return - end - for _, path in pairs(paths) do - if M.file_exists(path .. '/platformio.ini') then - vim.g.platformioRootDir = path - return - end - end - vim.notify('Could not find platformio.ini, run :Pioinit to create a new project', vim.log.levels.ERROR) -end - -function M.cd_pioini() - M.set_platformioRootDir() - vim.cmd('cd ' .. vim.g.platformioRootDir) -end - -function M.pio_install_check() - local handel = (jit.os == 'Windows') and assert(io.popen('where.exe pio 2>./nul')) or assert(io.popen('which pio 2>/dev/null')) - local pio_path = assert(handel:read('*a')) - handel:close() - - if #pio_path == 0 then - vim.notify('Platformio not found in the path', vim.log.levels.ERROR) - return false - end - return true -end - -function M.async_shell_cmd(cmd, callback) - local output = {} - - vim.fn.jobstart(cmd, { - stdout_buffered = true, - stderr_buffered = false, - - on_stdout = function(_, data) - if data then - for _, line in ipairs(data) do - if line ~= '' then - table.insert(output, line) - end - end - end - end, - - on_exit = function(_, code) - callback(output, code) - end, - }) -end - -function M.shell_cmd_blocking(command) - local handle = io.popen(command, 'r') - if not handle then - return nil, 'failed to run command' - end - - local result = handle:read('*a') - handle:close() - - return result -end - -return M diff --git a/lua/platformio/piolsserial.lua b/lua/platformio/piolsserial.lua index d045e3b2..afc04a4b 100644 --- a/lua/platformio/piolsserial.lua +++ b/lua/platformio/piolsserial.lua @@ -8,7 +8,7 @@ function M.parse_tty(lines) M.tty_list[k] = nil end local json_data = vim.json.decode(lines[1]) - for key, value in pairs(json_data) do + for _, value in pairs(json_data) do if value['description'] ~= 'n/a' then table.insert(M.tty_list, { port = value['port'], description = value['description'] }) end diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 28ea650f..e867fbce 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -79,17 +79,15 @@ function M.fix_pio_compile_commands() local path_map = {} local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') if pio_home then - -- Recursively find all binaries in PIO packages local pio_packages = M.get_pio_dir('packages') .. '/*/bin/*' - local found_binaries = vim.fn.glob(pio_packages, false, true) for _, full_path in ipairs(found_binaries) do -- Extract filename (e.g., riscv32-esp-elf-gcc) local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = full_path - print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) + -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) end end @@ -99,11 +97,9 @@ function M.fix_pio_compile_commands() if type(entry.command) == 'string' then local cmd_parts = vim.split(entry.command, ' ') local first_token = cmd_parts[1] - if first_token then -- Check if it's already a short name (not an absolute path) local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') - if not is_abs then local short_name = first_token:gsub('%.exe$', '') -- print('PioFix2: short_name=' .. short_name) @@ -147,11 +143,12 @@ M.queue = {} local pio_buffer = '' -- Persistent stream buffer ------------------------------------------------------ --- 1. The Dispatcher (The Brain) +-- The Dispatcher (The Brain) -- stylua: ignore function M.dispatcher(_, _, data) if #M.queue == 0 then return end + -- 1. attach partial buffer from previous data last line to 1st line pio_buffer = pio_buffer .. data[1] -- 2. If the chunk has more than one element, we've encountered newlines if #data > 1 then From 3402b36fd1b910e6053a8f53e6588219ac36a401 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 18:49:32 +0300 Subject: [PATCH 0490/1406] update --- lua/platformio/boilerplate.lua | 6 +++-- lua/platformio/utils/pio.lua | 48 ++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index aa10dd1a..1b76bb89 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -81,12 +81,14 @@ clangd --pch-storage=memory --pretty --ranking-model=decision_forest ---query-driver=%s/toolchain-*/**/bin/* +--query-driver=%s ]], content = function(self) local pio = require('platformio.utils.pio') - return string.format(self.template, pio.get_pio_dir('packages') or '**') + -- return string.format(self.template, pio.get_pio_dir('packages') or '**') + return string.format(self.template, pio.get_pio_toolchain_pattern() or '**') end, + --query-driver=%s/toolchain-*/**/bin/* --query-driver=%s/.platformio/packages/*/bin/riscv32-esp-elf-* --query-driver=%s/.platformio/**/packages/toolchain-*/**/bin/* --query-driver = [[clangd --query-driver=]] .. vim.env.HOME .. [[/.platformio/packages/*]] diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index e867fbce..1612a022 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -56,6 +56,52 @@ function M.get_pio_dir(type) return result end +------------------------------------------------------ +-- stylua: ignore +function M.get_pio_toolchain_pattern() + -- 1. Performance: Check if we already found it for this project + if _G._pio_arch_cache then return _G._pio_arch_cache end + + -- 2. Get the active environment's metadata via 'pio project config' + -- This is the most accurate way as it resolves all inheritance and board JSONs + local handle = io.popen('pio project config --json-output') + if not handle then return '/**/bin/*gcc*' end + local json_str = handle:read('*all') + handle:close() + + local ok, config = pcall(vim.json.decode, json_str) + if not ok or not config then return '/**/bin/*gcc*' end + + -- 3. Pick the right environment (handles multi-env projects) + local env_name = vim.g.pio_active_env or 'platformio' + local env_data = config[env_name] or config[next(config)] + + -- 4. Find the 'toolchain' package in the platform's required packages + -- We query the platform details directly + local platform = env_data.platform + local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') + if not p_handle then return '/**/bin/*gcc*' end + local p_json = p_handle:read('*all') + p_handle:close() + + local p_ok, p_data = pcall(vim.json.decode, p_json) + if not p_ok or not p_data.packages then return '/**/bin/*gcc*' end + + -- 5. Extract the architecture name from the toolchain package name + local arch_pattern = '/**/bin/*gcc*' + for pkg_name, _ in pairs(p_data.packages) do + if pkg_name:find('^toolchain%-') then + -- Strips 'toolchain-' and 'gcc' to get the core arch (e.g., 'riscv32-esp') + local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') + arch_pattern = '/**/bin/*' .. arch .. '*gcc*' + break + end + end + + -- 6. Cache it globally for the session to prevent lag + _G._pio_arch_cache = arch_pattern + return arch_pattern +end ------------------------------------------------------ -- stylua: ignore function M.fix_pio_compile_commands() @@ -211,6 +257,7 @@ end function M.handlePioinit() vim.notify('Pioinit: Success', vim.log.levels.INFO) local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') end -- Handle after poioinit execution @@ -220,4 +267,5 @@ function M.handlePiolib() end -- INFO: endDispatcher ------------------------------------------------------ + return M From 0bcd526d59ff4c89452c6f7d84ddb01711e76175 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 18:50:06 +0300 Subject: [PATCH 0491/1406] update --- lua/platformio/lspConfig/clangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 791d92d0..0b984951 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -9,7 +9,7 @@ boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core') -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') -boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) +-- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) From 778f22a34521e1e4ec615ffd61d4e2cd7c1033f2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 18:57:48 +0300 Subject: [PATCH 0492/1406] update --- lua/platformio/utils/pio.lua | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 1612a022..f8e84d5d 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -65,12 +65,12 @@ function M.get_pio_toolchain_pattern() -- 2. Get the active environment's metadata via 'pio project config' -- This is the most accurate way as it resolves all inheritance and board JSONs local handle = io.popen('pio project config --json-output') - if not handle then return '/**/bin/*gcc*' end + if not handle then return '**/toolchain-*/bin/*' end local json_str = handle:read('*all') handle:close() local ok, config = pcall(vim.json.decode, json_str) - if not ok or not config then return '/**/bin/*gcc*' end + if not ok or not config then return '**/toolchain-*/bin/*' end -- 3. Pick the right environment (handles multi-env projects) local env_name = vim.g.pio_active_env or 'platformio' @@ -80,15 +80,15 @@ function M.get_pio_toolchain_pattern() -- We query the platform details directly local platform = env_data.platform local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') - if not p_handle then return '/**/bin/*gcc*' end + if not p_handle then return '**/toolchain-*/bin/*' end local p_json = p_handle:read('*all') p_handle:close() local p_ok, p_data = pcall(vim.json.decode, p_json) - if not p_ok or not p_data.packages then return '/**/bin/*gcc*' end + if not p_ok or not p_data.packages then return '**/toolchain-*/bin/*' end -- 5. Extract the architecture name from the toolchain package name - local arch_pattern = '/**/bin/*gcc*' + local arch_pattern = '**/toolchain-*/bin/*' for pkg_name, _ in pairs(p_data.packages) do if pkg_name:find('^toolchain%-') then -- Strips 'toolchain-' and 'gcc' to get the core arch (e.g., 'riscv32-esp') From 59c51ff2c48f18ffc9906030f3220606c5f59a6c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 19:43:08 +0300 Subject: [PATCH 0493/1406] update --- lua/platformio/utils/pio.lua | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f8e84d5d..6621f281 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -56,6 +56,24 @@ function M.get_pio_dir(type) return result end +function M.detect_pio_env() + local f = io.open(vim.fn.getcwd() .. '/platformio.ini', 'r') + if f then + for line in f:lines() do + -- Matches the name inside [env:NAME] + local env = line:match('^%[env:(.+)%]') + if env then + f:close() + return env + end + end + f:close() + end + return 'platformio' -- Fallback +end + +-- Initialize the global variable +vim.g.pio_active_env = detect_pio_env() ------------------------------------------------------ -- stylua: ignore function M.get_pio_toolchain_pattern() @@ -73,7 +91,7 @@ function M.get_pio_toolchain_pattern() if not ok or not config then return '**/toolchain-*/bin/*' end -- 3. Pick the right environment (handles multi-env projects) - local env_name = vim.g.pio_active_env or 'platformio' + local env_name = M.detect_pio_env() local env_data = config[env_name] or config[next(config)] -- 4. Find the 'toolchain' package in the platform's required packages From 4ecc0d139cbd289eb77180b3b1a0069b043c1b2f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 19:50:17 +0300 Subject: [PATCH 0494/1406] update --- lua/platformio/boilerplate.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 1b76bb89..eb24764a 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -43,8 +43,8 @@ monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dt lib_ldf_mode = chain+ ;Library dependencies Finder ldf ]], content = function(self) - local pio = require('platformio.utils.pio') - return string.format(self.template, pio.get_pio_dir('core')) + -- local pio = require('platformio.utils.pio') + return string.format(self.template, require('platformio.utils.pio').get_pio_dir('core')) end, } From a3fde669e777aced61e2b83d83797facc8af5f1e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 20:28:41 +0300 Subject: [PATCH 0495/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/utils/misc.lua | 5 ++ lua/platformio/utils/pio.lua | 108 ++++++++++++++++++++------------- 3 files changed, 73 insertions(+), 42 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index eb24764a..c615c0bb 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -86,7 +86,7 @@ clangd content = function(self) local pio = require('platformio.utils.pio') -- return string.format(self.template, pio.get_pio_dir('packages') or '**') - return string.format(self.template, pio.get_pio_toolchain_pattern() or '**') + return string.format(self.template, get_pio_toolchain_pattern() or '**') end, --query-driver=%s/toolchain-*/**/bin/* --query-driver=%s/.platformio/packages/*/bin/riscv32-esp-elf-* diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 8eea81aa..a55c865e 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -5,6 +5,11 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' +------------------------------------------------------ +function M.normalize_path(path) + return path:gsub('\\', '/'):gsub('//+', '/') +end + ------------------------------------------------------ function M.strsplit(inputstr, del) local t = {} diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 6621f281..ecbcb90a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -38,7 +38,7 @@ function M.get_pio_dir(type) -- 4.0 Fallback Logic: INI -> Env Var -> Default local core_dir = core_val or os.getenv('PLATFORMIO_CORE_DIR' or (home .. map['core'].sub)):gsub('[\\/]+$', '') - core_dir = core_dir:gsub('\\', '/'):gsub('//+', '/') + core_dir = misc.normalize_path(core_dir) --core_dir:gsub('\\', '/'):gsub('//+', '/') -- if vim.fn.has('win32') == 1 then core_dir = core_dir:gsub('/', '\\') end if type == 'core' then return core_dir end @@ -49,76 +49,102 @@ function M.get_pio_dir(type) if result:find('${platformio.core_dir}', 1, true) then result = result:gsub('%${platformio.core_dir}', core_dir) end -- 6. Normalize Slashes for Windows - result = result:gsub('\\', '/'):gsub('//+', '/') + result = misc.normalize_path(result) --result:gsub('\\', '/'):gsub('//+', '/') -- if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end -- Ensure core_dir itself doesn't have trailing slashes for cleaner joins return result end +------------------------------------------------------ + +function _G.get_pio_toolchain_pattern() + -- 1. Check Session Cache (Keyed by Current Working Directory + Active Env) + local cwd = vim.fn.getcwd() + local cache_key = cwd .. (vim.g.pio_active_env or 'default') + if _G._pio_cache and _G._pio_cache[cache_key] then + return _G._pio_cache[cache_key] + end -function M.detect_pio_env() - local f = io.open(vim.fn.getcwd() .. '/platformio.ini', 'r') - if f then - for line in f:lines() do - -- Matches the name inside [env:NAME] - local env = line:match('^%[env:(.+)%]') - if env then - f:close() - return env + -- 2. Determine Active Environment Name + -- If not manually set via vim.g.pio_active_env, we'll find the first one in the file + local active_env = vim.g.pio_active_env + if not active_env then + local f = io.open(cwd .. '/platformio.ini', 'r') + if f then + for line in f:lines() do + active_env = line:match('^%[env:(.+)%]') + if active_env then + break + end end + f:close() end - f:close() end - return 'platformio' -- Fallback -end + active_env = active_env or 'platformio' --- Initialize the global variable -vim.g.pio_active_env = detect_pio_env() ------------------------------------------------------- --- stylua: ignore -function M.get_pio_toolchain_pattern() - -- 1. Performance: Check if we already found it for this project - if _G._pio_arch_cache then return _G._pio_arch_cache end - - -- 2. Get the active environment's metadata via 'pio project config' - -- This is the most accurate way as it resolves all inheritance and board JSONs + -- 3. Get Full Project Config (Resolves all inheritance/multiple envs) local handle = io.popen('pio project config --json-output') - if not handle then return '**/toolchain-*/bin/*' end + if not handle then + return '/**/bin/*gcc*' + end local json_str = handle:read('*all') handle:close() local ok, config = pcall(vim.json.decode, json_str) - if not ok or not config then return '**/toolchain-*/bin/*' end + if not ok or not config then + return '/**/bin/*gcc*' + end - -- 3. Pick the right environment (handles multi-env projects) - local env_name = M.detect_pio_env() - local env_data = config[env_name] or config[next(config)] + -- 4. Extract Platform for the specific Active Env + local env_data = config['env:' .. active_env] or config[active_env] + if not env_data or not env_data.platform then + -- Fallback to the first available env if active_env wasn't found + for name, data in pairs(config) do + if name:find('env:') then + env_data = data + break + end + end + end + + local platform = env_data and env_data.platform or '' + local core_dir = config.platformio and config.platformio.core_dir or (os.getenv('HOME') or os.getenv('USERPROFILE') .. '/.platformio') + local packages_base = misc.normalize_path(core_dir .. '/packages') - -- 4. Find the 'toolchain' package in the platform's required packages - -- We query the platform details directly - local platform = env_data.platform + -- 5. Query the Platform for its Toolchain Package local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') - if not p_handle then return '**/toolchain-*/bin/*' end + if not p_handle then + return misc.normalize_path(packages_base .. '/**/bin/*gcc*') + end local p_json = p_handle:read('*all') p_handle:close() local p_ok, p_data = pcall(vim.json.decode, p_json) - if not p_ok or not p_data.packages then return '**/toolchain-*/bin/*' end + if not p_ok or not p_data.packages then + return misc.normalize_path(packages_base .. '/**/bin/*gcc*') + end - -- 5. Extract the architecture name from the toolchain package name - local arch_pattern = '**/toolchain-*/bin/*' + -- 6. Identify the Arch Pattern + local arch_glob = '/**/bin/*gcc*' for pkg_name, _ in pairs(p_data.packages) do if pkg_name:find('^toolchain%-') then - -- Strips 'toolchain-' and 'gcc' to get the core arch (e.g., 'riscv32-esp') local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') - arch_pattern = '/**/bin/*' .. arch .. '*gcc*' + arch_glob = '/**/bin/*' .. arch .. '*gcc*' break end end - -- 6. Cache it globally for the session to prevent lag - _G._pio_arch_cache = arch_pattern - return arch_pattern + -- 7. Final Path & Windows Normalization + local final_pattern = misc.normalize_path(packages_base .. arch_glob) + if vim.fn.has('win32') == 1 then + final_pattern = final_pattern:gsub('/', '\\') + end + + -- Cache the result for this project/env combo + _G._pio_cache = _G._pio_cache or {} + _G._pio_cache[cache_key] = final_pattern + + return final_pattern end ------------------------------------------------------ -- stylua: ignore From ee329107b60f0e24f33f0545cc2cfff8a0c765f9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 20:46:53 +0300 Subject: [PATCH 0496/1406] update --- lua/platformio/utils/pio.lua | 84 +++++++++++++++++++----------------- 1 file changed, 44 insertions(+), 40 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index ecbcb90a..1242423a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -58,31 +58,15 @@ end ------------------------------------------------------ function _G.get_pio_toolchain_pattern() - -- 1. Check Session Cache (Keyed by Current Working Directory + Active Env) local cwd = vim.fn.getcwd() - local cache_key = cwd .. (vim.g.pio_active_env or 'default') + + -- 1. Check Session Cache + local cache_key = cwd .. (vim.g.pio_active_env or 'auto') if _G._pio_cache and _G._pio_cache[cache_key] then return _G._pio_cache[cache_key] end - -- 2. Determine Active Environment Name - -- If not manually set via vim.g.pio_active_env, we'll find the first one in the file - local active_env = vim.g.pio_active_env - if not active_env then - local f = io.open(cwd .. '/platformio.ini', 'r') - if f then - for line in f:lines() do - active_env = line:match('^%[env:(.+)%]') - if active_env then - break - end - end - f:close() - end - end - active_env = active_env or 'platformio' - - -- 3. Get Full Project Config (Resolves all inheritance/multiple envs) + -- 2. Get Full Project Config via JSON (Handles variable resolution) local handle = io.popen('pio project config --json-output') if not handle then return '/**/bin/*gcc*' @@ -95,36 +79,57 @@ function _G.get_pio_toolchain_pattern() return '/**/bin/*gcc*' end - -- 4. Extract Platform for the specific Active Env - local env_data = config['env:' .. active_env] or config[active_env] - if not env_data or not env_data.platform then - -- Fallback to the first available env if active_env wasn't found - for name, data in pairs(config) do - if name:find('env:') then - env_data = data - break + -- 3. Determine Active Environment + local active_env = vim.g.pio_active_env -- Manual override (from Picker) + + if not active_env then + -- A. Check Environment Variable PLATFORMIO_DEFAULT_ENVS + active_env = os.getenv('PLATFORMIO_DEFAULT_ENVS') + + -- B. Check default_envs in [platformio] section + if not active_env and config.platformio and config.platformio.default_envs then + active_env = config.platformio.default_envs + -- default_envs can be a comma-separated list; we take the first one + active_env = active_env:match('([^,%s]+)') + end + + -- C. Fallback: Find the first [env:...] section + if not active_env then + for name, _ in pairs(config) do + local env_match = name:match('^env:(.+)') + if env_match then + active_env = env_match + break + end end end end - local platform = env_data and env_data.platform or '' - local core_dir = config.platformio and config.platformio.core_dir or (os.getenv('HOME') or os.getenv('USERPROFILE') .. '/.platformio') - local packages_base = misc.normalize_path(core_dir .. '/packages') + -- 4. Extract Data for the Target Environment + local env_key = 'env:' .. (active_env or '') + local env_data = config[env_key] or config[active_env] - -- 5. Query the Platform for its Toolchain Package - local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') + if not env_data or not env_data.platform then + return '/**/bin/*gcc*' + end + + -- 5. Build Package Path & Query Platform for Toolchain + local core_dir = config.platformio and config.platformio.core_dir or (os.getenv('USERPROFILE') or os.getenv('HOME')) .. '/.platformio' + local packages_base = (core_dir .. '/packages'):gsub('\\', '/'):gsub('//+', '/') + + local p_handle = io.popen('pio platform show ' .. env_data.platform .. ' --json-output') if not p_handle then - return misc.normalize_path(packages_base .. '/**/bin/*gcc*') + return packages_base .. '/**/bin/*gcc*' end local p_json = p_handle:read('*all') p_handle:close() local p_ok, p_data = pcall(vim.json.decode, p_json) if not p_ok or not p_data.packages then - return misc.normalize_path(packages_base .. '/**/bin/*gcc*') + return packages_base .. '/**/bin/*gcc*' end - -- 6. Identify the Arch Pattern + -- 6. Extract Toolchain Architecture local arch_glob = '/**/bin/*gcc*' for pkg_name, _ in pairs(p_data.packages) do if pkg_name:find('^toolchain%-') then @@ -134,18 +139,17 @@ function _G.get_pio_toolchain_pattern() end end - -- 7. Final Path & Windows Normalization - local final_pattern = misc.normalize_path(packages_base .. arch_glob) + local final_pattern = (packages_base .. arch_glob):gsub('//+', '/') if vim.fn.has('win32') == 1 then final_pattern = final_pattern:gsub('/', '\\') end - -- Cache the result for this project/env combo + -- 7. Update Cache _G._pio_cache = _G._pio_cache or {} _G._pio_cache[cache_key] = final_pattern - return final_pattern end + ------------------------------------------------------ -- stylua: ignore function M.fix_pio_compile_commands() From f002402810bfe1726e8a2b05f57543e2fa7f362c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 20:54:48 +0300 Subject: [PATCH 0497/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 1242423a..8737a17f 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -59,7 +59,7 @@ end function _G.get_pio_toolchain_pattern() local cwd = vim.fn.getcwd() - + vim.g.pio.active_env = 'env:seeed_xiao_esp32c3' -- 1. Check Session Cache local cache_key = cwd .. (vim.g.pio_active_env or 'auto') if _G._pio_cache and _G._pio_cache[cache_key] then From 4add949a7e257945f808ac7339e60c314d24dd2f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 21:03:10 +0300 Subject: [PATCH 0498/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 8737a17f..ae31dc83 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -59,7 +59,7 @@ end function _G.get_pio_toolchain_pattern() local cwd = vim.fn.getcwd() - vim.g.pio.active_env = 'env:seeed_xiao_esp32c3' + vim.g.pio_active_env = 'env:seeed_xiao_esp32c3' -- 1. Check Session Cache local cache_key = cwd .. (vim.g.pio_active_env or 'auto') if _G._pio_cache and _G._pio_cache[cache_key] then From 3a12ecd7d0a0ab43a1c850a572048f2ebad17078 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 21:16:28 +0300 Subject: [PATCH 0499/1406] update --- lua/platformio/utils/pio.lua | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index ae31dc83..247d4487 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -57,28 +57,29 @@ function M.get_pio_dir(type) end ------------------------------------------------------ +-- stylua: ignore function _G.get_pio_toolchain_pattern() local cwd = vim.fn.getcwd() - vim.g.pio_active_env = 'env:seeed_xiao_esp32c3' + -- vim.g.pio_active_env = 'env:seeed_xiao_esp32c3' -- 1. Check Session Cache + print("toolchain: 1") local cache_key = cwd .. (vim.g.pio_active_env or 'auto') if _G._pio_cache and _G._pio_cache[cache_key] then return _G._pio_cache[cache_key] end + print("toolchain: 2") -- 2. Get Full Project Config via JSON (Handles variable resolution) local handle = io.popen('pio project config --json-output') - if not handle then - return '/**/bin/*gcc*' - end + if not handle then return '/**/bin/*gcc*' end local json_str = handle:read('*all') handle:close() + print("toolchain: 2.0") local ok, config = pcall(vim.json.decode, json_str) - if not ok or not config then - return '/**/bin/*gcc*' - end + if not ok or not config then return '/**/bin/*gcc*' end + print("toolchain: 3") -- 3. Determine Active Environment local active_env = vim.g.pio_active_env -- Manual override (from Picker) @@ -105,6 +106,7 @@ function _G.get_pio_toolchain_pattern() end end + print("toolchain: 4") -- 4. Extract Data for the Target Environment local env_key = 'env:' .. (active_env or '') local env_data = config[env_key] or config[active_env] @@ -113,6 +115,7 @@ function _G.get_pio_toolchain_pattern() return '/**/bin/*gcc*' end + print("toolchain: 5") -- 5. Build Package Path & Query Platform for Toolchain local core_dir = config.platformio and config.platformio.core_dir or (os.getenv('USERPROFILE') or os.getenv('HOME')) .. '/.platformio' local packages_base = (core_dir .. '/packages'):gsub('\\', '/'):gsub('//+', '/') @@ -121,6 +124,8 @@ function _G.get_pio_toolchain_pattern() if not p_handle then return packages_base .. '/**/bin/*gcc*' end + print("toolchain: 5.0") + local p_json = p_handle:read('*all') p_handle:close() @@ -128,7 +133,9 @@ function _G.get_pio_toolchain_pattern() if not p_ok or not p_data.packages then return packages_base .. '/**/bin/*gcc*' end + print("toolchain: 5.1") + print("toolchain: 6") -- 6. Extract Toolchain Architecture local arch_glob = '/**/bin/*gcc*' for pkg_name, _ in pairs(p_data.packages) do @@ -144,6 +151,7 @@ function _G.get_pio_toolchain_pattern() final_pattern = final_pattern:gsub('/', '\\') end + print("toolchain: 7") -- 7. Update Cache _G._pio_cache = _G._pio_cache or {} _G._pio_cache[cache_key] = final_pattern From ebd0fb0bb0affd3107679f9b87c9a1865f7e0cb5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 21:25:05 +0300 Subject: [PATCH 0500/1406] update --- lua/platformio/boilerplate.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index c615c0bb..4e3de869 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -84,9 +84,9 @@ clangd --query-driver=%s ]], content = function(self) - local pio = require('platformio.utils.pio') + -- local pio = require('platformio.utils.pio') -- return string.format(self.template, pio.get_pio_dir('packages') or '**') - return string.format(self.template, get_pio_toolchain_pattern() or '**') + return string.format(self.template, _G.get_pio_toolchain_pattern() or '**') end, --query-driver=%s/toolchain-*/**/bin/* --query-driver=%s/.platformio/packages/*/bin/riscv32-esp-elf-* From f7935357df254b562c74191ea5358065f14aab18 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 21:31:19 +0300 Subject: [PATCH 0501/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 247d4487..8a9e6cd0 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -60,7 +60,7 @@ end -- stylua: ignore function _G.get_pio_toolchain_pattern() local cwd = vim.fn.getcwd() - -- vim.g.pio_active_env = 'env:seeed_xiao_esp32c3' + vim.g.pio_active_env = 'seeed_xiao_esp32c3' -- 1. Check Session Cache print("toolchain: 1") local cache_key = cwd .. (vim.g.pio_active_env or 'auto') From bd7168f0c1249bd23a339b48f3f89b0cfbc204bd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 21:36:48 +0300 Subject: [PATCH 0502/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 8a9e6cd0..7087186e 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -60,7 +60,7 @@ end -- stylua: ignore function _G.get_pio_toolchain_pattern() local cwd = vim.fn.getcwd() - vim.g.pio_active_env = 'seeed_xiao_esp32c3' + vim.g.pio_active_env = 'env:seeed_xiao_esp32c3' -- 1. Check Session Cache print("toolchain: 1") local cache_key = cwd .. (vim.g.pio_active_env or 'auto') From 6966c8d3621e24cdc0ceb7965c3123c7d0e5cb1d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 21:50:03 +0300 Subject: [PATCH 0503/1406] update --- lua/platformio/utils/pio.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 7087186e..ae48e704 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -90,6 +90,7 @@ function _G.get_pio_toolchain_pattern() -- B. Check default_envs in [platformio] section if not active_env and config.platformio and config.platformio.default_envs then active_env = config.platformio.default_envs + print("toolchain: 3.0 " .. active_env) -- default_envs can be a comma-separated list; we take the first one active_env = active_env:match('([^,%s]+)') end @@ -100,6 +101,7 @@ function _G.get_pio_toolchain_pattern() local env_match = name:match('^env:(.+)') if env_match then active_env = env_match + print("toolchain: 3.1 " .. active_env) break end end From 6743305d125c10f9ae4c55ca43c42805cad0d6ab Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 21:55:51 +0300 Subject: [PATCH 0504/1406] update --- lua/platformio/utils/pio.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index ae48e704..7cf9276c 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -112,6 +112,7 @@ function _G.get_pio_toolchain_pattern() -- 4. Extract Data for the Target Environment local env_key = 'env:' .. (active_env or '') local env_data = config[env_key] or config[active_env] + print("toolchain: 4.0 " .. env_key) if not env_data or not env_data.platform then return '/**/bin/*gcc*' From 5f1222046b0f012b8bceeeb586a30390cfa69a63 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 21:59:47 +0300 Subject: [PATCH 0505/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 7cf9276c..1f5d0179 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -60,7 +60,7 @@ end -- stylua: ignore function _G.get_pio_toolchain_pattern() local cwd = vim.fn.getcwd() - vim.g.pio_active_env = 'env:seeed_xiao_esp32c3' + vim.g.pio_active_env = 'seeed_xiao_esp32c3' -- 1. Check Session Cache print("toolchain: 1") local cache_key = cwd .. (vim.g.pio_active_env or 'auto') From a1e485f353c33bdf2eb21923bc2e70de30e78c49 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 22:13:33 +0300 Subject: [PATCH 0506/1406] update --- lua/platformio/utils/pio.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 1f5d0179..2b20e249 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -112,6 +112,7 @@ function _G.get_pio_toolchain_pattern() -- 4. Extract Data for the Target Environment local env_key = 'env:' .. (active_env or '') local env_data = config[env_key] or config[active_env] + print(vim.inspect(config)) print("toolchain: 4.0 " .. env_key) if not env_data or not env_data.platform then From 7e1ae11ae8d541fda9a8e32b6301b6ba3e6dd75a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 22:17:19 +0300 Subject: [PATCH 0507/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 2b20e249..7a906f91 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -112,7 +112,7 @@ function _G.get_pio_toolchain_pattern() -- 4. Extract Data for the Target Environment local env_key = 'env:' .. (active_env or '') local env_data = config[env_key] or config[active_env] - print(vim.inspect(config)) + print(vim.inspect(config[env_key])) print("toolchain: 4.0 " .. env_key) if not env_data or not env_data.platform then From 92fa3ecd342784ec8805e11dc82dab315c2c2679 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 22:31:32 +0300 Subject: [PATCH 0508/1406] update --- lua/platformio/utils/pio.lua | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 7a906f91..6d9d8543 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -81,7 +81,8 @@ function _G.get_pio_toolchain_pattern() print("toolchain: 3") -- 3. Determine Active Environment - local active_env = vim.g.pio_active_env -- Manual override (from Picker) + -- local active_env = vim.g.pio_active_env -- Manual override (from Picker) + local active_env = nil if not active_env then -- A. Check Environment Variable PLATFORMIO_DEFAULT_ENVS @@ -92,8 +93,9 @@ function _G.get_pio_toolchain_pattern() active_env = config.platformio.default_envs print("toolchain: 3.0 " .. active_env) -- default_envs can be a comma-separated list; we take the first one + if active_env then active_env = active_env:match('([^,%s]+)') - end + end -- C. Fallback: Find the first [env:...] section if not active_env then From 4314c5cb885cdfb0fe603a9c57a4a2d4930a5c35 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 10 Apr 2026 22:34:07 +0300 Subject: [PATCH 0509/1406] update --- lua/platformio/utils/pio.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 6d9d8543..ea6e9bba 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -94,8 +94,9 @@ function _G.get_pio_toolchain_pattern() print("toolchain: 3.0 " .. active_env) -- default_envs can be a comma-separated list; we take the first one if active_env then - active_env = active_env:match('([^,%s]+)') + active_env = active_env:match('([^,%s]+)') end + end -- C. Fallback: Find the first [env:...] section if not active_env then From 001e967fb95a00f4569da0f6ff3d3719b35cf373 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 05:13:40 +0300 Subject: [PATCH 0510/1406] update --- lua/platformio/utils/pio.lua | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index ea6e9bba..fe93033e 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -101,12 +101,15 @@ function _G.get_pio_toolchain_pattern() -- C. Fallback: Find the first [env:...] section if not active_env then for name, _ in pairs(config) do - local env_match = name:match('^env:(.+)') - if env_match then - active_env = env_match - print("toolchain: 3.1 " .. active_env) - break + if type(name) == 'string' then + local env_match = name:match('^env:(.+)') + if env_match then + active_env = env_match + print("toolchain: 3.1 " .. active_env) + break + end end + end end end From 813f681004a08e30ce8695ed79b0067838952cb0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 05:22:48 +0300 Subject: [PATCH 0511/1406] update --- lua/platformio/utils/pio.lua | 86 +++++++++++------------------------- 1 file changed, 27 insertions(+), 59 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index fe93033e..821d906b 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -60,114 +60,82 @@ end -- stylua: ignore function _G.get_pio_toolchain_pattern() local cwd = vim.fn.getcwd() - vim.g.pio_active_env = 'seeed_xiao_esp32c3' - -- 1. Check Session Cache - print("toolchain: 1") + + -- 1. Performance: Check Session Cache local cache_key = cwd .. (vim.g.pio_active_env or 'auto') - if _G._pio_cache and _G._pio_cache[cache_key] then - return _G._pio_cache[cache_key] - end + if _G._pio_cache and _G._pio_cache[cache_key] then return _G._pio_cache[cache_key] end - print("toolchain: 2") - -- 2. Get Full Project Config via JSON (Handles variable resolution) + -- 2. Get Full Project Config via JSON local handle = io.popen('pio project config --json-output') if not handle then return '/**/bin/*gcc*' end local json_str = handle:read('*all') handle:close() - print("toolchain: 2.0") local ok, config = pcall(vim.json.decode, json_str) if not ok or not config then return '/**/bin/*gcc*' end - print("toolchain: 3") - -- 3. Determine Active Environment - -- local active_env = vim.g.pio_active_env -- Manual override (from Picker) - local active_env = nil + -- 3. Determine Active Environment (Priority: Manual > default_envs > First [env:]) + local active_env = vim.g.pio_active_env if not active_env then - -- A. Check Environment Variable PLATFORMIO_DEFAULT_ENVS - active_env = os.getenv('PLATFORMIO_DEFAULT_ENVS') - - -- B. Check default_envs in [platformio] section - if not active_env and config.platformio and config.platformio.default_envs then - active_env = config.platformio.default_envs - print("toolchain: 3.0 " .. active_env) - -- default_envs can be a comma-separated list; we take the first one - if active_env then - active_env = active_env:match('([^,%s]+)') - end + -- A. Check if default_envs is defined in [platformio] + if config.platformio and config.platformio.default_envs then + -- Handles comma-separated lists like "env1, env2" + active_env = tostring(config.platformio.default_envs):match('([^,%s]+)') end - -- C. Fallback: Find the first [env:...] section + -- B. Fallback: Find the first environment name starting with "env:" if not active_env then for name, _ in pairs(config) do + -- FIX: Check type to prevent "attempt to index local 'name' (a number value)" if type(name) == 'string' then local env_match = name:match('^env:(.+)') - if env_match then - active_env = env_match - print("toolchain: 3.1 " .. active_env) - break + if env_match then active_env = env_match break end end - end end end - print("toolchain: 4") - -- 4. Extract Data for the Target Environment + -- 4. Target the specific config block + -- PIO JSON uses "env:NAME" keys for environments local env_key = 'env:' .. (active_env or '') local env_data = config[env_key] or config[active_env] - print(vim.inspect(config[env_key])) - print("toolchain: 4.0 " .. env_key) - if not env_data or not env_data.platform then - return '/**/bin/*gcc*' - end + if not env_data or not env_data.platform then return '/**/bin/*gcc*' end - print("toolchain: 5") - -- 5. Build Package Path & Query Platform for Toolchain - local core_dir = config.platformio and config.platformio.core_dir or (os.getenv('USERPROFILE') or os.getenv('HOME')) .. '/.platformio' - local packages_base = (core_dir .. '/packages'):gsub('\\', '/'):gsub('//+', '/') + -- 5. Build Paths (Normalizing for Windows/Linux) + local home = os.getenv('HOME') or os.getenv('USERPROFILE') + local core_dir = (config.platformio and config.platformio.core_dir) or (home .. '/.platformio') + local packages_base = core_dir:gsub('\\', '/') .. '/packages' + -- 6. Query PIO for the Toolchain Architecture local p_handle = io.popen('pio platform show ' .. env_data.platform .. ' --json-output') - if not p_handle then - return packages_base .. '/**/bin/*gcc*' - end - print("toolchain: 5.0") - + if not p_handle then return packages_base .. '/**/bin/*gcc*' end local p_json = p_handle:read('*all') p_handle:close() local p_ok, p_data = pcall(vim.json.decode, p_json) - if not p_ok or not p_data.packages then - return packages_base .. '/**/bin/*gcc*' - end - print("toolchain: 5.1") + if not p_ok or not p_data.packages then return packages_base .. '/**/bin/*gcc*' end - print("toolchain: 6") - -- 6. Extract Toolchain Architecture local arch_glob = '/**/bin/*gcc*' for pkg_name, _ in pairs(p_data.packages) do - if pkg_name:find('^toolchain%-') then + if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') arch_glob = '/**/bin/*' .. arch .. '*gcc*' break end end + -- 7. Final Path Normalization local final_pattern = (packages_base .. arch_glob):gsub('//+', '/') - if vim.fn.has('win32') == 1 then - final_pattern = final_pattern:gsub('/', '\\') - end + if vim.fn.has('win32') == 1 then final_pattern = final_pattern:gsub('/', '\\') end - print("toolchain: 7") - -- 7. Update Cache + -- Save to cache _G._pio_cache = _G._pio_cache or {} _G._pio_cache[cache_key] = final_pattern return final_pattern end - ------------------------------------------------------ -- stylua: ignore function M.fix_pio_compile_commands() From 77007c8e3459c154ae4059661488fa7bdf3c7d2f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 05:35:54 +0300 Subject: [PATCH 0512/1406] update --- lua/platformio/utils/pio.lua | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 821d906b..7c4edd3e 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -64,18 +64,21 @@ function _G.get_pio_toolchain_pattern() -- 1. Performance: Check Session Cache local cache_key = cwd .. (vim.g.pio_active_env or 'auto') if _G._pio_cache and _G._pio_cache[cache_key] then return _G._pio_cache[cache_key] end + print("toolchain 1:") -- 2. Get Full Project Config via JSON local handle = io.popen('pio project config --json-output') if not handle then return '/**/bin/*gcc*' end local json_str = handle:read('*all') handle:close() + print("toolchain 2:") local ok, config = pcall(vim.json.decode, json_str) if not ok or not config then return '/**/bin/*gcc*' end -- 3. Determine Active Environment (Priority: Manual > default_envs > First [env:]) local active_env = vim.g.pio_active_env + print("toolchain 3:") if not active_env then -- A. Check if default_envs is defined in [platformio] @@ -83,13 +86,16 @@ function _G.get_pio_toolchain_pattern() -- Handles comma-separated lists like "env1, env2" active_env = tostring(config.platformio.default_envs):match('([^,%s]+)') end + print("toolchain 3.0:") -- B. Fallback: Find the first environment name starting with "env:" if not active_env then for name, _ in pairs(config) do + print("toolchain 3.0: name=" .. name) -- FIX: Check type to prevent "attempt to index local 'name' (a number value)" if type(name) == 'string' then local env_match = name:match('^env:(.+)') + print("toolchain 3.0: env_match=" .. env_match) if env_match then active_env = env_match break end end @@ -101,9 +107,11 @@ function _G.get_pio_toolchain_pattern() -- PIO JSON uses "env:NAME" keys for environments local env_key = 'env:' .. (active_env or '') local env_data = config[env_key] or config[active_env] + print("toolchain 4:") if not env_data or not env_data.platform then return '/**/bin/*gcc*' end + print("toolchain 5:") -- 5. Build Paths (Normalizing for Windows/Linux) local home = os.getenv('HOME') or os.getenv('USERPROFILE') local core_dir = (config.platformio and config.platformio.core_dir) or (home .. '/.platformio') @@ -114,13 +122,16 @@ function _G.get_pio_toolchain_pattern() if not p_handle then return packages_base .. '/**/bin/*gcc*' end local p_json = p_handle:read('*all') p_handle:close() + print("toolchain 6:") local p_ok, p_data = pcall(vim.json.decode, p_json) if not p_ok or not p_data.packages then return packages_base .. '/**/bin/*gcc*' end + print("toolchain 6.0:") local arch_glob = '/**/bin/*gcc*' for pkg_name, _ in pairs(p_data.packages) do if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then + print("toolchain 6.1: pkg_name=" .. pkg_name) local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') arch_glob = '/**/bin/*' .. arch .. '*gcc*' break @@ -130,6 +141,7 @@ function _G.get_pio_toolchain_pattern() -- 7. Final Path Normalization local final_pattern = (packages_base .. arch_glob):gsub('//+', '/') if vim.fn.has('win32') == 1 then final_pattern = final_pattern:gsub('/', '\\') end + print("toolchain 6.1: final_pattern=" .. final_pattern) -- Save to cache _G._pio_cache = _G._pio_cache or {} From f891ead1ab91b53075f7d2c0c0c5b3dc56202392 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 05:41:33 +0300 Subject: [PATCH 0513/1406] update --- lua/platformio/utils/pio.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 7c4edd3e..9e42d7cb 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -90,6 +90,7 @@ function _G.get_pio_toolchain_pattern() -- B. Fallback: Find the first environment name starting with "env:" if not active_env then + print(vim.inspect(config)) for name, _ in pairs(config) do print("toolchain 3.0: name=" .. name) -- FIX: Check type to prevent "attempt to index local 'name' (a number value)" From 441b62796e7185b01d929716cb401184b230acce Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 05:52:13 +0300 Subject: [PATCH 0514/1406] update --- lua/platformio/utils/pio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 9e42d7cb..3809b514 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -91,8 +91,8 @@ function _G.get_pio_toolchain_pattern() -- B. Fallback: Find the first environment name starting with "env:" if not active_env then print(vim.inspect(config)) - for name, _ in pairs(config) do - print("toolchain 3.0: name=" .. name) + for name, value in pairs(config) do + print("toolchain 3.0: name=" .. name .. ' value=' .. value) -- FIX: Check type to prevent "attempt to index local 'name' (a number value)" if type(name) == 'string' then local env_match = name:match('^env:(.+)') From 4b1192fae0b3ffd80985855150cc099ee590738c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 06:24:50 +0300 Subject: [PATCH 0515/1406] update --- lua/platformio/utils/pio.lua | 204 ++++++++++++++++++++++++++--------- 1 file changed, 152 insertions(+), 52 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 3809b514..88578fac 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -57,98 +57,198 @@ function M.get_pio_dir(type) end ------------------------------------------------------ --- stylua: ignore +--- stylua: ignore function _G.get_pio_toolchain_pattern() local cwd = vim.fn.getcwd() - - -- 1. Performance: Check Session Cache local cache_key = cwd .. (vim.g.pio_active_env or 'auto') - if _G._pio_cache and _G._pio_cache[cache_key] then return _G._pio_cache[cache_key] end - print("toolchain 1:") - -- 2. Get Full Project Config via JSON + if _G._pio_cache and _G._pio_cache[cache_key] then + return _G._pio_cache[cache_key] + end + local handle = io.popen('pio project config --json-output') - if not handle then return '/**/bin/*gcc*' end + if not handle then + return '/**/bin/*gcc*' + end local json_str = handle:read('*all') handle:close() - print("toolchain 2:") local ok, config = pcall(vim.json.decode, json_str) - if not ok or not config then return '/**/bin/*gcc*' end + if not ok or not config then + return '/**/bin/*gcc*' + end - -- 3. Determine Active Environment (Priority: Manual > default_envs > First [env:]) local active_env = vim.g.pio_active_env - print("toolchain 3:") - - if not active_env then - -- A. Check if default_envs is defined in [platformio] - if config.platformio and config.platformio.default_envs then - -- Handles comma-separated lists like "env1, env2" - active_env = tostring(config.platformio.default_envs):match('([^,%s]+)') - end - print("toolchain 3.0:") - - -- B. Fallback: Find the first environment name starting with "env:" - if not active_env then - print(vim.inspect(config)) - for name, value in pairs(config) do - print("toolchain 3.0: name=" .. name .. ' value=' .. value) - -- FIX: Check type to prevent "attempt to index local 'name' (a number value)" - if type(name) == 'string' then - local env_match = name:match('^env:(.+)') - print("toolchain 3.0: env_match=" .. env_match) - if env_match then active_env = env_match break - end + local env_data = nil + local core_dir = (os.getenv('HOME') or os.getenv('USERPROFILE')) .. '/.platformio' + + print('toolchain 1.0: core_dir= ' .. core_dir) + -- 1. Find the target environment in the array of objects + for _, item in ipairs(config) do + if type(item) == 'table' then + -- Identify the global 'platformio' config block + if item.name == 'platformio' then + core_dir = item.core_dir or core_dir + print('toolchain 1.1: core_dir= ' .. core_dir) + -- Priority: If no manual env is set, try to get default_envs + if not active_env and item.default_envs then + active_env = tostring(item.default_envs):match('([^,%s]+)') + print('toolchain 1.1: active_env= ' .. active_env) end end + + -- If we have an active_env, find its specific table + if active_env and (item.name == 'env:' .. active_env or item.name == active_env) then + env_data = item + print('toolchain 1.2: env_data= ' .. env_data) + end end end - -- 4. Target the specific config block - -- PIO JSON uses "env:NAME" keys for environments - local env_key = 'env:' .. (active_env or '') - local env_data = config[env_key] or config[active_env] - print("toolchain 4:") + -- 2. Fallback: If no env_data found yet, pick the first item starting with 'env:' + print('toolchain 2.0') + if not env_data then + for _, item in ipairs(config) do + if type(item) == 'table' and item.name and item.name:find('^env:') then + env_data = item + print('toolchain 2.1: env_data= ' .. env_data) + break + end + end + end - if not env_data or not env_data.platform then return '/**/bin/*gcc*' end + if not env_data or not env_data.platform then + return '/**/bin/*gcc*' + end + print('toolchain 3.0') - print("toolchain 5:") - -- 5. Build Paths (Normalizing for Windows/Linux) - local home = os.getenv('HOME') or os.getenv('USERPROFILE') - local core_dir = (config.platformio and config.platformio.core_dir) or (home .. '/.platformio') + -- 3. Resolve the Toolchain Path local packages_base = core_dir:gsub('\\', '/') .. '/packages' - - -- 6. Query PIO for the Toolchain Architecture local p_handle = io.popen('pio platform show ' .. env_data.platform .. ' --json-output') - if not p_handle then return packages_base .. '/**/bin/*gcc*' end + if not p_handle then + return packages_base .. '/**/bin/*gcc*' + end + print('toolchain 3.1') local p_json = p_handle:read('*all') p_handle:close() - print("toolchain 6:") local p_ok, p_data = pcall(vim.json.decode, p_json) - if not p_ok or not p_data.packages then return packages_base .. '/**/bin/*gcc*' end - print("toolchain 6.0:") + if not p_ok or not p_data.packages then + return packages_base .. '/**/bin/*gcc*' + end + print('toolchain 3.2') local arch_glob = '/**/bin/*gcc*' for pkg_name, _ in pairs(p_data.packages) do if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then - print("toolchain 6.1: pkg_name=" .. pkg_name) local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') arch_glob = '/**/bin/*' .. arch .. '*gcc*' + print('toolchain 3.3: arch_glob=' .. arch_glob) break end end - -- 7. Final Path Normalization local final_pattern = (packages_base .. arch_glob):gsub('//+', '/') - if vim.fn.has('win32') == 1 then final_pattern = final_pattern:gsub('/', '\\') end - print("toolchain 6.1: final_pattern=" .. final_pattern) + if vim.fn.has('win32') == 1 then + final_pattern = final_pattern:gsub('/', '\\') + print('toolchain 3.3: final_pattern=' .. final_pattern) + end - -- Save to cache _G._pio_cache = _G._pio_cache or {} _G._pio_cache[cache_key] = final_pattern return final_pattern end +-- function _G.get_pio_toolchain_pattern() +-- local cwd = vim.fn.getcwd() +-- +-- -- 1. Performance: Check Session Cache +-- local cache_key = cwd .. (vim.g.pio_active_env or 'auto') +-- if _G._pio_cache and _G._pio_cache[cache_key] then return _G._pio_cache[cache_key] end +-- print("toolchain 1:") +-- +-- -- 2. Get Full Project Config via JSON +-- local handle = io.popen('pio project config --json-output') +-- if not handle then return '/**/bin/*gcc*' end +-- local json_str = handle:read('*all') +-- handle:close() +-- print("toolchain 2:") +-- +-- local ok, config = pcall(vim.json.decode, json_str) +-- if not ok or not config then return '/**/bin/*gcc*' end +-- +-- -- 3. Determine Active Environment (Priority: Manual > default_envs > First [env:]) +-- local active_env = vim.g.pio_active_env +-- print("toolchain 3:") +-- +-- if not active_env then +-- -- A. Check if default_envs is defined in [platformio] +-- if config.platformio and config.platformio.default_envs then +-- -- Handles comma-separated lists like "env1, env2" +-- active_env = tostring(config.platformio.default_envs):match('([^,%s]+)') +-- end +-- print("toolchain 3.0:") +-- +-- -- B. Fallback: Find the first environment name starting with "env:" +-- if not active_env then +-- print(vim.inspect(config)) +-- for name, value in pairs(config) do +-- print("toolchain 3.0: name=" .. name .. ' value=' .. value) +-- -- FIX: Check type to prevent "attempt to index local 'name' (a number value)" +-- if type(name) == 'string' then +-- local env_match = name:match('^env:(.+)') +-- print("toolchain 3.0: env_match=" .. env_match) +-- if env_match then active_env = env_match break +-- end +-- end +-- end +-- end +-- end +-- +-- -- 4. Target the specific config block +-- -- PIO JSON uses "env:NAME" keys for environments +-- local env_key = 'env:' .. (active_env or '') +-- local env_data = config[env_key] or config[active_env] +-- print("toolchain 4:") +-- +-- if not env_data or not env_data.platform then return '/**/bin/*gcc*' end +-- +-- print("toolchain 5:") +-- -- 5. Build Paths (Normalizing for Windows/Linux) +-- local home = os.getenv('HOME') or os.getenv('USERPROFILE') +-- local core_dir = (config.platformio and config.platformio.core_dir) or (home .. '/.platformio') +-- local packages_base = core_dir:gsub('\\', '/') .. '/packages' +-- +-- -- 6. Query PIO for the Toolchain Architecture +-- local p_handle = io.popen('pio platform show ' .. env_data.platform .. ' --json-output') +-- if not p_handle then return packages_base .. '/**/bin/*gcc*' end +-- local p_json = p_handle:read('*all') +-- p_handle:close() +-- print("toolchain 6:") +-- +-- local p_ok, p_data = pcall(vim.json.decode, p_json) +-- if not p_ok or not p_data.packages then return packages_base .. '/**/bin/*gcc*' end +-- print("toolchain 6.0:") +-- +-- local arch_glob = '/**/bin/*gcc*' +-- for pkg_name, _ in pairs(p_data.packages) do +-- if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then +-- print("toolchain 6.1: pkg_name=" .. pkg_name) +-- local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') +-- arch_glob = '/**/bin/*' .. arch .. '*gcc*' +-- break +-- end +-- end +-- +-- -- 7. Final Path Normalization +-- local final_pattern = (packages_base .. arch_glob):gsub('//+', '/') +-- if vim.fn.has('win32') == 1 then final_pattern = final_pattern:gsub('/', '\\') end +-- print("toolchain 6.1: final_pattern=" .. final_pattern) +-- +-- -- Save to cache +-- _G._pio_cache = _G._pio_cache or {} +-- _G._pio_cache[cache_key] = final_pattern +-- return final_pattern +-- end ------------------------------------------------------ -- stylua: ignore function M.fix_pio_compile_commands() From 965bd9eca5d18988a80b56212480f39d0e69341a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 06:29:26 +0300 Subject: [PATCH 0516/1406] update --- lua/platformio/utils/pio.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 88578fac..00f4f170 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -109,9 +109,10 @@ function _G.get_pio_toolchain_pattern() print('toolchain 2.0') if not env_data then for _, item in ipairs(config) do + print('toolchain 2.1: item.name= ' .. item.name) if type(item) == 'table' and item.name and item.name:find('^env:') then env_data = item - print('toolchain 2.1: env_data= ' .. env_data) + print('toolchain 2.2: env_data= ' .. env_data) break end end From b16995e96f101140c4944a7f94dd679948479e6b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 06:30:38 +0300 Subject: [PATCH 0517/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 00f4f170..4a5346dc 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -89,7 +89,7 @@ function _G.get_pio_toolchain_pattern() -- Identify the global 'platformio' config block if item.name == 'platformio' then core_dir = item.core_dir or core_dir - print('toolchain 1.1: core_dir= ' .. core_dir) + print('toolchain 1.1: core_dir= ' .. item.core_dir) -- Priority: If no manual env is set, try to get default_envs if not active_env and item.default_envs then active_env = tostring(item.default_envs):match('([^,%s]+)') From 19e011f9efbd7c9cd0a2256adeab07384c02f6e8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 06:34:19 +0300 Subject: [PATCH 0518/1406] update --- lua/platformio/utils/pio.lua | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 4a5346dc..f6de7914 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -109,11 +109,13 @@ function _G.get_pio_toolchain_pattern() print('toolchain 2.0') if not env_data then for _, item in ipairs(config) do - print('toolchain 2.1: item.name= ' .. item.name) - if type(item) == 'table' and item.name and item.name:find('^env:') then - env_data = item - print('toolchain 2.2: env_data= ' .. env_data) - break + if type(item) == 'table' and item.name then + print('toolchain 2.1: item.name= ' .. item.name) + if item.name:find('^env:') then + env_data = item + print('toolchain 2.2: env_data= ' .. env_data) + break + end end end end From 1290495edaa1c6e6f2726e901058eca4174acd77 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 06:41:55 +0300 Subject: [PATCH 0519/1406] update --- lua/platformio/utils/pio.lua | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f6de7914..ef1b8a2a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -109,12 +109,15 @@ function _G.get_pio_toolchain_pattern() print('toolchain 2.0') if not env_data then for _, item in ipairs(config) do - if type(item) == 'table' and item.name then + if type(item) == 'table' then print('toolchain 2.1: item.name= ' .. item.name) - if item.name:find('^env:') then - env_data = item - print('toolchain 2.2: env_data= ' .. env_data) - break + print(vim.inspect(item)) + if item.name then + if item.name:find('^env:') then + env_data = item + print('toolchain 2.2: env_data= ' .. env_data) + break + end end end end From f8ac3e079667128c391f59a2123cc912ba69036a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 06:47:03 +0300 Subject: [PATCH 0520/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index ef1b8a2a..b99f3edf 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -110,9 +110,9 @@ function _G.get_pio_toolchain_pattern() if not env_data then for _, item in ipairs(config) do if type(item) == 'table' then - print('toolchain 2.1: item.name= ' .. item.name) print(vim.inspect(item)) if item.name then + print('toolchain 2.1: item.name= ' .. item.name) if item.name:find('^env:') then env_data = item print('toolchain 2.2: env_data= ' .. env_data) From 5fc6deea6523c04e92422d5dd98509b56d8dfa73 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 06:53:18 +0300 Subject: [PATCH 0521/1406] update --- lua/platformio/utils/pio.lua | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index b99f3edf..3b3b307e 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -111,6 +111,9 @@ function _G.get_pio_toolchain_pattern() for _, item in ipairs(config) do if type(item) == 'table' then print(vim.inspect(item)) + if type(item.name) == 'table' then + print(vim.inspect(item.name)) + end if item.name then print('toolchain 2.1: item.name= ' .. item.name) if item.name:find('^env:') then From cc8a8c8ed1693d87ab34be0baf4784e6016651e2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 06:58:55 +0300 Subject: [PATCH 0522/1406] update --- lua/platformio/utils/pio.lua | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 3b3b307e..99029e6a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -110,15 +110,17 @@ function _G.get_pio_toolchain_pattern() if not env_data then for _, item in ipairs(config) do if type(item) == 'table' then + print('toolchain 2.1') print(vim.inspect(item)) if type(item.name) == 'table' then + print('toolchain 2.2') print(vim.inspect(item.name)) end if item.name then - print('toolchain 2.1: item.name= ' .. item.name) + print('toolchain 2.3: item.name= ' .. item.name) if item.name:find('^env:') then env_data = item - print('toolchain 2.2: env_data= ' .. env_data) + print('toolchain 2.4: env_data= ' .. env_data) break end end From 8523ab6e6364b415b9ee4b7065a2ffd16629ec88 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 07:19:47 +0300 Subject: [PATCH 0523/1406] update --- lua/platformio/utils/pio.lua | 229 +++++++++++++++++++++++++++-------- 1 file changed, 178 insertions(+), 51 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 99029e6a..9b640fda 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -58,117 +58,244 @@ end ------------------------------------------------------ --- stylua: ignore +local function normalize(path) + return path:gsub('\\', '/'):gsub('//+', '/') +end + function _G.get_pio_toolchain_pattern() local cwd = vim.fn.getcwd() local cache_key = cwd .. (vim.g.pio_active_env or 'auto') - if _G._pio_cache and _G._pio_cache[cache_key] then + -- 1. Session Cache for Speed + _G._pio_cache = _G._pio_cache or {} + if _G._pio_cache[cache_key] then return _G._pio_cache[cache_key] end + -- 2. Fetch Project Config local handle = io.popen('pio project config --json-output') if not handle then return '/**/bin/*gcc*' end local json_str = handle:read('*all') handle:close() + print('tollchain 2.0') local ok, config = pcall(vim.json.decode, json_str) if not ok or not config then return '/**/bin/*gcc*' end + print('tollchain 2.1') local active_env = vim.g.pio_active_env - local env_data = nil - local core_dir = (os.getenv('HOME') or os.getenv('USERPROFILE')) .. '/.platformio' - - print('toolchain 1.0: core_dir= ' .. core_dir) - -- 1. Find the target environment in the array of objects - for _, item in ipairs(config) do - if type(item) == 'table' then - -- Identify the global 'platformio' config block - if item.name == 'platformio' then - core_dir = item.core_dir or core_dir - print('toolchain 1.1: core_dir= ' .. item.core_dir) - -- Priority: If no manual env is set, try to get default_envs - if not active_env and item.default_envs then - active_env = tostring(item.default_envs):match('([^,%s]+)') - print('toolchain 1.1: active_env= ' .. active_env) + local target_platform = nil + local home = os.getenv('HOME') or os.getenv('USERPROFILE') + local core_dir = home .. '/.platformio' + + -- 3. Parse Nested Array Structure + -- Structure: { { "section_name", { {"key", "val"}, ... } }, ... } + + -- First Pass: Determine Active Env if not set + if not active_env then + for _, section in ipairs(config) do + if section[1] == 'platformio' then + for _, kv in ipairs(section[2]) do + if kv[1] == 'default_envs' then + active_env = tostring(kv[2]):match('([^,%s]+)') + elseif kv[1] == 'core_dir' then + core_dir = kv[2] + end end end - - -- If we have an active_env, find its specific table - if active_env and (item.name == 'env:' .. active_env or item.name == active_env) then - env_data = item - print('toolchain 1.2: env_data= ' .. env_data) + end + end + print('tollchain 3.0') + + -- Second Pass: Find Platform for the Active Env + for _, section in ipairs(config) do + local name = section[1] + if active_env and (name == 'env:' .. active_env or name == active_env) then + for _, kv in ipairs(section[2]) do + if kv[1] == 'platform' then + target_platform = kv[2] + end end end end - -- 2. Fallback: If no env_data found yet, pick the first item starting with 'env:' - print('toolchain 2.0') - if not env_data then - for _, item in ipairs(config) do - if type(item) == 'table' then - print('toolchain 2.1') - print(vim.inspect(item)) - if type(item.name) == 'table' then - print('toolchain 2.2') - print(vim.inspect(item.name)) - end - if item.name then - print('toolchain 2.3: item.name= ' .. item.name) - if item.name:find('^env:') then - env_data = item - print('toolchain 2.4: env_data= ' .. env_data) - break + print('tollchain 4.0') + -- Fallback: If still no env, pick the first one available + if not target_platform then + for _, section in ipairs(config) do + if section[1]:find('^env:') then + for _, kv in ipairs(section[2]) do + if kv[1] == 'platform' then + target_platform = kv[2] end end + if target_platform then + break + end end end end - if not env_data or not env_data.platform then + if not target_platform then return '/**/bin/*gcc*' end - print('toolchain 3.0') + print('tollchain 5.0') - -- 3. Resolve the Toolchain Path - local packages_base = core_dir:gsub('\\', '/') .. '/packages' - local p_handle = io.popen('pio platform show ' .. env_data.platform .. ' --json-output') + -- 4. Query Platform for Toolchain Package Name + local p_handle = io.popen('pio platform show ' .. target_platform .. ' --json-output') if not p_handle then - return packages_base .. '/**/bin/*gcc*' + return '/**/bin/*gcc*' end - print('toolchain 3.1') + print('tollchain 6.0') local p_json = p_handle:read('*all') p_handle:close() local p_ok, p_data = pcall(vim.json.decode, p_json) if not p_ok or not p_data.packages then - return packages_base .. '/**/bin/*gcc*' + return '/**/bin/*gcc*' end + print('tollchain 7.0') - print('toolchain 3.2') + -- 5. Extract Arch and Build Pattern local arch_glob = '/**/bin/*gcc*' for pkg_name, _ in pairs(p_data.packages) do if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') arch_glob = '/**/bin/*' .. arch .. '*gcc*' - print('toolchain 3.3: arch_glob=' .. arch_glob) break end end - local final_pattern = (packages_base .. arch_glob):gsub('//+', '/') + print('tollchain 8.0') + -- 6. Final Path Assembly + local packages_path = normalize(core_dir .. '/packages') + local final_pattern = normalize(packages_path .. arch_glob) + if vim.fn.has('win32') == 1 then final_pattern = final_pattern:gsub('/', '\\') - print('toolchain 3.3: final_pattern=' .. final_pattern) end - _G._pio_cache = _G._pio_cache or {} + print('tollchain 9.0: final_pattern=' .. final_pattern) _G._pio_cache[cache_key] = final_pattern return final_pattern end + +--- +-- function _G.get_pio_toolchain_pattern() +-- local cwd = vim.fn.getcwd() +-- local cache_key = cwd .. (vim.g.pio_active_env or 'auto') +-- +-- if _G._pio_cache and _G._pio_cache[cache_key] then +-- return _G._pio_cache[cache_key] +-- end +-- +-- local handle = io.popen('pio project config --json-output') +-- if not handle then +-- return '/**/bin/*gcc*' +-- end +-- local json_str = handle:read('*all') +-- handle:close() +-- +-- local ok, config = pcall(vim.json.decode, json_str) +-- if not ok or not config then +-- return '/**/bin/*gcc*' +-- end +-- +-- local active_env = vim.g.pio_active_env +-- local env_data = nil +-- local core_dir = (os.getenv('HOME') or os.getenv('USERPROFILE')) .. '/.platformio' +-- +-- print('toolchain 1.0: core_dir= ' .. core_dir) +-- -- 1. Find the target environment in the array of objects +-- for _, item in ipairs(config) do +-- if type(item) == 'table' then +-- -- Identify the global 'platformio' config block +-- if item.name == 'platformio' then +-- core_dir = item.core_dir or core_dir +-- print('toolchain 1.1: core_dir= ' .. item.core_dir) +-- -- Priority: If no manual env is set, try to get default_envs +-- if not active_env and item.default_envs then +-- active_env = tostring(item.default_envs):match('([^,%s]+)') +-- print('toolchain 1.1: active_env= ' .. active_env) +-- end +-- end +-- +-- -- If we have an active_env, find its specific table +-- if active_env and (item.name == 'env:' .. active_env or item.name == active_env) then +-- env_data = item +-- print('toolchain 1.2: env_data= ' .. env_data) +-- end +-- end +-- end +-- +-- -- 2. Fallback: If no env_data found yet, pick the first item starting with 'env:' +-- print('toolchain 2.0') +-- if not env_data then +-- for _, item in ipairs(config) do +-- if type(item) == 'table' then +-- print('toolchain 2.1') +-- print(vim.inspect(item)) +-- if type(item.name) == 'table' then +-- print('toolchain 2.2') +-- print(vim.inspect(item.name)) +-- end +-- if item.name then +-- print('toolchain 2.3: item.name= ' .. item.name) +-- if item.name:find('^env:') then +-- env_data = item +-- print('toolchain 2.4: env_data= ' .. env_data) +-- break +-- end +-- end +-- end +-- end +-- end +-- +-- if not env_data or not env_data.platform then +-- return '/**/bin/*gcc*' +-- end +-- print('toolchain 3.0') +-- +-- -- 3. Resolve the Toolchain Path +-- local packages_base = core_dir:gsub('\\', '/') .. '/packages' +-- local p_handle = io.popen('pio platform show ' .. env_data.platform .. ' --json-output') +-- if not p_handle then +-- return packages_base .. '/**/bin/*gcc*' +-- end +-- print('toolchain 3.1') +-- local p_json = p_handle:read('*all') +-- p_handle:close() +-- +-- local p_ok, p_data = pcall(vim.json.decode, p_json) +-- if not p_ok or not p_data.packages then +-- return packages_base .. '/**/bin/*gcc*' +-- end +-- +-- print('toolchain 3.2') +-- local arch_glob = '/**/bin/*gcc*' +-- for pkg_name, _ in pairs(p_data.packages) do +-- if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then +-- local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') +-- arch_glob = '/**/bin/*' .. arch .. '*gcc*' +-- print('toolchain 3.3: arch_glob=' .. arch_glob) +-- break +-- end +-- end +-- +-- local final_pattern = (packages_base .. arch_glob):gsub('//+', '/') +-- if vim.fn.has('win32') == 1 then +-- final_pattern = final_pattern:gsub('/', '\\') +-- print('toolchain 3.3: final_pattern=' .. final_pattern) +-- end +-- +-- _G._pio_cache = _G._pio_cache or {} +-- _G._pio_cache[cache_key] = final_pattern +-- return final_pattern +-- end -- function _G.get_pio_toolchain_pattern() -- local cwd = vim.fn.getcwd() -- From ad7ca25369b99e62c215cb19ec2829fc879298f6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 07:30:15 +0300 Subject: [PATCH 0524/1406] update --- lua/platformio/utils/pio.lua | 253 +++++++++++------------------------ 1 file changed, 78 insertions(+), 175 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 9b640fda..fbeff3fa 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -58,60 +58,48 @@ end ------------------------------------------------------ --- stylua: ignore -local function normalize(path) - return path:gsub('\\', '/'):gsub('//+', '/') -end - function _G.get_pio_toolchain_pattern() local cwd = vim.fn.getcwd() local cache_key = cwd .. (vim.g.pio_active_env or 'auto') - -- 1. Session Cache for Speed _G._pio_cache = _G._pio_cache or {} if _G._pio_cache[cache_key] then return _G._pio_cache[cache_key] end - -- 2. Fetch Project Config local handle = io.popen('pio project config --json-output') if not handle then return '/**/bin/*gcc*' end local json_str = handle:read('*all') handle:close() - print('tollchain 2.0') local ok, config = pcall(vim.json.decode, json_str) if not ok or not config then return '/**/bin/*gcc*' end - print('tollchain 2.1') local active_env = vim.g.pio_active_env local target_platform = nil - local home = os.getenv('HOME') or os.getenv('USERPROFILE') - local core_dir = home .. '/.platformio' + local core_dir = (os.getenv('HOME') or os.getenv('USERPROFILE')) .. '/.platformio' - -- 3. Parse Nested Array Structure - -- Structure: { { "section_name", { {"key", "val"}, ... } }, ... } - - -- First Pass: Determine Active Env if not set + -- 1. Pass One: Extract default_envs and core_dir from 'platformio' section if not active_env then for _, section in ipairs(config) do if section[1] == 'platformio' then for _, kv in ipairs(section[2]) do if kv[1] == 'default_envs' then active_env = tostring(kv[2]):match('([^,%s]+)') - elseif kv[1] == 'core_dir' then + end + if kv[1] == 'core_dir' then core_dir = kv[2] end end end end end - print('tollchain 3.0') - -- Second Pass: Find Platform for the Active Env + -- 2. Pass Two: Find the platform for the active environment for _, section in ipairs(config) do local name = section[1] if active_env and (name == 'env:' .. active_env or name == active_env) then @@ -123,11 +111,10 @@ function _G.get_pio_toolchain_pattern() end end - print('tollchain 4.0') - -- Fallback: If still no env, pick the first one available + -- 3. Fallback: If still nothing, take the first platform from any 'env:' section if not target_platform then for _, section in ipairs(config) do - if section[1]:find('^env:') then + if type(section[1]) == 'string' and section[1]:find('^env:') then for _, kv in ipairs(section[2]) do if kv[1] == 'platform' then target_platform = kv[2] @@ -143,14 +130,12 @@ function _G.get_pio_toolchain_pattern() if not target_platform then return '/**/bin/*gcc*' end - print('tollchain 5.0') - -- 4. Query Platform for Toolchain Package Name + -- 4. Query the platform for the toolchain package name local p_handle = io.popen('pio platform show ' .. target_platform .. ' --json-output') if not p_handle then return '/**/bin/*gcc*' end - print('tollchain 6.0') local p_json = p_handle:read('*all') p_handle:close() @@ -158,9 +143,8 @@ function _G.get_pio_toolchain_pattern() if not p_ok or not p_data.packages then return '/**/bin/*gcc*' end - print('tollchain 7.0') - -- 5. Extract Arch and Build Pattern + -- 5. Extract Arch local arch_glob = '/**/bin/*gcc*' for pkg_name, _ in pairs(p_data.packages) do if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then @@ -170,223 +154,142 @@ function _G.get_pio_toolchain_pattern() end end - print('tollchain 8.0') - -- 6. Final Path Assembly - local packages_path = normalize(core_dir .. '/packages') - local final_pattern = normalize(packages_path .. arch_glob) + local final_pattern = (core_dir:gsub('\\', '/') .. '/packages' .. arch_glob):gsub('//+', '/') + -- if vim.fn.has('win32') == 1 then + -- final_pattern = final_pattern:gsub('/', '\\') + -- end - if vim.fn.has('win32') == 1 then - final_pattern = final_pattern:gsub('/', '\\') - end - - print('tollchain 9.0: final_pattern=' .. final_pattern) _G._pio_cache[cache_key] = final_pattern + print('tollchain 9.0: final_pattern=' .. final_pattern) return final_pattern end - ---- +-- local function normalize(path) +-- return path:gsub('\\', '/'):gsub('//+', '/') +-- end +-- -- function _G.get_pio_toolchain_pattern() -- local cwd = vim.fn.getcwd() -- local cache_key = cwd .. (vim.g.pio_active_env or 'auto') -- --- if _G._pio_cache and _G._pio_cache[cache_key] then +-- -- 1. Session Cache for Speed +-- _G._pio_cache = _G._pio_cache or {} +-- if _G._pio_cache[cache_key] then -- return _G._pio_cache[cache_key] -- end -- +-- -- 2. Fetch Project Config -- local handle = io.popen('pio project config --json-output') -- if not handle then -- return '/**/bin/*gcc*' -- end -- local json_str = handle:read('*all') -- handle:close() +-- print('tollchain 2.0') -- -- local ok, config = pcall(vim.json.decode, json_str) -- if not ok or not config then -- return '/**/bin/*gcc*' -- end +-- print('tollchain 2.1') -- -- local active_env = vim.g.pio_active_env --- local env_data = nil --- local core_dir = (os.getenv('HOME') or os.getenv('USERPROFILE')) .. '/.platformio' +-- local target_platform = nil +-- local home = os.getenv('HOME') or os.getenv('USERPROFILE') +-- local core_dir = home .. '/.platformio' +-- +-- -- 3. Parse Nested Array Structure +-- -- Structure: { { "section_name", { {"key", "val"}, ... } }, ... } -- --- print('toolchain 1.0: core_dir= ' .. core_dir) --- -- 1. Find the target environment in the array of objects --- for _, item in ipairs(config) do --- if type(item) == 'table' then --- -- Identify the global 'platformio' config block --- if item.name == 'platformio' then --- core_dir = item.core_dir or core_dir --- print('toolchain 1.1: core_dir= ' .. item.core_dir) --- -- Priority: If no manual env is set, try to get default_envs --- if not active_env and item.default_envs then --- active_env = tostring(item.default_envs):match('([^,%s]+)') --- print('toolchain 1.1: active_env= ' .. active_env) +-- -- First Pass: Determine Active Env if not set +-- if not active_env then +-- for _, section in ipairs(config) do +-- if section[1] == 'platformio' then +-- for _, kv in ipairs(section[2]) do +-- if kv[1] == 'default_envs' then +-- active_env = tostring(kv[2]):match('([^,%s]+)') +-- elseif kv[1] == 'core_dir' then +-- core_dir = kv[2] +-- end -- end -- end +-- end +-- end +-- print('tollchain 3.0') -- --- -- If we have an active_env, find its specific table --- if active_env and (item.name == 'env:' .. active_env or item.name == active_env) then --- env_data = item --- print('toolchain 1.2: env_data= ' .. env_data) +-- -- Second Pass: Find Platform for the Active Env +-- for _, section in ipairs(config) do +-- local name = section[1] +-- if active_env and (name == 'env:' .. active_env or name == active_env) then +-- for _, kv in ipairs(section[2]) do +-- if kv[1] == 'platform' then +-- target_platform = kv[2] +-- end -- end -- end -- end -- --- -- 2. Fallback: If no env_data found yet, pick the first item starting with 'env:' --- print('toolchain 2.0') --- if not env_data then --- for _, item in ipairs(config) do --- if type(item) == 'table' then --- print('toolchain 2.1') --- print(vim.inspect(item)) --- if type(item.name) == 'table' then --- print('toolchain 2.2') --- print(vim.inspect(item.name)) --- end --- if item.name then --- print('toolchain 2.3: item.name= ' .. item.name) --- if item.name:find('^env:') then --- env_data = item --- print('toolchain 2.4: env_data= ' .. env_data) --- break +-- print('tollchain 4.0') +-- -- Fallback: If still no env, pick the first one available +-- if not target_platform then +-- for _, section in ipairs(config) do +-- if section[1]:find('^env:') then +-- for _, kv in ipairs(section[2]) do +-- if kv[1] == 'platform' then +-- target_platform = kv[2] -- end -- end +-- if target_platform then +-- break +-- end -- end -- end -- end -- --- if not env_data or not env_data.platform then +-- if not target_platform then -- return '/**/bin/*gcc*' -- end --- print('toolchain 3.0') +-- print('tollchain 5.0') -- --- -- 3. Resolve the Toolchain Path --- local packages_base = core_dir:gsub('\\', '/') .. '/packages' --- local p_handle = io.popen('pio platform show ' .. env_data.platform .. ' --json-output') +-- -- 4. Query Platform for Toolchain Package Name +-- local p_handle = io.popen('pio platform show ' .. target_platform .. ' --json-output') -- if not p_handle then --- return packages_base .. '/**/bin/*gcc*' +-- return '/**/bin/*gcc*' -- end --- print('toolchain 3.1') +-- print('tollchain 6.0') -- local p_json = p_handle:read('*all') -- p_handle:close() -- -- local p_ok, p_data = pcall(vim.json.decode, p_json) -- if not p_ok or not p_data.packages then --- return packages_base .. '/**/bin/*gcc*' +-- return '/**/bin/*gcc*' -- end +-- print('tollchain 7.0') -- --- print('toolchain 3.2') +-- -- 5. Extract Arch and Build Pattern -- local arch_glob = '/**/bin/*gcc*' -- for pkg_name, _ in pairs(p_data.packages) do -- if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then -- local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') -- arch_glob = '/**/bin/*' .. arch .. '*gcc*' --- print('toolchain 3.3: arch_glob=' .. arch_glob) -- break -- end -- end -- --- local final_pattern = (packages_base .. arch_glob):gsub('//+', '/') +-- print('tollchain 8.0') +-- -- 6. Final Path Assembly +-- local packages_path = normalize(core_dir .. '/packages') +-- local final_pattern = normalize(packages_path .. arch_glob) +-- -- if vim.fn.has('win32') == 1 then -- final_pattern = final_pattern:gsub('/', '\\') --- print('toolchain 3.3: final_pattern=' .. final_pattern) -- end -- --- _G._pio_cache = _G._pio_cache or {} +-- print('tollchain 9.0: final_pattern=' .. final_pattern) -- _G._pio_cache[cache_key] = final_pattern -- return final_pattern -- end --- function _G.get_pio_toolchain_pattern() --- local cwd = vim.fn.getcwd() --- --- -- 1. Performance: Check Session Cache --- local cache_key = cwd .. (vim.g.pio_active_env or 'auto') --- if _G._pio_cache and _G._pio_cache[cache_key] then return _G._pio_cache[cache_key] end --- print("toolchain 1:") --- --- -- 2. Get Full Project Config via JSON --- local handle = io.popen('pio project config --json-output') --- if not handle then return '/**/bin/*gcc*' end --- local json_str = handle:read('*all') --- handle:close() --- print("toolchain 2:") --- --- local ok, config = pcall(vim.json.decode, json_str) --- if not ok or not config then return '/**/bin/*gcc*' end --- --- -- 3. Determine Active Environment (Priority: Manual > default_envs > First [env:]) --- local active_env = vim.g.pio_active_env --- print("toolchain 3:") --- --- if not active_env then --- -- A. Check if default_envs is defined in [platformio] --- if config.platformio and config.platformio.default_envs then --- -- Handles comma-separated lists like "env1, env2" --- active_env = tostring(config.platformio.default_envs):match('([^,%s]+)') --- end --- print("toolchain 3.0:") --- --- -- B. Fallback: Find the first environment name starting with "env:" --- if not active_env then --- print(vim.inspect(config)) --- for name, value in pairs(config) do --- print("toolchain 3.0: name=" .. name .. ' value=' .. value) --- -- FIX: Check type to prevent "attempt to index local 'name' (a number value)" --- if type(name) == 'string' then --- local env_match = name:match('^env:(.+)') --- print("toolchain 3.0: env_match=" .. env_match) --- if env_match then active_env = env_match break --- end --- end --- end --- end --- end --- --- -- 4. Target the specific config block --- -- PIO JSON uses "env:NAME" keys for environments --- local env_key = 'env:' .. (active_env or '') --- local env_data = config[env_key] or config[active_env] --- print("toolchain 4:") --- --- if not env_data or not env_data.platform then return '/**/bin/*gcc*' end --- --- print("toolchain 5:") --- -- 5. Build Paths (Normalizing for Windows/Linux) --- local home = os.getenv('HOME') or os.getenv('USERPROFILE') --- local core_dir = (config.platformio and config.platformio.core_dir) or (home .. '/.platformio') --- local packages_base = core_dir:gsub('\\', '/') .. '/packages' --- --- -- 6. Query PIO for the Toolchain Architecture --- local p_handle = io.popen('pio platform show ' .. env_data.platform .. ' --json-output') --- if not p_handle then return packages_base .. '/**/bin/*gcc*' end --- local p_json = p_handle:read('*all') --- p_handle:close() --- print("toolchain 6:") --- --- local p_ok, p_data = pcall(vim.json.decode, p_json) --- if not p_ok or not p_data.packages then return packages_base .. '/**/bin/*gcc*' end --- print("toolchain 6.0:") --- --- local arch_glob = '/**/bin/*gcc*' --- for pkg_name, _ in pairs(p_data.packages) do --- if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then --- print("toolchain 6.1: pkg_name=" .. pkg_name) --- local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') --- arch_glob = '/**/bin/*' .. arch .. '*gcc*' --- break --- end --- end -- --- -- 7. Final Path Normalization --- local final_pattern = (packages_base .. arch_glob):gsub('//+', '/') --- if vim.fn.has('win32') == 1 then final_pattern = final_pattern:gsub('/', '\\') end --- print("toolchain 6.1: final_pattern=" .. final_pattern) --- --- -- Save to cache --- _G._pio_cache = _G._pio_cache or {} --- _G._pio_cache[cache_key] = final_pattern --- return final_pattern --- end +--- ------------------------------------------------------ -- stylua: ignore function M.fix_pio_compile_commands() From a4b149468c947fb3871e580e3591dbaa321be2f6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 09:02:56 +0300 Subject: [PATCH 0525/1406] update --- lua/platformio/archived/tmp.lua | 73 ++++++++++++++++++++ lua/platformio/utils/pio.lua | 116 ++++++++++++++++++++++++-------- 2 files changed, 161 insertions(+), 28 deletions(-) create mode 100644 lua/platformio/archived/tmp.lua diff --git a/lua/platformio/archived/tmp.lua b/lua/platformio/archived/tmp.lua new file mode 100644 index 00000000..07264efa --- /dev/null +++ b/lua/platformio/archived/tmp.lua @@ -0,0 +1,73 @@ +M = {} +function M.get_pio_dir(type) + -- 1. Setup Base Paths + local home = os.getenv('HOME') or os.getenv('USERPROFILE') + + -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) + local map = { + core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, + packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, + platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, + } + + local core_ini, packages_ini, platforms_ini = nil, nil, nil + local core_map, packages_map, platforms_map = map['core'], map['packages'], map['platforms'] + if not core_map and not packages_map and not platforms_map then + return nil + end + + -- 3. Try to get explicit value from platformio.ini + ----------------------------------------------------- + local handle = io.popen('pio project config --json-output') + if handle then + local json_str = handle:read('*all') + local _, config = pcall(vim.json.decode, json_str) + for _, section in ipairs(config) do + if section[1] == 'platformio' then + for _, kv in ipairs(section[2]) do + if kv[1] == platforms_map.ini then + platforms_ini = tostring(kv[2]):match('([^,%s]+)') + end + if kv[1] == packages_map then + packages_ini = tostring(kv[2]):match('([^,%s]+)') + end + if kv[1] == core_map then + core_ini = kv[2] + end + end + end + end + handle:close() + end + + -- 4.0 Fallback Logic: INI -> Env Var -> Default + ----------------------------------------------------- + local core_dir = core_ini or os.getenv('PLATFORMIO_CORE_DIR' or (home .. map['core'].sub)):gsub('[\\/]+$', '') + core_dir = misc.normalize_path(core_dir) --core_dir:gsub('\\', '/'):gsub('//+', '/') + + if type == 'core' then + return core_dir + end + + local result + if type == 'packages' then + result = packages_ini or os.getenv(packages_map.env) or (core_dir .. packages_map.sub) + end + if type == 'platforms' then + result = platforms_ini or os.getenv(platforms_map.env) or (core_dir .. platforms_map.sub) + end + + -- 5. Expand ${platformio.core_dir} + if result:find('${platformio.core_dir}', 1, true) then + result = result:gsub('%${platformio.core_dir}', core_dir) + end + + -- 6. Normalize Slashes for Windows + result = misc.normalize_path(result) --result:gsub('\\', '/'):gsub('//+', '/') + -- if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end + + -- Ensure core_dir itself doesn't have trailing slashes for cleaner joins + return result +end + +return M diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index fbeff3fa..4e8dbb2b 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -18,43 +18,103 @@ function M.get_pio_dir(type) platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, } - local target_config = map[type] - if not target_config then return nil end + local core_ini, dir_ini = nil, nil + local core_map, dir_map = map['core'], map[type] + if not core_map and not dir_map then + return nil + end -- 3. Try to get explicit value from platformio.ini - local path = vim.fn.getcwd() .. '/platformio.ini' - local inifile = io.open(path, 'r') - local ini_val = nil - local core_val = nil - - if inifile then - for line in inifile:lines() do - if core_val == nil then core_val = line:match('^%s*' .. map['core'].ini .. '%s*=%s*([^;%s]+)') end - if ini_val == nil then ini_val = line:match('^%s*' .. target_config.ini .. '%s*=%s*([^;%s]+)') end - if ini_val and core_val then break end + local handle = io.popen('pio project config --json-output') + if handle then + local json_str = handle:read('*all') + local _, config = pcall(vim.json.decode, json_str) + for _, section in ipairs(config) do + if section[1] == 'platformio' then + for _, kv in ipairs(section[2]) do + if kv[1] == dir_map.ini then + dir_ini = tostring(kv[2]):match('([^,%s]+)') + end + if kv[1] == core_map.ini then + core_ini = kv[2] + end + end + break + end end - inifile:close() + handle:close() end -- 4.0 Fallback Logic: INI -> Env Var -> Default - local core_dir = core_val or os.getenv('PLATFORMIO_CORE_DIR' or (home .. map['core'].sub)):gsub('[\\/]+$', '') + local core_dir = core_ini or os.getenv('PLATFORMIO_CORE_DIR' or (home .. map['core'].sub)):gsub('[\\/]+$', '') core_dir = misc.normalize_path(core_dir) --core_dir:gsub('\\', '/'):gsub('//+', '/') - -- if vim.fn.has('win32') == 1 then core_dir = core_dir:gsub('/', '\\') end - if type == 'core' then return core_dir end - -- 4.1 Fallback Logic: INI -> Env Var -> Default - local result = ini_val or os.getenv(target_config.env) or (core_dir .. target_config.sub) + if type == 'core' then + return core_dir + end + + local result = dir_ini or os.getenv(dir_map.env) or (core_dir .. dir_map.sub) -- 5. Expand ${platformio.core_dir} - if result:find('${platformio.core_dir}', 1, true) then result = result:gsub('%${platformio.core_dir}', core_dir) end + if result:find('${platformio.core_dir}', 1, true) then + result = result:gsub('%${platformio.core_dir}', core_dir) + end -- 6. Normalize Slashes for Windows result = misc.normalize_path(result) --result:gsub('\\', '/'):gsub('//+', '/') - -- if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end - - -- Ensure core_dir itself doesn't have trailing slashes for cleaner joins return result end +-- function M.get_pio_dir(type) +-- -- 1. Setup Base Paths +-- local home = os.getenv('HOME') or os.getenv('USERPROFILE') +-- +-- -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) +-- local map = { +-- core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, +-- packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, +-- platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, +-- } +-- +-- local target_config = map[type] +-- if not target_config then return nil end +-- +-- -- 3. Try to get explicit value from platformio.ini +-- local path = vim.fn.getcwd() .. '/platformio.ini' +-- local inifile = io.open(path, 'r') +-- local ini_val = nil +-- local core_val = nil +-- ----------------------------------------------------- +-- --- +-- ----------------------------------------------------- +-- +-- if inifile then +-- for line in inifile:lines() do +-- if core_val == nil then core_val = line:match('^%s*' .. map['core'].ini .. '%s*=%s*([^;%s]+)') end +-- if ini_val == nil then ini_val = line:match('^%s*' .. target_config.ini .. '%s*=%s*([^;%s]+)') end +-- if ini_val and core_val then break end +-- end +-- inifile:close() +-- end +-- +-- -- 4.0 Fallback Logic: INI -> Env Var -> Default +-- local core_dir = core_val or os.getenv('PLATFORMIO_CORE_DIR' or (home .. map['core'].sub)):gsub('[\\/]+$', '') +-- core_dir = misc.normalize_path(core_dir) --core_dir:gsub('\\', '/'):gsub('//+', '/') +-- -- if vim.fn.has('win32') == 1 then core_dir = core_dir:gsub('/', '\\') end +-- if type == 'core' then return core_dir end +-- +-- -- 4.1 Fallback Logic: INI -> Env Var -> Default +-- local result = ini_val or os.getenv(target_config.env) or (core_dir .. target_config.sub) +-- +-- -- 5. Expand ${platformio.core_dir} +-- if result:find('${platformio.core_dir}', 1, true) then result = result:gsub('%${platformio.core_dir}', core_dir) end +-- +-- -- 6. Normalize Slashes for Windows +-- result = misc.normalize_path(result) --result:gsub('\\', '/'):gsub('//+', '/') +-- -- if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end +-- +-- -- Ensure core_dir itself doesn't have trailing slashes for cleaner joins +-- return result +-- end ------------------------------------------------------ --- stylua: ignore @@ -69,14 +129,14 @@ function _G.get_pio_toolchain_pattern() local handle = io.popen('pio project config --json-output') if not handle then - return '/**/bin/*gcc*' + return '**/toolchain-*/**/bin/*' end local json_str = handle:read('*all') handle:close() local ok, config = pcall(vim.json.decode, json_str) if not ok or not config then - return '/**/bin/*gcc*' + return '**/toolchain-*/**/bin/*' end local active_env = vim.g.pio_active_env @@ -128,24 +188,24 @@ function _G.get_pio_toolchain_pattern() end if not target_platform then - return '/**/bin/*gcc*' + return '**/toolchain-*/**/bin/*' end -- 4. Query the platform for the toolchain package name local p_handle = io.popen('pio platform show ' .. target_platform .. ' --json-output') if not p_handle then - return '/**/bin/*gcc*' + return '**/toolchain-*/**/bin/*' end local p_json = p_handle:read('*all') p_handle:close() local p_ok, p_data = pcall(vim.json.decode, p_json) if not p_ok or not p_data.packages then - return '/**/bin/*gcc*' + return '**/toolchain-*/**/bin/*' end -- 5. Extract Arch - local arch_glob = '/**/bin/*gcc*' + local arch_glob = '**/toolchain-*/**/bin/*' for pkg_name, _ in pairs(p_data.packages) do if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') From 758289efa8fe795cce8307b1f5474dea82470796 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 09:04:49 +0300 Subject: [PATCH 0526/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 4e8dbb2b..ccde6f5e 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -209,7 +209,7 @@ function _G.get_pio_toolchain_pattern() for pkg_name, _ in pairs(p_data.packages) do if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') - arch_glob = '/**/bin/*' .. arch .. '*gcc*' + arch_glob = '/**/bin/*' .. arch .. '*' break end end From 352550ff258c6eca994e0669860f211b9a734b1f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 09:17:24 +0300 Subject: [PATCH 0527/1406] update --- lua/platformio/utils/pio.lua | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index ccde6f5e..b42da119 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -129,14 +129,14 @@ function _G.get_pio_toolchain_pattern() local handle = io.popen('pio project config --json-output') if not handle then - return '**/toolchain-*/**/bin/*' + return '/**/bin/*' end local json_str = handle:read('*all') handle:close() local ok, config = pcall(vim.json.decode, json_str) if not ok or not config then - return '**/toolchain-*/**/bin/*' + return '/**/bin/*' end local active_env = vim.g.pio_active_env @@ -188,24 +188,24 @@ function _G.get_pio_toolchain_pattern() end if not target_platform then - return '**/toolchain-*/**/bin/*' + return '/**/bin/*' end -- 4. Query the platform for the toolchain package name local p_handle = io.popen('pio platform show ' .. target_platform .. ' --json-output') if not p_handle then - return '**/toolchain-*/**/bin/*' + return '/**/bin/*' end local p_json = p_handle:read('*all') p_handle:close() local p_ok, p_data = pcall(vim.json.decode, p_json) if not p_ok or not p_data.packages then - return '**/toolchain-*/**/bin/*' + return '/**/bin/*' end -- 5. Extract Arch - local arch_glob = '**/toolchain-*/**/bin/*' + local arch_glob = '/**/bin/*' for pkg_name, _ in pairs(p_data.packages) do if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') From 0a18a57fda06d3b3807f91bb7080eb4f58d3436c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 09:32:11 +0300 Subject: [PATCH 0528/1406] update --- lua/platformio/utils/pio.lua | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index b42da119..71b9d108 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -129,14 +129,14 @@ function _G.get_pio_toolchain_pattern() local handle = io.popen('pio project config --json-output') if not handle then - return '/**/bin/*' + return '/toolchain-*/**/bin/*' end local json_str = handle:read('*all') handle:close() local ok, config = pcall(vim.json.decode, json_str) if not ok or not config then - return '/**/bin/*' + return '/toolchain-*/**/bin/*' end local active_env = vim.g.pio_active_env @@ -188,24 +188,24 @@ function _G.get_pio_toolchain_pattern() end if not target_platform then - return '/**/bin/*' + return '/toolchain-*/**/bin/*' end -- 4. Query the platform for the toolchain package name local p_handle = io.popen('pio platform show ' .. target_platform .. ' --json-output') if not p_handle then - return '/**/bin/*' + return '/toolchain-*/**/bin/*' end local p_json = p_handle:read('*all') p_handle:close() local p_ok, p_data = pcall(vim.json.decode, p_json) if not p_ok or not p_data.packages then - return '/**/bin/*' + return '/toolchain-*/**/bin/*' end -- 5. Extract Arch - local arch_glob = '/**/bin/*' + local arch_glob = '/toolchain-*/**/bin/*' for pkg_name, _ in pairs(p_data.packages) do if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') From c4caec8c5e377da52e853b03677c65d2d49452bd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 12:54:53 +0300 Subject: [PATCH 0529/1406] update --- lua/platformio/archived/tmp.lua | 73 -------------- lua/platformio/utils/pio.lua | 167 +++----------------------------- 2 files changed, 13 insertions(+), 227 deletions(-) delete mode 100644 lua/platformio/archived/tmp.lua diff --git a/lua/platformio/archived/tmp.lua b/lua/platformio/archived/tmp.lua deleted file mode 100644 index 07264efa..00000000 --- a/lua/platformio/archived/tmp.lua +++ /dev/null @@ -1,73 +0,0 @@ -M = {} -function M.get_pio_dir(type) - -- 1. Setup Base Paths - local home = os.getenv('HOME') or os.getenv('USERPROFILE') - - -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) - local map = { - core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, - packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, - platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, - } - - local core_ini, packages_ini, platforms_ini = nil, nil, nil - local core_map, packages_map, platforms_map = map['core'], map['packages'], map['platforms'] - if not core_map and not packages_map and not platforms_map then - return nil - end - - -- 3. Try to get explicit value from platformio.ini - ----------------------------------------------------- - local handle = io.popen('pio project config --json-output') - if handle then - local json_str = handle:read('*all') - local _, config = pcall(vim.json.decode, json_str) - for _, section in ipairs(config) do - if section[1] == 'platformio' then - for _, kv in ipairs(section[2]) do - if kv[1] == platforms_map.ini then - platforms_ini = tostring(kv[2]):match('([^,%s]+)') - end - if kv[1] == packages_map then - packages_ini = tostring(kv[2]):match('([^,%s]+)') - end - if kv[1] == core_map then - core_ini = kv[2] - end - end - end - end - handle:close() - end - - -- 4.0 Fallback Logic: INI -> Env Var -> Default - ----------------------------------------------------- - local core_dir = core_ini or os.getenv('PLATFORMIO_CORE_DIR' or (home .. map['core'].sub)):gsub('[\\/]+$', '') - core_dir = misc.normalize_path(core_dir) --core_dir:gsub('\\', '/'):gsub('//+', '/') - - if type == 'core' then - return core_dir - end - - local result - if type == 'packages' then - result = packages_ini or os.getenv(packages_map.env) or (core_dir .. packages_map.sub) - end - if type == 'platforms' then - result = platforms_ini or os.getenv(platforms_map.env) or (core_dir .. platforms_map.sub) - end - - -- 5. Expand ${platformio.core_dir} - if result:find('${platformio.core_dir}', 1, true) then - result = result:gsub('%${platformio.core_dir}', core_dir) - end - - -- 6. Normalize Slashes for Windows - result = misc.normalize_path(result) --result:gsub('\\', '/'):gsub('//+', '/') - -- if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end - - -- Ensure core_dir itself doesn't have trailing slashes for cleaner joins - return result -end - -return M diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 71b9d108..b1f7140c 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -117,32 +117,26 @@ end -- end ------------------------------------------------------ ---- stylua: ignore +-- stylua: ignore function _G.get_pio_toolchain_pattern() local cwd = vim.fn.getcwd() local cache_key = cwd .. (vim.g.pio_active_env or 'auto') _G._pio_cache = _G._pio_cache or {} - if _G._pio_cache[cache_key] then - return _G._pio_cache[cache_key] - end + if _G._pio_cache[cache_key] then return _G._pio_cache[cache_key] end local handle = io.popen('pio project config --json-output') - if not handle then - return '/toolchain-*/**/bin/*' - end + if not handle then return '/toolchain-*/**/bin/*' end local json_str = handle:read('*all') handle:close() local ok, config = pcall(vim.json.decode, json_str) - if not ok or not config then - return '/toolchain-*/**/bin/*' - end + if not ok or not config then return '/toolchain-*/**/bin/*' end local active_env = vim.g.pio_active_env local target_platform = nil local core_dir = (os.getenv('HOME') or os.getenv('USERPROFILE')) .. '/.platformio' - + if active_env then print('active_env0: ' .. active_env) end -- 1. Pass One: Extract default_envs and core_dir from 'platformio' section if not active_env then for _, section in ipairs(config) do @@ -159,14 +153,13 @@ function _G.get_pio_toolchain_pattern() end end + if active_env then print('active_env1: ' .. active_env) end -- 2. Pass Two: Find the platform for the active environment for _, section in ipairs(config) do local name = section[1] if active_env and (name == 'env:' .. active_env or name == active_env) then for _, kv in ipairs(section[2]) do - if kv[1] == 'platform' then - target_platform = kv[2] - end + if kv[1] == 'platform' then target_platform = kv[2] end end end end @@ -176,9 +169,7 @@ function _G.get_pio_toolchain_pattern() for _, section in ipairs(config) do if type(section[1]) == 'string' and section[1]:find('^env:') then for _, kv in ipairs(section[2]) do - if kv[1] == 'platform' then - target_platform = kv[2] - end + if kv[1] == 'platform' then target_platform = kv[2] end end if target_platform then break @@ -187,22 +178,17 @@ function _G.get_pio_toolchain_pattern() end end - if not target_platform then - return '/toolchain-*/**/bin/*' - end + if not target_platform then return '/toolchain-*/**/bin/*' end + if active_env then print('target_platform4: ' .. target_platform) end -- 4. Query the platform for the toolchain package name local p_handle = io.popen('pio platform show ' .. target_platform .. ' --json-output') - if not p_handle then - return '/toolchain-*/**/bin/*' - end + if not p_handle then return '/toolchain-*/**/bin/*' end local p_json = p_handle:read('*all') p_handle:close() local p_ok, p_data = pcall(vim.json.decode, p_json) - if not p_ok or not p_data.packages then - return '/toolchain-*/**/bin/*' - end + if not p_ok or not p_data.packages then return '/toolchain-*/**/bin/*' end -- 5. Extract Arch local arch_glob = '/toolchain-*/**/bin/*' @@ -220,136 +206,9 @@ function _G.get_pio_toolchain_pattern() -- end _G._pio_cache[cache_key] = final_pattern - print('tollchain 9.0: final_pattern=' .. final_pattern) return final_pattern end --- local function normalize(path) --- return path:gsub('\\', '/'):gsub('//+', '/') --- end --- --- function _G.get_pio_toolchain_pattern() --- local cwd = vim.fn.getcwd() --- local cache_key = cwd .. (vim.g.pio_active_env or 'auto') --- --- -- 1. Session Cache for Speed --- _G._pio_cache = _G._pio_cache or {} --- if _G._pio_cache[cache_key] then --- return _G._pio_cache[cache_key] --- end --- --- -- 2. Fetch Project Config --- local handle = io.popen('pio project config --json-output') --- if not handle then --- return '/**/bin/*gcc*' --- end --- local json_str = handle:read('*all') --- handle:close() --- print('tollchain 2.0') --- --- local ok, config = pcall(vim.json.decode, json_str) --- if not ok or not config then --- return '/**/bin/*gcc*' --- end --- print('tollchain 2.1') --- --- local active_env = vim.g.pio_active_env --- local target_platform = nil --- local home = os.getenv('HOME') or os.getenv('USERPROFILE') --- local core_dir = home .. '/.platformio' --- --- -- 3. Parse Nested Array Structure --- -- Structure: { { "section_name", { {"key", "val"}, ... } }, ... } --- --- -- First Pass: Determine Active Env if not set --- if not active_env then --- for _, section in ipairs(config) do --- if section[1] == 'platformio' then --- for _, kv in ipairs(section[2]) do --- if kv[1] == 'default_envs' then --- active_env = tostring(kv[2]):match('([^,%s]+)') --- elseif kv[1] == 'core_dir' then --- core_dir = kv[2] --- end --- end --- end --- end --- end --- print('tollchain 3.0') --- --- -- Second Pass: Find Platform for the Active Env --- for _, section in ipairs(config) do --- local name = section[1] --- if active_env and (name == 'env:' .. active_env or name == active_env) then --- for _, kv in ipairs(section[2]) do --- if kv[1] == 'platform' then --- target_platform = kv[2] --- end --- end --- end --- end --- --- print('tollchain 4.0') --- -- Fallback: If still no env, pick the first one available --- if not target_platform then --- for _, section in ipairs(config) do --- if section[1]:find('^env:') then --- for _, kv in ipairs(section[2]) do --- if kv[1] == 'platform' then --- target_platform = kv[2] --- end --- end --- if target_platform then --- break --- end --- end --- end --- end --- --- if not target_platform then --- return '/**/bin/*gcc*' --- end --- print('tollchain 5.0') --- --- -- 4. Query Platform for Toolchain Package Name --- local p_handle = io.popen('pio platform show ' .. target_platform .. ' --json-output') --- if not p_handle then --- return '/**/bin/*gcc*' --- end --- print('tollchain 6.0') --- local p_json = p_handle:read('*all') --- p_handle:close() --- --- local p_ok, p_data = pcall(vim.json.decode, p_json) --- if not p_ok or not p_data.packages then --- return '/**/bin/*gcc*' --- end --- print('tollchain 7.0') --- --- -- 5. Extract Arch and Build Pattern --- local arch_glob = '/**/bin/*gcc*' --- for pkg_name, _ in pairs(p_data.packages) do --- if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then --- local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') --- arch_glob = '/**/bin/*' .. arch .. '*gcc*' --- break --- end --- end --- --- print('tollchain 8.0') --- -- 6. Final Path Assembly --- local packages_path = normalize(core_dir .. '/packages') --- local final_pattern = normalize(packages_path .. arch_glob) --- --- if vim.fn.has('win32') == 1 then --- final_pattern = final_pattern:gsub('/', '\\') --- end --- --- print('tollchain 9.0: final_pattern=' .. final_pattern) --- _G._pio_cache[cache_key] = final_pattern --- return final_pattern --- end --- ---- + ------------------------------------------------------ -- stylua: ignore function M.fix_pio_compile_commands() From ef8256c340b02c12d30b3f7a72ec5d3ea0be1383 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 13:08:48 +0300 Subject: [PATCH 0530/1406] update --- lua/platformio/utils/pio.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index b1f7140c..caca9806 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -136,7 +136,7 @@ function _G.get_pio_toolchain_pattern() local active_env = vim.g.pio_active_env local target_platform = nil local core_dir = (os.getenv('HOME') or os.getenv('USERPROFILE')) .. '/.platformio' - if active_env then print('active_env0: ' .. active_env) end +if active_env then print('active_env0: ' .. active_env) end -- 1. Pass One: Extract default_envs and core_dir from 'platformio' section if not active_env then for _, section in ipairs(config) do @@ -153,7 +153,7 @@ function _G.get_pio_toolchain_pattern() end end - if active_env then print('active_env1: ' .. active_env) end +if active_env then print(vim.inspect(active_env)) end -- 2. Pass Two: Find the platform for the active environment for _, section in ipairs(config) do local name = section[1] @@ -179,7 +179,7 @@ function _G.get_pio_toolchain_pattern() end if not target_platform then return '/toolchain-*/**/bin/*' end - if active_env then print('target_platform4: ' .. target_platform) end +if active_env then print('target_platform4: ' .. target_platform) end -- 4. Query the platform for the toolchain package name local p_handle = io.popen('pio platform show ' .. target_platform .. ' --json-output') From a1c56108b74d914774e46c5c2ca5e4e006a9319b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 18:51:54 +0300 Subject: [PATCH 0531/1406] update --- lua/platformio/boilerplate.lua | 126 +++++++++++++++++---------------- 1 file changed, 64 insertions(+), 62 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 4e3de869..6b1e0a61 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -74,6 +74,7 @@ clangd --completion-parse=always --completion-style=detailed --header-insertion=iwyu +--fallback-style=llvm, --header-insertion-decorators -j=12 --log=verbose @@ -88,6 +89,7 @@ clangd -- return string.format(self.template, pio.get_pio_dir('packages') or '**') return string.format(self.template, _G.get_pio_toolchain_pattern() or '**') end, + --header-insertion=iwyu --query-driver=%s/toolchain-*/**/bin/* --query-driver=%s/.platformio/packages/*/bin/riscv32-esp-elf-* --query-driver=%s/.platformio/**/packages/toolchain-*/**/bin/* @@ -96,6 +98,68 @@ clangd --query-driver=**/.platformio/packages/toolchain*/**/bin/*gcc* } +boilerplate['.clangd'] = { + content = [[ +CompileFlags: + Add: [ + --target=riscv32-esp-elf, + ] + Remove: [ + -fno-fat-lto-objects + -fno%-fat%-lto%-objects, + -fno%-canonical%-system%-headers, + -misc-definitions-in-headers, + -fno-tree-switch-conversion, + -mtext-section-literals, + -mlong-calls, + -mlongcalls, + -fstrict-volatile-bitfields, + -free*, + -fipa-pta*, + -march=*, + -mabi=*, + -mcpu=*, + ] +Diagnostics: + Suppress: [ + "misc-definitions-in-headers", + "pp_including_mainfile_in_preamble", + "misc-unused-using-decls", + "unused-includes", + ] + ClangTidy: + Remove: [ + readability-*, + cert-err58-cpp, + llvmlibc-*, + fuchsia-*, + hicpp-avoid-c-arrays, + cppcoreguidelines-*, + llvm-*, + google-*, + bugprone-*, + hicpp-vararg, + modernize-*, + ] +]], +} +boilerplate['.stylua.toml'] = { + content = [[ +syntax = "All" +column_width = 132 +line_endings = "Unix" +indent_type = "Spaces" +indent_width = 2 +quote_style = "AutoPreferSingle" +call_parentheses = "Always" +collapse_simple_statement = "Never" +space_after_function_names = "Never" + +[sort_requires] +enabled = false +]], +} + boilerplate['.clang-format'] = { content = [[ --- @@ -346,68 +410,6 @@ WhitespaceSensitiveMacros: ]], } -boilerplate['.clangd'] = { - content = [[ -CompileFlags: - Add: [ - --target=riscv32-esp-elf, - ] - Remove: [ - -fno-fat-lto-objects - -fno%-fat%-lto%-objects, - -fno%-canonical%-system%-headers, - -misc-definitions-in-headers, - -fno-tree-switch-conversion, - -mtext-section-literals, - -mlong-calls, - -mlongcalls, - -fstrict-volatile-bitfields, - -free*, - -fipa-pta*, - -march=*, - -mabi=*, - -mcpu=*, - ] -Diagnostics: - Suppress: [ - "misc-definitions-in-headers", - "pp_including_mainfile_in_preamble", - "misc-unused-using-decls", - "unused-includes", - ] - ClangTidy: - Remove: [ - readability-*, - cert-err58-cpp, - llvmlibc-*, - fuchsia-*, - hicpp-avoid-c-arrays, - cppcoreguidelines-*, - llvm-*, - google-*, - bugprone-*, - hicpp-vararg, - modernize-*, - ] -]], -} -boilerplate['.stylua.toml'] = { - content = [[ -syntax = "All" -column_width = 132 -line_endings = "Unix" -indent_type = "Spaces" -indent_width = 2 -quote_style = "AutoPreferSingle" -call_parentheses = "Always" -collapse_simple_statement = "Never" -space_after_function_names = "Never" - -[sort_requires] -enabled = false -]], -} - function M.boilerplate_gen(framework, src_path, filename) filename = filename or framework local entry = boilerplate[framework] From 8f7167a1efd6a669133bdcc42c7c031862e6c223 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 19:09:39 +0300 Subject: [PATCH 0532/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 6b1e0a61..c731093b 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -74,7 +74,7 @@ clangd --completion-parse=always --completion-style=detailed --header-insertion=iwyu ---fallback-style=llvm, +--fallback-style=llvm --header-insertion-decorators -j=12 --log=verbose From aca8792846cb895683d35f85cbe3bdb8f64d6c46 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 19:12:22 +0300 Subject: [PATCH 0533/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index c731093b..dfde718e 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -73,7 +73,7 @@ clangd --enable-config --completion-parse=always --completion-style=detailed ---header-insertion=iwyu +--header-insertion=never --fallback-style=llvm --header-insertion-decorators -j=12 From 829ec5919bb127bf11ed9ece7ecc113347d67a63 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 19:20:48 +0300 Subject: [PATCH 0534/1406] update --- lua/platformio/boilerplate.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index dfde718e..c9bb7e86 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -74,8 +74,8 @@ clangd --completion-parse=always --completion-style=detailed --header-insertion=never +--header-insertion-decorators=false --fallback-style=llvm ---header-insertion-decorators -j=12 --log=verbose --offset-encoding=utf-8 @@ -90,6 +90,7 @@ clangd return string.format(self.template, _G.get_pio_toolchain_pattern() or '**') end, --header-insertion=iwyu + --header-insertion-decorators --query-driver=%s/toolchain-*/**/bin/* --query-driver=%s/.platformio/packages/*/bin/riscv32-esp-elf-* --query-driver=%s/.platformio/**/packages/toolchain-*/**/bin/* From a34dca9e85a6bdd12c3fac8eb03405b5644325a1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 11 Apr 2026 19:27:56 +0300 Subject: [PATCH 0535/1406] update --- lua/platformio/boilerplate.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index c9bb7e86..f5b213ae 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -73,8 +73,8 @@ clangd --enable-config --completion-parse=always --completion-style=detailed ---header-insertion=never ---header-insertion-decorators=false +--header-insertion=iwyu +--detect-completion-context --fallback-style=llvm -j=12 --log=verbose From b391ace1f114ff0ecd28fba903b2d40d1cb4da59 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 06:52:49 +0300 Subject: [PATCH 0536/1406] update --- lua/platformio/utils/pio.lua | 180 ++++++++++++------------ lua/platformio/utils/pio_setup.lua | 208 +++++++++++++++++++++++++++ lua/platformio/utils/piodb.lua | 217 +++++++++++++++++++++++++++++ mini_nvimPlatformio.lua | 3 + 4 files changed, 518 insertions(+), 90 deletions(-) create mode 100644 lua/platformio/utils/pio_setup.lua create mode 100644 lua/platformio/utils/piodb.lua diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index caca9806..f604409a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -118,96 +118,96 @@ end ------------------------------------------------------ -- stylua: ignore -function _G.get_pio_toolchain_pattern() - local cwd = vim.fn.getcwd() - local cache_key = cwd .. (vim.g.pio_active_env or 'auto') - - _G._pio_cache = _G._pio_cache or {} - if _G._pio_cache[cache_key] then return _G._pio_cache[cache_key] end - - local handle = io.popen('pio project config --json-output') - if not handle then return '/toolchain-*/**/bin/*' end - local json_str = handle:read('*all') - handle:close() - - local ok, config = pcall(vim.json.decode, json_str) - if not ok or not config then return '/toolchain-*/**/bin/*' end - - local active_env = vim.g.pio_active_env - local target_platform = nil - local core_dir = (os.getenv('HOME') or os.getenv('USERPROFILE')) .. '/.platformio' -if active_env then print('active_env0: ' .. active_env) end - -- 1. Pass One: Extract default_envs and core_dir from 'platformio' section - if not active_env then - for _, section in ipairs(config) do - if section[1] == 'platformio' then - for _, kv in ipairs(section[2]) do - if kv[1] == 'default_envs' then - active_env = tostring(kv[2]):match('([^,%s]+)') - end - if kv[1] == 'core_dir' then - core_dir = kv[2] - end - end - end - end - end - -if active_env then print(vim.inspect(active_env)) end - -- 2. Pass Two: Find the platform for the active environment - for _, section in ipairs(config) do - local name = section[1] - if active_env and (name == 'env:' .. active_env or name == active_env) then - for _, kv in ipairs(section[2]) do - if kv[1] == 'platform' then target_platform = kv[2] end - end - end - end - - -- 3. Fallback: If still nothing, take the first platform from any 'env:' section - if not target_platform then - for _, section in ipairs(config) do - if type(section[1]) == 'string' and section[1]:find('^env:') then - for _, kv in ipairs(section[2]) do - if kv[1] == 'platform' then target_platform = kv[2] end - end - if target_platform then - break - end - end - end - end - - if not target_platform then return '/toolchain-*/**/bin/*' end -if active_env then print('target_platform4: ' .. target_platform) end - - -- 4. Query the platform for the toolchain package name - local p_handle = io.popen('pio platform show ' .. target_platform .. ' --json-output') - if not p_handle then return '/toolchain-*/**/bin/*' end - local p_json = p_handle:read('*all') - p_handle:close() - - local p_ok, p_data = pcall(vim.json.decode, p_json) - if not p_ok or not p_data.packages then return '/toolchain-*/**/bin/*' end - - -- 5. Extract Arch - local arch_glob = '/toolchain-*/**/bin/*' - for pkg_name, _ in pairs(p_data.packages) do - if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then - local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') - arch_glob = '/**/bin/*' .. arch .. '*' - break - end - end - - local final_pattern = (core_dir:gsub('\\', '/') .. '/packages' .. arch_glob):gsub('//+', '/') - -- if vim.fn.has('win32') == 1 then - -- final_pattern = final_pattern:gsub('/', '\\') - -- end - - _G._pio_cache[cache_key] = final_pattern - return final_pattern -end +-- function _G.get_pio_toolchain_pattern() +-- local cwd = vim.fn.getcwd() +-- local cache_key = cwd .. (vim.g.pio_active_env or 'auto') +-- +-- _G._pio_cache = _G._pio_cache or {} +-- if _G._pio_cache[cache_key] then return _G._pio_cache[cache_key] end +-- +-- local handle = io.popen('pio project config --json-output') +-- if not handle then return '/toolchain-*/**/bin/*' end +-- local json_str = handle:read('*all') +-- handle:close() +-- +-- local ok, config = pcall(vim.json.decode, json_str) +-- if not ok or not config then return '/toolchain-*/**/bin/*' end +-- +-- local active_env = vim.g.pio_active_env +-- local target_platform = nil +-- local core_dir = (os.getenv('HOME') or os.getenv('USERPROFILE')) .. '/.platformio' +-- if active_env then print('active_env0: ' .. active_env) end +-- -- 1. Pass One: Extract default_envs and core_dir from 'platformio' section +-- if not active_env then +-- for _, section in ipairs(config) do +-- if section[1] == 'platformio' then +-- for _, kv in ipairs(section[2]) do +-- if kv[1] == 'default_envs' then +-- active_env = tostring(kv[2]):match('([^,%s]+)') +-- end +-- if kv[1] == 'core_dir' then +-- core_dir = kv[2] +-- end +-- end +-- end +-- end +-- end +-- +-- if active_env then print(vim.inspect(active_env)) end +-- -- 2. Pass Two: Find the platform for the active environment +-- for _, section in ipairs(config) do +-- local name = section[1] +-- if active_env and (name == 'env:' .. active_env or name == active_env) then +-- for _, kv in ipairs(section[2]) do +-- if kv[1] == 'platform' then target_platform = kv[2] end +-- end +-- end +-- end +-- +-- -- 3. Fallback: If still nothing, take the first platform from any 'env:' section +-- if not target_platform then +-- for _, section in ipairs(config) do +-- if type(section[1]) == 'string' and section[1]:find('^env:') then +-- for _, kv in ipairs(section[2]) do +-- if kv[1] == 'platform' then target_platform = kv[2] end +-- end +-- if target_platform then +-- break +-- end +-- end +-- end +-- end +-- +-- if not target_platform then return '/toolchain-*/**/bin/*' end +-- if active_env then print('target_platform4: ' .. target_platform) end +-- +-- -- 4. Query the platform for the toolchain package name +-- local p_handle = io.popen('pio platform show ' .. target_platform .. ' --json-output') +-- if not p_handle then return '/toolchain-*/**/bin/*' end +-- local p_json = p_handle:read('*all') +-- p_handle:close() +-- +-- local p_ok, p_data = pcall(vim.json.decode, p_json) +-- if not p_ok or not p_data.packages then return '/toolchain-*/**/bin/*' end +-- +-- -- 5. Extract Arch +-- local arch_glob = '/toolchain-*/**/bin/*' +-- for pkg_name, _ in pairs(p_data.packages) do +-- if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then +-- local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') +-- arch_glob = '/**/bin/*' .. arch .. '*' +-- break +-- end +-- end +-- +-- local final_pattern = (core_dir:gsub('\\', '/') .. '/packages' .. arch_glob):gsub('//+', '/') +-- -- if vim.fn.has('win32') == 1 then +-- -- final_pattern = final_pattern:gsub('/', '\\') +-- -- end +-- +-- _G._pio_cache[cache_key] = final_pattern +-- return final_pattern +-- end ------------------------------------------------------ -- stylua: ignore diff --git a/lua/platformio/utils/pio_setup.lua b/lua/platformio/utils/pio_setup.lua new file mode 100644 index 00000000..31fe9de8 --- /dev/null +++ b/lua/platformio/utils/pio_setup.lua @@ -0,0 +1,208 @@ +local misc = require('platformio.utils.misc') +--1. The Core PIO Manager & Generic Extractor +--This manages the data cache and navigates your specific nested-list JSON structure. +--- stylua: ignore +local pio_manager = (function() + local cache = nil + + -- Generic extractor for nested structure: { { "name", { {"k","v"}, ... } }, ... } + local function find_in_data(data, section_name, key_name) + if not data or type(data) ~= 'table' then + return nil + end + for _, section in ipairs(data) do + if type(section) == 'table' and #section >= 2 then + local section_id = section[1] + local section_body = section[2] + + -- Match specific section or fallback to first "env:" found + local match_section = (not section_name and type(section_id) == 'string' and section_id:find('^env:')) or (section_id == section_name) + if match_section and type(section_body) == 'table' then + for _, kv in ipairs(section_body) do + if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then + return kv[2] + end + end + end + end + end + return nil + end + + local function refresh(callback) + -- Using vim.system to detect if the command exists + vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) + if obj.code == 0 then + local ok, decoded = pcall(vim.json.decode, obj.stdout) + if ok and decoded then + cache = decoded + if callback then + vim.schedule(callback) + end + end + else + -- Schedule notification to avoid error in the system callback thread + vim.schedule(function() + if obj.code == 127 then + vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + else + vim.notify('PIO Manager: Failed to fetch config (Error ' .. obj.code .. ')', vim.log.levels.WARN) + end + end) + end + end) + end + return { + refresh = refresh, + get = function(s, k) + return find_in_data(cache, s, k) + end, + } +end)() + +--2. Generic Toolchain & Sysroot Logic. These functions identify where the compiler and its C++ headers live. +-- Gets the compiler glob for clangd --query-driver +function _G.get_pio_toolchain_pattern() + local active_env = vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') + + -- Handle default_envs being a list/table + if type(active_env) == 'table' then + active_env = active_env[1] + end + local target_env = active_env and ('env:' .. active_env) or nil + local platform = pio_manager.get(target_env, 'platform') + local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('HOME') or os.getenv('USERPROFILE') .. '/.platformio/packages') + if not platform then + return '/**/bin/*' + end + + -- Sync call for toolchain name + local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') + if not p_handle then + return '/**/bin/*' + end + + local p_json = p_handle:read('*all') + p_handle:close() + local arch_glob = '/**/bin/*' + local p_ok, p_data = pcall(vim.json.decode, p_json) + if p_ok and p_data and type(p_data.packages) == 'table' then + for pkg_name, _ in pairs(p_data.packages) do + if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then + local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') + arch_glob = '/**/bin/*' .. arch .. '*' + break + end + end + end + -- local final = (packages_dir:gsub('\\', '/') .. arch_glob):gsub('//+', '/') + local final = packages_dir .. arch_glob + return (misc.normalize_path(final)) + -- return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final +end + +--3. Patches compile_commands.json with --sysroot to fix +-- Helper to generate the compilation database +local function pio_generate_db() + -- This runs in the background so it doesn't freeze Neovim + vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) + if obj.code ~= 0 then + return + end + local pattern = _G.get_pio_toolchain_pattern() + local toolchain_root = pattern:match('(.*toolchain%-[^/\\]+)') + if not toolchain_root or vim.fn.isdirectory(toolchain_root) == 0 then + return + end + + -- Find subdirectory containing 'include' (the sysroot) + local sysroot_path = nil + local subdirs = vim.fn.getcompletion(toolchain_root .. '/*', 'dir') + for _, dir in ipairs(subdirs) do + if vim.fn.isdirectory(dir .. '/include') == 1 then + sysroot_path = dir:gsub('\\', '/') + break + end + end + if sysroot_path then + local db_path = vim.fn.getcwd() .. '/compile_commands.json' + local f = io.open(db_path, 'r') + if not f then + return + end + local content = f:read('*all') + f:close() + + -- patch sysroot + local patched = content:gsub('("-i")', '"--sysroot=' .. sysroot_path .. '", %1') + local out = io.open(db_path, 'w') + if out then + out:write(patched) + out:close() + vim.schedule(function() + vim.notify('PIO: DB & Sysroot Patched') + end) + end + end + end) +end + +--4. Automation & File Watcher +--This handles the background synchronization when you save your project. +local function start_pio_watcher() + local path = vim.fn.getcwd() .. '/platformio.ini' + if vim.fn.filereadable(path) == 0 then + return + end + local w = vim.uv.new_fs_event() + if not w then + return + end + w:start( + path, + {}, + vim.schedule_wrap(function(err, _, events) + if err then + vim.notify('PIO Auto-Sync error', vim.log.levels.ERROR) + w:stop() + return + end + if events.change then + pio_manager.refresh(function() + pio_generate_db() + vim.cmd('LspRestart clangd') + vim.notify('PIO Auto-Sync Complete', vim.log.levels.INFO) + end) + end + end) + ) +end + +-- Exported setup function +return { + init = function() + if vim.fn.filereadable(vim.fn.getcwd() .. '/platformio.ini') == 1 then + pio_manager.refresh(function() + pio_generate_db() + start_pio_watcher() + end) + end + end, +} + +-- -- init.lua +-- +-- -- 1. Load the PIO logic +-- local pio = require("pio_setup") +-- pio.init() +-- +-- -- 2. Your LSP Setup +-- require('lspconfig').clangd.setup({ +-- cmd = { +-- "clangd", +-- "--background-index", +-- -- It calls the global function defined in pio_setup.lua +-- "--query-driver=" .. _G.get_pio_toolchain_pattern(), +-- "--header-insertion=never" +-- }, +-- }) diff --git a/lua/platformio/utils/piodb.lua b/lua/platformio/utils/piodb.lua new file mode 100644 index 00000000..df70ac16 --- /dev/null +++ b/lua/platformio/utils/piodb.lua @@ -0,0 +1,217 @@ +-- -- 1. The Robust Async PIO Manager & Extractor +-- -- Handles the async lifecycle and data extraction for nested list-of-lists +-- local pio_manager = (function() +-- local cache = nil +-- +-- -- Generic extractor for nested structure: { { "name", { {"k","v"}, ... } }, ... } +-- local function find_in_data(data, section_name, key_name) +-- if type(data) ~= 'table' then +-- return nil +-- end +-- for _, section in ipairs(data) do +-- -- Safety check: section must be a table with at least 2 elements +-- if type(section) == 'table' and #section >= 2 then +-- local section_id = section[1] +-- local section_body = section[2] +-- +-- -- Match specific section or fallback to first "env:" found +-- local match_section = (not section_name and type(section_id) == 'string' and section_id:find('^env:')) or (section_id == section_name) +-- +-- if match_section and type(section_body) == 'table' then +-- for _, kv in ipairs(section_body) do +-- -- Safety check: kv must be a table {"key", "value"} +-- if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then +-- return kv[2] +-- end +-- end +-- end +-- end +-- end +-- return nil +-- end +-- +-- local function refresh(callback) +-- -- Using vim.system (Nvim 0.10+) for non-blocking CLI calls +-- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) +-- if obj.code ~= 0 then +-- vim.schedule(function() +-- if obj.code == 127 then +-- vim.notify("PIO: 'pio' command not found in PATH", vim.log.levels.ERROR) +-- else +-- vim.notify('PIO: Config fetch failed (Code ' .. obj.code .. ')', vim.log.levels.WARN) +-- end +-- end) +-- return +-- end +-- +-- -- Safe JSON decoding +-- local ok, decoded = pcall(vim.json.decode, obj.stdout) +-- if ok and decoded then +-- cache = decoded +-- if callback then +-- vim.schedule(callback) +-- end +-- else +-- vim.schedule(function() +-- vim.notify('PIO: Failed to decode JSON output', vim.log.levels.ERROR) +-- end) +-- end +-- end) +-- end +-- +-- return { +-- refresh = refresh, +-- get = function(s, k) +-- return find_in_data(cache, s, k) +-- end, +-- } +-- end)() +-- +-- -- 2. Generic Toolchain & Sysroot Logic +-- -- Resolves the compiler path and patches compile_commands.json for +-- function _G.get_pio_toolchain_pattern() +-- local active_env = vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') +-- -- Handle default_envs being a list/table: take first string element +-- if type(active_env) == 'table' then +-- active_env = active_env[1] +-- end +-- +-- local target_env = active_env and ('env:' .. active_env) or nil +-- local platform = pio_manager.get(target_env, 'platform') +-- local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('HOME') or os.getenv('USERPROFILE') .. '/.platformio/packages') +-- +-- if not platform then +-- return '/**/bin/*gcc*' +-- end +-- +-- -- Sync call for platform info (acceptable as it's targeted and small) +-- local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') +-- if not p_handle then +-- return '/**/bin/*gcc*' +-- end +-- local p_json = p_handle:read('*all') +-- p_handle:close() +-- +-- local p_ok, p_data = pcall(vim.json.decode, p_json) +-- local arch_glob = '/**/bin/*gcc*' +-- +-- if p_ok and p_data and type(p_data.packages) == 'table' then +-- for pkg_name, _ in pairs(p_data.packages) do +-- if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then +-- local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') +-- arch_glob = '/**/bin/*' .. arch .. '*gcc*' +-- break +-- end +-- end +-- end +-- +-- local final = (packages_dir:gsub('\\', '/') .. arch_glob):gsub('//+', '/') +-- return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final +-- end +-- +-- -- Patches compile_commands.json with --sysroot to fix +-- local function pio_generate_db() +-- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) +-- if obj.code ~= 0 then +-- return +-- end +-- +-- local pattern = _G.get_pio_toolchain_pattern() +-- local toolchain_root = pattern:match('(.*toolchain%-[^/\\]+)') +-- if not toolchain_root or vim.fn.isdirectory(toolchain_root) == 0 then +-- return +-- end +-- +-- -- Generic sysroot finder: search for subdir with an 'include' folder +-- local sysroot_path = nil +-- local subdirs = vim.fn.getcompletion(toolchain_root .. '/*', 'dir') +-- for _, dir in ipairs(subdirs) do +-- if vim.fn.isdirectory(dir .. '/include') == 1 then +-- sysroot_path = dir:gsub('\\', '/') +-- break +-- end +-- end +-- +-- if sysroot_path then +-- local db_path = vim.fn.getcwd() .. '/compile_commands.json' +-- local f = io.open(db_path, 'r') +-- if not f then +-- return +-- end +-- local content = f:read('*all') +-- f:close() +-- +-- -- Insert sysroot at start of flag list to resolve Standard C++ headers +-- local patched = content:gsub('("-i")', '"--sysroot=' .. sysroot_path .. '", %1') +-- local out = io.open(db_path, 'w') +-- if out then +-- out:write(patched) +-- out:close() +-- vim.schedule(function() +-- vim.notify('PIO: DB & Sysroot Patched') +-- end) +-- end +-- end +-- end) +-- end +-- +-- -- 3. Automatic File Watcher +-- -- Detects changes to platformio.ini and restarts LSP automatically +-- local function start_pio_watcher() +-- local path = vim.fn.getcwd() .. '/platformio.ini' +-- if vim.fn.filereadable(path) == 0 then +-- return +-- end +-- +-- local w = vim.uv.new_fs_event() +-- if not w then +-- return +-- end +-- +-- w:start( +-- path, +-- {}, +-- vim.schedule_wrap(function(err, filename, events) +-- if err then +-- w:stop() +-- return +-- end +-- if events.change then +-- pio_manager.refresh(function() +-- pio_generate_db() +-- vim.cmd('LspRestart clangd') +-- end) +-- end +-- end) +-- ) +-- end +-- +-- -- 4. Safe Initialization +-- -- Only runs if a platformio.ini exists in the current directory +-- if vim.fn.filereadable(vim.fn.getcwd() .. '/platformio.ini') == 1 then +-- pio_manager.refresh(function() +-- pio_generate_db() +-- start_pio_watcher() +-- end) +-- end +-- +-- -- -- 1. Plugin Manager (Lazy.nvim) +-- -- require("lazy").setup("plugins") +-- -- +-- -- -- 2. THE PIO SETUP CODE (Paste everything here) +-- -- local pio_manager = (function() ... end)() +-- -- function _G.get_pio_toolchain_pattern() ... end +-- -- local function pio_generate_db() ... end +-- -- -- ... etc ... +-- -- +-- -- 3. LSP Configuration +-- -- local lspconfig = require('lspconfig') +-- -- +-- -- lspconfig.clangd.setup({ +-- -- cmd = { +-- -- "clangd", +-- -- "--background-index", +-- -- "--query-driver=" .. _G.get_pio_toolchain_pattern(), -- Uses the function above +-- -- "--header-insertion=never" +-- -- }, +-- -- }) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index ab08d93f..a1d14adf 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -377,6 +377,9 @@ if not vim.uv.fs_stat(pynvim_env) then -- vim.fn.system({ 'pip', 'install', '-U', 'platformio' }) end +-- Load the PIO logic +local pio = require('pio_setup') +pio.init() ---------------------------------------------------------------------------------------- -- INFO: configure nvim-platformio and load ----------------------------------------------------------------------------------------- From 8763a7854420790b3d69a92f7e8ca864d9fcbcab Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 06:56:00 +0300 Subject: [PATCH 0537/1406] update --- lua/platformio/{utils => }/pio_setup.lua | 0 mini_nvimPlatformio.lua | 6 +++--- 2 files changed, 3 insertions(+), 3 deletions(-) rename lua/platformio/{utils => }/pio_setup.lua (100%) diff --git a/lua/platformio/utils/pio_setup.lua b/lua/platformio/pio_setup.lua similarity index 100% rename from lua/platformio/utils/pio_setup.lua rename to lua/platformio/pio_setup.lua diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index a1d14adf..d530d419 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -377,9 +377,6 @@ if not vim.uv.fs_stat(pynvim_env) then -- vim.fn.system({ 'pip', 'install', '-U', 'platformio' }) end --- Load the PIO logic -local pio = require('pio_setup') -pio.init() ---------------------------------------------------------------------------------------- -- INFO: configure nvim-platformio and load ----------------------------------------------------------------------------------------- @@ -400,3 +397,6 @@ if pok then -- print("here" .. vim.inspect(pioConfig)) platformio.setup(pioConfig) end +-- Load the PIO logic +local pio = require('platformio.pio_setup') +pio.init() From cb5a3d599b8d8c5e8fff3a00413e41fd71bab9b7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 07:01:31 +0300 Subject: [PATCH 0538/1406] update --- mini_nvimPlatformio.lua | 3 --- plugin/platformio.lua | 4 ++++ 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index d530d419..ab08d93f 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -397,6 +397,3 @@ if pok then -- print("here" .. vim.inspect(pioConfig)) platformio.setup(pioConfig) end --- Load the PIO logic -local pio = require('platformio.pio_setup') -pio.init() diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 8b8774a5..9294e53b 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -6,6 +6,10 @@ -- +: At least one argument. -- -1: Zero or one argument (like ?, explicitly). +-- Load the PIO logic +local pio_setup = require('platformio.pio_setup') +pio_setup.init() + local misc = require('platformio.utils.misc') local pio = require('platformio.utils.pio') local piolsserial = require('platformio.piolsserial') From fcdb97acd5ba990374e9873c906f573cdeeaa629 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 07:10:46 +0300 Subject: [PATCH 0539/1406] update --- lua/platformio/pio_setup.lua | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 31fe9de8..f6afe688 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -63,12 +63,15 @@ end)() --2. Generic Toolchain & Sysroot Logic. These functions identify where the compiler and its C++ headers live. -- Gets the compiler glob for clangd --query-driver function _G.get_pio_toolchain_pattern() + print('toolchain 0:') local active_env = vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') + print('toolchain 1:') -- Handle default_envs being a list/table if type(active_env) == 'table' then active_env = active_env[1] end + print('toolchain 2:') local target_env = active_env and ('env:' .. active_env) or nil local platform = pio_manager.get(target_env, 'platform') local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('HOME') or os.getenv('USERPROFILE') .. '/.platformio/packages') @@ -76,12 +79,14 @@ function _G.get_pio_toolchain_pattern() return '/**/bin/*' end + print('toolchain 3:') -- Sync call for toolchain name local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') if not p_handle then return '/**/bin/*' end + print('toolchain 4:') local p_json = p_handle:read('*all') p_handle:close() local arch_glob = '/**/bin/*' @@ -95,6 +100,7 @@ function _G.get_pio_toolchain_pattern() end end end + print('toolchain 5:') -- local final = (packages_dir:gsub('\\', '/') .. arch_glob):gsub('//+', '/') local final = packages_dir .. arch_glob return (misc.normalize_path(final)) From 125d3085519d5acafb462a4e2f2b12a8d0fce511 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 07:19:00 +0300 Subject: [PATCH 0540/1406] update --- lua/platformio/pio_setup.lua | 57 ++++++++++++------------------------ 1 file changed, 19 insertions(+), 38 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index f6afe688..52bb1e8a 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,15 +1,14 @@ local misc = require('platformio.utils.misc') +local lsp = require('platformio.utils.lsp') --1. The Core PIO Manager & Generic Extractor --This manages the data cache and navigates your specific nested-list JSON structure. ---- stylua: ignore +-- stylua: ignore local pio_manager = (function() local cache = nil -- Generic extractor for nested structure: { { "name", { {"k","v"}, ... } }, ... } local function find_in_data(data, section_name, key_name) - if not data or type(data) ~= 'table' then - return nil - end + if not data or type(data) ~= 'table' then return nil end for _, section in ipairs(data) do if type(section) == 'table' and #section >= 2 then local section_id = section[1] @@ -19,9 +18,7 @@ local pio_manager = (function() local match_section = (not section_name and type(section_id) == 'string' and section_id:find('^env:')) or (section_id == section_name) if match_section and type(section_body) == 'table' then for _, kv in ipairs(section_body) do - if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then - return kv[2] - end + if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then return kv[2] end end end end @@ -36,9 +33,7 @@ local pio_manager = (function() local ok, decoded = pcall(vim.json.decode, obj.stdout) if ok and decoded then cache = decoded - if callback then - vim.schedule(callback) - end + if callback then vim.schedule(callback) end end else -- Schedule notification to avoid error in the system callback thread @@ -54,37 +49,30 @@ local pio_manager = (function() end return { refresh = refresh, - get = function(s, k) - return find_in_data(cache, s, k) - end, + get = function(s, k) return find_in_data(cache, s, k) end, } end)() --2. Generic Toolchain & Sysroot Logic. These functions identify where the compiler and its C++ headers live. -- Gets the compiler glob for clangd --query-driver +-- stylua: ignore function _G.get_pio_toolchain_pattern() print('toolchain 0:') local active_env = vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') print('toolchain 1:') -- Handle default_envs being a list/table - if type(active_env) == 'table' then - active_env = active_env[1] - end + if type(active_env) == 'table' then active_env = active_env[1] end print('toolchain 2:') local target_env = active_env and ('env:' .. active_env) or nil local platform = pio_manager.get(target_env, 'platform') local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('HOME') or os.getenv('USERPROFILE') .. '/.platformio/packages') - if not platform then - return '/**/bin/*' - end + if not platform then return '/**/bin/*' end print('toolchain 3:') -- Sync call for toolchain name local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') - if not p_handle then - return '/**/bin/*' - end + if not p_handle then return '/**/bin/*' end print('toolchain 4:') local p_json = p_handle:read('*all') @@ -109,12 +97,11 @@ end --3. Patches compile_commands.json with --sysroot to fix -- Helper to generate the compilation database +-- stylua: ignore local function pio_generate_db() -- This runs in the background so it doesn't freeze Neovim vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) - if obj.code ~= 0 then - return - end + if obj.code ~= 0 then return end local pattern = _G.get_pio_toolchain_pattern() local toolchain_root = pattern:match('(.*toolchain%-[^/\\]+)') if not toolchain_root or vim.fn.isdirectory(toolchain_root) == 0 then @@ -133,9 +120,7 @@ local function pio_generate_db() if sysroot_path then local db_path = vim.fn.getcwd() .. '/compile_commands.json' local f = io.open(db_path, 'r') - if not f then - return - end + if not f then return end local content = f:read('*all') f:close() @@ -145,9 +130,7 @@ local function pio_generate_db() if out then out:write(patched) out:close() - vim.schedule(function() - vim.notify('PIO: DB & Sysroot Patched') - end) + vim.schedule(function() vim.notify('PIO: DB & Sysroot Patched') end) end end end) @@ -155,15 +138,12 @@ end --4. Automation & File Watcher --This handles the background synchronization when you save your project. +-- stylua: ignore local function start_pio_watcher() local path = vim.fn.getcwd() .. '/platformio.ini' - if vim.fn.filereadable(path) == 0 then - return - end + if vim.fn.filereadable(path) == 0 then return end local w = vim.uv.new_fs_event() - if not w then - return - end + if not w then return end w:start( path, {}, @@ -176,7 +156,8 @@ local function start_pio_watcher() if events.change then pio_manager.refresh(function() pio_generate_db() - vim.cmd('LspRestart clangd') + lsp.lsp_restart('clangd') + -- vim.cmd('LspRestart clangd') vim.notify('PIO Auto-Sync Complete', vim.log.levels.INFO) end) end From 18122aa20bc76080d3dcccc806a3c2db5045270c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 07:36:13 +0300 Subject: [PATCH 0541/1406] update --- lua/platformio/pio_setup.lua | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 52bb1e8a..7d6524f1 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,6 +1,6 @@ local misc = require('platformio.utils.misc') local lsp = require('platformio.utils.lsp') ---1. The Core PIO Manager & Generic Extractor +-- INFO: 1. The Core PIO Manager & Generic Extractor --This manages the data cache and navigates your specific nested-list JSON structure. -- stylua: ignore local pio_manager = (function() @@ -53,7 +53,7 @@ local pio_manager = (function() } end)() ---2. Generic Toolchain & Sysroot Logic. These functions identify where the compiler and its C++ headers live. +-- INFO: 2. Generic Toolchain & Sysroot Logic. These functions identify where the compiler and its C++ headers live. -- Gets the compiler glob for clangd --query-driver -- stylua: ignore function _G.get_pio_toolchain_pattern() @@ -63,10 +63,17 @@ function _G.get_pio_toolchain_pattern() print('toolchain 1:') -- Handle default_envs being a list/table if type(active_env) == 'table' then active_env = active_env[1] end - print('toolchain 2:') + if active_env then print('toolchain 2:active_env=' .. active_env) end + local target_env = active_env and ('env:' .. active_env) or nil + if target_env then print('toolchain 2.0:target_env=' .. target_env) end + local platform = pio_manager.get(target_env, 'platform') + if platform then print('toolchain 2.1:platformio=' .. platform) end + local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('HOME') or os.getenv('USERPROFILE') .. '/.platformio/packages') + if packages_dir then print('toolchain 2.2:packages_dir=' .. packages_dir) end + if not platform then return '/**/bin/*' end print('toolchain 3:') @@ -95,7 +102,7 @@ function _G.get_pio_toolchain_pattern() -- return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final end ---3. Patches compile_commands.json with --sysroot to fix +-- INFO: 3. Patches compile_commands.json with --sysroot to fix -- Helper to generate the compilation database -- stylua: ignore local function pio_generate_db() @@ -136,7 +143,7 @@ local function pio_generate_db() end) end ---4. Automation & File Watcher +-- INFO: 4. Automation & File Watcher --This handles the background synchronization when you save your project. -- stylua: ignore local function start_pio_watcher() @@ -165,7 +172,7 @@ local function start_pio_watcher() ) end --- Exported setup function +-- INFO: Exported setup function return { init = function() if vim.fn.filereadable(vim.fn.getcwd() .. '/platformio.ini') == 1 then From 4e97f11213a020f4a337f538093932aca1bcc0c6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 07:46:28 +0300 Subject: [PATCH 0542/1406] update --- lua/platformio/pio_setup.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 7d6524f1..deb13e2b 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -33,6 +33,8 @@ local pio_manager = (function() local ok, decoded = pcall(vim.json.decode, obj.stdout) if ok and decoded then cache = decoded + if type(cache) == 'table' then print(vim.inspect(cache)) end + if callback then vim.schedule(callback) end end else From fb59b26924479cb3d611bef14d955b8011686382 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 07:51:09 +0300 Subject: [PATCH 0543/1406] update --- lua/platformio/pio_setup.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index deb13e2b..157ea8b4 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -33,7 +33,8 @@ local pio_manager = (function() local ok, decoded = pcall(vim.json.decode, obj.stdout) if ok and decoded then cache = decoded - if type(cache) == 'table' then print(vim.inspect(cache)) end + if type(cache) == 'table' then print(vim.inspect(cache)) + else print('no cahce')end if callback then vim.schedule(callback) end end From 44cc073eafe1366c50bdb8cc4198f5272ccbd467 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 07:56:07 +0300 Subject: [PATCH 0544/1406] update --- lua/platformio/pio_setup.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 157ea8b4..a74ea738 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -27,8 +27,10 @@ local pio_manager = (function() end local function refresh(callback) + print('refresh') -- Using vim.system to detect if the command exists vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) + print('obj') if obj.code == 0 then local ok, decoded = pcall(vim.json.decode, obj.stdout) if ok and decoded then From 81383cf8623af6db9a6f72bdf62452a5433fcbe7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 08:00:40 +0300 Subject: [PATCH 0545/1406] update --- lua/platformio/pio_setup.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index a74ea738..dd4c6e7e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -8,6 +8,7 @@ local pio_manager = (function() -- Generic extractor for nested structure: { { "name", { {"k","v"}, ... } }, ... } local function find_in_data(data, section_name, key_name) + print('find data') if not data or type(data) ~= 'table' then return nil end for _, section in ipairs(data) do if type(section) == 'table' and #section >= 2 then From c57d584f425f8f3f9c1b2ce0784b182237fe238e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 08:07:22 +0300 Subject: [PATCH 0546/1406] update --- lua/platformio/pio_setup.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index dd4c6e7e..55add40d 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -181,6 +181,7 @@ end -- INFO: Exported setup function return { init = function() + print('pio_setup initialize') if vim.fn.filereadable(vim.fn.getcwd() .. '/platformio.ini') == 1 then pio_manager.refresh(function() pio_generate_db() From 4bf2bda7dc0f501b17cb24da6c767d815b586b77 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 08:12:32 +0300 Subject: [PATCH 0547/1406] update --- lua/platformio/lspConfig/clangd.lua | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 0b984951..d980f82d 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -296,14 +296,12 @@ local pyrefly = { } vim.lsp.config('pyrefly', pyrefly) --- require('platformio.piolsp').piolsp() -if vim.fn.has('nvim-0.12') then - if #vim.lsp.get_clients() > 0 then - vim.cmd('lsp restart') - end -else - vim.cmd('LspRestart') -end +local lsp = require('platformio.utils.lsp') +lsp.lsp_restart('clangd') + +-- Load the PIO logic +local pio_setup = require('platformio.pio_setup') +pio_setup.init() local config = require('platformio').config if config.lspClangd.attach.enabled then From e9c10dc20d8f2a9f3599b68498afc6816e8f56f6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 08:15:00 +0300 Subject: [PATCH 0548/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 55add40d..c6832c3e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -181,8 +181,8 @@ end -- INFO: Exported setup function return { init = function() - print('pio_setup initialize') if vim.fn.filereadable(vim.fn.getcwd() .. '/platformio.ini') == 1 then + print('pio_setup initialize') pio_manager.refresh(function() pio_generate_db() start_pio_watcher() From 78e108a5a2d759400d1d820d78f858d3938ff59c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 08:31:10 +0300 Subject: [PATCH 0549/1406] update --- lua/platformio/lspConfig/clangd.lua | 7 +++---- lua/platformio/pio_setup.lua | 10 ++++------ 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index d980f82d..a0209404 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -296,12 +296,11 @@ local pyrefly = { } vim.lsp.config('pyrefly', pyrefly) -local lsp = require('platformio.utils.lsp') -lsp.lsp_restart('clangd') +-- restart lsp +require('platformio.utils.lsp').lsp_restart('clangd') -- Load the PIO logic -local pio_setup = require('platformio.pio_setup') -pio_setup.init() +require('platformio.pio_setup').init() local config = require('platformio').config if config.lspClangd.attach.enabled then diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index c6832c3e..9ccddd20 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -8,7 +8,6 @@ local pio_manager = (function() -- Generic extractor for nested structure: { { "name", { {"k","v"}, ... } }, ... } local function find_in_data(data, section_name, key_name) - print('find data') if not data or type(data) ~= 'table' then return nil end for _, section in ipairs(data) do if type(section) == 'table' and #section >= 2 then @@ -31,14 +30,13 @@ local pio_manager = (function() print('refresh') -- Using vim.system to detect if the command exists vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) - print('obj') if obj.code == 0 then local ok, decoded = pcall(vim.json.decode, obj.stdout) if ok and decoded then cache = decoded - if type(cache) == 'table' then print(vim.inspect(cache)) - else print('no cahce')end - + -- if type(cache) == 'table' then print(vim.inspect(cache)) + -- else print('no cahce')end + if not cache or type(cache) ~= 'table' then print('no cahce') end if callback then vim.schedule(callback) end end else @@ -63,7 +61,6 @@ end)() -- Gets the compiler glob for clangd --query-driver -- stylua: ignore function _G.get_pio_toolchain_pattern() - print('toolchain 0:') local active_env = vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') print('toolchain 1:') @@ -112,6 +109,7 @@ end -- Helper to generate the compilation database -- stylua: ignore local function pio_generate_db() + print('pio_generate_db 0') -- This runs in the background so it doesn't freeze Neovim vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) if obj.code ~= 0 then return end From 396febfc3d05e19f1e832dc99fbe243fa4fba6c6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 08:41:39 +0300 Subject: [PATCH 0550/1406] update --- lua/platformio/pio_setup.lua | 9 ++++----- lua/platformio/pioinit.lua | 8 ++++---- lua/platformio/piolib.lua | 8 ++++---- 3 files changed, 12 insertions(+), 13 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 9ccddd20..faf80bb2 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -27,7 +27,6 @@ local pio_manager = (function() end local function refresh(callback) - print('refresh') -- Using vim.system to detect if the command exists vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) if obj.code == 0 then @@ -36,7 +35,8 @@ local pio_manager = (function() cache = decoded -- if type(cache) == 'table' then print(vim.inspect(cache)) -- else print('no cahce')end - if not cache or type(cache) ~= 'table' then print('no cahce') end + if not cache or type(cache) ~= 'table' then print('no cahce') + else print('refreshed') end if callback then vim.schedule(callback) end end else @@ -63,7 +63,6 @@ end)() function _G.get_pio_toolchain_pattern() local active_env = vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') - print('toolchain 1:') -- Handle default_envs being a list/table if type(active_env) == 'table' then active_env = active_env[1] end if active_env then print('toolchain 2:active_env=' .. active_env) end @@ -98,9 +97,9 @@ function _G.get_pio_toolchain_pattern() end end end - print('toolchain 5:') -- local final = (packages_dir:gsub('\\', '/') .. arch_glob):gsub('//+', '/') local final = packages_dir .. arch_glob + print('toolchain 5: final=' .. final) return (misc.normalize_path(final)) -- return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final end @@ -109,10 +108,10 @@ end -- Helper to generate the compilation database -- stylua: ignore local function pio_generate_db() - print('pio_generate_db 0') -- This runs in the background so it doesn't freeze Neovim vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) if obj.code ~= 0 then return end + print('pio_generate_db 0') local pattern = _G.get_pio_toolchain_pattern() local toolchain_root = pattern:match('(.*toolchain%-[^/\\]+)') if not toolchain_root or vim.fn.isdirectory(toolchain_root) == 0 then diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index c1d3d911..bb2ca26a 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -64,10 +64,10 @@ local function pick_framework(board_details) cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', cb = pio.handlePioinit, }, - { - cmd = 'pio run -t compiledb', - cb = pio.handleDb, - }, + -- { + -- cmd = 'pio run -t compiledb', + -- cb = pio.handleDb, + -- }, }) end) return true diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 557e1f0c..71af53d0 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -67,10 +67,10 @@ local function pick_library(json_data) cmd = 'pio pkg install --library "' .. pkg_name .. '"', cb = pio.handlePiolib, }, - { - cmd = 'pio run -t compiledb', - cb = pio.handleDb, - }, + -- { + -- cmd = 'pio run -t compiledb', + -- cb = pio.handleDb, + -- }, }) end) return true From 17bd8d983d66dcb80c9161f5e8e774d7818afab3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 08:43:20 +0300 Subject: [PATCH 0551/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index faf80bb2..035389f5 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -179,7 +179,7 @@ end return { init = function() if vim.fn.filereadable(vim.fn.getcwd() .. '/platformio.ini') == 1 then - print('pio_setup initialize') + vim.notify('PIO setup initialize', vim.log.levels.INFO) pio_manager.refresh(function() pio_generate_db() start_pio_watcher() From 2cda5de69151e190a73a6e029be0e0d6a3e10bd5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 10:09:22 +0300 Subject: [PATCH 0552/1406] update --- lua/platformio/pio_setup.lua | 62 ++++++++++++++++++++++++++++++------ 1 file changed, 52 insertions(+), 10 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 035389f5..ecb8db30 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -9,16 +9,55 @@ local pio_manager = (function() -- Generic extractor for nested structure: { { "name", { {"k","v"}, ... } }, ... } local function find_in_data(data, section_name, key_name) if not data or type(data) ~= 'table' then return nil end + + -- 1. SPECIFIC SEARCH: Look for a specific section (e.g., "platformio") + if section_name then + for _, section in ipairs(data) do + if type(section) == 'table' and #section >= 2 then + local section_id = section[1] + local section_body = section[2] + + -- Match specific section or fallback to first "env:" found + local match_section = (not section_name and type(section_id) == 'string' and section_id:find('^env:')) or (section_id == section_name) + if match_section and type(section_body) == 'table' then + for _, kv in ipairs(section_body) do + if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then return kv[2] end + if type(kv) == "table" and #kv >= 2 and kv[1] == key_name then + local val = kv[2] + -- Nil Check: Only return if the value is not nil or an empty table + if val ~= nil and (type(val) ~= "table" or #val > 0) then + return val + end + end + end + end + end + end + else + end + -- 2. FALLBACK: Search all 'env:' sections if specific search failed or was skipped for _, section in ipairs(data) do - if type(section) == 'table' and #section >= 2 then - local section_id = section[1] - local section_body = section[2] - - -- Match specific section or fallback to first "env:" found - local match_section = (not section_name and type(section_id) == 'string' and section_id:find('^env:')) or (section_id == section_name) - if match_section and type(section_body) == 'table' then - for _, kv in ipairs(section_body) do - if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then return kv[2] end + if type(section) == "table" and #section >= 2 then + local s_id = section[1] + local s_body = section[2] + + -- Match only hardware environments, skipping global [env] + if type(s_id) == "string" and s_id:find("^env:") then + -- Return extracted environment name if looking for default_envs + if key_name == "default_envs" then + return s_id:match("^env:(.+)") + end + + -- Otherwise, look for the requested key inside this first env + if type(s_body) == "table" then + for _, kv in ipairs(s_body) do + if type(kv) == "table" and #kv >= 2 and kv[1] == key_name then + local val = kv[2] + if val ~= nil and (type(val) ~= "table" or #val > 0) then + return val + end + end + end end end end @@ -61,7 +100,10 @@ end)() -- Gets the compiler glob for clangd --query-driver -- stylua: ignore function _G.get_pio_toolchain_pattern() - local active_env = vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') + -- local active_env = vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') + local active_env = vim.g.pio_active_env + or pio_manager.get("platformio", "default_envs") + or pio_manager.get(nil, "default_envs") -- Handle default_envs being a list/table if type(active_env) == 'table' then active_env = active_env[1] end From 6de171ad76dbfe125a8723a66eec59bc53111387 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 10:36:06 +0300 Subject: [PATCH 0553/1406] update --- lua/platformio/pio_setup.lua | 127 ++++++++++++++++++++++++++--------- 1 file changed, 97 insertions(+), 30 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index ecb8db30..d058ba97 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -10,22 +10,16 @@ local pio_manager = (function() local function find_in_data(data, section_name, key_name) if not data or type(data) ~= 'table' then return nil end - -- 1. SPECIFIC SEARCH: Look for a specific section (e.g., "platformio") + -- INFO: 1. SPECIFIC SEARCH if section_name then for _, section in ipairs(data) do if type(section) == 'table' and #section >= 2 then - local section_id = section[1] - local section_body = section[2] - - -- Match specific section or fallback to first "env:" found - local match_section = (not section_name and type(section_id) == 'string' and section_id:find('^env:')) or (section_id == section_name) - if match_section and type(section_body) == 'table' then - for _, kv in ipairs(section_body) do - if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then return kv[2] end - if type(kv) == "table" and #kv >= 2 and kv[1] == key_name then + if section[1] == section_name and type(section[2]) == 'table' then + for _, kv in ipairs(section[2]) do + if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then + -- Check if value is valid (not nil, not empty string, not empty table) local val = kv[2] - -- Nil Check: Only return if the value is not nil or an empty table - if val ~= nil and (type(val) ~= "table" or #val > 0) then + if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then return val end end @@ -33,27 +27,34 @@ local pio_manager = (function() end end end - else end - -- 2. FALLBACK: Search all 'env:' sections if specific search failed or was skipped + + -- INFO: 2. FALLBACK SEARCH (If we reach here, Step 1 failed or was skipped) + local fallback_env_found = nil for _, section in ipairs(data) do - if type(section) == "table" and #section >= 2 then + if type(section) == 'table' and #section >= 2 then local s_id = section[1] - local s_body = section[2] + -- Look for hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] + if type(s_id) == 'string' and s_id:find('^env:') then + fallback_env_found = s_id:match('^env:(.+)') - -- Match only hardware environments, skipping global [env] - if type(s_id) == "string" and s_id:find("^env:") then - -- Return extracted environment name if looking for default_envs - if key_name == "default_envs" then - return s_id:match("^env:(.+)") + -- If we were looking for default_envs, we just found our fallback + if key_name == 'default_envs' then + vim.schedule(function() + vim.notify("PIO: 'default_envs' empty. Falling back to: " .. fallback_env_found, vim.log.levels.WARN) + end) + return fallback_env_found end - -- Otherwise, look for the requested key inside this first env - if type(s_body) == "table" then - for _, kv in ipairs(s_body) do - if type(kv) == "table" and #kv >= 2 and kv[1] == key_name then + -- If looking for a key (like 'platform') inside this fallback env + if type(section[2]) == 'table' then + for _, kv in ipairs(section[2]) do + if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then local val = kv[2] - if val ~= nil and (type(val) ~= "table" or #val > 0) then + if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then + vim.schedule(function() + vim.notify("PIO: Using '" .. key_name .. "' from fallback env: " .. fallback_env_found, vim.log.levels.INFO) + end) return val end end @@ -62,6 +63,65 @@ local pio_manager = (function() end end end + + -- INFO: 3. FINAL ERROR If even fallback fails + if key_name == 'platform' or key_name == 'packages_dir' then + vim.schedule(function() + vim.notify("PIO: Critical key '" .. key_name .. "' not found anywhere!", vim.log.levels.ERROR) + end) + end + -- -- 1. SPECIFIC SEARCH: Look for a specific section (e.g., "platformio") + -- if section_name then + -- for _, section in ipairs(data) do + -- if type(section) == 'table' and #section >= 2 then + -- local section_id = section[1] + -- local section_body = section[2] + -- + -- -- Match specific section or fallback to first "env:" found + -- local match_section = (not section_name and type(section_id) == 'string' and section_id:find('^env:')) or (section_id == section_name) + -- if match_section and type(section_body) == 'table' then + -- for _, kv in ipairs(section_body) do + -- if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then return kv[2] end + -- if type(kv) == "table" and #kv >= 2 and kv[1] == key_name then + -- local val = kv[2] + -- -- Nil Check: Only return if the value is not nil or an empty table + -- if val ~= nil and (type(val) ~= "table" or #val > 0) then + -- return val + -- end + -- end + -- end + -- end + -- end + -- end + -- else + -- end + -- -- 2. FALLBACK: Search all 'env:' sections if specific search failed or was skipped + -- for _, section in ipairs(data) do + -- if type(section) == "table" and #section >= 2 then + -- local s_id = section[1] + -- local s_body = section[2] + -- + -- -- Match only hardware environments, skipping global [env] + -- if type(s_id) == "string" and s_id:find("^env:") then + -- -- Return extracted environment name if looking for default_envs + -- if key_name == "default_envs" then + -- return s_id:match("^env:(.+)") + -- end + -- + -- -- Otherwise, look for the requested key inside this first env + -- if type(s_body) == "table" then + -- for _, kv in ipairs(s_body) do + -- if type(kv) == "table" and #kv >= 2 and kv[1] == key_name then + -- local val = kv[2] + -- if val ~= nil and (type(val) ~= "table" or #val > 0) then + -- return val + -- end + -- end + -- end + -- end + -- end + -- end + -- end return nil end @@ -74,9 +134,14 @@ local pio_manager = (function() cache = decoded -- if type(cache) == 'table' then print(vim.inspect(cache)) -- else print('no cahce')end - if not cache or type(cache) ~= 'table' then print('no cahce') - else print('refreshed') end - if callback then vim.schedule(callback) end + if not cache or type(cache) ~= 'table' then + print('no cahce') + else + print('refreshed') + end + if callback then + vim.schedule(callback) + end end else -- Schedule notification to avoid error in the system callback thread @@ -92,7 +157,9 @@ local pio_manager = (function() end return { refresh = refresh, - get = function(s, k) return find_in_data(cache, s, k) end, + get = function(s, k) + return find_in_data(cache, s, k) + end, } end)() From f1a0729f32d931dc5455026374ad569f01a3a549 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 18:59:55 +0300 Subject: [PATCH 0554/1406] update --- lua/platformio/boilerplate.lua | 72 +++++---- lua/platformio/init.lua | 6 +- lua/platformio/lspConfig/clangd.lua | 8 - lua/platformio/pio_setup.lua | 137 +++++------------- lua/platformio/utils/lsp.lua | 32 +++- lua/platformio/utils/piodb.lua | 217 ---------------------------- 6 files changed, 107 insertions(+), 365 deletions(-) delete mode 100644 lua/platformio/utils/piodb.lua diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index f5b213ae..88dc66af 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -102,46 +102,42 @@ clangd boilerplate['.clangd'] = { content = [[ CompileFlags: - Add: [ - --target=riscv32-esp-elf, - ] - Remove: [ - -fno-fat-lto-objects - -fno%-fat%-lto%-objects, - -fno%-canonical%-system%-headers, - -misc-definitions-in-headers, - -fno-tree-switch-conversion, - -mtext-section-literals, - -mlong-calls, - -mlongcalls, - -fstrict-volatile-bitfields, - -free*, - -fipa-pta*, - -march=*, - -mabi=*, - -mcpu=*, - ] + Add: + - "--target=riscv32-esp-elf" + Remove: + - "-fno-fat-lto-objects" + - "-fno%-fat%-lto%-objects" + - "-fno%-canonical%-system%-headers" + - "-misc-definitions-in-headers" + - "-fno-tree-switch-conversion" + - "-mtext-section-literals" + - "-mlong-calls" + - "-mlongcalls" + - "-fstrict-volatile-bitfields" + - "-free*" + - "-fipa-pta*" + - "-march=*" + - "-mabi=*" + - "-mcpu=*" Diagnostics: - Suppress: [ - "misc-definitions-in-headers", - "pp_including_mainfile_in_preamble", - "misc-unused-using-decls", - "unused-includes", - ] + Suppress: + - "misc-definitions-in-headers" + - "pp_including_mainfile_in_preamble" + - "misc-unused-using-decls" + - "unused-includes" ClangTidy: - Remove: [ - readability-*, - cert-err58-cpp, - llvmlibc-*, - fuchsia-*, - hicpp-avoid-c-arrays, - cppcoreguidelines-*, - llvm-*, - google-*, - bugprone-*, - hicpp-vararg, - modernize-*, - ] + Remove: + - "readability-*" + - "cert-err58-cpp" + - "llvmlibc-*" + - "fuchsia-*" + - "hicpp-avoid-c-arrays" + - "cppcoreguidelines-*" + - "llvm-*" + - "google-*" + - "bugprone-*" + - "hicpp-vararg" + - "modernize-*" ]], } boilerplate['.stylua.toml'] = { diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index 43815194..8482bb33 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -183,10 +183,8 @@ function M.setup(user_config) require('platformio.piomenu').piomenu(M.config) - if M.config.lspClangd.enabled == true then - -- vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) - require('platformio.lspConfig.clangd') - end + -- Load the PIO setup logic + require('platformio.pio_setup').init() end return M diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index a0209404..0ef9a900 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -298,12 +298,4 @@ vim.lsp.config('pyrefly', pyrefly) -- restart lsp require('platformio.utils.lsp').lsp_restart('clangd') - --- Load the PIO logic -require('platformio.pio_setup').init() - -local config = require('platformio').config -if config.lspClangd.attach.enabled then - require('platformio.lspConfig.attach') -end ---------------------------------------------------------------------------------- diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index d058ba97..6b5de896 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,5 +1,6 @@ local misc = require('platformio.utils.misc') local lsp = require('platformio.utils.lsp') + -- INFO: 1. The Core PIO Manager & Generic Extractor --This manages the data cache and navigates your specific nested-list JSON structure. -- stylua: ignore @@ -10,17 +11,18 @@ local pio_manager = (function() local function find_in_data(data, section_name, key_name) if not data or type(data) ~= 'table' then return nil end - -- INFO: 1. SPECIFIC SEARCH + -- INFO: 1. SPECIFIC SEARCH: Look for a specific section (e.g., "platformio") if section_name then for _, section in ipairs(data) do if type(section) == 'table' and #section >= 2 then - if section[1] == section_name and type(section[2]) == 'table' then - for _, kv in ipairs(section[2]) do - if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then - -- Check if value is valid (not nil, not empty string, not empty table) - local val = kv[2] - if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then - return val + local s_id = section[1] + local s_body = section[2] + if s_id == section_name and type(s_body) == "table" then + for _, kv in ipairs(s_body) do + if type(kv) == "table" and #kv >= 2 and kv[1] == key_name then + local val = kv[2] + if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then + return val end end end @@ -34,6 +36,7 @@ local pio_manager = (function() for _, section in ipairs(data) do if type(section) == 'table' and #section >= 2 then local s_id = section[1] + local s_body = section[2] -- Look for hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] if type(s_id) == 'string' and s_id:find('^env:') then fallback_env_found = s_id:match('^env:(.+)') @@ -47,8 +50,8 @@ local pio_manager = (function() end -- If looking for a key (like 'platform') inside this fallback env - if type(section[2]) == 'table' then - for _, kv in ipairs(section[2]) do + if type(s_body) == 'table' then + for _, kv in ipairs(s_body) do if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then local val = kv[2] if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then @@ -67,83 +70,17 @@ local pio_manager = (function() -- INFO: 3. FINAL ERROR If even fallback fails if key_name == 'platform' or key_name == 'packages_dir' then vim.schedule(function() - vim.notify("PIO: Critical key '" .. key_name .. "' not found anywhere!", vim.log.levels.ERROR) + vim.notify("PIO: Critical key '" .. key_name .. "' not found anywhere!", vim.log.levels.INFO) end) end - -- -- 1. SPECIFIC SEARCH: Look for a specific section (e.g., "platformio") - -- if section_name then - -- for _, section in ipairs(data) do - -- if type(section) == 'table' and #section >= 2 then - -- local section_id = section[1] - -- local section_body = section[2] - -- - -- -- Match specific section or fallback to first "env:" found - -- local match_section = (not section_name and type(section_id) == 'string' and section_id:find('^env:')) or (section_id == section_name) - -- if match_section and type(section_body) == 'table' then - -- for _, kv in ipairs(section_body) do - -- if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then return kv[2] end - -- if type(kv) == "table" and #kv >= 2 and kv[1] == key_name then - -- local val = kv[2] - -- -- Nil Check: Only return if the value is not nil or an empty table - -- if val ~= nil and (type(val) ~= "table" or #val > 0) then - -- return val - -- end - -- end - -- end - -- end - -- end - -- end - -- else - -- end - -- -- 2. FALLBACK: Search all 'env:' sections if specific search failed or was skipped - -- for _, section in ipairs(data) do - -- if type(section) == "table" and #section >= 2 then - -- local s_id = section[1] - -- local s_body = section[2] - -- - -- -- Match only hardware environments, skipping global [env] - -- if type(s_id) == "string" and s_id:find("^env:") then - -- -- Return extracted environment name if looking for default_envs - -- if key_name == "default_envs" then - -- return s_id:match("^env:(.+)") - -- end - -- - -- -- Otherwise, look for the requested key inside this first env - -- if type(s_body) == "table" then - -- for _, kv in ipairs(s_body) do - -- if type(kv) == "table" and #kv >= 2 and kv[1] == key_name then - -- local val = kv[2] - -- if val ~= nil and (type(val) ~= "table" or #val > 0) then - -- return val - -- end - -- end - -- end - -- end - -- end - -- end - -- end return nil end + ------------------------------------------------------------------------------------------ local function refresh(callback) -- Using vim.system to detect if the command exists vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) - if obj.code == 0 then - local ok, decoded = pcall(vim.json.decode, obj.stdout) - if ok and decoded then - cache = decoded - -- if type(cache) == 'table' then print(vim.inspect(cache)) - -- else print('no cahce')end - if not cache or type(cache) ~= 'table' then - print('no cahce') - else - print('refreshed') - end - if callback then - vim.schedule(callback) - end - end - else + if obj.code ~= 0 then -- Schedule notification to avoid error in the system callback thread vim.schedule(function() if obj.code == 127 then @@ -152,6 +89,17 @@ local pio_manager = (function() vim.notify('PIO Manager: Failed to fetch config (Error ' .. obj.code .. ')', vim.log.levels.WARN) end end) + return + end + local ok, decoded = pcall(vim.json.decode, obj.stdout) + if ok and decoded then + cache = decoded + if not cache or type(cache) ~= 'table' then + print('no cahce') + else + print('cahced ok') + end + if callback then vim.schedule(callback) end end end) end @@ -163,6 +111,7 @@ local pio_manager = (function() } end)() +------------------------------------------------------------------------------------------------------ -- INFO: 2. Generic Toolchain & Sysroot Logic. These functions identify where the compiler and its C++ headers live. -- Gets the compiler glob for clangd --query-driver -- stylua: ignore @@ -202,6 +151,7 @@ function _G.get_pio_toolchain_pattern() if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') arch_glob = '/**/bin/*' .. arch .. '*' + print('toolchain 4: arch_glob=' .. arch_glob) break end end @@ -255,6 +205,7 @@ local function pio_generate_db() end) end +------------------------------------------------------------------------------------------------------ -- INFO: 4. Automation & File Watcher --This handles the background synchronization when you save your project. -- stylua: ignore @@ -284,11 +235,20 @@ local function start_pio_watcher() ) end --- INFO: Exported setup function +------------------------------------------------------------------------------------------------------ +-- INFO: 5. Exported setup function return { init = function() if vim.fn.filereadable(vim.fn.getcwd() .. '/platformio.ini') == 1 then vim.notify('PIO setup initialize', vim.log.levels.INFO) + local config = require('platformio').config + if config.lspClangd.enabled == true then + -- vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) + require('platformio.lspConfig.clangd') + end + if config.lspClangd.attach.enabled then + require('platformio.lspConfig.attach') + end pio_manager.refresh(function() pio_generate_db() start_pio_watcher() @@ -296,20 +256,3 @@ return { end end, } - --- -- init.lua --- --- -- 1. Load the PIO logic --- local pio = require("pio_setup") --- pio.init() --- --- -- 2. Your LSP Setup --- require('lspconfig').clangd.setup({ --- cmd = { --- "clangd", --- "--background-index", --- -- It calls the global function defined in pio_setup.lua --- "--query-driver=" .. _G.get_pio_toolchain_pattern(), --- "--header-insertion=never" --- }, --- }) diff --git a/lua/platformio/utils/lsp.lua b/lua/platformio/utils/lsp.lua index f85c1694..2ff24227 100644 --- a/lua/platformio/utils/lsp.lua +++ b/lua/platformio/utils/lsp.lua @@ -1,6 +1,6 @@ local M = {} ---- stylua: ignore +-- stylua: ignore function M.lsp_restart(name) if vim.fn.has('nvim-0.12') == 1 then -- local clients = vim.lsp.get_clients({ name = name }) @@ -33,4 +33,34 @@ function M.lsp_restart(name) end end +-- function M.lsp_restarti() +-- local bufnr = nvim_get_current_buf() +-- local clients = lsp.get_clients({ bufnr = bufnr }) +-- +-- if #clients == 0 then +-- -- I'm using my own implementation of `vim.lsp.enable()` +-- -- To work with default one change group name from `MyLsp` to `nvim.lsp.enable` +-- -- It is not tested with default one, so not sure if it would 100% work. +-- api.nvim_exec_autocmds('FileType', { group = 'MyLsp', buffer = bufnr }) +-- return +-- end +-- +-- for _, c in ipairs(clients) do +-- local attached_buffers = vim.tbl_keys(c.attached_buffers) ---@type integer[] +-- local config = c.config +-- lsp.stop_client(c.id, true) +-- vim.defer_fn(function() +-- local id = lsp.start(config) +-- if id then +-- for _, b in ipairs(attached_buffers) do +-- lsp.buf_attach_client(b, id) +-- end +-- vim.notify(string.format('Lsp `%s` has been restarted.', config.name)) +-- else +-- vim.notify(string.format('Error restarting `%s`.', config.name), vim.log.levels.ERROR) +-- end +-- end, 600) +-- end +-- end + return M diff --git a/lua/platformio/utils/piodb.lua b/lua/platformio/utils/piodb.lua deleted file mode 100644 index df70ac16..00000000 --- a/lua/platformio/utils/piodb.lua +++ /dev/null @@ -1,217 +0,0 @@ --- -- 1. The Robust Async PIO Manager & Extractor --- -- Handles the async lifecycle and data extraction for nested list-of-lists --- local pio_manager = (function() --- local cache = nil --- --- -- Generic extractor for nested structure: { { "name", { {"k","v"}, ... } }, ... } --- local function find_in_data(data, section_name, key_name) --- if type(data) ~= 'table' then --- return nil --- end --- for _, section in ipairs(data) do --- -- Safety check: section must be a table with at least 2 elements --- if type(section) == 'table' and #section >= 2 then --- local section_id = section[1] --- local section_body = section[2] --- --- -- Match specific section or fallback to first "env:" found --- local match_section = (not section_name and type(section_id) == 'string' and section_id:find('^env:')) or (section_id == section_name) --- --- if match_section and type(section_body) == 'table' then --- for _, kv in ipairs(section_body) do --- -- Safety check: kv must be a table {"key", "value"} --- if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then --- return kv[2] --- end --- end --- end --- end --- end --- return nil --- end --- --- local function refresh(callback) --- -- Using vim.system (Nvim 0.10+) for non-blocking CLI calls --- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) --- if obj.code ~= 0 then --- vim.schedule(function() --- if obj.code == 127 then --- vim.notify("PIO: 'pio' command not found in PATH", vim.log.levels.ERROR) --- else --- vim.notify('PIO: Config fetch failed (Code ' .. obj.code .. ')', vim.log.levels.WARN) --- end --- end) --- return --- end --- --- -- Safe JSON decoding --- local ok, decoded = pcall(vim.json.decode, obj.stdout) --- if ok and decoded then --- cache = decoded --- if callback then --- vim.schedule(callback) --- end --- else --- vim.schedule(function() --- vim.notify('PIO: Failed to decode JSON output', vim.log.levels.ERROR) --- end) --- end --- end) --- end --- --- return { --- refresh = refresh, --- get = function(s, k) --- return find_in_data(cache, s, k) --- end, --- } --- end)() --- --- -- 2. Generic Toolchain & Sysroot Logic --- -- Resolves the compiler path and patches compile_commands.json for --- function _G.get_pio_toolchain_pattern() --- local active_env = vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') --- -- Handle default_envs being a list/table: take first string element --- if type(active_env) == 'table' then --- active_env = active_env[1] --- end --- --- local target_env = active_env and ('env:' .. active_env) or nil --- local platform = pio_manager.get(target_env, 'platform') --- local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('HOME') or os.getenv('USERPROFILE') .. '/.platformio/packages') --- --- if not platform then --- return '/**/bin/*gcc*' --- end --- --- -- Sync call for platform info (acceptable as it's targeted and small) --- local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') --- if not p_handle then --- return '/**/bin/*gcc*' --- end --- local p_json = p_handle:read('*all') --- p_handle:close() --- --- local p_ok, p_data = pcall(vim.json.decode, p_json) --- local arch_glob = '/**/bin/*gcc*' --- --- if p_ok and p_data and type(p_data.packages) == 'table' then --- for pkg_name, _ in pairs(p_data.packages) do --- if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then --- local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') --- arch_glob = '/**/bin/*' .. arch .. '*gcc*' --- break --- end --- end --- end --- --- local final = (packages_dir:gsub('\\', '/') .. arch_glob):gsub('//+', '/') --- return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final --- end --- --- -- Patches compile_commands.json with --sysroot to fix --- local function pio_generate_db() --- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) --- if obj.code ~= 0 then --- return --- end --- --- local pattern = _G.get_pio_toolchain_pattern() --- local toolchain_root = pattern:match('(.*toolchain%-[^/\\]+)') --- if not toolchain_root or vim.fn.isdirectory(toolchain_root) == 0 then --- return --- end --- --- -- Generic sysroot finder: search for subdir with an 'include' folder --- local sysroot_path = nil --- local subdirs = vim.fn.getcompletion(toolchain_root .. '/*', 'dir') --- for _, dir in ipairs(subdirs) do --- if vim.fn.isdirectory(dir .. '/include') == 1 then --- sysroot_path = dir:gsub('\\', '/') --- break --- end --- end --- --- if sysroot_path then --- local db_path = vim.fn.getcwd() .. '/compile_commands.json' --- local f = io.open(db_path, 'r') --- if not f then --- return --- end --- local content = f:read('*all') --- f:close() --- --- -- Insert sysroot at start of flag list to resolve Standard C++ headers --- local patched = content:gsub('("-i")', '"--sysroot=' .. sysroot_path .. '", %1') --- local out = io.open(db_path, 'w') --- if out then --- out:write(patched) --- out:close() --- vim.schedule(function() --- vim.notify('PIO: DB & Sysroot Patched') --- end) --- end --- end --- end) --- end --- --- -- 3. Automatic File Watcher --- -- Detects changes to platformio.ini and restarts LSP automatically --- local function start_pio_watcher() --- local path = vim.fn.getcwd() .. '/platformio.ini' --- if vim.fn.filereadable(path) == 0 then --- return --- end --- --- local w = vim.uv.new_fs_event() --- if not w then --- return --- end --- --- w:start( --- path, --- {}, --- vim.schedule_wrap(function(err, filename, events) --- if err then --- w:stop() --- return --- end --- if events.change then --- pio_manager.refresh(function() --- pio_generate_db() --- vim.cmd('LspRestart clangd') --- end) --- end --- end) --- ) --- end --- --- -- 4. Safe Initialization --- -- Only runs if a platformio.ini exists in the current directory --- if vim.fn.filereadable(vim.fn.getcwd() .. '/platformio.ini') == 1 then --- pio_manager.refresh(function() --- pio_generate_db() --- start_pio_watcher() --- end) --- end --- --- -- -- 1. Plugin Manager (Lazy.nvim) --- -- require("lazy").setup("plugins") --- -- --- -- -- 2. THE PIO SETUP CODE (Paste everything here) --- -- local pio_manager = (function() ... end)() --- -- function _G.get_pio_toolchain_pattern() ... end --- -- local function pio_generate_db() ... end --- -- -- ... etc ... --- -- --- -- 3. LSP Configuration --- -- local lspconfig = require('lspconfig') --- -- --- -- lspconfig.clangd.setup({ --- -- cmd = { --- -- "clangd", --- -- "--background-index", --- -- "--query-driver=" .. _G.get_pio_toolchain_pattern(), -- Uses the function above --- -- "--header-insertion=never" --- -- }, --- -- }) From 0f85dcb4c394f356a3057efad6d77617437b4513 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 19:21:15 +0300 Subject: [PATCH 0555/1406] update --- lua/platformio/lspConfig/clangd.lua | 20 --------------- lua/platformio/pio_setup.lua | 40 +++++++++++++++++++++-------- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 0ef9a900..3e662286 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -1,23 +1,3 @@ ----------------------------------------------------------------------------------------- --- INFO: create clangd required files ------------------------------------------------------------------------------------------ -local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) - -boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) --- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) --- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') - --- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - -boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) - -boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) --- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) --- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) ---------------------------------------------------------------------------------- - local ok, result ok, result = pcall(require, 'fidget') if ok then diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 6b5de896..a00e201a 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -239,20 +239,40 @@ end -- INFO: 5. Exported setup function return { init = function() - if vim.fn.filereadable(vim.fn.getcwd() .. '/platformio.ini') == 1 then + local config = require('platformio').config + if config.lspClangd.enabled == true then vim.notify('PIO setup initialize', vim.log.levels.INFO) - local config = require('platformio').config - if config.lspClangd.enabled == true then - -- vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) - require('platformio.lspConfig.clangd') - end + ---------------------------------------------------------------------------------------- + -- INFO: create clangd required files + ----------------------------------------------------------------------------------------- + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) + + boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) + -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) + -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') + + -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + + boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) + + boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) + -- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) + -- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) + --------------------------------------------------------------------------------- + + -- vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) + require('platformio.lspConfig.clangd') if config.lspClangd.attach.enabled then require('platformio.lspConfig.attach') end - pio_manager.refresh(function() - pio_generate_db() - start_pio_watcher() - end) + if vim.fn.filereadable(vim.fn.getcwd() .. '/platformio.ini') == 1 then + pio_manager.refresh(function() + pio_generate_db() + start_pio_watcher() + end) + end end end, } From 3328ae98bf043c6a0306425d4efe4d4473cdfa32 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 19:29:43 +0300 Subject: [PATCH 0556/1406] update --- lua/platformio/boilerplate.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 88dc66af..9adeb003 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -74,7 +74,6 @@ clangd --completion-parse=always --completion-style=detailed --header-insertion=iwyu ---detect-completion-context --fallback-style=llvm -j=12 --log=verbose From e7643951b5f231056ddabc386ab30449c69ebc77 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 19:45:22 +0300 Subject: [PATCH 0557/1406] update --- lua/platformio/pio_setup.lua | 51 +++++++++++++++++++++++++++++------- 1 file changed, 42 insertions(+), 9 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index a00e201a..eb8aae48 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -209,32 +209,65 @@ end -- INFO: 4. Automation & File Watcher --This handles the background synchronization when you save your project. -- stylua: ignore +-- local function start_pio_watcher() +-- local path = vim.fn.getcwd() .. '/platformio.ini' +-- if vim.fn.filereadable(path) == 0 then return end +-- local w = vim.uv.new_fs_event() +-- if not w then return end +-- w:start( +-- path, +-- {}, +-- vim.schedule_wrap(function(err, _, events) +-- if err then +-- vim.notify('PIO Auto-Sync error', vim.log.levels.ERROR) +-- w:stop() +-- return +-- end +-- if events.change then +-- pio_manager.refresh(function() +-- pio_generate_db() +-- lsp.lsp_restart('clangd') +-- -- vim.cmd('LspRestart clangd') +-- vim.notify('PIO Auto-Sync Complete', vim.log.levels.INFO) +-- end) +-- end +-- end) +-- ) +-- end + +local last_trigger = 0 -- Global variable to track time +-- stylua: ignore local function start_pio_watcher() local path = vim.fn.getcwd() .. '/platformio.ini' if vim.fn.filereadable(path) == 0 then return end + local w = vim.uv.new_fs_event() if not w then return end + w:start( path, {}, - vim.schedule_wrap(function(err, _, events) - if err then - vim.notify('PIO Auto-Sync error', vim.log.levels.ERROR) - w:stop() - return - end + vim.schedule_wrap(function(err, filename, events) + if err then w:stop() return end + + -- 1. Check if we've triggered too recently (5-second cooldown) + local current_time = os.time() + -- Skip this event to prevent infinite loop + if (current_time - last_trigger) < 5 then return end + if events.change then + last_trigger = current_time -- Update last trigger time + + vim.notify('PIO: Auto-Syncing changes...', vim.log.levels.INFO) + pio_manager.refresh(function() pio_generate_db() lsp.lsp_restart('clangd') - -- vim.cmd('LspRestart clangd') - vim.notify('PIO Auto-Sync Complete', vim.log.levels.INFO) end) end end) ) end - ------------------------------------------------------------------------------------------------------ -- INFO: 5. Exported setup function return { From 1cde3e10eb03d9df4ce51b7c1b0d44cd47b0756a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 19:48:13 +0300 Subject: [PATCH 0558/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index eb8aae48..b6171ae8 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -44,7 +44,7 @@ local pio_manager = (function() -- If we were looking for default_envs, we just found our fallback if key_name == 'default_envs' then vim.schedule(function() - vim.notify("PIO: 'default_envs' empty. Falling back to: " .. fallback_env_found, vim.log.levels.WARN) + vim.notify("PIO: 'default_envs' empty. Falling back to: " .. fallback_env_found, vim.log.levels.INFO) end) return fallback_env_found end From 0de95794bf8578cd3474f196ba7ddab3e004b663 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 21:00:13 +0300 Subject: [PATCH 0559/1406] update --- lua/platformio/boilerplate.lua | 45 +++++++++++++++++----------------- lua/platformio/pio_setup.lua | 7 ++++-- 2 files changed, 28 insertions(+), 24 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 9adeb003..ba971104 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -4,8 +4,10 @@ local uv = vim.loop local boilerplate = {} +-- INFO: main.cpp --- stylua: ignore boilerplate['arduino'] = { + rewrite = false, content = [[ #include @@ -19,7 +21,9 @@ void loop() { ]], } +-- INFO: platformio.ini boilerplate['platformio.ini'] = { + rewrite = true, template = [[ [platformio] core_dir = %s @@ -48,7 +52,9 @@ lib_ldf_mode = chain+ ;Library dependencies Finder ldf end, } +-- INFO: enable_toolchain.py boilerplate['enable_toolchain.py'] = { + rewrite = false, content = [[ from SCons.Script import DefaultEnvironment env = DefaultEnvironment() @@ -62,7 +68,9 @@ print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") ]], } +-- INFO: .clangd_cmd boilerplate['.clangd_cmd'] = { + rewrite = true, template = [[ clangd --all-scopes-completion @@ -98,7 +106,9 @@ clangd --query-driver=**/.platformio/packages/toolchain*/**/bin/*gcc* } +-- INFO: .clangd boilerplate['.clangd'] = { + rewrite = false, content = [[ CompileFlags: Add: @@ -139,7 +149,10 @@ Diagnostics: - "modernize-*" ]], } + +-- INFO: .stylua.toml boilerplate['.stylua.toml'] = { + rewrite = false, content = [[ syntax = "All" column_width = 132 @@ -156,7 +169,9 @@ enabled = false ]], } +-- INFO: .clang-format boilerplate['.clang-format'] = { + rewrite = false, content = [[ --- Language: Cpp @@ -415,7 +430,9 @@ function M.boilerplate_gen(framework, src_path, filename) -- local file_path = src_path .. '/' .. filename if vim.uv.fs_stat(file_path) then - return -- return if file exists + if not entry.rewrite then + return -- return if file exists and not rewritable + end end if vim.fn.isdirectory(src_path) == 0 then @@ -430,27 +447,11 @@ function M.boilerplate_gen(framework, src_path, filename) end -- local closeOnexit = type(exit_callback) == 'function' + -- local text = type(entry.content) == 'function' and entry:content() or entry.content local text = type(entry.content) == 'function' and entry:content() or entry.content - uv.fs_write(fd, text, 0) - uv.fs_close(fd) - - -- uv.fs_open(file_path, 'w', 420, function(_, fd) -- crtete file if directory of the path exists - -- if not fd then - -- print('failed to create file: ' .. file_path .. '/' .. entry.filename) - -- return - -- end - -- uv.fs_write(fd, entry.content, 0, function(werr, _) - -- if werr then - -- print('failed to write to file: ' .. file_path .. '/' .. entry.filename) - -- return - -- end - -- uv.fs_close(fd, function(cerr) - -- if cerr then - -- print('failed to close file: ' .. file_path .. '/' .. entry.filename) - -- return - -- end - -- end) - -- end) - -- end) + if text then + uv.fs_write(fd, text, 0) + uv.fs_close(fd) + end end return M diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b6171ae8..220e3c2c 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -235,6 +235,8 @@ end -- ) -- end +-- INFO: 5. Automation & File Watcher +--This handles the background synchronization when you save your project platformio.ini local last_trigger = 0 -- Global variable to track time -- stylua: ignore local function start_pio_watcher() @@ -247,7 +249,7 @@ local function start_pio_watcher() w:start( path, {}, - vim.schedule_wrap(function(err, filename, events) + vim.schedule_wrap(function(err, _, events) if err then w:stop() return end -- 1. Check if we've triggered too recently (5-second cooldown) @@ -268,8 +270,9 @@ local function start_pio_watcher() end) ) end + ------------------------------------------------------------------------------------------------------ --- INFO: 5. Exported setup function +-- INFO: 6. Exported setup function return { init = function() local config = require('platformio').config From 704e0bbaee28e1a8901497eeb6cc4e80e0bded06 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 21:11:37 +0300 Subject: [PATCH 0560/1406] update --- lua/platformio/pio_setup.lua | 62 ++++++++++-------------------------- 1 file changed, 17 insertions(+), 45 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 220e3c2c..5cdef3a1 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -208,36 +208,7 @@ end ------------------------------------------------------------------------------------------------------ -- INFO: 4. Automation & File Watcher --This handles the background synchronization when you save your project. --- stylua: ignore --- local function start_pio_watcher() --- local path = vim.fn.getcwd() .. '/platformio.ini' --- if vim.fn.filereadable(path) == 0 then return end --- local w = vim.uv.new_fs_event() --- if not w then return end --- w:start( --- path, --- {}, --- vim.schedule_wrap(function(err, _, events) --- if err then --- vim.notify('PIO Auto-Sync error', vim.log.levels.ERROR) --- w:stop() --- return --- end --- if events.change then --- pio_manager.refresh(function() --- pio_generate_db() --- lsp.lsp_restart('clangd') --- -- vim.cmd('LspRestart clangd') --- vim.notify('PIO Auto-Sync Complete', vim.log.levels.INFO) --- end) --- end --- end) --- ) --- end - --- INFO: 5. Automation & File Watcher ---This handles the background synchronization when you save your project platformio.ini -local last_trigger = 0 -- Global variable to track time +local debounce_timer = vim.uv.new_timer() -- stylua: ignore local function start_pio_watcher() local path = vim.fn.getcwd() .. '/platformio.ini' @@ -247,25 +218,26 @@ local function start_pio_watcher() if not w then return end w:start( - path, - {}, + path, {}, vim.schedule_wrap(function(err, _, events) - if err then w:stop() return end + if err or not events.change then return end - -- 1. Check if we've triggered too recently (5-second cooldown) - local current_time = os.time() - -- Skip this event to prevent infinite loop - if (current_time - last_trigger) < 5 then return end + -- 1. Stop any existing timer (cancel previous "half-finished" events) + if debounce_timer then + debounce_timer:stop() - if events.change then - last_trigger = current_time -- Update last trigger time + -- 2. Start a 500ms window. Logic only runs if NO more events happen in this time. + debounce_timer:start( 500, 0, + vim.schedule_wrap(function() + vim.notify('PIO: Config change detected. Refreshing...', vim.log.levels.INFO) - vim.notify('PIO: Auto-Syncing changes...', vim.log.levels.INFO) - - pio_manager.refresh(function() - pio_generate_db() - lsp.lsp_restart('clangd') - end) + pio_manager.refresh(function() + pio_generate_db() + -- 3. Only restart LSP if the pattern actually changed or DB was updated + lsp.lsp_restart('clangd') + end) + end) + ) end end) ) From 68528370bf96a2c4479f160666f8d655819d2259 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 21:35:58 +0300 Subject: [PATCH 0561/1406] update --- lua/platformio/pio_setup.lua | 9 --------- 1 file changed, 9 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 5cdef3a1..b27c18f7 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -123,25 +123,17 @@ function _G.get_pio_toolchain_pattern() -- Handle default_envs being a list/table if type(active_env) == 'table' then active_env = active_env[1] end - if active_env then print('toolchain 2:active_env=' .. active_env) end local target_env = active_env and ('env:' .. active_env) or nil - if target_env then print('toolchain 2.0:target_env=' .. target_env) end - local platform = pio_manager.get(target_env, 'platform') - if platform then print('toolchain 2.1:platformio=' .. platform) end - local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('HOME') or os.getenv('USERPROFILE') .. '/.platformio/packages') - if packages_dir then print('toolchain 2.2:packages_dir=' .. packages_dir) end if not platform then return '/**/bin/*' end - print('toolchain 3:') -- Sync call for toolchain name local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') if not p_handle then return '/**/bin/*' end - print('toolchain 4:') local p_json = p_handle:read('*all') p_handle:close() local arch_glob = '/**/bin/*' @@ -151,7 +143,6 @@ function _G.get_pio_toolchain_pattern() if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') arch_glob = '/**/bin/*' .. arch .. '*' - print('toolchain 4: arch_glob=' .. arch_glob) break end end From 56055e3b2818a5373b0431523b5f8bb681c315cc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 12 Apr 2026 21:51:42 +0300 Subject: [PATCH 0562/1406] update --- lua/platformio/pio_setup.lua | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b27c18f7..b5689977 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -7,11 +7,11 @@ local lsp = require('platformio.utils.lsp') local pio_manager = (function() local cache = nil - -- Generic extractor for nested structure: { { "name", { {"k","v"}, ... } }, ... } + -- INFO: 1 Generic extractor for nested structure: { { "name", { {"k","v"}, ... } }, ... } local function find_in_data(data, section_name, key_name) if not data or type(data) ~= 'table' then return nil end - -- INFO: 1. SPECIFIC SEARCH: Look for a specific section (e.g., "platformio") + -- INFO: 1.0 SPECIFIC SEARCH: Look for a specific section (e.g., "platformio") if section_name then for _, section in ipairs(data) do if type(section) == 'table' and #section >= 2 then @@ -31,7 +31,7 @@ local pio_manager = (function() end end - -- INFO: 2. FALLBACK SEARCH (If we reach here, Step 1 failed or was skipped) + -- INFO: 1.1 FALLBACK SEARCH (If we reach here, Step 1 failed or was skipped) local fallback_env_found = nil for _, section in ipairs(data) do if type(section) == 'table' and #section >= 2 then @@ -67,7 +67,7 @@ local pio_manager = (function() end end - -- INFO: 3. FINAL ERROR If even fallback fails + -- INFO: 1.2 FINAL ERROR If even fallback fails if key_name == 'platform' or key_name == 'packages_dir' then vim.schedule(function() vim.notify("PIO: Critical key '" .. key_name .. "' not found anywhere!", vim.log.levels.INFO) @@ -77,6 +77,7 @@ local pio_manager = (function() end ------------------------------------------------------------------------------------------ + -- INFO: 2. Asynchronous Refresh local function refresh(callback) -- Using vim.system to detect if the command exists vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) @@ -116,10 +117,8 @@ end)() -- Gets the compiler glob for clangd --query-driver -- stylua: ignore function _G.get_pio_toolchain_pattern() - -- local active_env = vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') - local active_env = vim.g.pio_active_env - or pio_manager.get("platformio", "default_envs") - or pio_manager.get(nil, "default_envs") + local active_env = vim.g.pio_active_env or pio_manager.get("platformio", "default_envs") + -- or pio_manager.get(nil, "default_envs") -- Handle default_envs being a list/table if type(active_env) == 'table' then active_env = active_env[1] end From b9abec3445afa43c21a5c93328487c7c7bfea250 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 05:06:59 +0300 Subject: [PATCH 0563/1406] update --- lua/platformio/archived/pio_setup.lua | 275 +++++++++++++++++++++++ lua/platformio/pio_setup.lua | 312 ++++++++++++++------------ 2 files changed, 440 insertions(+), 147 deletions(-) create mode 100644 lua/platformio/archived/pio_setup.lua diff --git a/lua/platformio/archived/pio_setup.lua b/lua/platformio/archived/pio_setup.lua new file mode 100644 index 00000000..8acfa255 --- /dev/null +++ b/lua/platformio/archived/pio_setup.lua @@ -0,0 +1,275 @@ +local misc = require('platformio.utils.misc') +local lsp = require('platformio.utils.lsp') + +local debounce_timer = vim.uv.new_timer() +-- INFO: 1. The Core PIO Manager & Generic Extractor +--This manages the data cache and navigates your specific nested-list JSON structure. +-- stylua: ignore +local pio_manager = (function() + local cache = nil + + -- INFO: 1 Generic extractor for nested structure: { { "name", { {"k","v"}, ... } }, ... } + local function find_in_data(data, section_name, key_name) + if not data or type(data) ~= 'table' then return nil end + + -- INFO: 1.0 SPECIFIC SEARCH: Look for a specific section (e.g., "platformio") + if section_name then + for _, section in ipairs(data) do + if type(section) == 'table' and #section >= 2 then + local s_id, s_body = section[1], section[2] + if s_id == section_name and type(s_body) == "table" then + for _, kv in ipairs(s_body) do + if type(kv) == "table" and #kv >= 2 and kv[1] == key_name then + local val = kv[2] + if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then + return val + end + end + end + end + end + end + end + + -- INFO: 1.1 FALLBACK SEARCH (If we reach here, Step 1 failed or was skipped) + local fallback_env_found = nil + for _, section in ipairs(data) do + if type(section) == 'table' and #section >= 2 then + local s_id = section[1] + local s_body = section[2] + -- Look for hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] + if type(s_id) == 'string' and s_id:find('^env:') then + fallback_env_found = s_id:match('^env:(.+)') + + -- If we were looking for default_envs, we just found our fallback + if key_name == 'default_envs' then + vim.schedule(function() + vim.notify("PIO: 'default_envs' empty. Falling back to: " .. fallback_env_found, vim.log.levels.INFO) + end) + return fallback_env_found + end + + -- If looking for a key (like 'platform') inside this fallback env + if type(s_body) == 'table' then + for _, kv in ipairs(s_body) do + if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then + local val = kv[2] + if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then + vim.schedule(function() + vim.notify("PIO: Using '" .. key_name .. "' from fallback env: " .. fallback_env_found, vim.log.levels.INFO) + end) + return val + end + end + end + end + end + end + end + + -- INFO: 1.2 FINAL ERROR If even fallback fails + if key_name == 'platform' or key_name == 'packages_dir' then + vim.schedule(function() + vim.notify("PIO: Critical key '" .. key_name .. "' not found anywhere!", vim.log.levels.INFO) + end) + end + return nil + end + ------------------------------------------------------------------------------------------ + + -- INFO: 2. Asynchronous Refresh + local function refresh(callback) + -- Using vim.system to detect if the command exists + vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) + if obj.code ~= 0 then + -- Schedule notification to avoid error in the system callback thread + vim.schedule(function() + if obj.code == 127 then + vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + else + vim.notify('PIO Manager: Failed to fetch config (Error ' .. obj.code .. ')', vim.log.levels.WARN) + end + end) + return + end + local ok, decoded = pcall(vim.json.decode, obj.stdout) + if ok and decoded then + cache = decoded + if not cache or type(cache) ~= 'table' then + print('no cahce') + else + print('cahced ok') + end + if callback then vim.schedule(callback) end + end + end) + end + return { + refresh = refresh, + get = function(s, k) + return find_in_data(cache, s, k) + end, + } +end)() + +------------------------------------------------------------------------------------------------------ +-- INFO: 2. Generic Toolchain & Sysroot Logic. These functions identify where the compiler and its C++ headers live. +-- Gets the compiler glob for clangd --query-driver +-- stylua: ignore +function _G.get_pio_toolchain_pattern() + local active_env = vim.g.pio_active_env or pio_manager.get("platformio", "default_envs") + -- or pio_manager.get(nil, "default_envs") + + -- Handle default_envs being a list/table + if type(active_env) == 'table' then active_env = active_env[1] end + + local target_env = active_env and ('env:' .. active_env) or nil + local platform = pio_manager.get(target_env, 'platform') + local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('HOME') or os.getenv('USERPROFILE') .. '/.platformio/packages') + + if not platform then return '/**/bin/*' end + + -- Sync call for toolchain name + local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') + if not p_handle then return '/**/bin/*' end + + local p_json = p_handle:read('*all') + p_handle:close() + local arch_glob = '/**/bin/*' + local p_ok, p_data = pcall(vim.json.decode, p_json) + if p_ok and p_data and type(p_data.packages) == 'table' then + for pkg_name, _ in pairs(p_data.packages) do + if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then + local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') + arch_glob = '/**/bin/*' .. arch .. '*' + break + end + end + end + -- local final = (packages_dir:gsub('\\', '/') .. arch_glob):gsub('//+', '/') + local final = packages_dir .. arch_glob + print('toolchain 5: final=' .. final) + return (misc.normalize_path(final)) + -- return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final +end + +-- INFO: 3. Patches compile_commands.json with --sysroot to fix +-- Helper to generate the compilation database +-- stylua: ignore +local function pio_generate_db() + -- This runs in the background so it doesn't freeze Neovim + vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) + if obj.code ~= 0 then return end + print('pio_generate_db 0') + local pattern = _G.get_pio_toolchain_pattern() + local toolchain_root = pattern:match('(.*toolchain%-[^/\\]+)') + if not toolchain_root or vim.fn.isdirectory(toolchain_root) == 0 then + return + end + + -- Find subdirectory containing 'include' (the sysroot) + local sysroot_path = nil + local subdirs = vim.fn.getcompletion(toolchain_root .. '/*', 'dir') + for _, dir in ipairs(subdirs) do + if vim.fn.isdirectory(dir .. '/include') == 1 then + sysroot_path = dir:gsub('\\', '/') + break + end + end + if sysroot_path then + local db_path = vim.fn.getcwd() .. '/compile_commands.json' + local f = io.open(db_path, 'r') + if not f then return end + local content = f:read('*all') + f:close() + + -- patch sysroot + local patched = content:gsub('("-i")', '"--sysroot=' .. sysroot_path .. '", %1') + local out = io.open(db_path, 'w') + if out then + out:write(patched) + out:close() + vim.schedule(function() vim.notify('PIO: DB & Sysroot Patched') end) + end + end + end) +end + +------------------------------------------------------------------------------------------------------ +-- INFO: 4. Automation & File Watcher +--This handles the background synchronization when you save your project. +-- stylua: ignore +local function start_pio_watcher() + local path = vim.fn.getcwd() .. '/platformio.ini' + if vim.fn.filereadable(path) == 0 then return end + + local w = vim.uv.new_fs_event() + if not w then return end + + w:start( + path, {}, + vim.schedule_wrap(function(err, _, events) + if err or not events.change then return end + + -- 1. Stop any existing timer (cancel previous "half-finished" events) + if debounce_timer then + debounce_timer:stop() + + -- 2. Start a 500ms window. Logic only runs if NO more events happen in this time. + debounce_timer:start( 500, 0, + vim.schedule_wrap(function() + vim.notify('PIO: Config change detected. Refreshing...', vim.log.levels.INFO) + + pio_manager.refresh(function() + pio_generate_db() + -- 3. Only restart LSP if the pattern actually changed or DB was updated + lsp.lsp_restart('clangd') + end) + end) + ) + end + end) + ) +end + +------------------------------------------------------------------------------------------------------ +-- INFO: 6. Exported setup function +return { + init = function() + local config = require('platformio').config + if config.lspClangd.enabled == true then + vim.notify('PIO setup initialize', vim.log.levels.INFO) + ---------------------------------------------------------------------------------------- + -- INFO: create clangd required files + ----------------------------------------------------------------------------------------- + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) + + boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) + -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) + -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') + + -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + + boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) + + boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) + -- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) + -- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) + --------------------------------------------------------------------------------- + + -- vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) + require('platformio.lspConfig.clangd') + if config.lspClangd.attach.enabled then + require('platformio.lspConfig.attach') + end + if vim.fn.filereadable(vim.fn.getcwd() .. '/platformio.ini') == 1 then + pio_manager.refresh(function() + pio_generate_db() + start_pio_watcher() + end) + end + end + end, +} diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b5689977..0ad1f87b 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,173 +1,187 @@ -local misc = require('platformio.utils.misc') -local lsp = require('platformio.utils.lsp') +-- lua/pio_setup.lua +-- This module manages PlatformIO project integration, LSP toolchain detection, +-- and automatic sysroot patching for standard library headers (, etc.) + +local debounce_timer = vim.uv.new_timer() --- INFO: 1. The Core PIO Manager & Generic Extractor ---This manages the data cache and navigates your specific nested-list JSON structure. --- stylua: ignore local pio_manager = (function() - local cache = nil + local cache = nil -- Stores the decoded platformio.ini JSON structure - -- INFO: 1 Generic extractor for nested structure: { { "name", { {"k","v"}, ... } }, ... } + -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' + -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } local function find_in_data(data, section_name, key_name) - if not data or type(data) ~= 'table' then return nil end - - -- INFO: 1.0 SPECIFIC SEARCH: Look for a specific section (e.g., "platformio") - if section_name then - for _, section in ipairs(data) do - if type(section) == 'table' and #section >= 2 then - local s_id = section[1] - local s_body = section[2] - if s_id == section_name and type(s_body) == "table" then - for _, kv in ipairs(s_body) do - if type(kv) == "table" and #kv >= 2 and kv[1] == key_name then - local val = kv[2] - if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then - return val - end - end - end - end - end - end + -- Safety check: Ensure data is a valid table from a successful JSON decode + if type(data) ~= 'table' then + return nil end - -- INFO: 1.1 FALLBACK SEARCH (If we reach here, Step 1 failed or was skipped) - local fallback_env_found = nil for _, section in ipairs(data) do + -- Each section must be a table with at least 2 elements: [1]=name, [2]=content if type(section) == 'table' and #section >= 2 then - local s_id = section[1] - local s_body = section[2] - -- Look for hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] - if type(s_id) == 'string' and s_id:find('^env:') then - fallback_env_found = s_id:match('^env:(.+)') + local s_id = section[1] -- Section header string + local s_body = section[2] -- Table of key-value pairs - -- If we were looking for default_envs, we just found our fallback - if key_name == 'default_envs' then - vim.schedule(function() - vim.notify("PIO: 'default_envs' empty. Falling back to: " .. fallback_env_found, vim.log.levels.INFO) - end) - return fallback_env_found - end - - -- If looking for a key (like 'platform') inside this fallback env - if type(s_body) == 'table' then - for _, kv in ipairs(s_body) do - if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then - local val = kv[2] - if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then - vim.schedule(function() - vim.notify("PIO: Using '" .. key_name .. "' from fallback env: " .. fallback_env_found, vim.log.levels.INFO) - end) - return val - end + if s_id == section_name and type(s_body) == 'table' then + for _, kv in ipairs(s_body) do + -- Each kv is a table: [1]=key, [2]=value + if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then + local val = kv[2] + -- Treat empty strings or empty tables as nil to trigger fallback logic + if val == nil or val == '' or (type(val) == 'table' and #val == 0) then + return nil end + return val end end end end end - - -- INFO: 1.2 FINAL ERROR If even fallback fails - if key_name == 'platform' or key_name == 'packages_dir' then - vim.schedule(function() - vim.notify("PIO: Critical key '" .. key_name .. "' not found anywhere!", vim.log.levels.INFO) - end) - end return nil end - ------------------------------------------------------------------------------------------ - -- INFO: 2. Asynchronous Refresh + -- ASYNC REFRESH: Fetches the latest config from PlatformIO CLI local function refresh(callback) - -- Using vim.system to detect if the command exists - vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) - if obj.code ~= 0 then - -- Schedule notification to avoid error in the system callback thread - vim.schedule(function() - if obj.code == 127 then - vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) - else - vim.notify('PIO Manager: Failed to fetch config (Error ' .. obj.code .. ')', vim.log.levels.WARN) + local function execute_pio(attempts) + -- Use Neovim's async system call to prevent UI freezing + vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) + -- Error Checking: obj.code 0 means success + if obj.code == 0 and obj.stdout then + local ok, decoded = pcall(vim.json.decode, obj.stdout) + if ok and decoded then + cache = decoded + if callback then + vim.schedule(callback) + end + return end - end) - return - end - local ok, decoded = pcall(vim.json.decode, obj.stdout) - if ok and decoded then - cache = decoded - if not cache or type(cache) ~= 'table' then - print('no cahce') + end + + -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save + if attempts > 0 then + vim.defer_fn(function() + execute_pio(attempts - 1) + end, 500) else - print('cahced ok') + vim.schedule(function() + if obj.code ~= 0 then + vim.notify('PIO: Config Error. Check platformio.ini syntax.', vim.log.levels.WARN) + end + end) end - if callback then vim.schedule(callback) end - end - end) + end) + end + execute_pio(1) end + return { refresh = refresh, get = function(s, k) - return find_in_data(cache, s, k) + if not cache then + return nil + end + local res = find_in_data(cache, s, k) + + -- FALLBACK: If default_envs is missing/empty, find the first hardware [env:xxx] block + if k == 'default_envs' and not res then + for _, section in ipairs(cache) do + if type(section) == 'table' and type(section[1]) == 'string' then + local name = section[1] + if name:find('^env:') then + local fallback = name:match('^env:(.+)') + if fallback then + vim.schedule(function() + vim.notify('PIO: default_envs empty. Using: ' .. fallback, vim.log.levels.INFO) + end) + return fallback + end + end + end + end + end + return res end, } end)() ------------------------------------------------------------------------------------------------------- --- INFO: 2. Generic Toolchain & Sysroot Logic. These functions identify where the compiler and its C++ headers live. --- Gets the compiler glob for clangd --query-driver --- stylua: ignore +-- LSP HELPER: Returns the glob pattern for clangd's --query-driver +-- e.g., C:\Users\tom\.platformio\packages\toolchain-riscv32-esp\bin\* function _G.get_pio_toolchain_pattern() - local active_env = vim.g.pio_active_env or pio_manager.get("platformio", "default_envs") - -- or pio_manager.get(nil, "default_envs") - - -- Handle default_envs being a list/table - if type(active_env) == 'table' then active_env = active_env[1] end + local ok_env, active_env = pcall(function() + return vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') + end) + if not ok_env or not active_env then + return '/**/bin/*' + end - local target_env = active_env and ('env:' .. active_env) or nil + local target_env = 'env:' .. active_env local platform = pio_manager.get(target_env, 'platform') - local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('HOME') or os.getenv('USERPROFILE') .. '/.platformio/packages') + -- Determine the packages directory (Windows vs Linux/Mac home folders) + local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('USERPROFILE') or os.getenv('HOME') .. '/.platformio/packages') - if not platform then return '/**/bin/*' end + if not platform then + return '/**/bin/*' + end - -- Sync call for toolchain name + -- Use pio platform show to find which toolchain packages are associated with the platform local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') - if not p_handle then return '/**/bin/*' end - - local p_json = p_handle:read('*all') + if not p_handle then + return '/**/bin/*' + end + local raw_json = p_handle:read('*all') p_handle:close() - local arch_glob = '/**/bin/*' - local p_ok, p_data = pcall(vim.json.decode, p_json) - if p_ok and p_data and type(p_data.packages) == 'table' then - for pkg_name, _ in pairs(p_data.packages) do - if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then - local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') - arch_glob = '/**/bin/*' .. arch .. '*' - break + + local p_ok, p_data = pcall(vim.json.decode, raw_json) + if not p_ok or not p_data or not p_data.packages then + return '/**/bin/*' + end + + local toolchain_folder = '' + for _, pkg in ipairs(p_data.packages) do + -- Skip ULP (low power) toolchains and find the primary one for the architecture + if pkg.name and pkg.name:find('^toolchain%-') and not pkg.name:find('ulp') then + local check_path = (packages_dir .. '/' .. pkg.name):gsub('\\', '/') + if vim.fn.isdirectory(check_path) == 1 then + toolchain_folder = pkg.name + -- Verification: Match the toolchain name against the compiler used in compile_commands.json + local db_path = vim.fn.getcwd() .. '/compile_commands.json' + local f = io.open(db_path, 'r') + if f then + local head = f:read(2048) -- Read enough to find the compiler path + f:close() + -- If the DB mentions "riscv32-esp", we ensure we picked the matching folder + if head and head:find(pkg.name:gsub('toolchain%-', '')) then + break + end + end end end end - -- local final = (packages_dir:gsub('\\', '/') .. arch_glob):gsub('//+', '/') - local final = packages_dir .. arch_glob - print('toolchain 5: final=' .. final) - return (misc.normalize_path(final)) - -- return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final + + if toolchain_folder == '' then + return '/**/bin/*' + end + + -- Normalize paths for the OS and ensure backslashes for Windows if needed + local final = (packages_dir:gsub('\\', '/') .. '/' .. toolchain_folder .. '/bin/*'):gsub('//+', '/') + return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final end --- INFO: 3. Patches compile_commands.json with --sysroot to fix --- Helper to generate the compilation database --- stylua: ignore +-- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag local function pio_generate_db() - -- This runs in the background so it doesn't freeze Neovim vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) - if obj.code ~= 0 then return end - print('pio_generate_db 0') + if obj.code ~= 0 then + return + end + + -- Isolate the toolchain root from the pattern (e.g. .../toolchain-riscv32-esp) local pattern = _G.get_pio_toolchain_pattern() - local toolchain_root = pattern:match('(.*toolchain%-[^/\\]+)') + local toolchain_root = pattern:match('(.-toolchain%-[^/\\]+)') if not toolchain_root or vim.fn.isdirectory(toolchain_root) == 0 then return end - -- Find subdirectory containing 'include' (the sysroot) + -- FIND SYSROOT: Locate the internal folder that contains the /include directory + -- This folder is necessary for clangd to find standard C++ headers like local sysroot_path = nil local subdirs = vim.fn.getcompletion(toolchain_root .. '/*', 'dir') for _, dir in ipairs(subdirs) do @@ -176,55 +190,59 @@ local function pio_generate_db() break end end + if sysroot_path then local db_path = vim.fn.getcwd() .. '/compile_commands.json' local f = io.open(db_path, 'r') - if not f then return end + if not f then + return + end local content = f:read('*all') f:close() - -- patch sysroot - local patched = content:gsub('("-i")', '"--sysroot=' .. sysroot_path .. '", %1') - local out = io.open(db_path, 'w') - if out then - out:write(patched) - out:close() - vim.schedule(function() vim.notify('PIO: DB & Sysroot Patched') end) + -- Inject the --sysroot flag into every command in the JSON file + if content and content ~= '' then + local patched = content:gsub('("-i")', '"--sysroot=' .. sysroot_path .. '", %1') + local out = io.open(db_path, 'w') + if out then + out:write(patched) + out:close() + end end end end) end ------------------------------------------------------------------------------------------------------- --- INFO: 4. Automation & File Watcher ---This handles the background synchronization when you save your project. -local debounce_timer = vim.uv.new_timer() --- stylua: ignore +-- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync local function start_pio_watcher() local path = vim.fn.getcwd() .. '/platformio.ini' - if vim.fn.filereadable(path) == 0 then return end + if vim.fn.filereadable(path) == 0 then + return + end local w = vim.uv.new_fs_event() - if not w then return end - + if not w then + return + end w:start( - path, {}, + path, + {}, vim.schedule_wrap(function(err, _, events) - if err or not events.change then return end + if err or not events or not events.change then + return + end - -- 1. Stop any existing timer (cancel previous "half-finished" events) if debounce_timer then + -- DEBOUNCE: Stops and restarts the timer to ensure we only sync ONCE after typing stops debounce_timer:stop() - - -- 2. Start a 500ms window. Logic only runs if NO more events happen in this time. - debounce_timer:start( 500, 0, + debounce_timer:start( + 500, + 0, vim.schedule_wrap(function() - vim.notify('PIO: Config change detected. Refreshing...', vim.log.levels.INFO) - pio_manager.refresh(function() pio_generate_db() - -- 3. Only restart LSP if the pattern actually changed or DB was updated - lsp.lsp_restart('clangd') + vim.cmd('LspRestart clangd') + vim.notify('PIO: Syncing Environment...') end) end) ) From bab3ccea611dda64298114ac2d72ca4947f464e0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 05:19:58 +0300 Subject: [PATCH 0564/1406] update --- lua/platformio/pio_setup.lua | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 0ad1f87b..05b668d9 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,3 +1,6 @@ +local misc = require('platformio.utils.misc') +local lsp = require('platformio.utils.lsp') + -- lua/pio_setup.lua -- This module manages PlatformIO project integration, LSP toolchain detection, -- and automatic sysroot patching for standard library headers (, etc.) @@ -161,9 +164,11 @@ function _G.get_pio_toolchain_pattern() return '/**/bin/*' end + local final = packages_dir .. toolchain_folder + print('toolchain 5: final=' .. final) -- Normalize paths for the OS and ensure backslashes for Windows if needed - local final = (packages_dir:gsub('\\', '/') .. '/' .. toolchain_folder .. '/bin/*'):gsub('//+', '/') - return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final + return (misc.normalize_path(final)) + -- return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final end -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag @@ -241,7 +246,7 @@ local function start_pio_watcher() vim.schedule_wrap(function() pio_manager.refresh(function() pio_generate_db() - vim.cmd('LspRestart clangd') + lsp.lsp_restart('clangd') vim.notify('PIO: Syncing Environment...') end) end) From 9a857a6087a9135c6d044cae2290b14dfee115e5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 05:27:02 +0300 Subject: [PATCH 0565/1406] update --- lua/platformio/pio_setup.lua | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 05b668d9..1336199f 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -44,6 +44,9 @@ local pio_manager = (function() -- ASYNC REFRESH: Fetches the latest config from PlatformIO CLI local function refresh(callback) + vim.schedule(function() + vim.notify('PIO: Fetching Config...', vim.log.levels.INFO) + end) local function execute_pio(attempts) -- Use Neovim's async system call to prevent UI freezing vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) @@ -173,6 +176,9 @@ end -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag local function pio_generate_db() + vim.schedule(function() + vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) + end) vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) if obj.code ~= 0 then return @@ -212,6 +218,9 @@ local function pio_generate_db() if out then out:write(patched) out:close() + vim.schedule(function() + vim.notify('PIO: Sync Complete!', vim.log.levels.INFO) + end) end end end From 71b58b41ebb73f23a2aef2d2145bf79871aa911e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 05:27:26 +0300 Subject: [PATCH 0566/1406] update --- lua/platformio/archived/pio_setup.lua | 550 +++++++++++++------------- 1 file changed, 275 insertions(+), 275 deletions(-) diff --git a/lua/platformio/archived/pio_setup.lua b/lua/platformio/archived/pio_setup.lua index 8acfa255..f929dc42 100644 --- a/lua/platformio/archived/pio_setup.lua +++ b/lua/platformio/archived/pio_setup.lua @@ -1,275 +1,275 @@ -local misc = require('platformio.utils.misc') -local lsp = require('platformio.utils.lsp') - -local debounce_timer = vim.uv.new_timer() --- INFO: 1. The Core PIO Manager & Generic Extractor ---This manages the data cache and navigates your specific nested-list JSON structure. --- stylua: ignore -local pio_manager = (function() - local cache = nil - - -- INFO: 1 Generic extractor for nested structure: { { "name", { {"k","v"}, ... } }, ... } - local function find_in_data(data, section_name, key_name) - if not data or type(data) ~= 'table' then return nil end - - -- INFO: 1.0 SPECIFIC SEARCH: Look for a specific section (e.g., "platformio") - if section_name then - for _, section in ipairs(data) do - if type(section) == 'table' and #section >= 2 then - local s_id, s_body = section[1], section[2] - if s_id == section_name and type(s_body) == "table" then - for _, kv in ipairs(s_body) do - if type(kv) == "table" and #kv >= 2 and kv[1] == key_name then - local val = kv[2] - if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then - return val - end - end - end - end - end - end - end - - -- INFO: 1.1 FALLBACK SEARCH (If we reach here, Step 1 failed or was skipped) - local fallback_env_found = nil - for _, section in ipairs(data) do - if type(section) == 'table' and #section >= 2 then - local s_id = section[1] - local s_body = section[2] - -- Look for hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] - if type(s_id) == 'string' and s_id:find('^env:') then - fallback_env_found = s_id:match('^env:(.+)') - - -- If we were looking for default_envs, we just found our fallback - if key_name == 'default_envs' then - vim.schedule(function() - vim.notify("PIO: 'default_envs' empty. Falling back to: " .. fallback_env_found, vim.log.levels.INFO) - end) - return fallback_env_found - end - - -- If looking for a key (like 'platform') inside this fallback env - if type(s_body) == 'table' then - for _, kv in ipairs(s_body) do - if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then - local val = kv[2] - if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then - vim.schedule(function() - vim.notify("PIO: Using '" .. key_name .. "' from fallback env: " .. fallback_env_found, vim.log.levels.INFO) - end) - return val - end - end - end - end - end - end - end - - -- INFO: 1.2 FINAL ERROR If even fallback fails - if key_name == 'platform' or key_name == 'packages_dir' then - vim.schedule(function() - vim.notify("PIO: Critical key '" .. key_name .. "' not found anywhere!", vim.log.levels.INFO) - end) - end - return nil - end - ------------------------------------------------------------------------------------------ - - -- INFO: 2. Asynchronous Refresh - local function refresh(callback) - -- Using vim.system to detect if the command exists - vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) - if obj.code ~= 0 then - -- Schedule notification to avoid error in the system callback thread - vim.schedule(function() - if obj.code == 127 then - vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) - else - vim.notify('PIO Manager: Failed to fetch config (Error ' .. obj.code .. ')', vim.log.levels.WARN) - end - end) - return - end - local ok, decoded = pcall(vim.json.decode, obj.stdout) - if ok and decoded then - cache = decoded - if not cache or type(cache) ~= 'table' then - print('no cahce') - else - print('cahced ok') - end - if callback then vim.schedule(callback) end - end - end) - end - return { - refresh = refresh, - get = function(s, k) - return find_in_data(cache, s, k) - end, - } -end)() - ------------------------------------------------------------------------------------------------------- --- INFO: 2. Generic Toolchain & Sysroot Logic. These functions identify where the compiler and its C++ headers live. --- Gets the compiler glob for clangd --query-driver --- stylua: ignore -function _G.get_pio_toolchain_pattern() - local active_env = vim.g.pio_active_env or pio_manager.get("platformio", "default_envs") - -- or pio_manager.get(nil, "default_envs") - - -- Handle default_envs being a list/table - if type(active_env) == 'table' then active_env = active_env[1] end - - local target_env = active_env and ('env:' .. active_env) or nil - local platform = pio_manager.get(target_env, 'platform') - local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('HOME') or os.getenv('USERPROFILE') .. '/.platformio/packages') - - if not platform then return '/**/bin/*' end - - -- Sync call for toolchain name - local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') - if not p_handle then return '/**/bin/*' end - - local p_json = p_handle:read('*all') - p_handle:close() - local arch_glob = '/**/bin/*' - local p_ok, p_data = pcall(vim.json.decode, p_json) - if p_ok and p_data and type(p_data.packages) == 'table' then - for pkg_name, _ in pairs(p_data.packages) do - if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then - local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') - arch_glob = '/**/bin/*' .. arch .. '*' - break - end - end - end - -- local final = (packages_dir:gsub('\\', '/') .. arch_glob):gsub('//+', '/') - local final = packages_dir .. arch_glob - print('toolchain 5: final=' .. final) - return (misc.normalize_path(final)) - -- return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final -end - --- INFO: 3. Patches compile_commands.json with --sysroot to fix --- Helper to generate the compilation database --- stylua: ignore -local function pio_generate_db() - -- This runs in the background so it doesn't freeze Neovim - vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) - if obj.code ~= 0 then return end - print('pio_generate_db 0') - local pattern = _G.get_pio_toolchain_pattern() - local toolchain_root = pattern:match('(.*toolchain%-[^/\\]+)') - if not toolchain_root or vim.fn.isdirectory(toolchain_root) == 0 then - return - end - - -- Find subdirectory containing 'include' (the sysroot) - local sysroot_path = nil - local subdirs = vim.fn.getcompletion(toolchain_root .. '/*', 'dir') - for _, dir in ipairs(subdirs) do - if vim.fn.isdirectory(dir .. '/include') == 1 then - sysroot_path = dir:gsub('\\', '/') - break - end - end - if sysroot_path then - local db_path = vim.fn.getcwd() .. '/compile_commands.json' - local f = io.open(db_path, 'r') - if not f then return end - local content = f:read('*all') - f:close() - - -- patch sysroot - local patched = content:gsub('("-i")', '"--sysroot=' .. sysroot_path .. '", %1') - local out = io.open(db_path, 'w') - if out then - out:write(patched) - out:close() - vim.schedule(function() vim.notify('PIO: DB & Sysroot Patched') end) - end - end - end) -end - ------------------------------------------------------------------------------------------------------- --- INFO: 4. Automation & File Watcher ---This handles the background synchronization when you save your project. --- stylua: ignore -local function start_pio_watcher() - local path = vim.fn.getcwd() .. '/platformio.ini' - if vim.fn.filereadable(path) == 0 then return end - - local w = vim.uv.new_fs_event() - if not w then return end - - w:start( - path, {}, - vim.schedule_wrap(function(err, _, events) - if err or not events.change then return end - - -- 1. Stop any existing timer (cancel previous "half-finished" events) - if debounce_timer then - debounce_timer:stop() - - -- 2. Start a 500ms window. Logic only runs if NO more events happen in this time. - debounce_timer:start( 500, 0, - vim.schedule_wrap(function() - vim.notify('PIO: Config change detected. Refreshing...', vim.log.levels.INFO) - - pio_manager.refresh(function() - pio_generate_db() - -- 3. Only restart LSP if the pattern actually changed or DB was updated - lsp.lsp_restart('clangd') - end) - end) - ) - end - end) - ) -end - ------------------------------------------------------------------------------------------------------- --- INFO: 6. Exported setup function -return { - init = function() - local config = require('platformio').config - if config.lspClangd.enabled == true then - vim.notify('PIO setup initialize', vim.log.levels.INFO) - ---------------------------------------------------------------------------------------- - -- INFO: create clangd required files - ----------------------------------------------------------------------------------------- - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) - - boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) - -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) - -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') - - -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - - boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) - - boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) - -- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) - -- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) - --------------------------------------------------------------------------------- - - -- vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) - require('platformio.lspConfig.clangd') - if config.lspClangd.attach.enabled then - require('platformio.lspConfig.attach') - end - if vim.fn.filereadable(vim.fn.getcwd() .. '/platformio.ini') == 1 then - pio_manager.refresh(function() - pio_generate_db() - start_pio_watcher() - end) - end - end - end, -} +-- local misc = require('platformio.utils.misc') +-- local lsp = require('platformio.utils.lsp') +-- +-- local debounce_timer = vim.uv.new_timer() +-- -- INFO: 1. The Core PIO Manager & Generic Extractor +-- --This manages the data cache and navigates your specific nested-list JSON structure. +-- -- stylua: ignore +-- local pio_manager = (function() +-- local cache = nil +-- +-- -- INFO: 1 Generic extractor for nested structure: { { "name", { {"k","v"}, ... } }, ... } +-- local function find_in_data(data, section_name, key_name) +-- if not data or type(data) ~= 'table' then return nil end +-- +-- -- INFO: 1.0 SPECIFIC SEARCH: Look for a specific section (e.g., "platformio") +-- if section_name then +-- for _, section in ipairs(data) do +-- if type(section) == 'table' and #section >= 2 then +-- local s_id, s_body = section[1], section[2] +-- if s_id == section_name and type(s_body) == "table" then +-- for _, kv in ipairs(s_body) do +-- if type(kv) == "table" and #kv >= 2 and kv[1] == key_name then +-- local val = kv[2] +-- if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then +-- return val +-- end +-- end +-- end +-- end +-- end +-- end +-- end +-- +-- -- INFO: 1.1 FALLBACK SEARCH (If we reach here, Step 1 failed or was skipped) +-- local fallback_env_found = nil +-- for _, section in ipairs(data) do +-- if type(section) == 'table' and #section >= 2 then +-- local s_id = section[1] +-- local s_body = section[2] +-- -- Look for hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] +-- if type(s_id) == 'string' and s_id:find('^env:') then +-- fallback_env_found = s_id:match('^env:(.+)') +-- +-- -- If we were looking for default_envs, we just found our fallback +-- if key_name == 'default_envs' then +-- vim.schedule(function() +-- vim.notify("PIO: 'default_envs' empty. Falling back to: " .. fallback_env_found, vim.log.levels.INFO) +-- end) +-- return fallback_env_found +-- end +-- +-- -- If looking for a key (like 'platform') inside this fallback env +-- if type(s_body) == 'table' then +-- for _, kv in ipairs(s_body) do +-- if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then +-- local val = kv[2] +-- if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then +-- vim.schedule(function() +-- vim.notify("PIO: Using '" .. key_name .. "' from fallback env: " .. fallback_env_found, vim.log.levels.INFO) +-- end) +-- return val +-- end +-- end +-- end +-- end +-- end +-- end +-- end +-- +-- -- INFO: 1.2 FINAL ERROR If even fallback fails +-- if key_name == 'platform' or key_name == 'packages_dir' then +-- vim.schedule(function() +-- vim.notify("PIO: Critical key '" .. key_name .. "' not found anywhere!", vim.log.levels.INFO) +-- end) +-- end +-- return nil +-- end +-- ------------------------------------------------------------------------------------------ +-- +-- -- INFO: 2. Asynchronous Refresh +-- local function refresh(callback) +-- -- Using vim.system to detect if the command exists +-- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) +-- if obj.code ~= 0 then +-- -- Schedule notification to avoid error in the system callback thread +-- vim.schedule(function() +-- if obj.code == 127 then +-- vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) +-- else +-- vim.notify('PIO Manager: Failed to fetch config (Error ' .. obj.code .. ')', vim.log.levels.WARN) +-- end +-- end) +-- return +-- end +-- local ok, decoded = pcall(vim.json.decode, obj.stdout) +-- if ok and decoded then +-- cache = decoded +-- if not cache or type(cache) ~= 'table' then +-- print('no cahce') +-- else +-- print('cahced ok') +-- end +-- if callback then vim.schedule(callback) end +-- end +-- end) +-- end +-- return { +-- refresh = refresh, +-- get = function(s, k) +-- return find_in_data(cache, s, k) +-- end, +-- } +-- end)() +-- +-- ------------------------------------------------------------------------------------------------------ +-- -- INFO: 2. Generic Toolchain & Sysroot Logic. These functions identify where the compiler and its C++ headers live. +-- -- Gets the compiler glob for clangd --query-driver +-- -- stylua: ignore +-- function _G.get_pio_toolchain_pattern() +-- local active_env = vim.g.pio_active_env or pio_manager.get("platformio", "default_envs") +-- -- or pio_manager.get(nil, "default_envs") +-- +-- -- Handle default_envs being a list/table +-- if type(active_env) == 'table' then active_env = active_env[1] end +-- +-- local target_env = active_env and ('env:' .. active_env) or nil +-- local platform = pio_manager.get(target_env, 'platform') +-- local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('HOME') or os.getenv('USERPROFILE') .. '/.platformio/packages') +-- +-- if not platform then return '/**/bin/*' end +-- +-- -- Sync call for toolchain name +-- local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') +-- if not p_handle then return '/**/bin/*' end +-- +-- local p_json = p_handle:read('*all') +-- p_handle:close() +-- local arch_glob = '/**/bin/*' +-- local p_ok, p_data = pcall(vim.json.decode, p_json) +-- if p_ok and p_data and type(p_data.packages) == 'table' then +-- for pkg_name, _ in pairs(p_data.packages) do +-- if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then +-- local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') +-- arch_glob = '/**/bin/*' .. arch .. '*' +-- break +-- end +-- end +-- end +-- -- local final = (packages_dir:gsub('\\', '/') .. arch_glob):gsub('//+', '/') +-- local final = packages_dir .. arch_glob +-- print('toolchain 5: final=' .. final) +-- return (misc.normalize_path(final)) +-- -- return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final +-- end +-- +-- -- INFO: 3. Patches compile_commands.json with --sysroot to fix +-- -- Helper to generate the compilation database +-- -- stylua: ignore +-- local function pio_generate_db() +-- -- This runs in the background so it doesn't freeze Neovim +-- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) +-- if obj.code ~= 0 then return end +-- print('pio_generate_db 0') +-- local pattern = _G.get_pio_toolchain_pattern() +-- local toolchain_root = pattern:match('(.*toolchain%-[^/\\]+)') +-- if not toolchain_root or vim.fn.isdirectory(toolchain_root) == 0 then +-- return +-- end +-- +-- -- Find subdirectory containing 'include' (the sysroot) +-- local sysroot_path = nil +-- local subdirs = vim.fn.getcompletion(toolchain_root .. '/*', 'dir') +-- for _, dir in ipairs(subdirs) do +-- if vim.fn.isdirectory(dir .. '/include') == 1 then +-- sysroot_path = dir:gsub('\\', '/') +-- break +-- end +-- end +-- if sysroot_path then +-- local db_path = vim.fn.getcwd() .. '/compile_commands.json' +-- local f = io.open(db_path, 'r') +-- if not f then return end +-- local content = f:read('*all') +-- f:close() +-- +-- -- patch sysroot +-- local patched = content:gsub('("-i")', '"--sysroot=' .. sysroot_path .. '", %1') +-- local out = io.open(db_path, 'w') +-- if out then +-- out:write(patched) +-- out:close() +-- vim.schedule(function() vim.notify('PIO: DB & Sysroot Patched') end) +-- end +-- end +-- end) +-- end +-- +-- ------------------------------------------------------------------------------------------------------ +-- -- INFO: 4. Automation & File Watcher +-- --This handles the background synchronization when you save your project. +-- -- stylua: ignore +-- local function start_pio_watcher() +-- local path = vim.fn.getcwd() .. '/platformio.ini' +-- if vim.fn.filereadable(path) == 0 then return end +-- +-- local w = vim.uv.new_fs_event() +-- if not w then return end +-- +-- w:start( +-- path, {}, +-- vim.schedule_wrap(function(err, _, events) +-- if err or not events.change then return end +-- +-- -- 1. Stop any existing timer (cancel previous "half-finished" events) +-- if debounce_timer then +-- debounce_timer:stop() +-- +-- -- 2. Start a 500ms window. Logic only runs if NO more events happen in this time. +-- debounce_timer:start( 500, 0, +-- vim.schedule_wrap(function() +-- vim.notify('PIO: Config change detected. Refreshing...', vim.log.levels.INFO) +-- +-- pio_manager.refresh(function() +-- pio_generate_db() +-- -- 3. Only restart LSP if the pattern actually changed or DB was updated +-- lsp.lsp_restart('clangd') +-- end) +-- end) +-- ) +-- end +-- end) +-- ) +-- end +-- +-- ------------------------------------------------------------------------------------------------------ +-- -- INFO: 6. Exported setup function +-- return { +-- init = function() +-- local config = require('platformio').config +-- if config.lspClangd.enabled == true then +-- vim.notify('PIO setup initialize', vim.log.levels.INFO) +-- ---------------------------------------------------------------------------------------- +-- -- INFO: create clangd required files +-- ----------------------------------------------------------------------------------------- +-- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +-- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) +-- +-- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +-- boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) +-- -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) +-- -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') +-- +-- -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) +-- +-- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) +-- +-- boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) +-- -- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) +-- -- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) +-- --------------------------------------------------------------------------------- +-- +-- -- vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) +-- require('platformio.lspConfig.clangd') +-- if config.lspClangd.attach.enabled then +-- require('platformio.lspConfig.attach') +-- end +-- if vim.fn.filereadable(vim.fn.getcwd() .. '/platformio.ini') == 1 then +-- pio_manager.refresh(function() +-- pio_generate_db() +-- start_pio_watcher() +-- end) +-- end +-- end +-- end, +-- } From b715c2aa02b35e4d9cc3b96d4dc0cb6304245544 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 05:53:27 +0300 Subject: [PATCH 0567/1406] update --- lua/platformio/lspConfig/clangd.lua | 5 +- lua/platformio/pio_setup.lua | 8 +- lua/platformio/utils/pio.lua | 148 +--------------------------- mini_nvimPlatformio.lua | 10 +- 4 files changed, 15 insertions(+), 156 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 3e662286..638217c1 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -125,7 +125,8 @@ vim.lsp.config('*', { -- INFO: configure clangd lsp server ----------------------------------------------------------------------------------------- local cmd = { 'clangd' } -local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) +-- local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) +local fname = string.format('%s/.clangd_cmd', vim.uv.cwd()) -- if vim.fn.filereadable(fname) == 1 then if vim.uv.fs_stat(fname) then ok, result = pcall(vim.fn.readfile, fname) @@ -156,7 +157,7 @@ local clangd = { completeUnimported = true, fallback_flags = { '-std=c++17' }, clangdFileStatus = true, - compilationDatabasePath = vim.fn.getcwd(), + compilationDatabasePath = vim.uv.cwd(), }, } vim.lsp.config('clangd', clangd) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 1336199f..4498a825 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -149,7 +149,7 @@ function _G.get_pio_toolchain_pattern() if vim.fn.isdirectory(check_path) == 1 then toolchain_folder = pkg.name -- Verification: Match the toolchain name against the compiler used in compile_commands.json - local db_path = vim.fn.getcwd() .. '/compile_commands.json' + local db_path = vim.uv.cwd() .. '/compile_commands.json' local f = io.open(db_path, 'r') if f then local head = f:read(2048) -- Read enough to find the compiler path @@ -203,7 +203,7 @@ local function pio_generate_db() end if sysroot_path then - local db_path = vim.fn.getcwd() .. '/compile_commands.json' + local db_path = vim.uv.cwd() .. '/compile_commands.json' local f = io.open(db_path, 'r') if not f then return @@ -229,7 +229,7 @@ end -- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync local function start_pio_watcher() - local path = vim.fn.getcwd() .. '/platformio.ini' + local path = vim.uv.cwd() .. '/platformio.ini' if vim.fn.filereadable(path) == 0 then return end @@ -297,7 +297,7 @@ return { if config.lspClangd.attach.enabled then require('platformio.lspConfig.attach') end - if vim.fn.filereadable(vim.fn.getcwd() .. '/platformio.ini') == 1 then + if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then pio_manager.refresh(function() pio_generate_db() start_pio_watcher() diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f604409a..1a0f2f46 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -64,155 +64,11 @@ function M.get_pio_dir(type) result = misc.normalize_path(result) --result:gsub('\\', '/'):gsub('//+', '/') return result end --- function M.get_pio_dir(type) --- -- 1. Setup Base Paths --- local home = os.getenv('HOME') or os.getenv('USERPROFILE') --- --- -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) --- local map = { --- core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, --- packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, --- platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, --- } --- --- local target_config = map[type] --- if not target_config then return nil end --- --- -- 3. Try to get explicit value from platformio.ini --- local path = vim.fn.getcwd() .. '/platformio.ini' --- local inifile = io.open(path, 'r') --- local ini_val = nil --- local core_val = nil --- ----------------------------------------------------- --- --- --- ----------------------------------------------------- --- --- if inifile then --- for line in inifile:lines() do --- if core_val == nil then core_val = line:match('^%s*' .. map['core'].ini .. '%s*=%s*([^;%s]+)') end --- if ini_val == nil then ini_val = line:match('^%s*' .. target_config.ini .. '%s*=%s*([^;%s]+)') end --- if ini_val and core_val then break end --- end --- inifile:close() --- end --- --- -- 4.0 Fallback Logic: INI -> Env Var -> Default --- local core_dir = core_val or os.getenv('PLATFORMIO_CORE_DIR' or (home .. map['core'].sub)):gsub('[\\/]+$', '') --- core_dir = misc.normalize_path(core_dir) --core_dir:gsub('\\', '/'):gsub('//+', '/') --- -- if vim.fn.has('win32') == 1 then core_dir = core_dir:gsub('/', '\\') end --- if type == 'core' then return core_dir end --- --- -- 4.1 Fallback Logic: INI -> Env Var -> Default --- local result = ini_val or os.getenv(target_config.env) or (core_dir .. target_config.sub) --- --- -- 5. Expand ${platformio.core_dir} --- if result:find('${platformio.core_dir}', 1, true) then result = result:gsub('%${platformio.core_dir}', core_dir) end --- --- -- 6. Normalize Slashes for Windows --- result = misc.normalize_path(result) --result:gsub('\\', '/'):gsub('//+', '/') --- -- if vim.fn.has('win32') == 1 then result = result:gsub('/', '\\') end --- --- -- Ensure core_dir itself doesn't have trailing slashes for cleaner joins --- return result --- end ------------------------------------------------------- - --- stylua: ignore --- function _G.get_pio_toolchain_pattern() --- local cwd = vim.fn.getcwd() --- local cache_key = cwd .. (vim.g.pio_active_env or 'auto') --- --- _G._pio_cache = _G._pio_cache or {} --- if _G._pio_cache[cache_key] then return _G._pio_cache[cache_key] end --- --- local handle = io.popen('pio project config --json-output') --- if not handle then return '/toolchain-*/**/bin/*' end --- local json_str = handle:read('*all') --- handle:close() --- --- local ok, config = pcall(vim.json.decode, json_str) --- if not ok or not config then return '/toolchain-*/**/bin/*' end --- --- local active_env = vim.g.pio_active_env --- local target_platform = nil --- local core_dir = (os.getenv('HOME') or os.getenv('USERPROFILE')) .. '/.platformio' --- if active_env then print('active_env0: ' .. active_env) end --- -- 1. Pass One: Extract default_envs and core_dir from 'platformio' section --- if not active_env then --- for _, section in ipairs(config) do --- if section[1] == 'platformio' then --- for _, kv in ipairs(section[2]) do --- if kv[1] == 'default_envs' then --- active_env = tostring(kv[2]):match('([^,%s]+)') --- end --- if kv[1] == 'core_dir' then --- core_dir = kv[2] --- end --- end --- end --- end --- end --- --- if active_env then print(vim.inspect(active_env)) end --- -- 2. Pass Two: Find the platform for the active environment --- for _, section in ipairs(config) do --- local name = section[1] --- if active_env and (name == 'env:' .. active_env or name == active_env) then --- for _, kv in ipairs(section[2]) do --- if kv[1] == 'platform' then target_platform = kv[2] end --- end --- end --- end --- --- -- 3. Fallback: If still nothing, take the first platform from any 'env:' section --- if not target_platform then --- for _, section in ipairs(config) do --- if type(section[1]) == 'string' and section[1]:find('^env:') then --- for _, kv in ipairs(section[2]) do --- if kv[1] == 'platform' then target_platform = kv[2] end --- end --- if target_platform then --- break --- end --- end --- end --- end --- --- if not target_platform then return '/toolchain-*/**/bin/*' end --- if active_env then print('target_platform4: ' .. target_platform) end --- --- -- 4. Query the platform for the toolchain package name --- local p_handle = io.popen('pio platform show ' .. target_platform .. ' --json-output') --- if not p_handle then return '/toolchain-*/**/bin/*' end --- local p_json = p_handle:read('*all') --- p_handle:close() --- --- local p_ok, p_data = pcall(vim.json.decode, p_json) --- if not p_ok or not p_data.packages then return '/toolchain-*/**/bin/*' end --- --- -- 5. Extract Arch --- local arch_glob = '/toolchain-*/**/bin/*' --- for pkg_name, _ in pairs(p_data.packages) do --- if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then --- local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') --- arch_glob = '/**/bin/*' .. arch .. '*' --- break --- end --- end --- --- local final_pattern = (core_dir:gsub('\\', '/') .. '/packages' .. arch_glob):gsub('//+', '/') --- -- if vim.fn.has('win32') == 1 then --- -- final_pattern = final_pattern:gsub('/', '\\') --- -- end --- --- _G._pio_cache[cache_key] = final_pattern --- return final_pattern --- end ------------------------------------------------------ -- stylua: ignore function M.fix_pio_compile_commands() - local filename = vim.fn.getcwd() .. '/compile_commands.json' + local filename = vim.uv.cwd() .. '/compile_commands.json' local file = io.open(filename, 'r') if not file then return end @@ -365,7 +221,7 @@ function M.handlePioinit() vim.notify('Pioinit: Success', vim.log.levels.INFO) local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - boilerplate_gen(M.selected_framework, vim.fn.getcwd() .. '/src', 'main.cpp') + boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') end -- Handle after poioinit execution -- stylua: ignore diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index ab08d93f..2cce1c2e 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -228,14 +228,15 @@ local plugins = { { 'batoaqaa/nvim-platformio.lua', cond = function() - -- local platformioRootDir = vim.fs.root(vim.fn.getcwd(), { 'platformio.ini' }) -- cwd and parents - local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.fn.getcwd() or nil + -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.fn.getcwd() or nil + local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.uv.cwd() or nil if platformioRootDir and vim.fs.find('.pio', { path = platformioRootDir, type = 'directory' })[1] then -- if platformio.ini file and .pio folder exist in cwd, enable plugin to install plugin (if not istalled) and load it. vim.g.platformioRootDir = platformioRootDir elseif (vim.uv or vim.loop).fs_stat(vim.env.XDG_DATA_HOME .. '/lazy/nvim-platformio.lua') == nil then -- if nvim-platformio not installed, enable plugin to install it first time - vim.g.platformioRootDir = vim.fn.getcwd() + -- vim.g.platformioRootDir = vim.fn.getcwd() + vim.g.platformioRootDir = vim.uv.cwd() else -- if nvim-platformio.lua installed but disabled, create Pioinit command vim.api.nvim_create_user_command('Pioinit', function() --available only if no platformio.ini and .pio in cwd vim.api.nvim_create_autocmd('User', { @@ -250,7 +251,8 @@ local plugins = { end end, }) - vim.g.platformioRootDir = vim.fn.getcwd() + -- vim.g.platformioRootDir = vim.fn.getcwd() + vim.g.platformioRootDir = vim.uv.cwd() require('lazy').restore({ plguins = { 'nvim-platformio.lua' }, show = false }) end, {}) end From 084d43a87318f892225fd682956263a04b68089e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 06:06:59 +0300 Subject: [PATCH 0568/1406] update --- lua/platformio/pio_setup.lua | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 4498a825..a8267695 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -176,9 +176,20 @@ end -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag local function pio_generate_db() + -- Check if we actually have an active environment before running + local active_env = vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') + if not active_env then + -- Silent return or a minor info message + vim.schedule(function() + vim.notify('PIO: No board configured yet. Skipping DB generation.', vim.log.levels.INFO) + end) + return + end + vim.schedule(function() vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) end) + vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) if obj.code ~= 0 then return @@ -299,7 +310,13 @@ return { end if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then pio_manager.refresh(function() - pio_generate_db() + -- We check if we have data inside the refresh callback + local env = pio_manager.get('platformio', 'default_envs') + if env then + pio_generate_db() + start_pio_watcher() + end + -- pio_generate_db() start_pio_watcher() end) end From cfbc384c8ed5b22efc345bd3da4f8073dc8c5ac1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 08:36:01 +0300 Subject: [PATCH 0569/1406] update --- lua/platformio/boilerplate.lua | 5 ++- lua/platformio/pio_setup.lua | 59 ++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 3 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index ba971104..841598a4 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -92,9 +92,8 @@ clangd --query-driver=%s ]], content = function(self) - -- local pio = require('platformio.utils.pio') - -- return string.format(self.template, pio.get_pio_dir('packages') or '**') - return string.format(self.template, _G.get_pio_toolchain_pattern() or '**') + -- return string.format(self.template, _G.get_pio_toolchain_pattern() or '**') + return string.format(self.template, _G.get_pio_sdk_info() or '**') end, --header-insertion=iwyu --header-insertion-decorators diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index a8267695..b6689dbb 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -55,6 +55,13 @@ local pio_manager = (function() local ok, decoded = pcall(vim.json.decode, obj.stdout) if ok and decoded then cache = decoded + vim.schedule(function() + if not cache or type(cache) ~= 'table' then + vim.notify('PIO: Fetching Config failed. Check platformio.ini syntax.', vim.log.levels.INFO) + else + vim.notify('PIO: Fetching Config successful', vim.log.levels.INFO) + end + end) if callback then vim.schedule(callback) end @@ -109,6 +116,58 @@ local pio_manager = (function() } end)() +function _G.get_pio_sdk_info() + local pio_info = { includes = {}, cc_path = '' } + if vim.fn.filereadable('platformio.ini') == 0 then + return nil + end + + local handle = io.popen('pio run -t envdump') + if not handle then + return nil + end + + local packages_dir, cc_name, toolchain_pkg = '', '', '' + + for line in handle:lines() do + -- 1. Get the global packages directory + packages_dir = packages_dir ~= '' and packages_dir or line:match("'PROJECT_PACKAGES_DIR': '([^']+)'") + + -- 2. Get the compiler executable name (e.g., riscv32-esp-elf-gcc) + cc_name = cc_name ~= '' and cc_name or line:match("'CC': '([^']+)'") + + -- 3. Find the specific toolchain package name from the PACKAGES list + -- Matches lines like "- toolchain-riscv32-esp @ 14.2.0" + local pkg = line:match('%- (toolchain%-[^ ]+)') + if pkg then + toolchain_pkg = pkg + end + + -- 4. Collect include paths + local path_list = line:match("'CPPPATH': %[(.+)%]") + if path_list then + for path in path_list:gmatch("'([^']+)'") do + table.insert(pio_info.includes, '-I' .. path) + end + end + end + handle:close() + + -- Construct the absolute path: //bin/ + if packages_dir ~= '' and toolchain_pkg ~= '' and cc_name ~= '' then + local full_path = packages_dir .. '/' .. toolchain_pkg .. '/bin/' .. cc_name + if vim.fn.executable(full_path) == 1 then + pio_info.cc_path = full_path + end + end + + local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' + print('toolchain 5: final=' .. final) + -- Normalize paths for the OS and ensure backslashes for Windows if needed + return (misc.normalize_path(final)) + -- return pio_info +end + -- LSP HELPER: Returns the glob pattern for clangd's --query-driver -- e.g., C:\Users\tom\.platformio\packages\toolchain-riscv32-esp\bin\* function _G.get_pio_toolchain_pattern() From 0bd1a5a97c4b8ca9ee52bb815d6fc150d333f6ba Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 09:01:10 +0300 Subject: [PATCH 0570/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/pioCommands.lua | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 841598a4..844ad88b 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -23,7 +23,7 @@ void loop() { -- INFO: platformio.ini boilerplate['platformio.ini'] = { - rewrite = true, + rewrite = false, template = [[ [platformio] core_dir = %s diff --git a/lua/platformio/pioCommands.lua b/lua/platformio/pioCommands.lua index 2f0ef23f..647cabfd 100644 --- a/lua/platformio/pioCommands.lua +++ b/lua/platformio/pioCommands.lua @@ -5,7 +5,7 @@ local ToggleTerminal = require('platformio.utils.term').ToggleTerminal -- stylua: ignore function M.piolsp() - require('platformio.utils.lsp').lsp_restart() + require('platformio.utils.lsp').lsp_restart('clangd') -- local ok, err = pcall(vim.cmd.lsp, { args = { 'restart' } }) -- if ok then vim.notify('LSP restarted' .. err) -- else vim.notify('LSP restart failed: ' .. err) end From 253dd7f32b0783c245f5e1f21efb1489bfd7b448 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 10:08:03 +0300 Subject: [PATCH 0571/1406] update --- lua/platformio/pio_setup.lua | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b6689dbb..90ed2eda 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -110,8 +110,11 @@ local pio_manager = (function() end end end + elseif k == 'default_envs' and res and type(res) == 'table' then + return res[1] + else + return res end - return res end, } end)() From 3ad54359f6e073abc5649e07d1d9db4b8c102aa4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 10:14:50 +0300 Subject: [PATCH 0572/1406] update --- lua/platformio/pio_setup.lua | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 90ed2eda..144a5c7c 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -110,6 +110,9 @@ local pio_manager = (function() end end end + vim.schedule(function() + vim.notify('PIO: Config Error. Check platformio.ini no env', vim.log.levels.WARN) + end) elseif k == 'default_envs' and res and type(res) == 'table' then return res[1] else From 8f1c43c0453dcb4030237374b91e847aa4a91afd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 10:21:02 +0300 Subject: [PATCH 0573/1406] update --- lua/platformio/pio_setup.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 144a5c7c..aaa6eacb 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -168,7 +168,7 @@ function _G.get_pio_sdk_info() end local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' - print('toolchain 5: final=' .. final) + print('get_pio_sdk_info(): final=' .. final) -- Normalize paths for the OS and ensure backslashes for Windows if needed return (misc.normalize_path(final)) -- return pio_info @@ -233,7 +233,7 @@ function _G.get_pio_toolchain_pattern() end local final = packages_dir .. toolchain_folder - print('toolchain 5: final=' .. final) + print('get_pio_toolchain 5: final=' .. final) -- Normalize paths for the OS and ensure backslashes for Windows if needed return (misc.normalize_path(final)) -- return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final From ef2042c5a38a1966cb8a66036c2c1517d9f4f3ff Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 10:33:20 +0300 Subject: [PATCH 0574/1406] update --- lua/platformio/pio_setup.lua | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index aaa6eacb..5118a656 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -160,7 +160,7 @@ function _G.get_pio_sdk_info() handle:close() -- Construct the absolute path: //bin/ - if packages_dir ~= '' and toolchain_pkg ~= '' and cc_name ~= '' then + if packages_dir and packages_dir ~= '' and toolchain_pkg and toolchain_pkg ~= '' and cc_name ~= '' then local full_path = packages_dir .. '/' .. toolchain_pkg .. '/bin/' .. cc_name if vim.fn.executable(full_path) == 1 then pio_info.cc_path = full_path @@ -240,9 +240,11 @@ function _G.get_pio_toolchain_pattern() end -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag +-- stylua: ignore local function pio_generate_db() -- Check if we actually have an active environment before running local active_env = vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') + if not active_env then -- Silent return or a minor info message vim.schedule(function() @@ -251,21 +253,19 @@ local function pio_generate_db() return end - vim.schedule(function() - vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) - end) + vim.schedule(function() vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) end) vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) - if obj.code ~= 0 then - return - end + if obj.code ~= 0 then return end -- Isolate the toolchain root from the pattern (e.g. .../toolchain-riscv32-esp) - local pattern = _G.get_pio_toolchain_pattern() - local toolchain_root = pattern:match('(.-toolchain%-[^/\\]+)') - if not toolchain_root or vim.fn.isdirectory(toolchain_root) == 0 then - return - end + -- local pattern = _G.get_pio_toolchain_pattern() + local pattern = _G.get_pio_sdk_info() + + local toolchain_root = nil + if pattern then toolchain_root = pattern:match('(.-toolchain%-[^/\\]+)') end + + if not toolchain_root or vim.fn.isdirectory(toolchain_root) == 0 then return end -- FIND SYSROOT: Locate the internal folder that contains the /include directory -- This folder is necessary for clangd to find standard C++ headers like @@ -281,9 +281,7 @@ local function pio_generate_db() if sysroot_path then local db_path = vim.uv.cwd() .. '/compile_commands.json' local f = io.open(db_path, 'r') - if not f then - return - end + if not f then return end local content = f:read('*all') f:close() From 69380bf5f12140be7d5b9297156b2a2b0183b55d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 11:48:25 +0300 Subject: [PATCH 0575/1406] update --- lua/platformio/pio_setup.lua | 41 +++++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 5118a656..fe3856e8 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -269,12 +269,31 @@ local function pio_generate_db() -- FIND SYSROOT: Locate the internal folder that contains the /include directory -- This folder is necessary for clangd to find standard C++ headers like + -- local sysroot_path = nil + -- local subdirs = vim.fn.getcompletion(toolchain_root .. '/*', 'dir') + -- for _, dir in ipairs(subdirs) do + -- if vim.fn.isdirectory(dir .. '/include') == 1 then + -- sysroot_path = dir:gsub('\\', '/') + -- break + -- end + -- end + local sysroot_path = nil - local subdirs = vim.fn.getcompletion(toolchain_root .. '/*', 'dir') - for _, dir in ipairs(subdirs) do - if vim.fn.isdirectory(dir .. '/include') == 1 then - sysroot_path = dir:gsub('\\', '/') - break + local handle = vim.uv.fs_scandir(toolchain_root) + if handle then + while true do + local name, type = vim.uv.fs_scandir_next(handle) + if not name then break end + -- Check if the entry is a directory (or a symlink to one) + if type == "directory" or type == "link" then + local full_path = toolchain_root .. '/' .. name + -- Check if 'include' exists inside this directory + local stat = vim.uv.fs_stat(full_path .. '/include') + if stat and stat.type == "directory" then + sysroot_path = full_path:gsub('\\', '/') + break + end + end end end @@ -328,6 +347,18 @@ local function start_pio_watcher() 0, vim.schedule_wrap(function() pio_manager.refresh(function() + vim.system({ 'pio', 'project', 'metadata', '--json-output-path', 'pio_metadata.json' }, { text = true }, function(obj) + if obj.code == 0 then + vim.schedule(function() + print('PIO Metadata updated!') + vim.cmd('LspRestart clangd') + end) + else + vim.schedule(function() + print('PIO Metadata failed: ' .. obj.stderr) + end) + end + end) pio_generate_db() lsp.lsp_restart('clangd') vim.notify('PIO: Syncing Environment...') From 99db6d675373af66861d8514e9c8b667a3be14aa Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 15:28:13 +0300 Subject: [PATCH 0576/1406] update --- lua/platformio/pio_setup.lua | 158 ++++++++++++++++++++++------------- 1 file changed, 98 insertions(+), 60 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index fe3856e8..b853c597 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,3 +1,6 @@ +M = {} + +M.metadata = nil local misc = require('platformio.utils.misc') local lsp = require('platformio.utils.lsp') @@ -170,7 +173,8 @@ function _G.get_pio_sdk_info() local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' print('get_pio_sdk_info(): final=' .. final) -- Normalize paths for the OS and ensure backslashes for Windows if needed - return (misc.normalize_path(final)) + -- return (misc.normalize_path(final)) + return M.metadata.driver_path -- return pio_info end @@ -322,8 +326,8 @@ end -- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync local function start_pio_watcher() - local path = vim.uv.cwd() .. '/platformio.ini' - if vim.fn.filereadable(path) == 0 then + local platformioini = vim.uv.cwd() .. '/platformio.ini' + if vim.fn.filereadable(platformioini) == 0 then return end @@ -332,7 +336,7 @@ local function start_pio_watcher() return end w:start( - path, + platformioini, {}, vim.schedule_wrap(function(err, _, events) if err or not events or not events.change then @@ -347,21 +351,55 @@ local function start_pio_watcher() 0, vim.schedule_wrap(function() pio_manager.refresh(function() - vim.system({ 'pio', 'project', 'metadata', '--json-output-path', 'pio_metadata.json' }, { text = true }, function(obj) - if obj.code == 0 then - vim.schedule(function() - print('PIO Metadata updated!') - vim.cmd('LspRestart clangd') - end) - else - vim.schedule(function() - print('PIO Metadata failed: ' .. obj.stderr) - end) + vim.system({ 'pio', 'project', 'metadata', '--json-output' }, { text = true }, function(obj) + -- Error Checking: obj.code 0 means success + if obj.code == 0 and obj.stdout then + local ok, raw_data = pcall(vim.json.decode, obj.stdout) + if ok and raw_data then + local _, env = next(raw_data) + if not env then + return + end + local fallback_flags = {} + -- 1. Process Includes + if env.includes then + for category, paths in pairs(env.includes) do + -- If it's a toolchain path, use -isystem to suppress warnings + -- and tell clangd these are standard libraries + local flag = (category == 'toolchain') and '-isystem' or '-I' + + for _, path in ipairs(paths) do + table.insert(fallback_flags, flag .. path) + end + end + end + -- 2. Process Defines + if env.defines then + for _, define in ipairs(env.defines) do + table.insert(fallback_flags, '-D' .. define) + end + end + M.metadata = { + driver_path = env.cc_path:match('(.*[/\\])') .. '/*', + cc_path = env.cc_path or '', + fallback_flags = fallback_flags, + } + -- M.metadata = decoded + vim.schedule(function() + pio_generate_db() + lsp.lsp_restart('clangd') + vim.notify('PIO: Syncing Environment successful') + end) + else + vim.schedule(function() + vim.notify('PIO: Syncing Environment failed') + end) + end end end) - pio_generate_db() - lsp.lsp_restart('clangd') - vim.notify('PIO: Syncing Environment...') + -- pio_generate_db() + -- lsp.lsp_restart('clangd') + -- vim.notify('PIO: Syncing Environment...') end) end) ) @@ -372,48 +410,48 @@ end ------------------------------------------------------------------------------------------------------ -- INFO: 6. Exported setup function -return { - init = function() - local config = require('platformio').config - if config.lspClangd.enabled == true then - vim.notify('PIO setup initialize', vim.log.levels.INFO) - ---------------------------------------------------------------------------------------- - -- INFO: create clangd required files - ----------------------------------------------------------------------------------------- - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) - - boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) - -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) - -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') - - -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - - boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) - - boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) - -- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) - -- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) - --------------------------------------------------------------------------------- - - -- vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) - require('platformio.lspConfig.clangd') - if config.lspClangd.attach.enabled then - require('platformio.lspConfig.attach') - end - if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then - pio_manager.refresh(function() - -- We check if we have data inside the refresh callback - local env = pio_manager.get('platformio', 'default_envs') - if env then - pio_generate_db() - start_pio_watcher() - end - -- pio_generate_db() +function M.init() + local config = require('platformio').config + if config.lspClangd.enabled == true then + vim.notify('PIO setup initialize', vim.log.levels.INFO) + ---------------------------------------------------------------------------------------- + -- INFO: create clangd required files + ----------------------------------------------------------------------------------------- + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) + + boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) + -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) + -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') + + -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + + boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) + + boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) + -- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) + -- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) + --------------------------------------------------------------------------------- + + -- vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) + require('platformio.lspConfig.clangd') + if config.lspClangd.attach.enabled then + require('platformio.lspConfig.attach') + end + if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then + pio_manager.refresh(function() + -- We check if we have data inside the refresh callback + local env = pio_manager.get('platformio', 'default_envs') + if env then + pio_generate_db() start_pio_watcher() - end) - end + end + -- pio_generate_db() + start_pio_watcher() + end) end - end, -} + end +end + +return M From e90c7714526c83c93313dbb7cc203f8db08afb67 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 15:52:00 +0300 Subject: [PATCH 0577/1406] update --- lua/platformio/pio_setup.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b853c597..3265094e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -173,8 +173,9 @@ function _G.get_pio_sdk_info() local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' print('get_pio_sdk_info(): final=' .. final) -- Normalize paths for the OS and ensure backslashes for Windows if needed - -- return (misc.normalize_path(final)) - return M.metadata.driver_path + print(M.metadata.driver_path) + return (misc.normalize_path(final)) + -- return M.metadata.driver_path -- return pio_info end From aa94552f97a18cebc96fd55bd92d77c39f69dba6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 15:53:10 +0300 Subject: [PATCH 0578/1406] update --- lua/platformio/pio_setup.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 3265094e..7f7610c6 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,6 +1,6 @@ M = {} -M.metadata = nil +M.metadata = {} local misc = require('platformio.utils.misc') local lsp = require('platformio.utils.lsp') @@ -173,9 +173,9 @@ function _G.get_pio_sdk_info() local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' print('get_pio_sdk_info(): final=' .. final) -- Normalize paths for the OS and ensure backslashes for Windows if needed - print(M.metadata.driver_path) - return (misc.normalize_path(final)) - -- return M.metadata.driver_path + -- print(M.metadata.driver_path) + -- return (misc.normalize_path(final)) + return M.metadata.driver_path -- return pio_info end From 683e6e438f72635f9fc604db5f1210b1916c003f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 15:58:57 +0300 Subject: [PATCH 0579/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 7f7610c6..c8aaa570 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -381,7 +381,7 @@ local function start_pio_watcher() end end M.metadata = { - driver_path = env.cc_path:match('(.*[/\\])') .. '/*', + driver_path = env.cc_path:match('(.*[/\\])') .. '/*' or '**', cc_path = env.cc_path or '', fallback_flags = fallback_flags, } From d6f16c1682955e1f3f8e59c728053164550f10eb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 16:03:50 +0300 Subject: [PATCH 0580/1406] update --- lua/platformio/pio_setup.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index c8aaa570..0190e5a6 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -173,9 +173,9 @@ function _G.get_pio_sdk_info() local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' print('get_pio_sdk_info(): final=' .. final) -- Normalize paths for the OS and ensure backslashes for Windows if needed - -- print(M.metadata.driver_path) - -- return (misc.normalize_path(final)) - return M.metadata.driver_path + print(vim.inspect(M.metadata)) + return (misc.normalize_path(final)) + -- return M.metadata.driver_path -- return pio_info end From 40f8385ba280d0f8289be71f300fe82aa25becd2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 13 Apr 2026 16:07:05 +0300 Subject: [PATCH 0581/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 0190e5a6..7adb17b3 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,6 +1,6 @@ M = {} -M.metadata = {} +M.metadata = nil local misc = require('platformio.utils.misc') local lsp = require('platformio.utils.lsp') From 13c8a4e600d14774c33d6cc5a7f6a31990a3e443 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 07:31:37 +0300 Subject: [PATCH 0582/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/pio_setup.lua | 102 ++++++++++++++++++--------------- mini_nvimPlatformio.lua | 5 +- 3 files changed, 62 insertions(+), 47 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 844ad88b..c469da39 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -44,7 +44,7 @@ monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dt ;extra_scripts = ; pre:enable_toolchain.py ; enabled global env 'PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN' -lib_ldf_mode = chain+ ;Library dependencies Finder ldf +lib_ldf_mode = chain ;Library dependencies Finder ldf ]], content = function(self) -- local pio = require('platformio.utils.pio') diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 7adb17b3..f4efa67a 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -352,55 +352,58 @@ local function start_pio_watcher() 0, vim.schedule_wrap(function() pio_manager.refresh(function() - vim.system({ 'pio', 'project', 'metadata', '--json-output' }, { text = true }, function(obj) - -- Error Checking: obj.code 0 means success - if obj.code == 0 and obj.stdout then - local ok, raw_data = pcall(vim.json.decode, obj.stdout) - if ok and raw_data then - local _, env = next(raw_data) - if not env then - return - end - local fallback_flags = {} - -- 1. Process Includes - if env.includes then - for category, paths in pairs(env.includes) do - -- If it's a toolchain path, use -isystem to suppress warnings - -- and tell clangd these are standard libraries - local flag = (category == 'toolchain') and '-isystem' or '-I' - - for _, path in ipairs(paths) do - table.insert(fallback_flags, flag .. path) + local board_env = pio_manager.get('platformio', 'default_envs') + if board_env then + vim.system({ 'pio', 'project', 'metadata', '-e', board_env, '--json-output' }, { text = true }, function(obj) + -- Error Checking: obj.code 0 means success + if obj.code == 0 and obj.stdout then + local ok, raw_data = pcall(vim.json.decode, obj.stdout) + if ok and raw_data then + local _, env = next(raw_data) + if not env then + return + end + local fallback_flags = {} + -- 1. Process Includes + if env.includes then + for category, paths in pairs(env.includes) do + -- If it's a toolchain path, use -isystem to suppress warnings + -- and tell clangd these are standard libraries + local flag = (category == 'toolchain') and '-isystem' or '-I' + + for _, path in ipairs(paths) do + table.insert(fallback_flags, flag .. path) + end end end - end - -- 2. Process Defines - if env.defines then - for _, define in ipairs(env.defines) do - table.insert(fallback_flags, '-D' .. define) + -- 2. Process Defines + if env.defines then + for _, define in ipairs(env.defines) do + table.insert(fallback_flags, '-D' .. define) + end end + M.metadata = { + driver_path = env.cc_path:match('(.*[/\\])') .. '/*' or '**', + cc_path = env.cc_path or '', + fallback_flags = fallback_flags, + } + -- M.metadata = decoded + vim.schedule(function() + pio_generate_db() + lsp.lsp_restart('clangd') + vim.notify('PIO: Syncing Environment successful') + end) + else + vim.schedule(function() + vim.notify('PIO: Syncing Environment failed') + end) end - M.metadata = { - driver_path = env.cc_path:match('(.*[/\\])') .. '/*' or '**', - cc_path = env.cc_path or '', - fallback_flags = fallback_flags, - } - -- M.metadata = decoded - vim.schedule(function() - pio_generate_db() - lsp.lsp_restart('clangd') - vim.notify('PIO: Syncing Environment successful') - end) - else - vim.schedule(function() - vim.notify('PIO: Syncing Environment failed') - end) end - end - end) - -- pio_generate_db() - -- lsp.lsp_restart('clangd') - -- vim.notify('PIO: Syncing Environment...') + end) + -- pio_generate_db() + -- lsp.lsp_restart('clangd') + -- vim.notify('PIO: Syncing Environment...') + end end) end) ) @@ -435,7 +438,6 @@ function M.init() -- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) --------------------------------------------------------------------------------- - -- vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) require('platformio.lspConfig.clangd') if config.lspClangd.attach.enabled then require('platformio.lspConfig.attach') @@ -455,4 +457,14 @@ function M.init() end end +-- local pio = require('pio_utils') +-- +-- require('lspconfig').clangd.setup({ +-- on_new_config = function(new_config, _) +-- if pio.data then +-- new_config.cmd = { "clangd", "--query-driver=" .. pio.data.cc_path } +-- new_config.init_options = { fallbackFlags = pio.data.fallback_flags } +-- end +-- end +-- }) return M diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 2cce1c2e..f4598f41 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -337,7 +337,10 @@ vim.uv.os_setenv('PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN', 'true') vim.uv.os_setenv('PLATFORMIO_CORE_DIR', platformio_core_dir) vim.g.python_host_prog = pynvim_python vim.g.python3_host_prog = pynvim_python -vim.env.PATH = pynvim_bin .. (isWindows and ';' or ':') .. vim.env.PATH + +vim.env.PATH = pynvim_bin + .. (isWindows and '; C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/bin/ ;' or ': C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/bin/ :') + .. vim.env.PATH vim.env.VIRTUAL_ENV = pynvim_env if vim.fn.isdirectory(platformio_core_dir) == 0 then From f57323307197a9ce5cc4b300a4f3c371c18243ca Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 11:01:05 +0300 Subject: [PATCH 0583/1406] update --- lua/platformio/archived/pio_setup.lua | 2 + lua/platformio/boilerplate.lua | 4 +- lua/platformio/pio_setup.lua | 537 +++++++++++++++----------- lua/platformio/utils/pio.lua | 2 +- pio_setup.lua | 480 +++++++++++++++++++++++ 5 files changed, 787 insertions(+), 238 deletions(-) create mode 100644 pio_setup.lua diff --git a/lua/platformio/archived/pio_setup.lua b/lua/platformio/archived/pio_setup.lua index f929dc42..7f6be736 100644 --- a/lua/platformio/archived/pio_setup.lua +++ b/lua/platformio/archived/pio_setup.lua @@ -2,8 +2,10 @@ -- local lsp = require('platformio.utils.lsp') -- -- local debounce_timer = vim.uv.new_timer() +-- -- -- INFO: 1. The Core PIO Manager & Generic Extractor -- --This manages the data cache and navigates your specific nested-list JSON structure. +-- -- -- stylua: ignore -- local pio_manager = (function() -- local cache = nil diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index c469da39..8417503f 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -92,8 +92,8 @@ clangd --query-driver=%s ]], content = function(self) - -- return string.format(self.template, _G.get_pio_toolchain_pattern() or '**') - return string.format(self.template, _G.get_pio_sdk_info() or '**') + return string.format(self.template, _G.get_pio_toolchain_pattern() or '**') + -- return string.format(self.template, _G.get_pio_sdk_info() or '**') end, --header-insertion=iwyu --header-insertion-decorators diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index f4efa67a..142db8f9 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,8 +1,15 @@ M = {} -M.metadata = nil +M.metadata = { + active_env = '', + driver_path = '', + cc_path = '', + fallback_flags = {}, +} + local misc = require('platformio.utils.misc') local lsp = require('platformio.utils.lsp') +local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -- lua/pio_setup.lua -- This module manages PlatformIO project integration, LSP toolchain detection, @@ -10,9 +17,52 @@ local lsp = require('platformio.utils.lsp') local debounce_timer = vim.uv.new_timer() +-- INFO: +-- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag +-- stylua: ignore +local function pio_generate_db() + vim.schedule(function() vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) end) + vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) + if obj.code ~= 0 then + vim.schedule(function() vim.notify('PIO: Generating Compile Database failed', vim.log.levels.INFO) end) + return + end + vim.schedule(function() vim.notify('PIO: Generating Compile Database successful', vim.log.levels.INFO) end) + end) +end + +-- stylua: ignore +local function GetActivePioEnv() + local file = io.open('platformio.ini', 'r') + if not file then + return nil + end + + local first_env = nil + for line in file:lines() do + -- 1. Try to find the explicit default_envs first + local default = line:match('^default_envs%s*=%s*(%S+)') + if default then + file:close() + return default + end + + -- 2. Capture the first [env:NAME] we see as a fallback + if not first_env then + first_env = line:match('^%[env:(%S+)%]') + end + end + + file:close() + -- Return the first env found if no default was explicitly set + return first_env +end + +-- INFO: 1. The Core PIO Manager & Generic Extractor local pio_manager = (function() local cache = nil -- Stores the decoded platformio.ini JSON structure + -- INFO: -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } local function find_in_data(data, section_name, key_name) @@ -45,52 +95,131 @@ local pio_manager = (function() return nil end + -- INFO: -- ASYNC REFRESH: Fetches the latest config from PlatformIO CLI local function refresh(callback) vim.schedule(function() vim.notify('PIO: Fetching Config...', vim.log.levels.INFO) end) + -- INFO: local function execute_pio(attempts) - -- Use Neovim's async system call to prevent UI freezing - vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) - -- Error Checking: obj.code 0 means success - if obj.code == 0 and obj.stdout then - local ok, decoded = pcall(vim.json.decode, obj.stdout) - if ok and decoded then - cache = decoded + if M.metadata.active_env then + vim.system({ 'pio', 'project', 'metadata', '-e', M.metadata.active_env, '--json-output' }, { text = true }, function(obj) + if obj.code ~= 0 then + -- Schedule notification to avoid error in the system callback thread vim.schedule(function() - if not cache or type(cache) ~= 'table' then - vim.notify('PIO: Fetching Config failed. Check platformio.ini syntax.', vim.log.levels.INFO) + if obj.code == 127 then + vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else - vim.notify('PIO: Fetching Config successful', vim.log.levels.INFO) + vim.notify('PIO Manager: Failed to fetch config (Error ' .. obj.code .. ')', vim.log.levels.WARN) end end) - if callback then - vim.schedule(callback) - end return end - end - - -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save - if attempts > 0 then - vim.defer_fn(function() - execute_pio(attempts - 1) - end, 500) - else - vim.schedule(function() - if obj.code ~= 0 then - vim.notify('PIO: Config Error. Check platformio.ini syntax.', vim.log.levels.WARN) + -- Error Checking: obj.code 0 means success + if obj.code == 0 and obj.stdout then + local ok, raw_data = pcall(vim.json.decode, obj.stdout) + if ok and raw_data then + local _, env = next(raw_data) + if not env then + return + end + local fallback_flags = {} + -- 1. Process Includes + if env.includes then + for category, paths in pairs(env.includes) do + -- If it's a toolchain path, use -isystem to suppress warnings + -- and tell clangd these are standard libraries + local flag = (category == 'toolchain') and '-isystem' or '-I' + + for _, path in ipairs(paths) do + table.insert(fallback_flags, flag .. path) + end + end + end + -- 2. Process Defines + if env.defines then + for _, define in ipairs(env.defines) do + table.insert(fallback_flags, '-D' .. define) + end + end + M.metadata = { + driver_path = env.cc_path:match('(.*[/\\])') .. '/*' or '**', + cc_path = env.cc_path or '', + fallback_flags = fallback_flags, + } + -- M.metadata = decoded + if callback then + vim.schedule(callback) + end + -- vim.schedule(function() + -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + -- pio_generate_db() + -- lsp.lsp_restart('clangd') + -- vim.notify('PIO: Syncing Environment successful') + -- end) + else + vim.schedule(function() + vim.notify('PIO: Syncing Environment failed') + end) end - end) - end - end) + end + -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save + if attempts > 0 then + vim.defer_fn(function() + execute_pio(attempts - 1) + end, 500) + else + vim.schedule(function() + if obj.code ~= 0 then + vim.notify('PIO: Config Error. Check platformio.ini syntax.', vim.log.levels.WARN) + end + end) + end + end) + end + -- Use Neovim's async system call to prevent UI freezing + -- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) + -- -- Error Checking: obj.code 0 means success + -- if obj.code == 0 and obj.stdout then + -- local ok, decoded = pcall(vim.json.decode, obj.stdout) + -- if ok and decoded then + -- cache = decoded + -- vim.schedule(function() + -- if not cache or type(cache) ~= 'table' then + -- vim.notify('PIO: Fetching Config failed. Check platformio.ini syntax.', vim.log.levels.INFO) + -- else + -- vim.notify('PIO: Fetching Config successful', vim.log.levels.INFO) + -- end + -- end) + -- if callback then + -- vim.schedule(callback) + -- end + -- return + -- end + -- end + -- + -- -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save + -- if attempts > 0 then + -- vim.defer_fn(function() + -- execute_pio(attempts - 1) + -- end, 500) + -- else + -- vim.schedule(function() + -- if obj.code ~= 0 then + -- vim.notify('PIO: Config Error. Check platformio.ini syntax.', vim.log.levels.WARN) + -- end + -- end) + -- end + -- end) end execute_pio(1) end + -- INFO: return { refresh = refresh, + -- INFO: get = function(s, k) if not cache then return nil @@ -125,6 +254,7 @@ local pio_manager = (function() } end)() +-- INFO: function _G.get_pio_sdk_info() local pio_info = { includes = {}, cc_path = '' } if vim.fn.filereadable('platformio.ini') == 0 then @@ -179,231 +309,160 @@ function _G.get_pio_sdk_info() -- return pio_info end +-- INFO: -- LSP HELPER: Returns the glob pattern for clangd's --query-driver -- e.g., C:\Users\tom\.platformio\packages\toolchain-riscv32-esp\bin\* function _G.get_pio_toolchain_pattern() - local ok_env, active_env = pcall(function() - return vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') - end) - if not ok_env or not active_env then - return '/**/bin/*' - end - - local target_env = 'env:' .. active_env - local platform = pio_manager.get(target_env, 'platform') - -- Determine the packages directory (Windows vs Linux/Mac home folders) - local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('USERPROFILE') or os.getenv('HOME') .. '/.platformio/packages') - - if not platform then - return '/**/bin/*' - end - - -- Use pio platform show to find which toolchain packages are associated with the platform - local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') - if not p_handle then - return '/**/bin/*' - end - local raw_json = p_handle:read('*all') - p_handle:close() - - local p_ok, p_data = pcall(vim.json.decode, raw_json) - if not p_ok or not p_data or not p_data.packages then - return '/**/bin/*' - end - - local toolchain_folder = '' - for _, pkg in ipairs(p_data.packages) do - -- Skip ULP (low power) toolchains and find the primary one for the architecture - if pkg.name and pkg.name:find('^toolchain%-') and not pkg.name:find('ulp') then - local check_path = (packages_dir .. '/' .. pkg.name):gsub('\\', '/') - if vim.fn.isdirectory(check_path) == 1 then - toolchain_folder = pkg.name - -- Verification: Match the toolchain name against the compiler used in compile_commands.json - local db_path = vim.uv.cwd() .. '/compile_commands.json' - local f = io.open(db_path, 'r') - if f then - local head = f:read(2048) -- Read enough to find the compiler path - f:close() - -- If the DB mentions "riscv32-esp", we ensure we picked the matching folder - if head and head:find(pkg.name:gsub('toolchain%-', '')) then - break - end - end - end - end - end - - if toolchain_folder == '' then - return '/**/bin/*' - end - - local final = packages_dir .. toolchain_folder - print('get_pio_toolchain 5: final=' .. final) - -- Normalize paths for the OS and ensure backslashes for Windows if needed - return (misc.normalize_path(final)) + return M.metadata.driver_path + -- local ok_env, active_env = pcall(function() + -- return vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') + -- end) + -- if not ok_env or not active_env then + -- return '/**/bin/*' + -- end + -- + -- local target_env = 'env:' .. active_env + -- local platform = pio_manager.get(target_env, 'platform') + -- -- Determine the packages directory (Windows vs Linux/Mac home folders) + -- local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('USERPROFILE') or os.getenv('HOME') .. '/.platformio/packages') + -- + -- if not platform then + -- return '/**/bin/*' + -- end + -- + -- -- Use pio platform show to find which toolchain packages are associated with the platform + -- local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') + -- if not p_handle then + -- return '/**/bin/*' + -- end + -- local raw_json = p_handle:read('*all') + -- p_handle:close() + -- + -- local p_ok, p_data = pcall(vim.json.decode, raw_json) + -- if not p_ok or not p_data or not p_data.packages then + -- return '/**/bin/*' + -- end + -- + -- local toolchain_folder = '' + -- for _, pkg in ipairs(p_data.packages) do + -- -- Skip ULP (low power) toolchains and find the primary one for the architecture + -- if pkg.name and pkg.name:find('^toolchain%-') and not pkg.name:find('ulp') then + -- local check_path = (packages_dir .. '/' .. pkg.name):gsub('\\', '/') + -- if vim.fn.isdirectory(check_path) == 1 then + -- toolchain_folder = pkg.name + -- -- Verification: Match the toolchain name against the compiler used in compile_commands.json + -- local db_path = vim.uv.cwd() .. '/compile_commands.json' + -- local f = io.open(db_path, 'r') + -- if f then + -- local head = f:read(2048) -- Read enough to find the compiler path + -- f:close() + -- -- If the DB mentions "riscv32-esp", we ensure we picked the matching folder + -- if head and head:find(pkg.name:gsub('toolchain%-', '')) then + -- break + -- end + -- end + -- end + -- end + -- end + -- + -- if toolchain_folder == '' then + -- return '/**/bin/*' + -- end + -- + -- local final = packages_dir .. toolchain_folder + -- print('get_pio_toolchain 5: final=' .. final) + -- -- Normalize paths for the OS and ensure backslashes for Windows if needed + -- return (misc.normalize_path(final)) -- return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final end --- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag --- stylua: ignore -local function pio_generate_db() - -- Check if we actually have an active environment before running - local active_env = vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') - - if not active_env then - -- Silent return or a minor info message - vim.schedule(function() - vim.notify('PIO: No board configured yet. Skipping DB generation.', vim.log.levels.INFO) - end) - return - end - - vim.schedule(function() vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) end) - - vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) - if obj.code ~= 0 then return end - - -- Isolate the toolchain root from the pattern (e.g. .../toolchain-riscv32-esp) - -- local pattern = _G.get_pio_toolchain_pattern() - local pattern = _G.get_pio_sdk_info() - - local toolchain_root = nil - if pattern then toolchain_root = pattern:match('(.-toolchain%-[^/\\]+)') end - - if not toolchain_root or vim.fn.isdirectory(toolchain_root) == 0 then return end - - -- FIND SYSROOT: Locate the internal folder that contains the /include directory - -- This folder is necessary for clangd to find standard C++ headers like - -- local sysroot_path = nil - -- local subdirs = vim.fn.getcompletion(toolchain_root .. '/*', 'dir') - -- for _, dir in ipairs(subdirs) do - -- if vim.fn.isdirectory(dir .. '/include') == 1 then - -- sysroot_path = dir:gsub('\\', '/') - -- break - -- end - -- end - - local sysroot_path = nil - local handle = vim.uv.fs_scandir(toolchain_root) - if handle then - while true do - local name, type = vim.uv.fs_scandir_next(handle) - if not name then break end - -- Check if the entry is a directory (or a symlink to one) - if type == "directory" or type == "link" then - local full_path = toolchain_root .. '/' .. name - -- Check if 'include' exists inside this directory - local stat = vim.uv.fs_stat(full_path .. '/include') - if stat and stat.type == "directory" then - sysroot_path = full_path:gsub('\\', '/') - break - end - end - end - end - - if sysroot_path then - local db_path = vim.uv.cwd() .. '/compile_commands.json' - local f = io.open(db_path, 'r') - if not f then return end - local content = f:read('*all') - f:close() - - -- Inject the --sysroot flag into every command in the JSON file - if content and content ~= '' then - local patched = content:gsub('("-i")', '"--sysroot=' .. sysroot_path .. '", %1') - local out = io.open(db_path, 'w') - if out then - out:write(patched) - out:close() - vim.schedule(function() - vim.notify('PIO: Sync Complete!', vim.log.levels.INFO) - end) - end - end - end - end) -end - +-- INFO: -- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync +-- stylua: ignore local function start_pio_watcher() local platformioini = vim.uv.cwd() .. '/platformio.ini' - if vim.fn.filereadable(platformioini) == 0 then - return - end + if vim.fn.filereadable(platformioini) == 0 then return end local w = vim.uv.new_fs_event() - if not w then - return - end + if not w then return end w:start( - platformioini, - {}, + platformioini, {}, vim.schedule_wrap(function(err, _, events) if err or not events or not events.change then return end if debounce_timer then - -- DEBOUNCE: Stops and restarts the timer to ensure we only sync ONCE after typing stops + -- 1. Stop any existing timer (cancel previous "half-finished" events) debounce_timer:stop() + + -- 2. Start a 500ms window. Logic only runs if NO more events happen in this time. debounce_timer:start( 500, 0, vim.schedule_wrap(function() + M.metadata.active_env = GetActivePioEnv() pio_manager.refresh(function() - local board_env = pio_manager.get('platformio', 'default_envs') - if board_env then - vim.system({ 'pio', 'project', 'metadata', '-e', board_env, '--json-output' }, { text = true }, function(obj) - -- Error Checking: obj.code 0 means success - if obj.code == 0 and obj.stdout then - local ok, raw_data = pcall(vim.json.decode, obj.stdout) - if ok and raw_data then - local _, env = next(raw_data) - if not env then - return - end - local fallback_flags = {} - -- 1. Process Includes - if env.includes then - for category, paths in pairs(env.includes) do - -- If it's a toolchain path, use -isystem to suppress warnings - -- and tell clangd these are standard libraries - local flag = (category == 'toolchain') and '-isystem' or '-I' - - for _, path in ipairs(paths) do - table.insert(fallback_flags, flag .. path) - end - end - end - -- 2. Process Defines - if env.defines then - for _, define in ipairs(env.defines) do - table.insert(fallback_flags, '-D' .. define) - end - end - M.metadata = { - driver_path = env.cc_path:match('(.*[/\\])') .. '/*' or '**', - cc_path = env.cc_path or '', - fallback_flags = fallback_flags, - } - -- M.metadata = decoded - vim.schedule(function() - pio_generate_db() - lsp.lsp_restart('clangd') - vim.notify('PIO: Syncing Environment successful') - end) - else - vim.schedule(function() - vim.notify('PIO: Syncing Environment failed') - end) - end - end - end) - -- pio_generate_db() - -- lsp.lsp_restart('clangd') - -- vim.notify('PIO: Syncing Environment...') - end + + vim.schedule(function() + boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + pio_generate_db() + lsp.lsp_restart('clangd') + vim.notify('PIO: Syncing Environment successful') + end) + -- if M.metadata.active_env then + -- pio_generate_db() + -- start_pio_watcher() + -- end + -- local board_env = pio_manager.get('platformio', 'default_envs') + -- if board_env then + -- vim.system({ 'pio', 'project', 'metadata', '-e', board_env, '--json-output' }, { text = true }, function(obj) + -- -- Error Checking: obj.code 0 means success + -- if obj.code == 0 and obj.stdout then + -- local ok, raw_data = pcall(vim.json.decode, obj.stdout) + -- if ok and raw_data then + -- local _, env = next(raw_data) + -- if not env then + -- return + -- end + -- local fallback_flags = {} + -- -- 1. Process Includes + -- if env.includes then + -- for category, paths in pairs(env.includes) do + -- -- If it's a toolchain path, use -isystem to suppress warnings + -- -- and tell clangd these are standard libraries + -- local flag = (category == 'toolchain') and '-isystem' or '-I' + -- + -- for _, path in ipairs(paths) do + -- table.insert(fallback_flags, flag .. path) + -- end + -- end + -- end + -- -- 2. Process Defines + -- if env.defines then + -- for _, define in ipairs(env.defines) do + -- table.insert(fallback_flags, '-D' .. define) + -- end + -- end + -- M.metadata = { + -- driver_path = env.cc_path:match('(.*[/\\])') .. '/*' or '**', + -- cc_path = env.cc_path or '', + -- fallback_flags = fallback_flags, + -- } + -- -- M.metadata = decoded + -- vim.schedule(function() + -- pio_generate_db() + -- lsp.lsp_restart('clangd') + -- vim.notify('PIO: Syncing Environment successful') + -- end) + -- else + -- vim.schedule(function() + -- vim.notify('PIO: Syncing Environment failed') + -- end) + -- end + -- end + -- end) + -- end end) end) ) @@ -421,7 +480,6 @@ function M.init() ---------------------------------------------------------------------------------------- -- INFO: create clangd required files ----------------------------------------------------------------------------------------- - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.g.platformioRootDir) @@ -443,13 +501,22 @@ function M.init() require('platformio.lspConfig.attach') end if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then + M.metadata.active_env = GetActivePioEnv() pio_manager.refresh(function() - -- We check if we have data inside the refresh callback - local env = pio_manager.get('platformio', 'default_envs') - if env then + vim.schedule(function() + boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) pio_generate_db() - start_pio_watcher() - end + lsp.lsp_restart('clangd') + vim.notify('PIO: Syncing Environment successful') + end) + -- We check if we have data inside the refresh callback + -- local env = pio_manager.get('platformio', 'default_envs') + -- if M.metadata.active_env then + -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + -- pio_generate_db() + -- lsp.lsp_restart('clangd') + -- start_pio_watcher() + -- end -- pio_generate_db() start_pio_watcher() end) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 1a0f2f46..4885f45f 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -220,7 +220,7 @@ end function M.handlePioinit() vim.notify('Pioinit: Success', vim.log.levels.INFO) local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') end -- Handle after poioinit execution diff --git a/pio_setup.lua b/pio_setup.lua new file mode 100644 index 00000000..c486df75 --- /dev/null +++ b/pio_setup.lua @@ -0,0 +1,480 @@ +-- M = {} +-- +-- M.metadata = nil +-- local misc = require('platformio.utils.misc') +-- local lsp = require('platformio.utils.lsp') +-- +-- -- lua/pio_setup.lua +-- -- This module manages PlatformIO project integration, LSP toolchain detection, +-- -- and automatic sysroot patching for standard library headers (, etc.) +-- +-- local debounce_timer = vim.uv.new_timer() +-- +-- -- INFO: 1. The Core PIO Manager & Generic Extractor +-- local pio_manager = (function() +-- local cache = nil -- Stores the decoded platformio.ini JSON structure +-- +-- -- INFO: +-- -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' +-- -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } +-- local function find_in_data(data, section_name, key_name) +-- -- Safety check: Ensure data is a valid table from a successful JSON decode +-- if type(data) ~= 'table' then +-- return nil +-- end +-- +-- for _, section in ipairs(data) do +-- -- Each section must be a table with at least 2 elements: [1]=name, [2]=content +-- if type(section) == 'table' and #section >= 2 then +-- local s_id = section[1] -- Section header string +-- local s_body = section[2] -- Table of key-value pairs +-- +-- if s_id == section_name and type(s_body) == 'table' then +-- for _, kv in ipairs(s_body) do +-- -- Each kv is a table: [1]=key, [2]=value +-- if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then +-- local val = kv[2] +-- -- Treat empty strings or empty tables as nil to trigger fallback logic +-- if val == nil or val == '' or (type(val) == 'table' and #val == 0) then +-- return nil +-- end +-- return val +-- end +-- end +-- end +-- end +-- end +-- return nil +-- end +-- +-- -- INFO: +-- -- ASYNC REFRESH: Fetches the latest config from PlatformIO CLI +-- local function refresh(callback) +-- vim.schedule(function() +-- vim.notify('PIO: Fetching Config...', vim.log.levels.INFO) +-- end) +-- -- INFO: +-- local function execute_pio(attempts) +-- -- Use Neovim's async system call to prevent UI freezing +-- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) +-- -- Error Checking: obj.code 0 means success +-- if obj.code == 0 and obj.stdout then +-- local ok, decoded = pcall(vim.json.decode, obj.stdout) +-- if ok and decoded then +-- cache = decoded +-- vim.schedule(function() +-- if not cache or type(cache) ~= 'table' then +-- vim.notify('PIO: Fetching Config failed. Check platformio.ini syntax.', vim.log.levels.INFO) +-- else +-- vim.notify('PIO: Fetching Config successful', vim.log.levels.INFO) +-- end +-- end) +-- if callback then +-- vim.schedule(callback) +-- end +-- return +-- end +-- end +-- +-- -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save +-- if attempts > 0 then +-- vim.defer_fn(function() +-- execute_pio(attempts - 1) +-- end, 500) +-- else +-- vim.schedule(function() +-- if obj.code ~= 0 then +-- vim.notify('PIO: Config Error. Check platformio.ini syntax.', vim.log.levels.WARN) +-- end +-- end) +-- end +-- end) +-- end +-- execute_pio(1) +-- end +-- +-- -- INFO: +-- return { +-- refresh = refresh, +-- -- INFO: +-- get = function(s, k) +-- if not cache then +-- return nil +-- end +-- local res = find_in_data(cache, s, k) +-- +-- -- FALLBACK: If default_envs is missing/empty, find the first hardware [env:xxx] block +-- if k == 'default_envs' and not res then +-- for _, section in ipairs(cache) do +-- if type(section) == 'table' and type(section[1]) == 'string' then +-- local name = section[1] +-- if name:find('^env:') then +-- local fallback = name:match('^env:(.+)') +-- if fallback then +-- vim.schedule(function() +-- vim.notify('PIO: default_envs empty. Using: ' .. fallback, vim.log.levels.INFO) +-- end) +-- return fallback +-- end +-- end +-- end +-- end +-- vim.schedule(function() +-- vim.notify('PIO: Config Error. Check platformio.ini no env', vim.log.levels.WARN) +-- end) +-- elseif k == 'default_envs' and res and type(res) == 'table' then +-- return res[1] +-- else +-- return res +-- end +-- end, +-- } +-- end)() +-- +-- -- INFO: +-- function _G.get_pio_sdk_info() +-- local pio_info = { includes = {}, cc_path = '' } +-- if vim.fn.filereadable('platformio.ini') == 0 then +-- return nil +-- end +-- +-- local handle = io.popen('pio run -t envdump') +-- if not handle then +-- return nil +-- end +-- +-- local packages_dir, cc_name, toolchain_pkg = '', '', '' +-- +-- for line in handle:lines() do +-- -- 1. Get the global packages directory +-- packages_dir = packages_dir ~= '' and packages_dir or line:match("'PROJECT_PACKAGES_DIR': '([^']+)'") +-- +-- -- 2. Get the compiler executable name (e.g., riscv32-esp-elf-gcc) +-- cc_name = cc_name ~= '' and cc_name or line:match("'CC': '([^']+)'") +-- +-- -- 3. Find the specific toolchain package name from the PACKAGES list +-- -- Matches lines like "- toolchain-riscv32-esp @ 14.2.0" +-- local pkg = line:match('%- (toolchain%-[^ ]+)') +-- if pkg then +-- toolchain_pkg = pkg +-- end +-- +-- -- 4. Collect include paths +-- local path_list = line:match("'CPPPATH': %[(.+)%]") +-- if path_list then +-- for path in path_list:gmatch("'([^']+)'") do +-- table.insert(pio_info.includes, '-I' .. path) +-- end +-- end +-- end +-- handle:close() +-- +-- -- Construct the absolute path: //bin/ +-- if packages_dir and packages_dir ~= '' and toolchain_pkg and toolchain_pkg ~= '' and cc_name ~= '' then +-- local full_path = packages_dir .. '/' .. toolchain_pkg .. '/bin/' .. cc_name +-- if vim.fn.executable(full_path) == 1 then +-- pio_info.cc_path = full_path +-- end +-- end +-- +-- local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' +-- print('get_pio_sdk_info(): final=' .. final) +-- -- Normalize paths for the OS and ensure backslashes for Windows if needed +-- print(vim.inspect(M.metadata)) +-- return (misc.normalize_path(final)) +-- -- return M.metadata.driver_path +-- -- return pio_info +-- end +-- +-- -- INFO: +-- -- LSP HELPER: Returns the glob pattern for clangd's --query-driver +-- -- e.g., C:\Users\tom\.platformio\packages\toolchain-riscv32-esp\bin\* +-- function _G.get_pio_toolchain_pattern() +-- local ok_env, active_env = pcall(function() +-- return vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') +-- end) +-- if not ok_env or not active_env then +-- return '/**/bin/*' +-- end +-- +-- local target_env = 'env:' .. active_env +-- local platform = pio_manager.get(target_env, 'platform') +-- -- Determine the packages directory (Windows vs Linux/Mac home folders) +-- local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('USERPROFILE') or os.getenv('HOME') .. '/.platformio/packages') +-- +-- if not platform then +-- return '/**/bin/*' +-- end +-- +-- -- Use pio platform show to find which toolchain packages are associated with the platform +-- local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') +-- if not p_handle then +-- return '/**/bin/*' +-- end +-- local raw_json = p_handle:read('*all') +-- p_handle:close() +-- +-- local p_ok, p_data = pcall(vim.json.decode, raw_json) +-- if not p_ok or not p_data or not p_data.packages then +-- return '/**/bin/*' +-- end +-- +-- local toolchain_folder = '' +-- for _, pkg in ipairs(p_data.packages) do +-- -- Skip ULP (low power) toolchains and find the primary one for the architecture +-- if pkg.name and pkg.name:find('^toolchain%-') and not pkg.name:find('ulp') then +-- local check_path = (packages_dir .. '/' .. pkg.name):gsub('\\', '/') +-- if vim.fn.isdirectory(check_path) == 1 then +-- toolchain_folder = pkg.name +-- -- Verification: Match the toolchain name against the compiler used in compile_commands.json +-- local db_path = vim.uv.cwd() .. '/compile_commands.json' +-- local f = io.open(db_path, 'r') +-- if f then +-- local head = f:read(2048) -- Read enough to find the compiler path +-- f:close() +-- -- If the DB mentions "riscv32-esp", we ensure we picked the matching folder +-- if head and head:find(pkg.name:gsub('toolchain%-', '')) then +-- break +-- end +-- end +-- end +-- end +-- end +-- +-- if toolchain_folder == '' then +-- return '/**/bin/*' +-- end +-- +-- local final = packages_dir .. toolchain_folder +-- print('get_pio_toolchain 5: final=' .. final) +-- -- Normalize paths for the OS and ensure backslashes for Windows if needed +-- return (misc.normalize_path(final)) +-- -- return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final +-- end +-- +-- -- INFO: +-- -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag +-- -- stylua: ignore +-- local function pio_generate_db() +-- -- Check if we actually have an active environment before running +-- local active_env = vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') +-- +-- if not active_env then +-- -- Silent return or a minor info message +-- vim.schedule(function() +-- vim.notify('PIO: No board configured yet. Skipping DB generation.', vim.log.levels.INFO) +-- end) +-- return +-- end +-- +-- vim.schedule(function() vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) end) +-- +-- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) +-- if obj.code ~= 0 then return end +-- +-- -- Isolate the toolchain root from the pattern (e.g. .../toolchain-riscv32-esp) +-- -- local pattern = _G.get_pio_toolchain_pattern() +-- local pattern = _G.get_pio_sdk_info() +-- +-- local toolchain_root = nil +-- if pattern then toolchain_root = pattern:match('(.-toolchain%-[^/\\]+)') end +-- +-- if not toolchain_root or vim.fn.isdirectory(toolchain_root) == 0 then return end +-- +-- -- FIND SYSROOT: Locate the internal folder that contains the /include directory +-- -- This folder is necessary for clangd to find standard C++ headers like +-- -- local sysroot_path = nil +-- -- local subdirs = vim.fn.getcompletion(toolchain_root .. '/*', 'dir') +-- -- for _, dir in ipairs(subdirs) do +-- -- if vim.fn.isdirectory(dir .. '/include') == 1 then +-- -- sysroot_path = dir:gsub('\\', '/') +-- -- break +-- -- end +-- -- end +-- +-- local sysroot_path = nil +-- local handle = vim.uv.fs_scandir(toolchain_root) +-- if handle then +-- while true do +-- local name, type = vim.uv.fs_scandir_next(handle) +-- if not name then break end +-- -- Check if the entry is a directory (or a symlink to one) +-- if type == "directory" or type == "link" then +-- local full_path = toolchain_root .. '/' .. name +-- -- Check if 'include' exists inside this directory +-- local stat = vim.uv.fs_stat(full_path .. '/include') +-- if stat and stat.type == "directory" then +-- sysroot_path = full_path:gsub('\\', '/') +-- break +-- end +-- end +-- end +-- end +-- +-- if sysroot_path then +-- local db_path = vim.uv.cwd() .. '/compile_commands.json' +-- local f = io.open(db_path, 'r') +-- if not f then return end +-- local content = f:read('*all') +-- f:close() +-- +-- -- Inject the --sysroot flag into every command in the JSON file +-- if content and content ~= '' then +-- local patched = content:gsub('("-i")', '"--sysroot=' .. sysroot_path .. '", %1') +-- local out = io.open(db_path, 'w') +-- if out then +-- out:write(patched) +-- out:close() +-- vim.schedule(function() +-- vim.notify('PIO: Sync Complete!', vim.log.levels.INFO) +-- end) +-- end +-- end +-- end +-- end) +-- end +-- +-- -- INFO: +-- -- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync +-- local function start_pio_watcher() +-- local platformioini = vim.uv.cwd() .. '/platformio.ini' +-- if vim.fn.filereadable(platformioini) == 0 then +-- return +-- end +-- +-- local w = vim.uv.new_fs_event() +-- if not w then +-- return +-- end +-- w:start( +-- platformioini, +-- {}, +-- vim.schedule_wrap(function(err, _, events) +-- if err or not events or not events.change then +-- return +-- end +-- +-- if debounce_timer then +-- -- DEBOUNCE: Stops and restarts the timer to ensure we only sync ONCE after typing stops +-- debounce_timer:stop() +-- debounce_timer:start( +-- 500, +-- 0, +-- vim.schedule_wrap(function() +-- pio_manager.refresh(function() +-- local board_env = pio_manager.get('platformio', 'default_envs') +-- if board_env then +-- vim.system({ 'pio', 'project', 'metadata', '-e', board_env, '--json-output' }, { text = true }, function(obj) +-- -- Error Checking: obj.code 0 means success +-- if obj.code == 0 and obj.stdout then +-- local ok, raw_data = pcall(vim.json.decode, obj.stdout) +-- if ok and raw_data then +-- local _, env = next(raw_data) +-- if not env then +-- return +-- end +-- local fallback_flags = {} +-- -- 1. Process Includes +-- if env.includes then +-- for category, paths in pairs(env.includes) do +-- -- If it's a toolchain path, use -isystem to suppress warnings +-- -- and tell clangd these are standard libraries +-- local flag = (category == 'toolchain') and '-isystem' or '-I' +-- +-- for _, path in ipairs(paths) do +-- table.insert(fallback_flags, flag .. path) +-- end +-- end +-- end +-- -- 2. Process Defines +-- if env.defines then +-- for _, define in ipairs(env.defines) do +-- table.insert(fallback_flags, '-D' .. define) +-- end +-- end +-- M.metadata = { +-- driver_path = env.cc_path:match('(.*[/\\])') .. '/*' or '**', +-- cc_path = env.cc_path or '', +-- fallback_flags = fallback_flags, +-- } +-- -- M.metadata = decoded +-- vim.schedule(function() +-- pio_generate_db() +-- lsp.lsp_restart('clangd') +-- vim.notify('PIO: Syncing Environment successful') +-- end) +-- else +-- vim.schedule(function() +-- vim.notify('PIO: Syncing Environment failed') +-- end) +-- end +-- end +-- end) +-- -- pio_generate_db() +-- -- lsp.lsp_restart('clangd') +-- -- vim.notify('PIO: Syncing Environment...') +-- end +-- end) +-- end) +-- ) +-- end +-- end) +-- ) +-- end +-- +-- ------------------------------------------------------------------------------------------------------ +-- -- INFO: 6. Exported setup function +-- function M.init() +-- local config = require('platformio').config +-- if config.lspClangd.enabled == true then +-- vim.notify('PIO setup initialize', vim.log.levels.INFO) +-- ---------------------------------------------------------------------------------------- +-- -- INFO: create clangd required files +-- ----------------------------------------------------------------------------------------- +-- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +-- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) +-- +-- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +-- boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) +-- -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) +-- -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') +-- +-- -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) +-- +-- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) +-- +-- boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) +-- -- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) +-- -- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) +-- --------------------------------------------------------------------------------- +-- +-- require('platformio.lspConfig.clangd') +-- if config.lspClangd.attach.enabled then +-- require('platformio.lspConfig.attach') +-- end +-- if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then +-- pio_manager.refresh(function() +-- -- We check if we have data inside the refresh callback +-- local env = pio_manager.get('platformio', 'default_envs') +-- if env then +-- pio_generate_db() +-- start_pio_watcher() +-- end +-- -- pio_generate_db() +-- start_pio_watcher() +-- end) +-- end +-- end +-- end +-- +-- -- local pio = require('pio_utils') +-- -- +-- -- require('lspconfig').clangd.setup({ +-- -- on_new_config = function(new_config, _) +-- -- if pio.data then +-- -- new_config.cmd = { "clangd", "--query-driver=" .. pio.data.cc_path } +-- -- new_config.init_options = { fallbackFlags = pio.data.fallback_flags } +-- -- end +-- -- end +-- -- }) +-- return M From e757b2095c29c0620d9672d6be077a738aea9394 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 11:12:00 +0300 Subject: [PATCH 0584/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 4885f45f..f1b5374b 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -218,10 +218,10 @@ end -- Handle after poioinit execution -- stylua: ignore function M.handlePioinit() - vim.notify('Pioinit: Success', vim.log.levels.INFO) local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + vim.notify('Pioinit: Success', vim.log.levels.INFO) end -- Handle after poioinit execution -- stylua: ignore From 07eda3a01b1abc72bdf4ea7706c2aa80e0b5d550 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 11:21:13 +0300 Subject: [PATCH 0585/1406] update --- lua/platformio/pio_setup.lua | 138 ++++++++++++++++++----------------- 1 file changed, 71 insertions(+), 67 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 142db8f9..6ee87e82 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -103,81 +103,85 @@ local pio_manager = (function() end) -- INFO: local function execute_pio(attempts) - if M.metadata.active_env then - vim.system({ 'pio', 'project', 'metadata', '-e', M.metadata.active_env, '--json-output' }, { text = true }, function(obj) - if obj.code ~= 0 then - -- Schedule notification to avoid error in the system callback thread - vim.schedule(function() - if obj.code == 127 then - vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) - else - vim.notify('PIO Manager: Failed to fetch config (Error ' .. obj.code .. ')', vim.log.levels.WARN) - end - end) - return - end - -- Error Checking: obj.code 0 means success - if obj.code == 0 and obj.stdout then - local ok, raw_data = pcall(vim.json.decode, obj.stdout) - if ok and raw_data then - local _, env = next(raw_data) - if not env then - return - end - local fallback_flags = {} - -- 1. Process Includes - if env.includes then - for category, paths in pairs(env.includes) do - -- If it's a toolchain path, use -isystem to suppress warnings - -- and tell clangd these are standard libraries - local flag = (category == 'toolchain') and '-isystem' or '-I' - - for _, path in ipairs(paths) do - table.insert(fallback_flags, flag .. path) - end - end - end - -- 2. Process Defines - if env.defines then - for _, define in ipairs(env.defines) do - table.insert(fallback_flags, '-D' .. define) + if not M.metadata.active_env or M.metadata.active_env == '' then + vim.schedule(function() + vim.notify('PIO: no env: found, add board first', vim.log.levels.ERROR) + end) + return + end + vim.system({ 'pio', 'project', 'metadata', '-e', M.metadata.active_env, '--json-output' }, { text = true }, function(obj) + if obj.code ~= 0 then + -- Schedule notification to avoid error in the system callback thread + vim.schedule(function() + if obj.code == 127 then + vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + else + vim.notify('PIO Manager: Failed to fetch config (Error ' .. obj.code .. ')', vim.log.levels.WARN) + end + end) + return + end + -- Error Checking: obj.code 0 means success + if obj.code == 0 and obj.stdout then + local ok, raw_data = pcall(vim.json.decode, obj.stdout) + if ok and raw_data then + local _, env = next(raw_data) + if not env then + return + end + local fallback_flags = {} + -- 1. Process Includes + if env.includes then + for category, paths in pairs(env.includes) do + -- If it's a toolchain path, use -isystem to suppress warnings + -- and tell clangd these are standard libraries + local flag = (category == 'toolchain') and '-isystem' or '-I' + + for _, path in ipairs(paths) do + table.insert(fallback_flags, flag .. path) end end - M.metadata = { - driver_path = env.cc_path:match('(.*[/\\])') .. '/*' or '**', - cc_path = env.cc_path or '', - fallback_flags = fallback_flags, - } - -- M.metadata = decoded - if callback then - vim.schedule(callback) + end + -- 2. Process Defines + if env.defines then + for _, define in ipairs(env.defines) do + table.insert(fallback_flags, '-D' .. define) end - -- vim.schedule(function() - -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - -- pio_generate_db() - -- lsp.lsp_restart('clangd') - -- vim.notify('PIO: Syncing Environment successful') - -- end) - else - vim.schedule(function() - vim.notify('PIO: Syncing Environment failed') - end) end - end - -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save - if attempts > 0 then - vim.defer_fn(function() - execute_pio(attempts - 1) - end, 500) + M.metadata = { + driver_path = env.cc_path:match('(.*[/\\])') .. '/*' or '**', + cc_path = env.cc_path or '', + fallback_flags = fallback_flags, + } + -- M.metadata = decoded + if callback then + vim.schedule(callback) + end + -- vim.schedule(function() + -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + -- pio_generate_db() + -- lsp.lsp_restart('clangd') + -- vim.notify('PIO: Syncing Environment successful') + -- end) else vim.schedule(function() - if obj.code ~= 0 then - vim.notify('PIO: Config Error. Check platformio.ini syntax.', vim.log.levels.WARN) - end + vim.notify('PIO: Syncing Environment failed') end) end - end) - end + end + -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save + if attempts > 0 then + vim.defer_fn(function() + execute_pio(attempts - 1) + end, 500) + else + vim.schedule(function() + if obj.code ~= 0 then + vim.notify('PIO: Config Error. Check platformio.ini syntax.', vim.log.levels.WARN) + end + end) + end + end) -- Use Neovim's async system call to prevent UI freezing -- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) -- -- Error Checking: obj.code 0 means success From 1af840a76534ddece9c0213f04c25b85b381251c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 11:47:09 +0300 Subject: [PATCH 0586/1406] update --- lua/platformio/pio_setup.lua | 55 +++++++++++++++--------------------- 1 file changed, 22 insertions(+), 33 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 6ee87e82..986a8f08 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -35,6 +35,7 @@ end local function GetActivePioEnv() local file = io.open('platformio.ini', 'r') if not file then + M.metadata.active_env = '' return nil end @@ -157,12 +158,6 @@ local pio_manager = (function() if callback then vim.schedule(callback) end - -- vim.schedule(function() - -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - -- pio_generate_db() - -- lsp.lsp_restart('clangd') - -- vim.notify('PIO: Syncing Environment successful') - -- end) else vim.schedule(function() vim.notify('PIO: Syncing Environment failed') @@ -485,46 +480,40 @@ function M.init() -- INFO: create clangd required files ----------------------------------------------------------------------------------------- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') - - -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) - boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) - -- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) - -- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) --------------------------------------------------------------------------------- require('platformio.lspConfig.clangd') if config.lspClangd.attach.enabled then require('platformio.lspConfig.attach') end - if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then - M.metadata.active_env = GetActivePioEnv() - pio_manager.refresh(function() - vim.schedule(function() - boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - pio_generate_db() - lsp.lsp_restart('clangd') - vim.notify('PIO: Syncing Environment successful') - end) - -- We check if we have data inside the refresh callback - -- local env = pio_manager.get('platformio', 'default_envs') - -- if M.metadata.active_env then - -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - -- pio_generate_db() - -- lsp.lsp_restart('clangd') - -- start_pio_watcher() - -- end - -- pio_generate_db() - start_pio_watcher() + + -- if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then + -- M.metadata.active_env = GetActivePioEnv() + pio_manager.refresh(function() + vim.schedule(function() + boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + pio_generate_db() + lsp.lsp_restart('clangd') + vim.notify('PIO: Syncing Environment successful') end) - end + -- We check if we have data inside the refresh callback + -- local env = pio_manager.get('platformio', 'default_envs') + -- if M.metadata.active_env then + -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + -- pio_generate_db() + -- lsp.lsp_restart('clangd') + -- start_pio_watcher() + -- end + -- pio_generate_db() + start_pio_watcher() + end) + -- end end end From bbc1fe625218c0947d836eae438bf2fc2c35b900 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 11:52:14 +0300 Subject: [PATCH 0587/1406] update --- lua/platformio/pio_setup.lua | 65 +----------------------------------- 1 file changed, 1 insertion(+), 64 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 986a8f08..f751c8be 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -380,7 +380,7 @@ end -- stylua: ignore local function start_pio_watcher() local platformioini = vim.uv.cwd() .. '/platformio.ini' - if vim.fn.filereadable(platformioini) == 0 then return end + -- if vim.fn.filereadable(platformioini) == 0 then return end local w = vim.uv.new_fs_event() if not w then return end @@ -409,59 +409,6 @@ local function start_pio_watcher() lsp.lsp_restart('clangd') vim.notify('PIO: Syncing Environment successful') end) - -- if M.metadata.active_env then - -- pio_generate_db() - -- start_pio_watcher() - -- end - -- local board_env = pio_manager.get('platformio', 'default_envs') - -- if board_env then - -- vim.system({ 'pio', 'project', 'metadata', '-e', board_env, '--json-output' }, { text = true }, function(obj) - -- -- Error Checking: obj.code 0 means success - -- if obj.code == 0 and obj.stdout then - -- local ok, raw_data = pcall(vim.json.decode, obj.stdout) - -- if ok and raw_data then - -- local _, env = next(raw_data) - -- if not env then - -- return - -- end - -- local fallback_flags = {} - -- -- 1. Process Includes - -- if env.includes then - -- for category, paths in pairs(env.includes) do - -- -- If it's a toolchain path, use -isystem to suppress warnings - -- -- and tell clangd these are standard libraries - -- local flag = (category == 'toolchain') and '-isystem' or '-I' - -- - -- for _, path in ipairs(paths) do - -- table.insert(fallback_flags, flag .. path) - -- end - -- end - -- end - -- -- 2. Process Defines - -- if env.defines then - -- for _, define in ipairs(env.defines) do - -- table.insert(fallback_flags, '-D' .. define) - -- end - -- end - -- M.metadata = { - -- driver_path = env.cc_path:match('(.*[/\\])') .. '/*' or '**', - -- cc_path = env.cc_path or '', - -- fallback_flags = fallback_flags, - -- } - -- -- M.metadata = decoded - -- vim.schedule(function() - -- pio_generate_db() - -- lsp.lsp_restart('clangd') - -- vim.notify('PIO: Syncing Environment successful') - -- end) - -- else - -- vim.schedule(function() - -- vim.notify('PIO: Syncing Environment failed') - -- end) - -- end - -- end - -- end) - -- end end) end) ) @@ -517,14 +464,4 @@ function M.init() end end --- local pio = require('pio_utils') --- --- require('lspconfig').clangd.setup({ --- on_new_config = function(new_config, _) --- if pio.data then --- new_config.cmd = { "clangd", "--query-driver=" .. pio.data.cc_path } --- new_config.init_options = { fallbackFlags = pio.data.fallback_flags } --- end --- end --- }) return M From 591f8eeda85ea4edfdc14d21ae13971c9ebef953 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 12:44:03 +0300 Subject: [PATCH 0588/1406] update --- lua/platformio/pio_setup.lua | 101 +++++++++++++++++++++-------------- 1 file changed, 62 insertions(+), 39 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index f751c8be..05f16f90 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -98,16 +98,13 @@ local pio_manager = (function() -- INFO: -- ASYNC REFRESH: Fetches the latest config from PlatformIO CLI + -- stylua: ignore local function refresh(callback) - vim.schedule(function() - vim.notify('PIO: Fetching Config...', vim.log.levels.INFO) - end) + vim.schedule(function() vim.notify('PIO: Fetching Config...', vim.log.levels.INFO) end) -- INFO: local function execute_pio(attempts) if not M.metadata.active_env or M.metadata.active_env == '' then - vim.schedule(function() - vim.notify('PIO: no env: found, add board first', vim.log.levels.ERROR) - end) + vim.schedule(function() vim.notify('PIO: no env: found, add board first', vim.log.levels.ERROR) end) return end vim.system({ 'pio', 'project', 'metadata', '-e', M.metadata.active_env, '--json-output' }, { text = true }, function(obj) @@ -127,9 +124,7 @@ local pio_manager = (function() local ok, raw_data = pcall(vim.json.decode, obj.stdout) if ok and raw_data then local _, env = next(raw_data) - if not env then - return - end + if not env then return end local fallback_flags = {} -- 1. Process Includes if env.includes then @@ -137,17 +132,12 @@ local pio_manager = (function() -- If it's a toolchain path, use -isystem to suppress warnings -- and tell clangd these are standard libraries local flag = (category == 'toolchain') and '-isystem' or '-I' - - for _, path in ipairs(paths) do - table.insert(fallback_flags, flag .. path) - end + for _, path in ipairs(paths) do table.insert(fallback_flags, flag .. path) end end end -- 2. Process Defines if env.defines then - for _, define in ipairs(env.defines) do - table.insert(fallback_flags, '-D' .. define) - end + for _, define in ipairs(env.defines) do table.insert(fallback_flags, '-D' .. define) end end M.metadata = { driver_path = env.cc_path:match('(.*[/\\])') .. '/*' or '**', @@ -155,25 +145,17 @@ local pio_manager = (function() fallback_flags = fallback_flags, } -- M.metadata = decoded - if callback then - vim.schedule(callback) - end + if callback then vim.schedule(callback) end else - vim.schedule(function() - vim.notify('PIO: Syncing Environment failed') - end) + vim.schedule(function() vim.notify('PIO: Syncing Environment failed') end) end end -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save if attempts > 0 then - vim.defer_fn(function() - execute_pio(attempts - 1) - end, 500) + vim.defer_fn(function() execute_pio(attempts - 1) end, 500) else vim.schedule(function() - if obj.code ~= 0 then - vim.notify('PIO: Config Error. Check platformio.ini syntax.', vim.log.levels.WARN) - end + if obj.code ~= 0 then vim.notify('PIO: Config Error. Check platformio.ini syntax.', vim.log.levels.WARN) end end) end end) @@ -378,31 +360,72 @@ end -- INFO: -- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync -- stylua: ignore +-- local function start_pio_watcher() +-- local platformioini = vim.uv.cwd() .. '/platformio.ini' +-- -- if vim.fn.filereadable(platformioini) == 0 then return end +-- +-- local w = vim.uv.new_fs_event() +-- if not w then return end +-- w:start( platformioini, {}, +-- vim.schedule_wrap(function(err, _, events) +-- if err or not events or not events.change then +-- return +-- end +-- +-- if debounce_timer then +-- -- 1. Stop any existing timer (cancel previous "half-finished" events) +-- debounce_timer:stop() +-- +-- -- 2. Start a 500ms window. Logic only runs if NO more events happen in this time. +-- debounce_timer:start( +-- 500, +-- 0, +-- vim.schedule_wrap(function() +-- M.metadata.active_env = GetActivePioEnv() +-- pio_manager.refresh(function() +-- +-- vim.schedule(function() +-- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) +-- pio_generate_db() +-- lsp.lsp_restart('clangd') +-- vim.notify('PIO: Syncing Environment successful') +-- end) +-- end) +-- end) +-- ) +-- end +-- end) +-- ) +-- end + local function start_pio_watcher() - local platformioini = vim.uv.cwd() .. '/platformio.ini' - -- if vim.fn.filereadable(platformioini) == 0 then return end + local dir_path = vim.uv.cwd() + if not dir_path then return end + -- Create a directory watcher local w = vim.uv.new_fs_event() - if not w then return end + if not w then + return + end + + -- Watch the directory for file creation or the file itself for changes w:start( - platformioini, {}, - vim.schedule_wrap(function(err, _, events) + dir_path, + {}, + vim.schedule_wrap(function(err, filename, events) if err or not events or not events.change then return end - + -- Trigger only if the changed file is platformio.ini + if filename == 'platformio.ini' then if debounce_timer then - -- 1. Stop any existing timer (cancel previous "half-finished" events) debounce_timer:stop() - - -- 2. Start a 500ms window. Logic only runs if NO more events happen in this time. debounce_timer:start( 500, 0, vim.schedule_wrap(function() M.metadata.active_env = GetActivePioEnv() pio_manager.refresh(function() - vim.schedule(function() boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) pio_generate_db() @@ -413,10 +436,10 @@ local function start_pio_watcher() end) ) end + end end) ) end - ------------------------------------------------------------------------------------------------------ -- INFO: 6. Exported setup function function M.init() From 29028b63538f5acca9a246f21a420fdf9b8e969a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 12:45:34 +0300 Subject: [PATCH 0589/1406] update --- lua/platformio/pio_setup.lua | 30 ++++++++++-------------------- 1 file changed, 10 insertions(+), 20 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 05f16f90..b698fc34 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -463,27 +463,17 @@ function M.init() require('platformio.lspConfig.attach') end - -- if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then - -- M.metadata.active_env = GetActivePioEnv() - pio_manager.refresh(function() - vim.schedule(function() - boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - pio_generate_db() - lsp.lsp_restart('clangd') - vim.notify('PIO: Syncing Environment successful') + start_pio_watcher() + if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then + pio_manager.refresh(function() + vim.schedule(function() + boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + pio_generate_db() + lsp.lsp_restart('clangd') + vim.notify('PIO: Syncing Environment successful') + end) end) - -- We check if we have data inside the refresh callback - -- local env = pio_manager.get('platformio', 'default_envs') - -- if M.metadata.active_env then - -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - -- pio_generate_db() - -- lsp.lsp_restart('clangd') - -- start_pio_watcher() - -- end - -- pio_generate_db() - start_pio_watcher() - end) - -- end + end end end From eca332edccdd9749d1829197884c6bec0d40ea97 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 13:33:57 +0300 Subject: [PATCH 0590/1406] update --- lua/platformio/pio_setup.lua | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b698fc34..1896db98 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -39,24 +39,21 @@ local function GetActivePioEnv() return nil end - local first_env = nil + local result_env = nil for line in file:lines() do -- 1. Try to find the explicit default_envs first local default = line:match('^default_envs%s*=%s*(%S+)') if default then - file:close() - return default - end - + result_env= default -- 2. Capture the first [env:NAME] we see as a fallback - if not first_env then - first_env = line:match('^%[env:(%S+)%]') + elseif not result_env then + result_env = line:match('^%[env:(%S+)%]') end end - file:close() + print(result_env) -- Return the first env found if no default was explicitly set - return first_env + return result_env end -- INFO: 1. The Core PIO Manager & Generic Extractor @@ -139,8 +136,9 @@ local pio_manager = (function() if env.defines then for _, define in ipairs(env.defines) do table.insert(fallback_flags, '-D' .. define) end end + M.metadata = { - driver_path = env.cc_path:match('(.*[/\\])') .. '/*' or '**', + driver_path = misc.normalize_path(env.cc_path:match('(.*[/\\])') .. '*') or '**', cc_path = env.cc_path or '', fallback_flags = fallback_flags, } @@ -465,6 +463,7 @@ function M.init() start_pio_watcher() if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then + M.metadata.active_env = GetActivePioEnv() pio_manager.refresh(function() vim.schedule(function() boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) From a7488da910b9a8967d23a61d8d38b1e0d9c3921b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 21:45:29 +0300 Subject: [PATCH 0591/1406] update --- lua/platformio/boilerplate.lua | 3 +- lua/platformio/pio_setup.lua | 415 +++++++++++++++++++-------------- 2 files changed, 237 insertions(+), 181 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 8417503f..b7fbec3a 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -92,7 +92,8 @@ clangd --query-driver=%s ]], content = function(self) - return string.format(self.template, _G.get_pio_toolchain_pattern() or '**') + return string.format(self.template, _G.metadata.driver_path or '**') + -- return string.format(self.template, _G.get_pio_toolchain_pattern() or '**') -- return string.format(self.template, _G.get_pio_sdk_info() or '**') end, --header-insertion=iwyu diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 1896db98..7b58e52c 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,6 +1,11 @@ M = {} -M.metadata = { +_G.metadata = { + envs = {}, + default_envs = {}, + core_dir = '', + packages_dir = '', + platforms_dir = '', active_env = '', driver_path = '', cc_path = '', @@ -17,6 +22,91 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local debounce_timer = vim.uv.new_timer() +------------------------------------------------------ +--- stylua: ignore +function M.get_pio_env(type) + -- 1. Setup Base Paths + local home = os.getenv('HOME') or os.getenv('USERPROFILE') + + -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) + local map = { + core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, + packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, + platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, + } + + -- INFO: 3. Try to get explicit value from platformio.ini + -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' + -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } + vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) + if ext_obj.code ~= 0 then + -- Schedule notification to avoid error in the system callback thread + vim.schedule(function() + if ext_obj.code == 127 then + vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + else + vim.notify('PIO Manager: Failed to fetch config (Error ' .. ext_obj.code .. ')', vim.log.levels.WARN) + end + end) + return + end + _G.metadata.core_dir = '' + _G.metadata.packages_dir = '' + _G.metadata.platforms_dir = '' + _G.metadata.default_envs = {} + _G.metadata.envs = {} + + local decoded = vim.json.decode(ext_obj.stdout) + for _, section in ipairs(decoded) do + if type(section) == 'table' and #section >= 2 then + local name, data = section[1], section[2] + -- 1. Extract Global PlatformIO Settings + if name == 'platformio' then + for _, kv in ipairs(data) do + local key, val = kv[1], kv[2] + if _G.metadata[key] ~= nil then + _G.metadata[key] = val + end + end + -- 2. Extract all hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] + elseif name:match('^env:') then + local env_name = name:match('^env:(.+)') + _G.metadata.envs[env_name] = {} + for _, kv in ipairs(data) do + _G.metadata.envs[env_name][kv[1]] = kv[2] + end + end + end + end + if #_G.metadata.default_envs > 0 then + _G.metadata.active_env = _G.metadata.default_envs[1] + else + _G.metadata.active_env = next(_G.metadata.envs) + end + -- Data is now in pio_config.core_dir, pio_config.envs.esp32c3_supermini, etc. + vim.schedule(function() + print('Core Dir: ' .. _G.metadata.core_dir) + end) + end) + + for _, kv in ipairs(map) do + -- 4.0 Fallback Logic: INI -> Env Var -> Default + local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') + -- 5. Expand ${platformio.core_dir} + if result:find('${platformio.core_dir}', 1, true) then + result = result:gsub('%${platformio.core_dir}', _G.metadata.core_dir) + end + -- 6. Normalize Slashes for Windows + _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') + end + return _G.metadata[map[type].ini] +end + + + + + + -- INFO: -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag -- stylua: ignore @@ -31,11 +121,12 @@ local function pio_generate_db() end) end +-- INFO: -- stylua: ignore local function GetActivePioEnv() local file = io.open('platformio.ini', 'r') if not file then - M.metadata.active_env = '' + _G.metadata.active_env = '' return nil end @@ -57,12 +148,10 @@ local function GetActivePioEnv() end -- INFO: 1. The Core PIO Manager & Generic Extractor +--- stylua: ignore local pio_manager = (function() local cache = nil -- Stores the decoded platformio.ini JSON structure - -- INFO: - -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' - -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } local function find_in_data(data, section_name, key_name) -- Safety check: Ensure data is a valid table from a successful JSON decode if type(data) ~= 'table' then @@ -93,106 +182,170 @@ local pio_manager = (function() return nil end - -- INFO: - -- ASYNC REFRESH: Fetches the latest config from PlatformIO CLI - -- stylua: ignore + -- INFO: ASYNC REFRESH: Fetches the latest config from PlatformIO CLI + --- stylua: ignore local function refresh(callback) - vim.schedule(function() vim.notify('PIO: Fetching Config...', vim.log.levels.INFO) end) + vim.schedule(function() + vim.notify('PIO: Fetching Config...', vim.log.levels.INFO) + end) -- INFO: - local function execute_pio(attempts) - if not M.metadata.active_env or M.metadata.active_env == '' then - vim.schedule(function() vim.notify('PIO: no env: found, add board first', vim.log.levels.ERROR) end) - return - end - vim.system({ 'pio', 'project', 'metadata', '-e', M.metadata.active_env, '--json-output' }, { text = true }, function(obj) - if obj.code ~= 0 then + local function get_metadata(attempts) + -- INFO: internal: pio project metadata + vim.system({ 'pio', 'project', 'metadata', '-e', _G.metadata.active_env, '--json-output' }, { text = true }, function(int_obj) + if int_obj.code ~= 0 then -- Schedule notification to avoid error in the system callback thread vim.schedule(function() - if obj.code == 127 then + if int_obj.code == 127 then vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else - vim.notify('PIO Manager: Failed to fetch config (Error ' .. obj.code .. ')', vim.log.levels.WARN) + vim.notify('PIO Manager: Failed to fetch config (Error ' .. int_obj.code .. ')', vim.log.levels.WARN) end end) return end - -- Error Checking: obj.code 0 means success - if obj.code == 0 and obj.stdout then - local ok, raw_data = pcall(vim.json.decode, obj.stdout) + _G.metadata.active_env = GetActivePioEnv() + if not _G.metadata.active_env or _G.metadata.active_env == '' then + vim.schedule(function() + vim.notify('PIO: no env: found, add board first', vim.log.levels.ERROR) + end) + return + end + -- Error Checking: int_obj.code 0 means success + if int_obj.code == 0 and int_obj.stdout then + local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) if ok and raw_data then local _, env = next(raw_data) - if not env then return end + if not env then + return + end local fallback_flags = {} -- 1. Process Includes - if env.includes then - for category, paths in pairs(env.includes) do - -- If it's a toolchain path, use -isystem to suppress warnings - -- and tell clangd these are standard libraries - local flag = (category == 'toolchain') and '-isystem' or '-I' - for _, path in ipairs(paths) do table.insert(fallback_flags, flag .. path) end - end - end + -- if env.includes then + -- for category, paths in pairs(env.includes) do + -- -- If it's a toolchain path, use -isystem to suppress warnings + -- -- and tell clangd these are standard libraries + -- local flag = (category == 'toolchain') and '-isystem' or '-I' + -- for _, path in ipairs(paths) do + -- table.insert(fallback_flags, flag .. path) + -- end + -- end + -- end -- 2. Process Defines if env.defines then - for _, define in ipairs(env.defines) do table.insert(fallback_flags, '-D' .. define) end + for _, define in ipairs(env.defines) do + table.insert(fallback_flags, '-D' .. define) + end end - M.metadata = { - driver_path = misc.normalize_path(env.cc_path:match('(.*[/\\])') .. '*') or '**', - cc_path = env.cc_path or '', - fallback_flags = fallback_flags, - } - -- M.metadata = decoded - if callback then vim.schedule(callback) end + _G.metadata.driver_path = misc.normalize_path(env.cc_path:match('(.*[/\\])') .. '*') or '**' + _G.metadata.cc_path = env.cc_path or '' + _G.metadata.fallback_flags = fallback_flags + + print(vim.inspect(_G.metadata)) + if callback then + vim.notify('PIO: Syncing Environment successful') + vim.schedule(callback) + end else - vim.schedule(function() vim.notify('PIO: Syncing Environment failed') end) + vim.schedule(function() + vim.notify('PIO: Syncing Environment failed') + end) end end -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save if attempts > 0 then - vim.defer_fn(function() execute_pio(attempts - 1) end, 500) + vim.defer_fn(function() + get_metadata(attempts - 1) + end, 500) else vim.schedule(function() - if obj.code ~= 0 then vim.notify('PIO: Config Error. Check platformio.ini syntax.', vim.log.levels.WARN) end + if int_obj.code ~= 0 then + vim.notify('PIO: Config Error. Check platformio.ini syntax.', vim.log.levels.WARN) + end end) end end) - -- Use Neovim's async system call to prevent UI freezing - -- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) - -- -- Error Checking: obj.code 0 means success - -- if obj.code == 0 and obj.stdout then - -- local ok, decoded = pcall(vim.json.decode, obj.stdout) - -- if ok and decoded then - -- cache = decoded - -- vim.schedule(function() - -- if not cache or type(cache) ~= 'table' then - -- vim.notify('PIO: Fetching Config failed. Check platformio.ini syntax.', vim.log.levels.INFO) - -- else - -- vim.notify('PIO: Fetching Config successful', vim.log.levels.INFO) - -- end - -- end) - -- if callback then - -- vim.schedule(callback) - -- end - -- return - -- end - -- end - -- - -- -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save - -- if attempts > 0 then - -- vim.defer_fn(function() - -- execute_pio(attempts - 1) - -- end, 500) - -- else - -- vim.schedule(function() - -- if obj.code ~= 0 then - -- vim.notify('PIO: Config Error. Check platformio.ini syntax.', vim.log.levels.WARN) - -- end - -- end) - -- end - -- end) end - execute_pio(1) + + -- local function get_pio_env(type) + -- 1. Setup Base Paths + local home = os.getenv('HOME') or os.getenv('USERPROFILE') + -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) + local map = { + core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, + packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, + platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, + } + + -- INFO: 3. Try to get explicit value from platformio.ini + -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' + -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } + vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) + if ext_obj.code ~= 0 then + -- Schedule notification to avoid error in the system callback thread + vim.schedule(function() + if ext_obj.code == 127 then + vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + else + vim.notify('PIO Manager: Failed to fetch config (Error ' .. ext_obj.code .. ')', vim.log.levels.WARN) + end + end) + return + end + _G.metadata.core_dir = '' + _G.metadata.packages_dir = '' + _G.metadata.platforms_dir = '' + _G.metadata.default_envs = {} + _G.metadata.envs = {} + + local decoded = vim.json.decode(ext_obj.stdout) + for _, section in ipairs(decoded) do + if type(section) == 'table' and #section >= 2 then + local name, data = section[1], section[2] + -- 1. Extract Global PlatformIO Settings + if name == 'platformio' then + for _, kv in ipairs(data) do + local key, val = kv[1], kv[2] + if _G.metadata[key] ~= nil then + _G.metadata[key] = val + end + end + -- 2. Extract all hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] + elseif name:match('^env:') then + local env_name = name:match('^env:(.+)') + _G.metadata.envs[env_name] = {} + for _, kv in ipairs(data) do + _G.metadata.envs[env_name][kv[1]] = kv[2] + end + end + end + end + if #_G.metadata.default_envs > 0 then + _G.metadata.active_env = _G.metadata.default_envs[1] + else + _G.metadata.active_env = next(_G.metadata.envs) + end + -- Data is now in pio_config.core_dir, pio_config.envs.esp32c3_supermini, etc. + vim.schedule(function() + print('Core Dir: ' .. _G.metadata.core_dir) + end) + end) + + for _, kv in ipairs(map) do + -- 4.0 Fallback Logic: INI -> Env Var -> Default + local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') + -- 5. Expand ${platformio.core_dir} + if type(result) == 'string' then + if result:find('${platformio.core_dir}', 1, true) then + result = result:gsub('%${platformio.core_dir}', _G.metadata.core_dir) + end + end + -- 6. Normalize Slashes for Windows + _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') + end + -- return _G.metadata[map[type].ini] + -- end + get_metadata(1) end -- INFO: @@ -282,9 +435,9 @@ function _G.get_pio_sdk_info() local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' print('get_pio_sdk_info(): final=' .. final) -- Normalize paths for the OS and ensure backslashes for Windows if needed - print(vim.inspect(M.metadata)) + print(vim.inspect(_G.metadata)) return (misc.normalize_path(final)) - -- return M.metadata.driver_path + -- return _G.metadata.driver_path -- return pio_info end @@ -292,110 +445,12 @@ end -- LSP HELPER: Returns the glob pattern for clangd's --query-driver -- e.g., C:\Users\tom\.platformio\packages\toolchain-riscv32-esp\bin\* function _G.get_pio_toolchain_pattern() - return M.metadata.driver_path - -- local ok_env, active_env = pcall(function() - -- return vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') - -- end) - -- if not ok_env or not active_env then - -- return '/**/bin/*' - -- end - -- - -- local target_env = 'env:' .. active_env - -- local platform = pio_manager.get(target_env, 'platform') - -- -- Determine the packages directory (Windows vs Linux/Mac home folders) - -- local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('USERPROFILE') or os.getenv('HOME') .. '/.platformio/packages') - -- - -- if not platform then - -- return '/**/bin/*' - -- end - -- - -- -- Use pio platform show to find which toolchain packages are associated with the platform - -- local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') - -- if not p_handle then - -- return '/**/bin/*' - -- end - -- local raw_json = p_handle:read('*all') - -- p_handle:close() - -- - -- local p_ok, p_data = pcall(vim.json.decode, raw_json) - -- if not p_ok or not p_data or not p_data.packages then - -- return '/**/bin/*' - -- end - -- - -- local toolchain_folder = '' - -- for _, pkg in ipairs(p_data.packages) do - -- -- Skip ULP (low power) toolchains and find the primary one for the architecture - -- if pkg.name and pkg.name:find('^toolchain%-') and not pkg.name:find('ulp') then - -- local check_path = (packages_dir .. '/' .. pkg.name):gsub('\\', '/') - -- if vim.fn.isdirectory(check_path) == 1 then - -- toolchain_folder = pkg.name - -- -- Verification: Match the toolchain name against the compiler used in compile_commands.json - -- local db_path = vim.uv.cwd() .. '/compile_commands.json' - -- local f = io.open(db_path, 'r') - -- if f then - -- local head = f:read(2048) -- Read enough to find the compiler path - -- f:close() - -- -- If the DB mentions "riscv32-esp", we ensure we picked the matching folder - -- if head and head:find(pkg.name:gsub('toolchain%-', '')) then - -- break - -- end - -- end - -- end - -- end - -- end - -- - -- if toolchain_folder == '' then - -- return '/**/bin/*' - -- end - -- - -- local final = packages_dir .. toolchain_folder - -- print('get_pio_toolchain 5: final=' .. final) - -- -- Normalize paths for the OS and ensure backslashes for Windows if needed - -- return (misc.normalize_path(final)) - -- return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final + return _G.metadata.driver_path end -- INFO: -- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync -- stylua: ignore --- local function start_pio_watcher() --- local platformioini = vim.uv.cwd() .. '/platformio.ini' --- -- if vim.fn.filereadable(platformioini) == 0 then return end --- --- local w = vim.uv.new_fs_event() --- if not w then return end --- w:start( platformioini, {}, --- vim.schedule_wrap(function(err, _, events) --- if err or not events or not events.change then --- return --- end --- --- if debounce_timer then --- -- 1. Stop any existing timer (cancel previous "half-finished" events) --- debounce_timer:stop() --- --- -- 2. Start a 500ms window. Logic only runs if NO more events happen in this time. --- debounce_timer:start( --- 500, --- 0, --- vim.schedule_wrap(function() --- M.metadata.active_env = GetActivePioEnv() --- pio_manager.refresh(function() --- --- vim.schedule(function() --- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) --- pio_generate_db() --- lsp.lsp_restart('clangd') --- vim.notify('PIO: Syncing Environment successful') --- end) --- end) --- end) --- ) --- end --- end) --- ) --- end - local function start_pio_watcher() local dir_path = vim.uv.cwd() if not dir_path then return end @@ -406,7 +461,7 @@ local function start_pio_watcher() return end - -- Watch the directory for file creation or the file itself for changes + -- Watch the directory for platformio.ini creation or changes w:start( dir_path, {}, @@ -422,7 +477,7 @@ local function start_pio_watcher() 500, 0, vim.schedule_wrap(function() - M.metadata.active_env = GetActivePioEnv() + -- _G.metadata.active_env = GetActivePioEnv() pio_manager.refresh(function() vim.schedule(function() boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) @@ -463,7 +518,7 @@ function M.init() start_pio_watcher() if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then - M.metadata.active_env = GetActivePioEnv() + -- _G.metadata.active_env = GetActivePioEnv() pio_manager.refresh(function() vim.schedule(function() boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) From 3487b0f6ff6deaef5ed354ffb1485d0b91f403ed Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 21:57:21 +0300 Subject: [PATCH 0592/1406] update --- lua/platformio/pio_setup.lua | 156 +++++++++++++++++------------------ 1 file changed, 78 insertions(+), 78 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 7b58e52c..8f4bc230 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -24,83 +24,83 @@ local debounce_timer = vim.uv.new_timer() ------------------------------------------------------ --- stylua: ignore -function M.get_pio_env(type) - -- 1. Setup Base Paths - local home = os.getenv('HOME') or os.getenv('USERPROFILE') - - -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) - local map = { - core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, - packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, - platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, - } - - -- INFO: 3. Try to get explicit value from platformio.ini - -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' - -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } - vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) - if ext_obj.code ~= 0 then - -- Schedule notification to avoid error in the system callback thread - vim.schedule(function() - if ext_obj.code == 127 then - vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) - else - vim.notify('PIO Manager: Failed to fetch config (Error ' .. ext_obj.code .. ')', vim.log.levels.WARN) - end - end) - return - end - _G.metadata.core_dir = '' - _G.metadata.packages_dir = '' - _G.metadata.platforms_dir = '' - _G.metadata.default_envs = {} - _G.metadata.envs = {} - - local decoded = vim.json.decode(ext_obj.stdout) - for _, section in ipairs(decoded) do - if type(section) == 'table' and #section >= 2 then - local name, data = section[1], section[2] - -- 1. Extract Global PlatformIO Settings - if name == 'platformio' then - for _, kv in ipairs(data) do - local key, val = kv[1], kv[2] - if _G.metadata[key] ~= nil then - _G.metadata[key] = val - end - end - -- 2. Extract all hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] - elseif name:match('^env:') then - local env_name = name:match('^env:(.+)') - _G.metadata.envs[env_name] = {} - for _, kv in ipairs(data) do - _G.metadata.envs[env_name][kv[1]] = kv[2] - end - end - end - end - if #_G.metadata.default_envs > 0 then - _G.metadata.active_env = _G.metadata.default_envs[1] - else - _G.metadata.active_env = next(_G.metadata.envs) - end - -- Data is now in pio_config.core_dir, pio_config.envs.esp32c3_supermini, etc. - vim.schedule(function() - print('Core Dir: ' .. _G.metadata.core_dir) - end) - end) - - for _, kv in ipairs(map) do - -- 4.0 Fallback Logic: INI -> Env Var -> Default - local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') - -- 5. Expand ${platformio.core_dir} - if result:find('${platformio.core_dir}', 1, true) then - result = result:gsub('%${platformio.core_dir}', _G.metadata.core_dir) - end - -- 6. Normalize Slashes for Windows - _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') - end - return _G.metadata[map[type].ini] -end +-- function M.get_pio_env(type) +-- -- 1. Setup Base Paths +-- local home = os.getenv('HOME') or os.getenv('USERPROFILE') +-- +-- -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) +-- local map = { +-- core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, +-- packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, +-- platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, +-- } +-- +-- -- INFO: 3. Try to get explicit value from platformio.ini +-- -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' +-- -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } +-- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) +-- if ext_obj.code ~= 0 then +-- -- Schedule notification to avoid error in the system callback thread +-- vim.schedule(function() +-- if ext_obj.code == 127 then +-- vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) +-- else +-- vim.notify('PIO Manager: Failed to fetch config (Error ' .. ext_obj.code .. ')', vim.log.levels.WARN) +-- end +-- end) +-- return +-- end +-- _G.metadata.core_dir = '' +-- _G.metadata.packages_dir = '' +-- _G.metadata.platforms_dir = '' +-- _G.metadata.default_envs = {} +-- _G.metadata.envs = {} +-- +-- local decoded = vim.json.decode(ext_obj.stdout) +-- for _, section in ipairs(decoded) do +-- if type(section) == 'table' and #section >= 2 then +-- local name, data = section[1], section[2] +-- -- 1. Extract Global PlatformIO Settings +-- if name == 'platformio' then +-- for _, kv in ipairs(data) do +-- local key, val = kv[1], kv[2] +-- if _G.metadata[key] ~= nil then +-- _G.metadata[key] = val +-- end +-- end +-- -- 2. Extract all hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] +-- elseif name:match('^env:') then +-- local env_name = name:match('^env:(.+)') +-- _G.metadata.envs[env_name] = {} +-- for _, kv in ipairs(data) do +-- _G.metadata.envs[env_name][kv[1]] = kv[2] +-- end +-- end +-- end +-- end +-- if #_G.metadata.default_envs > 0 then +-- _G.metadata.active_env = _G.metadata.default_envs[1] +-- else +-- _G.metadata.active_env = next(_G.metadata.envs) +-- end +-- -- Data is now in pio_config.core_dir, pio_config.envs.esp32c3_supermini, etc. +-- vim.schedule(function() +-- print('Core Dir: ' .. _G.metadata.core_dir) +-- end) +-- end) +-- +-- for _, kv in ipairs(map) do +-- -- 4.0 Fallback Logic: INI -> Env Var -> Default +-- local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') +-- -- 5. Expand ${platformio.core_dir} +-- if result:find('${platformio.core_dir}', 1, true) then +-- result = result:gsub('%${platformio.core_dir}', _G.metadata.core_dir) +-- end +-- -- 6. Normalize Slashes for Windows +-- _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') +-- end +-- return _G.metadata[map[type].ini] +-- end @@ -198,7 +198,7 @@ local pio_manager = (function() if int_obj.code == 127 then vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else - vim.notify('PIO Manager: Failed to fetch config (Error ' .. int_obj.code .. ')', vim.log.levels.WARN) + vim.notify('PIO Manager: Failed to fetch metadata (Error ' .. int_obj.code .. ')', vim.log.levels.WARN) end end) return From 4feebf37752461f5131e456436d7ab9debfc8c12 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 22:19:01 +0300 Subject: [PATCH 0593/1406] update --- lua/platformio/pio_setup.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 8f4bc230..0575be01 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -198,7 +198,7 @@ local pio_manager = (function() if int_obj.code == 127 then vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else - vim.notify('PIO Manager: Failed to fetch metadata (Error ' .. int_obj.code .. ')', vim.log.levels.WARN) + vim.notify('PIO Manager: Failed to fetch metadata (Error ' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) end end) return @@ -287,7 +287,7 @@ local pio_manager = (function() if ext_obj.code == 127 then vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else - vim.notify('PIO Manager: Failed to fetch config (Error ' .. ext_obj.code .. ')', vim.log.levels.WARN) + vim.notify('PIO Manager: Failed to fetch config (Error ' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) end end) return From ede9d047263a9918eb46eb25baa3e74f0f0cc1fb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 22:23:42 +0300 Subject: [PATCH 0594/1406] update --- lua/platformio/pio_setup.lua | 88 +----------------------------------- 1 file changed, 2 insertions(+), 86 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 0575be01..15f3cbba 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -22,91 +22,6 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local debounce_timer = vim.uv.new_timer() ------------------------------------------------------- ---- stylua: ignore --- function M.get_pio_env(type) --- -- 1. Setup Base Paths --- local home = os.getenv('HOME') or os.getenv('USERPROFILE') --- --- -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) --- local map = { --- core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, --- packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, --- platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, --- } --- --- -- INFO: 3. Try to get explicit value from platformio.ini --- -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' --- -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } --- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) --- if ext_obj.code ~= 0 then --- -- Schedule notification to avoid error in the system callback thread --- vim.schedule(function() --- if ext_obj.code == 127 then --- vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) --- else --- vim.notify('PIO Manager: Failed to fetch config (Error ' .. ext_obj.code .. ')', vim.log.levels.WARN) --- end --- end) --- return --- end --- _G.metadata.core_dir = '' --- _G.metadata.packages_dir = '' --- _G.metadata.platforms_dir = '' --- _G.metadata.default_envs = {} --- _G.metadata.envs = {} --- --- local decoded = vim.json.decode(ext_obj.stdout) --- for _, section in ipairs(decoded) do --- if type(section) == 'table' and #section >= 2 then --- local name, data = section[1], section[2] --- -- 1. Extract Global PlatformIO Settings --- if name == 'platformio' then --- for _, kv in ipairs(data) do --- local key, val = kv[1], kv[2] --- if _G.metadata[key] ~= nil then --- _G.metadata[key] = val --- end --- end --- -- 2. Extract all hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] --- elseif name:match('^env:') then --- local env_name = name:match('^env:(.+)') --- _G.metadata.envs[env_name] = {} --- for _, kv in ipairs(data) do --- _G.metadata.envs[env_name][kv[1]] = kv[2] --- end --- end --- end --- end --- if #_G.metadata.default_envs > 0 then --- _G.metadata.active_env = _G.metadata.default_envs[1] --- else --- _G.metadata.active_env = next(_G.metadata.envs) --- end --- -- Data is now in pio_config.core_dir, pio_config.envs.esp32c3_supermini, etc. --- vim.schedule(function() --- print('Core Dir: ' .. _G.metadata.core_dir) --- end) --- end) --- --- for _, kv in ipairs(map) do --- -- 4.0 Fallback Logic: INI -> Env Var -> Default --- local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') --- -- 5. Expand ${platformio.core_dir} --- if result:find('${platformio.core_dir}', 1, true) then --- result = result:gsub('%${platformio.core_dir}', _G.metadata.core_dir) --- end --- -- 6. Normalize Slashes for Windows --- _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') --- end --- return _G.metadata[map[type].ini] --- end - - - - - - -- INFO: -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag -- stylua: ignore @@ -191,7 +106,8 @@ local pio_manager = (function() -- INFO: local function get_metadata(attempts) -- INFO: internal: pio project metadata - vim.system({ 'pio', 'project', 'metadata', '-e', _G.metadata.active_env, '--json-output' }, { text = true }, function(int_obj) + -- vim.system({ 'pio', 'project', 'metadata', '-e', _G.metadata.active_env, '--json-output' }, { text = true }, function(int_obj) + vim.system({ 'pio', 'project', 'metadata', '-e', 'seeed_xiao_esp32c3', '--json-output' }, { text = true }, function(int_obj) if int_obj.code ~= 0 then -- Schedule notification to avoid error in the system callback thread vim.schedule(function() From 5a4722bf380d257ca97bb6476dd423ffa959832f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 22:36:11 +0300 Subject: [PATCH 0595/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 15f3cbba..438593ce 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -386,7 +386,7 @@ local function start_pio_watcher() return end -- Trigger only if the changed file is platformio.ini - if filename == 'platformio.ini' then + if filename == 'platformio.ini' and (events.change or events.rename) then if debounce_timer then debounce_timer:stop() debounce_timer:start( From f5214b1978a3e08d617a3a9b847572c52fda59ac Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 22:56:59 +0300 Subject: [PATCH 0596/1406] update --- lua/platformio/pio_setup.lua | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 438593ce..0c79eb40 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -107,6 +107,9 @@ local pio_manager = (function() local function get_metadata(attempts) -- INFO: internal: pio project metadata -- vim.system({ 'pio', 'project', 'metadata', '-e', _G.metadata.active_env, '--json-output' }, { text = true }, function(int_obj) + vim.schedule(function() + print(_G.metadata.active_env) + end) vim.system({ 'pio', 'project', 'metadata', '-e', 'seeed_xiao_esp32c3', '--json-output' }, { text = true }, function(int_obj) if int_obj.code ~= 0 then -- Schedule notification to avoid error in the system callback thread @@ -159,12 +162,14 @@ local pio_manager = (function() print(vim.inspect(_G.metadata)) if callback then - vim.notify('PIO: Syncing Environment successful') - vim.schedule(callback) + vim.schedule(function() + vim.notify('PIO: Syncing Environment successful', vim.log.levels.INFO) + callback() + end) end else vim.schedule(function() - vim.notify('PIO: Syncing Environment failed') + vim.notify('PIO: Syncing Environment failed', vim.log.levels.WARN) end) end end From c11fe3b33171877f3bbe4613d11426aacc92903a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 23:00:28 +0300 Subject: [PATCH 0597/1406] update --- lua/platformio/pio_setup.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 0c79eb40..674e0540 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -117,7 +117,7 @@ local pio_manager = (function() if int_obj.code == 127 then vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else - vim.notify('PIO Manager: Failed to fetch metadata (Error ' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + vim.notify('PIO Manager: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) end end) return @@ -208,7 +208,7 @@ local pio_manager = (function() if ext_obj.code == 127 then vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else - vim.notify('PIO Manager: Failed to fetch config (Error ' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + vim.notify('PIO Manager: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) end end) return From d89d673e75927319c6f94f538f23c6eb028d5d08 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 23:03:35 +0300 Subject: [PATCH 0598/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 674e0540..bec17f1a 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -108,7 +108,7 @@ local pio_manager = (function() -- INFO: internal: pio project metadata -- vim.system({ 'pio', 'project', 'metadata', '-e', _G.metadata.active_env, '--json-output' }, { text = true }, function(int_obj) vim.schedule(function() - print(_G.metadata.active_env) + print('env: ' .. _G.metadata.active_env) end) vim.system({ 'pio', 'project', 'metadata', '-e', 'seeed_xiao_esp32c3', '--json-output' }, { text = true }, function(int_obj) if int_obj.code ~= 0 then From 95391a150e834542420a9105de98e0488805c53d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 23:13:03 +0300 Subject: [PATCH 0599/1406] update --- lua/platformio/pio_setup.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index bec17f1a..a1f86844 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -216,6 +216,7 @@ local pio_manager = (function() _G.metadata.core_dir = '' _G.metadata.packages_dir = '' _G.metadata.platforms_dir = '' + _G.metadata.active_env = '' _G.metadata.default_envs = {} _G.metadata.envs = {} @@ -248,7 +249,7 @@ local pio_manager = (function() end -- Data is now in pio_config.core_dir, pio_config.envs.esp32c3_supermini, etc. vim.schedule(function() - print('Core Dir: ' .. _G.metadata.core_dir) + print('active_env: ' .. _G.metadata.active_env) end) end) From 3e8c7150f036a4a77ccbca7731acb048171c376b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 23:20:36 +0300 Subject: [PATCH 0600/1406] update --- lua/platformio/pio_setup.lua | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index a1f86844..22ab2b45 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -108,8 +108,14 @@ local pio_manager = (function() -- INFO: internal: pio project metadata -- vim.system({ 'pio', 'project', 'metadata', '-e', _G.metadata.active_env, '--json-output' }, { text = true }, function(int_obj) vim.schedule(function() - print('env: ' .. _G.metadata.active_env) + print('active_env0: ' .. _G.metadata.active_env) end) + if not _G.metadata.active_env or _G.metadata.active_env == '' then + vim.schedule(function() + vim.notify('PIO: no env: found, add board first', vim.log.levels.ERROR) + end) + return + end vim.system({ 'pio', 'project', 'metadata', '-e', 'seeed_xiao_esp32c3', '--json-output' }, { text = true }, function(int_obj) if int_obj.code ~= 0 then -- Schedule notification to avoid error in the system callback thread @@ -122,13 +128,6 @@ local pio_manager = (function() end) return end - _G.metadata.active_env = GetActivePioEnv() - if not _G.metadata.active_env or _G.metadata.active_env == '' then - vim.schedule(function() - vim.notify('PIO: no env: found, add board first', vim.log.levels.ERROR) - end) - return - end -- Error Checking: int_obj.code 0 means success if int_obj.code == 0 and int_obj.stdout then local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) @@ -249,7 +248,7 @@ local pio_manager = (function() end -- Data is now in pio_config.core_dir, pio_config.envs.esp32c3_supermini, etc. vim.schedule(function() - print('active_env: ' .. _G.metadata.active_env) + print('active_env1: ' .. _G.metadata.active_env) end) end) From f52b928a8322fe151aa5b1efa84173d5c92146f3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 14 Apr 2026 23:29:33 +0300 Subject: [PATCH 0601/1406] update --- lua/platformio/pio_setup.lua | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 22ab2b45..e9fb074b 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -242,13 +242,15 @@ local pio_manager = (function() end end if #_G.metadata.default_envs > 0 then - _G.metadata.active_env = _G.metadata.default_envs[1] + _G.metadata.active_env = _G.metadata.default_envs[1] or '' else - _G.metadata.active_env = next(_G.metadata.envs) + _G.metadata.active_env = next(_G.metadata.envs) or '' end -- Data is now in pio_config.core_dir, pio_config.envs.esp32c3_supermini, etc. vim.schedule(function() - print('active_env1: ' .. _G.metadata.active_env) + if _G.metadata.active_env then + print('active_env1: ' .. _G.metadata.active_env) + end end) end) From d542d3c666ac5ac9797a873f8aa8c001b19f4ebc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 05:54:32 +0300 Subject: [PATCH 0602/1406] update --- lua/platformio/pio_setup.lua | 53 ++++++++++++++++++------------------ 1 file changed, 27 insertions(+), 26 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index e9fb074b..5fdd020a 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -103,12 +103,13 @@ local pio_manager = (function() vim.schedule(function() vim.notify('PIO: Fetching Config...', vim.log.levels.INFO) end) - -- INFO: + + -- INFO: get metadata local function get_metadata(attempts) -- INFO: internal: pio project metadata -- vim.system({ 'pio', 'project', 'metadata', '-e', _G.metadata.active_env, '--json-output' }, { text = true }, function(int_obj) vim.schedule(function() - print('active_env0: ' .. _G.metadata.active_env) + print('active_env inner: ' .. _G.metadata.active_env) end) if not _G.metadata.active_env or _G.metadata.active_env == '' then vim.schedule(function() @@ -187,10 +188,9 @@ local pio_manager = (function() end) end - -- local function get_pio_env(type) - -- 1. Setup Base Paths + -- INFO: -- 1. Setup Base Paths local home = os.getenv('HOME') or os.getenv('USERPROFILE') - -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) + -- INFO: -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) local map = { core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, @@ -227,7 +227,8 @@ local pio_manager = (function() if name == 'platformio' then for _, kv in ipairs(data) do local key, val = kv[1], kv[2] - if _G.metadata[key] ~= nil then + if key ~= nil then + -- if _G.metadata[key] ~= nil then _G.metadata[key] = val end end @@ -246,29 +247,29 @@ local pio_manager = (function() else _G.metadata.active_env = next(_G.metadata.envs) or '' end - -- Data is now in pio_config.core_dir, pio_config.envs.esp32c3_supermini, etc. - vim.schedule(function() - if _G.metadata.active_env then - print('active_env1: ' .. _G.metadata.active_env) - end - end) - end) - for _, kv in ipairs(map) do - -- 4.0 Fallback Logic: INI -> Env Var -> Default - local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') - -- 5. Expand ${platformio.core_dir} - if type(result) == 'string' then - if result:find('${platformio.core_dir}', 1, true) then - result = result:gsub('%${platformio.core_dir}', _G.metadata.core_dir) + for _, kv in ipairs(map) do + -- 4.0 Fallback Logic: INI -> Env Var -> Default + local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') + -- 5. Expand ${platformio.core_dir} + if type(result) == 'string' then + if result:find('${platformio.core_dir}', 1, true) then + result = result:gsub('%${platformio.core_dir}', _G.metadata.core_dir) + end end + -- 6. Normalize Slashes for Windows + _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') end - -- 6. Normalize Slashes for Windows - _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') - end - -- return _G.metadata[map[type].ini] - -- end - get_metadata(1) + -- return _G.metadata[map[type].ini] + -- end + + if _G.metadata.active_env ~= '' then + vim.schedule(function() + print('active_env outer: ' .. _G.metadata.active_env) + end) + get_metadata(1) + end + end) end -- INFO: From dca578ff6ef2168da9a660bfef6e48e51c706f91 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 06:38:22 +0300 Subject: [PATCH 0603/1406] update --- lua/platformio/pio_setup.lua | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 5fdd020a..1eb3b31b 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -109,7 +109,7 @@ local pio_manager = (function() -- INFO: internal: pio project metadata -- vim.system({ 'pio', 'project', 'metadata', '-e', _G.metadata.active_env, '--json-output' }, { text = true }, function(int_obj) vim.schedule(function() - print('active_env inner: ' .. _G.metadata.active_env) + print('active_env metadata: ' .. _G.metadata.active_env) end) if not _G.metadata.active_env or _G.metadata.active_env == '' then vim.schedule(function() @@ -150,14 +150,14 @@ local pio_manager = (function() -- end -- end -- 2. Process Defines - if env.defines then - for _, define in ipairs(env.defines) do - table.insert(fallback_flags, '-D' .. define) - end - end + -- if env.defines then + -- for _, define in ipairs(env.defines) do + -- table.insert(fallback_flags, '-D' .. define) + -- end + -- end _G.metadata.driver_path = misc.normalize_path(env.cc_path:match('(.*[/\\])') .. '*') or '**' - _G.metadata.cc_path = env.cc_path or '' + _G.metadata.cc_path = misc.normalize_path(env.cc_path) or '' _G.metadata.fallback_flags = fallback_flags print(vim.inspect(_G.metadata)) @@ -193,8 +193,8 @@ local pio_manager = (function() -- INFO: -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) local map = { core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, - packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, - platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, + packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, + platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, } -- INFO: 3. Try to get explicit value from platformio.ini @@ -258,14 +258,15 @@ local pio_manager = (function() end end -- 6. Normalize Slashes for Windows - _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') + -- _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') + _G.metadata[kv.ini] = result:gsub('\\', '/'):gsub('//+', '/') end -- return _G.metadata[map[type].ini] -- end if _G.metadata.active_env ~= '' then vim.schedule(function() - print('active_env outer: ' .. _G.metadata.active_env) + print('active_env config: ' .. _G.metadata.active_env) end) get_metadata(1) end @@ -407,7 +408,7 @@ local function start_pio_watcher() boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) pio_generate_db() lsp.lsp_restart('clangd') - vim.notify('PIO: Syncing Environment successful') + -- vim.notify('PIO: Syncing Environment successful') end) end) end) @@ -448,7 +449,7 @@ function M.init() boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) pio_generate_db() lsp.lsp_restart('clangd') - vim.notify('PIO: Syncing Environment successful') + -- vim.notify('PIO: Syncing Environment successful') end) end) end From 407e8a67d54fd87d7ff384dc2dd21242cdb9ad10 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 06:51:58 +0300 Subject: [PATCH 0604/1406] update --- lua/platformio/pio_setup.lua | 26 +++++++++----------------- 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 1eb3b31b..5f4ba86e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -101,7 +101,7 @@ local pio_manager = (function() --- stylua: ignore local function refresh(callback) vim.schedule(function() - vim.notify('PIO: Fetching Config...', vim.log.levels.INFO) + vim.notify('PIO: Fetching Config ...', vim.log.levels.INFO) end) -- INFO: get metadata @@ -109,15 +109,9 @@ local pio_manager = (function() -- INFO: internal: pio project metadata -- vim.system({ 'pio', 'project', 'metadata', '-e', _G.metadata.active_env, '--json-output' }, { text = true }, function(int_obj) vim.schedule(function() - print('active_env metadata: ' .. _G.metadata.active_env) + vim.notify('PIO: Fetching metadata ...', vim.log.levels.INFO) end) - if not _G.metadata.active_env or _G.metadata.active_env == '' then - vim.schedule(function() - vim.notify('PIO: no env: found, add board first', vim.log.levels.ERROR) - end) - return - end - vim.system({ 'pio', 'project', 'metadata', '-e', 'seeed_xiao_esp32c3', '--json-output' }, { text = true }, function(int_obj) + vim.system({ 'pio', 'project', 'metadata', '-e', _G.metadata.active_env, '--json-output' }, { text = true }, function(int_obj) if int_obj.code ~= 0 then -- Schedule notification to avoid error in the system callback thread vim.schedule(function() @@ -163,7 +157,7 @@ local pio_manager = (function() print(vim.inspect(_G.metadata)) if callback then vim.schedule(function() - vim.notify('PIO: Syncing Environment successful', vim.log.levels.INFO) + vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) callback() end) end @@ -178,12 +172,6 @@ local pio_manager = (function() vim.defer_fn(function() get_metadata(attempts - 1) end, 500) - else - vim.schedule(function() - if int_obj.code ~= 0 then - vim.notify('PIO: Config Error. Check platformio.ini syntax.', vim.log.levels.WARN) - end - end) end end) end @@ -266,9 +254,13 @@ local pio_manager = (function() if _G.metadata.active_env ~= '' then vim.schedule(function() - print('active_env config: ' .. _G.metadata.active_env) + vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) end) get_metadata(1) + else + vim.schedule(function() + vim.notify('PIO: no [env:] found, add board first', vim.log.levels.ERROR) + end) end end) end From 17a8152711639f1b437ed4e6f3021799219c6e56 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 07:47:35 +0300 Subject: [PATCH 0605/1406] update --- lua/platformio/pio_setup.lua | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 5f4ba86e..a22a236c 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -373,13 +373,13 @@ local function start_pio_watcher() if not dir_path then return end -- Create a directory watcher - local w = vim.uv.new_fs_event() - if not w then + local handle = vim.uv.new_fs_event() + if not handle then return end -- Watch the directory for platformio.ini creation or changes - w:start( + handle:start( dir_path, {}, vim.schedule_wrap(function(err, filename, events) @@ -387,20 +387,19 @@ local function start_pio_watcher() return end -- Trigger only if the changed file is platformio.ini - if filename == 'platformio.ini' and (events.change or events.rename) then + -- if filename == 'platformio.ini' and (events.change or events.rename) then + if filename == 'platformio.ini' and (events.change) then if debounce_timer then debounce_timer:stop() debounce_timer:start( 500, 0, vim.schedule_wrap(function() - -- _G.metadata.active_env = GetActivePioEnv() pio_manager.refresh(function() vim.schedule(function() boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) pio_generate_db() lsp.lsp_restart('clangd') - -- vim.notify('PIO: Syncing Environment successful') end) end) end) @@ -433,15 +432,16 @@ function M.init() require('platformio.lspConfig.attach') end + -- Always start the watcher so it can catch a future 'pio init' start_pio_watcher() + + -- If the file already exists, do an initial sync if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then - -- _G.metadata.active_env = GetActivePioEnv() pio_manager.refresh(function() vim.schedule(function() boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) pio_generate_db() lsp.lsp_restart('clangd') - -- vim.notify('PIO: Syncing Environment successful') end) end) end From 964b784e1bfa8feb34ddae818f42ee3b5abe6f53 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 08:08:12 +0300 Subject: [PATCH 0606/1406] update --- lua/platformio/pio_setup.lua | 77 +++++++++++++++--------------------- 1 file changed, 31 insertions(+), 46 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index a22a236c..08245720 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -29,39 +29,19 @@ local function pio_generate_db() vim.schedule(function() vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) end) vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) if obj.code ~= 0 then - vim.schedule(function() vim.notify('PIO: Generating Compile Database failed', vim.log.levels.INFO) end) + vim.schedule(function() + if obj.code == 127 then + vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + else + vim.notify('PIO Manager: Generating Compile Database failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + end + end) return end vim.schedule(function() vim.notify('PIO: Generating Compile Database successful', vim.log.levels.INFO) end) end) end --- INFO: --- stylua: ignore -local function GetActivePioEnv() - local file = io.open('platformio.ini', 'r') - if not file then - _G.metadata.active_env = '' - return nil - end - - local result_env = nil - for line in file:lines() do - -- 1. Try to find the explicit default_envs first - local default = line:match('^default_envs%s*=%s*(%S+)') - if default then - result_env= default - -- 2. Capture the first [env:NAME] we see as a fallback - elseif not result_env then - result_env = line:match('^%[env:(%S+)%]') - end - end - file:close() - print(result_env) - -- Return the first env found if no default was explicitly set - return result_env -end - -- INFO: 1. The Core PIO Manager & Generic Extractor --- stylua: ignore local pio_manager = (function() @@ -372,6 +352,7 @@ local function start_pio_watcher() local dir_path = vim.uv.cwd() if not dir_path then return end + local last_trigger = 0 -- Create a directory watcher local handle = vim.uv.new_fs_event() if not handle then @@ -383,29 +364,33 @@ local function start_pio_watcher() dir_path, {}, vim.schedule_wrap(function(err, filename, events) - if err or not events or not events.change then - return - end + if err or not events or not events.change then return end -- Trigger only if the changed file is platformio.ini - -- if filename == 'platformio.ini' and (events.change or events.rename) then - if filename == 'platformio.ini' and (events.change) then - if debounce_timer then - debounce_timer:stop() - debounce_timer:start( - 500, - 0, - vim.schedule_wrap(function() - pio_manager.refresh(function() - vim.schedule(function() - boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - pio_generate_db() - lsp.lsp_restart('clangd') + if filename == 'platformio.ini' and (events.change or events.rename) then + local current_time = vim.uv.now() + -- IGNORE events if they happen within 100ms of the last one + if current_time - last_trigger < 100 then + return + end + last_trigger = current_time + + if debounce_timer then + debounce_timer:stop() + debounce_timer:start( + 500, + 0, + vim.schedule_wrap(function() + pio_manager.refresh(function() + vim.schedule(function() + boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + pio_generate_db() + lsp.lsp_restart('clangd') + end) end) end) - end) - ) + ) + end end - end end) ) end From f2d2f9013e56a75e37a5a1a9e9f190b49f20e53e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 08:25:47 +0300 Subject: [PATCH 0607/1406] update --- lua/platformio/pio_setup.lua | 50 ++++++++++++++++++------------------ 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 08245720..214e6378 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -84,14 +84,13 @@ local pio_manager = (function() vim.notify('PIO: Fetching Config ...', vim.log.levels.INFO) end) - -- INFO: get metadata + -- INFO: get project metadata local function get_metadata(attempts) - -- INFO: internal: pio project metadata - -- vim.system({ 'pio', 'project', 'metadata', '-e', _G.metadata.active_env, '--json-output' }, { text = true }, function(int_obj) - vim.schedule(function() - vim.notify('PIO: Fetching metadata ...', vim.log.levels.INFO) - end) vim.system({ 'pio', 'project', 'metadata', '-e', _G.metadata.active_env, '--json-output' }, { text = true }, function(int_obj) + vim.schedule(function() + vim.notify('PIO: Fetching metadata ...', vim.log.levels.INFO) + end) + if int_obj.code ~= 0 then -- Schedule notification to avoid error in the system callback thread vim.schedule(function() @@ -103,7 +102,7 @@ local pio_manager = (function() end) return end - -- Error Checking: int_obj.code 0 means success + if int_obj.code == 0 and int_obj.stdout then local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) if ok and raw_data then @@ -352,7 +351,7 @@ local function start_pio_watcher() local dir_path = vim.uv.cwd() if not dir_path then return end - local last_trigger = 0 + -- local last_trigger = 0 -- Create a directory watcher local handle = vim.uv.new_fs_event() if not handle then @@ -366,13 +365,14 @@ local function start_pio_watcher() vim.schedule_wrap(function(err, filename, events) if err or not events or not events.change then return end -- Trigger only if the changed file is platformio.ini - if filename == 'platformio.ini' and (events.change or events.rename) then - local current_time = vim.uv.now() - -- IGNORE events if they happen within 100ms of the last one - if current_time - last_trigger < 100 then - return - end - last_trigger = current_time + -- if filename == 'platformio.ini' and (events.change or events.rename) then + if filename == 'platformio.ini' and (events.change) then + -- local current_time = vim.uv.now() + -- -- IGNORE events if they happen within 100ms of the last one + -- if current_time - last_trigger < 100 then + -- return + -- end + -- last_trigger = current_time if debounce_timer then debounce_timer:stop() @@ -381,11 +381,11 @@ local function start_pio_watcher() 0, vim.schedule_wrap(function() pio_manager.refresh(function() - vim.schedule(function() - boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - pio_generate_db() - lsp.lsp_restart('clangd') - end) + -- vim.schedule(function() + boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + pio_generate_db() + lsp.lsp_restart('clangd') + -- end) end) end) ) @@ -423,11 +423,11 @@ function M.init() -- If the file already exists, do an initial sync if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then pio_manager.refresh(function() - vim.schedule(function() - boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - pio_generate_db() - lsp.lsp_restart('clangd') - end) + -- vim.schedule(function() + boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + pio_generate_db() + lsp.lsp_restart('clangd') + -- end) end) end end From b3b220d2b8ab33081dfb117a3e7f92b3dd85d149 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 08:39:21 +0300 Subject: [PATCH 0608/1406] update --- lua/platformio/pio_setup.lua | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 214e6378..6614db3e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -351,7 +351,7 @@ local function start_pio_watcher() local dir_path = vim.uv.cwd() if not dir_path then return end - -- local last_trigger = 0 + local last_trigger = 0 -- Create a directory watcher local handle = vim.uv.new_fs_event() if not handle then @@ -365,14 +365,14 @@ local function start_pio_watcher() vim.schedule_wrap(function(err, filename, events) if err or not events or not events.change then return end -- Trigger only if the changed file is platformio.ini - -- if filename == 'platformio.ini' and (events.change or events.rename) then - if filename == 'platformio.ini' and (events.change) then - -- local current_time = vim.uv.now() - -- -- IGNORE events if they happen within 100ms of the last one - -- if current_time - last_trigger < 100 then - -- return - -- end - -- last_trigger = current_time + if filename == 'platformio.ini' and (events.change or events.rename) then + -- ignore events within time + local current_time = vim.uv.now() + -- IGNORE events if they happen within 100ms of the last one + if current_time - last_trigger < 100 then + return + end + last_trigger = current_time if debounce_timer then debounce_timer:stop() From 732cd7a1ad9968d14e02b5af6857ed6b709a3fdf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 08:41:29 +0300 Subject: [PATCH 0609/1406] update --- lua/platformio/pio_setup.lua | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 6614db3e..81502b33 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -351,28 +351,30 @@ local function start_pio_watcher() local dir_path = vim.uv.cwd() if not dir_path then return end - local last_trigger = 0 -- Create a directory watcher local handle = vim.uv.new_fs_event() - if not handle then - return - end + if not handle then return end + -- local last_trigger = 0 -- Watch the directory for platformio.ini creation or changes handle:start( dir_path, - {}, + { + watch_entry = false, -- watch the file/dir itself + stat = false, -- use stat to detect changes (slower but more reliable on some FS) + recursive = false, -- watch subdirectories (if path is a directory) + }, vim.schedule_wrap(function(err, filename, events) if err or not events or not events.change then return end -- Trigger only if the changed file is platformio.ini if filename == 'platformio.ini' and (events.change or events.rename) then - -- ignore events within time - local current_time = vim.uv.now() - -- IGNORE events if they happen within 100ms of the last one - if current_time - last_trigger < 100 then - return - end - last_trigger = current_time + -- -- ignore events within time + -- local current_time = vim.uv.now() + -- -- IGNORE events if they happen within 100ms of the last one + -- if current_time - last_trigger < 100 then + -- return + -- end + -- last_trigger = current_time if debounce_timer then debounce_timer:stop() From 69e194ea9c670a63ef13f7144a347b70c8b3c08f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 08:57:07 +0300 Subject: [PATCH 0610/1406] update --- lua/platformio/pio_setup.lua | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 81502b33..405f463c 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -112,16 +112,22 @@ local pio_manager = (function() end local fallback_flags = {} -- 1. Process Includes - -- if env.includes then - -- for category, paths in pairs(env.includes) do - -- -- If it's a toolchain path, use -isystem to suppress warnings - -- -- and tell clangd these are standard libraries - -- local flag = (category == 'toolchain') and '-isystem' or '-I' - -- for _, path in ipairs(paths) do - -- table.insert(fallback_flags, flag .. path) - -- end - -- end - -- end + if env.includes then + for category, paths in pairs(env.includes) do + -- If it's a toolchain path, use -isystem to suppress warnings + -- and tell clangd these are standard libraries + if category == 'toolchain' then + local flag = '-isystem' + for _, path in ipairs(paths) do + table.insert(fallback_flags, flag .. path) + end + end + -- local flag = (category == 'toolchain') and '-isystem' or '-I' + -- for _, path in ipairs(paths) do + -- table.insert(fallback_flags, flag .. path) + -- end + end + end -- 2. Process Defines -- if env.defines then -- for _, define in ipairs(env.defines) do From ef1007cffe721cfc8e43df8489b27db2e4841527 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 10:04:34 +0300 Subject: [PATCH 0611/1406] update --- lua/platformio/archived/fix_compiledb.py | 63 ++++++++++++++++++++ lua/platformio/archived/ufix_compiledb.py | 72 +++++++++++++++++++++++ lua/platformio/pio_setup.lua | 7 ++- 3 files changed, 139 insertions(+), 3 deletions(-) create mode 100644 lua/platformio/archived/fix_compiledb.py create mode 100644 lua/platformio/archived/ufix_compiledb.py diff --git a/lua/platformio/archived/fix_compiledb.py b/lua/platformio/archived/fix_compiledb.py new file mode 100644 index 00000000..bcaf49e3 --- /dev/null +++ b/lua/platformio/archived/fix_compiledb.py @@ -0,0 +1,63 @@ +import json +import os + +# Grab the environment from PlatformIO +Import("env") + +def get_toolchain_metadata(): + """Detects active toolchain and returns (cc_path, sysroot, target_triplet).""" + platform = env.PioPlatform() + + # List of known Espressif toolchains and their internal triplets + toolchains = [ + ("toolchain-riscv32-esp", "riscv32-esp-elf"), + ("toolchain-xtensa-esp32", "xtensa-esp32-elf"), + ("toolchain-xtensa-esp32s2", "xtensa-esp32s2-elf"), + ("toolchain-xtensa-esp32s3", "xtensa-esp32s3-elf"), + ] + + for pkg_name, triplet in toolchains: + pkg_dir = platform.get_package_dir(pkg_name) + if pkg_dir: + # Construct paths + cc_name = f"{triplet}-gcc" + cc_path = os.path.join(pkg_dir, "bin", cc_name) + if os.name == "nt": + cc_path += ".exe" + + sysroot = os.path.join(pkg_dir, triplet) + + # Return cleaned forward-slash paths for clangd compatibility + return cc_path.replace("\\", "/"), sysroot.replace("\\", "/"), triplet + + return None, None, None + +def update_compilation_db(source, target, env_inner): + """Callback to fix the JSON file after generation.""" + db_path = str(target) + cc_path, sysroot, triplet = get_toolchain_metadata() + + if not cc_path or not os.path.exists(db_path): + print(f"-- [FixDB] Toolchain not detected or {db_path} missing.") + return + + with open(db_path, "r") as f: + db = json.load(f) + + for entry in db: + # Inject the correct target and sysroot + extra_flags = f" --target={triplet} --sysroot=\"{sysroot}\"" + + if "--target=" not in entry["command"]: + # Replace relative compiler name with absolute path + entry["command"] = entry["command"].replace(f"{triplet}-gcc", f"\"{cc_path}\"") + entry["command"] += extra_flags + + with open(db_path, "w") as f: + json.dump(db, f, indent=2) + + print(f"\n-- [FixDB] Auto-detected {triplet}") + print(f"-- [FixDB] Injected sysroot: {sysroot}") + +# Register the hook +env.AddPostAction("$PROJECT_DIR/compile_commands.json", update_compilation_db) diff --git a/lua/platformio/archived/ufix_compiledb.py b/lua/platformio/archived/ufix_compiledb.py new file mode 100644 index 00000000..c206f438 --- /dev/null +++ b/lua/platformio/archived/ufix_compiledb.py @@ -0,0 +1,72 @@ +import glob +import json +import os + +Import("env") + + +def get_dynamic_toolchain(): + """Scans all installed packages to find the active toolchain and triplet.""" + platform = env.PioPlatform() + # Get the directory where all packages for this platform are stored + packages_dir = platform.get_package_dir("") or "" + + # Scan for any toolchain packages currently in use + for pkg_name in platform.packages.keys(): + if not pkg_name.startswith("toolchain-"): + continue + + pkg_dir = platform.get_package_dir(pkg_name) + if not pkg_dir: + continue + + # Logic: The triplet is usually the name of the folder inside /bin + # before the '-gcc' suffix. e.g., 'riscv32-esp-elf-gcc' -> 'riscv32-esp-elf' + bin_dir = os.path.join(pkg_dir, "bin") + gcc_files = glob.glob(os.path.join(bin_dir, "*-gcc*")) + + if gcc_files: + # Extract triplet from the first gcc binary found + # e.g., C:/.../bin/xtensa-esp32-elf-gcc.exe -> xtensa-esp32-elf + filename = os.path.basename(gcc_files[0]) + triplet = filename.split("-gcc")[0] + + cc_path = gcc_files[0].replace("\\", "/") + sysroot = os.path.join(pkg_dir, triplet).replace("\\", "/") + + if os.path.isdir(sysroot): + return cc_path, sysroot, triplet + + return None, None, None + + +def update_compilation_db(source, target, env_inner): + db_path = str(target) + cc_path, sysroot, triplet = get_dynamic_toolchain() + + if not cc_path or not os.path.exists(db_path): + print("-- [UniversalFix] Toolchain not found via dynamic scan.") + return + + with open(db_path, "r") as f: + db = json.load(f) + + for entry in db: + extra_flags = f' --target={triplet} --sysroot="{sysroot}"' + # Replace the compiler command if it's just the binary name + if triplet in entry["command"] and "--target=" not in entry["command"]: + # This regex-like replacement ensures we don't break existing flags + entry["command"] = entry["command"].replace( + f"{triplet}-gcc", f'"{cc_path}"' + ) + entry["command"] += extra_flags + + with open(db_path, "w") as f: + json.dump(db, f, indent=2) + + print(f"\n-- [UniversalFix] Detected: {triplet}") + print(f"-- [UniversalFix] Sysroot: {sysroot}") + + +# Hook into the compilation database generation +env.AddPostAction("$PROJECT_DIR/compile_commands.json", update_compilation_db) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 405f463c..bf6105da 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -85,8 +85,9 @@ local pio_manager = (function() end) -- INFO: get project metadata - local function get_metadata(attempts) - vim.system({ 'pio', 'project', 'metadata', '-e', _G.metadata.active_env, '--json-output' }, { text = true }, function(int_obj) + local function get_metadata(attempts, env) + local active_env = env or _G.metadata.active_env + vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(int_obj) vim.schedule(function() vim.notify('PIO: Fetching metadata ...', vim.log.levels.INFO) end) @@ -241,7 +242,7 @@ local pio_manager = (function() vim.schedule(function() vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) end) - get_metadata(1) + get_metadata(1, _G.metadata.active_env) else vim.schedule(function() vim.notify('PIO: no [env:] found, add board first', vim.log.levels.ERROR) From 41154d4d01ee3daf1dc72dd1d296d82f3a54199f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 11:01:51 +0300 Subject: [PATCH 0612/1406] update --- lua/platformio/boilerplate.lua | 17 +++++++++++++++++ lua/platformio/lspConfig/clangd.lua | 26 +++++++++++++++++--------- lua/platformio/pio_setup.lua | 2 ++ 3 files changed, 36 insertions(+), 9 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index b7fbec3a..4f4306c6 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -68,6 +68,23 @@ print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") ]], } +-- INFO: .clangd_init_options +boilerplate['.clangd_init_options'] = { + rewrite = true, + template = [[ +usePlaceholders = true, +completeUnimported = true, +fallbackFlags =%s, +clangdFileStatus = true, +compilationDatabasePath = %s, +]], + content = function(self) + return string.format(self.template, "{ '-std=c++17' }" or '{}', vim.uv.cwd()) + -- return string.format(self.template, _G.get_pio_toolchain_pattern() or '**') + -- return string.format(self.template, _G.get_pio_sdk_info() or '**') + end, +} + -- INFO: .clangd_cmd boilerplate['.clangd_cmd'] = { rewrite = true, diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 638217c1..a58ea2e4 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -125,9 +125,7 @@ vim.lsp.config('*', { -- INFO: configure clangd lsp server ----------------------------------------------------------------------------------------- local cmd = { 'clangd' } --- local fname = string.format('%s/.clangd_cmd', vim.fn.getcwd()) local fname = string.format('%s/.clangd_cmd', vim.uv.cwd()) --- if vim.fn.filereadable(fname) == 1 then if vim.uv.fs_stat(fname) then ok, result = pcall(vim.fn.readfile, fname) if ok then @@ -136,6 +134,22 @@ if vim.uv.fs_stat(fname) then end end +local init_options = { + usePlaceholders = true, + completeUnimported = true, + fallbackFlags = { '-std=c++17' }, + clangdFileStatus = true, + compilationDatabasePath = vim.uv.cwd(), +} +fname = string.format('%s/.clangd_init_options', vim.uv.cwd()) +if vim.uv.fs_stat(fname) then + ok, result = pcall(vim.fn.readfile, fname) + if ok then + init_options = result + -- print(vim.inspect(cmd)) + end +end + local clangd = { cmd = cmd, filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, @@ -152,13 +166,7 @@ local clangd = { }, workspace_required = true, single_file_support = true, - init_options = { - usePlaceholders = true, - completeUnimported = true, - fallback_flags = { '-std=c++17' }, - clangdFileStatus = true, - compilationDatabasePath = vim.uv.cwd(), - }, + init_options = init_options, } vim.lsp.config('clangd', clangd) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index bf6105da..fd2e981a 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -392,6 +392,7 @@ local function start_pio_watcher() pio_manager.refresh(function() -- vim.schedule(function() boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) pio_generate_db() lsp.lsp_restart('clangd') -- end) @@ -434,6 +435,7 @@ function M.init() pio_manager.refresh(function() -- vim.schedule(function() boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) pio_generate_db() lsp.lsp_restart('clangd') -- end) From 99e902ee06bd4f26792ec6943bb1bbd4a1dbe3fc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 11:43:27 +0300 Subject: [PATCH 0613/1406] update --- lua/platformio/boilerplate.lua | 18 +++++++++-------- lua/platformio/pio_setup.lua | 36 ++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 8 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 4f4306c6..59520d67 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -72,16 +72,18 @@ print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") boilerplate['.clangd_init_options'] = { rewrite = true, template = [[ -usePlaceholders = true, -completeUnimported = true, -fallbackFlags =%s, -clangdFileStatus = true, -compilationDatabasePath = %s, +usePlaceholders=true, +completeUnimported=true, +fallbackFlags=%s, +clangdFileStatus=true, +compilationDatabasePath=%s, ]], content = function(self) - return string.format(self.template, "{ '-std=c++17' }" or '{}', vim.uv.cwd()) - -- return string.format(self.template, _G.get_pio_toolchain_pattern() or '**') - -- return string.format(self.template, _G.get_pio_sdk_info() or '**') + return string.format( + self.template, + ("{'-std=c++17','target=" .. _G.metadata.triplet .. "','sysroot=" .. _G.metadata.sysroot .. "'}") or "{ '-std=c++17' }", + vim.uv.cwd() + ) end, } diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index fd2e981a..d80fc043 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -9,6 +9,8 @@ _G.metadata = { active_env = '', driver_path = '', cc_path = '', + triplet = '', + sysroot = '', fallback_flags = {}, } @@ -22,6 +24,36 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local debounce_timer = vim.uv.new_timer() +-- INFO: +-- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag +-- stylua: ignore +local function get_sysroot_triplet(bin_path) + -- Use Neovim's loop (uv) for file system scanning + local luv = vim.loop or vim.uv + local handle = luv.fs_scandir(bin_path) + if not handle then return nil, 'Invalid path' end + + while true do + local name = luv.fs_scandir_next(handle) + if not name then break end + + -- Search for the G++ compiler binary + -- Matches triplet prefix from names like 'riscv32-esp-elf-g++' or 'xtensa-esp32-elf-g++.exe' + local triplet = name:match('^(.*)%-g%+%+.*$') + + if triplet then + -- Get the toolchain root (parent of /bin) + local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') + local sysroot_path = toolchain_root .. '/' .. triplet + + -- Verify if the folder actually exists + if vim.fn.isdirectory(sysroot_path) == 1 then return triplet, sysroot_path end + end + end + return nil, 'No valid triplet folder found' +end + + -- INFO: -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag -- stylua: ignore @@ -140,6 +172,10 @@ local pio_manager = (function() _G.metadata.cc_path = misc.normalize_path(env.cc_path) or '' _G.metadata.fallback_flags = fallback_flags + local triplet, sysroot = get_sysroot_triplet(_G.metadata.cc_path) + _G.metadata.triplet = triplet + _G.metadata.sysroot = sysroot + print(vim.inspect(_G.metadata)) if callback then vim.schedule(function() From e3beaf20e6724e82604fab6978cef68a2f7b9728 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 11:48:26 +0300 Subject: [PATCH 0614/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 59520d67..7f4f9f4e 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -81,7 +81,7 @@ compilationDatabasePath=%s, content = function(self) return string.format( self.template, - ("{'-std=c++17','target=" .. _G.metadata.triplet .. "','sysroot=" .. _G.metadata.sysroot .. "'}") or "{ '-std=c++17' }", + ("{'-std=c++17','target=" .. _G.metadata.triplet or '' .. "','sysroot=" .. _G.metadata.sysroot or '' .. "'}") or "{ '-std=c++17' }", vim.uv.cwd() ) end, From d01f3efdb1b4da5f355c5187853659838a8d4c42 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 11:56:06 +0300 Subject: [PATCH 0615/1406] update --- lua/platformio/pio_setup.lua | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index d80fc043..44ca0e4e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -173,8 +173,10 @@ local pio_manager = (function() _G.metadata.fallback_flags = fallback_flags local triplet, sysroot = get_sysroot_triplet(_G.metadata.cc_path) - _G.metadata.triplet = triplet - _G.metadata.sysroot = sysroot + if triplet then + _G.metadata.triplet = triplet + _G.metadata.sysroot = sysroot + end print(vim.inspect(_G.metadata)) if callback then From 2820e5091910af5eab161a490b2cbcaabb241dab Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 13:24:00 +0300 Subject: [PATCH 0616/1406] update --- lua/platformio/boilerplate.lua | 4 ++-- lua/platformio/pio_setup.lua | 13 +++++++------ 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 7f4f9f4e..3bd671ce 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -74,14 +74,14 @@ boilerplate['.clangd_init_options'] = { template = [[ usePlaceholders=true, completeUnimported=true, -fallbackFlags=%s, +fallbackFlags={%s}, clangdFileStatus=true, compilationDatabasePath=%s, ]], content = function(self) return string.format( self.template, - ("{'-std=c++17','target=" .. _G.metadata.triplet or '' .. "','sysroot=" .. _G.metadata.sysroot or '' .. "'}") or "{ '-std=c++17' }", + ("'-std=c++17','target=" .. _G.metadata.triplet .. "','sysroot=" .. _G.metadata.sysroot .. "'") or "'-std=c++17'", vim.uv.cwd() ) end, diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 44ca0e4e..e3d912f6 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -172,12 +172,6 @@ local pio_manager = (function() _G.metadata.cc_path = misc.normalize_path(env.cc_path) or '' _G.metadata.fallback_flags = fallback_flags - local triplet, sysroot = get_sysroot_triplet(_G.metadata.cc_path) - if triplet then - _G.metadata.triplet = triplet - _G.metadata.sysroot = sysroot - end - print(vim.inspect(_G.metadata)) if callback then vim.schedule(function() @@ -430,7 +424,14 @@ local function start_pio_watcher() pio_manager.refresh(function() -- vim.schedule(function() boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + + local triplet, sysroot = get_sysroot_triplet(_G.metadata.cc_path) + if triplet then + _G.metadata.triplet = triplet + _G.metadata.sysroot = sysroot + end boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) + pio_generate_db() lsp.lsp_restart('clangd') -- end) From c33540a3128df393557ffd50044dbe92455c3ebf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 13:32:30 +0300 Subject: [PATCH 0617/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/pio_setup.lua | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 3bd671ce..b0565811 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -81,7 +81,7 @@ compilationDatabasePath=%s, content = function(self) return string.format( self.template, - ("'-std=c++17','target=" .. _G.metadata.triplet .. "','sysroot=" .. _G.metadata.sysroot .. "'") or "'-std=c++17'", + ("'-std=c++17','--target=" .. _G.metadata.triplet .. "','--sysroot=" .. _G.metadata.sysroot .. "'") or "'-std=c++17'", vim.uv.cwd() ) end, diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index e3d912f6..a427ccfb 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -30,6 +30,8 @@ local debounce_timer = vim.uv.new_timer() local function get_sysroot_triplet(bin_path) -- Use Neovim's loop (uv) for file system scanning local luv = vim.loop or vim.uv + + vim.notify("ccpath= " .. bin_path, vim.log.levels.INFO) local handle = luv.fs_scandir(bin_path) if not handle then return nil, 'Invalid path' end @@ -42,6 +44,7 @@ local function get_sysroot_triplet(bin_path) local triplet = name:match('^(.*)%-g%+%+.*$') if triplet then + vim.notify("triplet= " .. triplet, vim.log.levels.INFO) -- Get the toolchain root (parent of /bin) local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') local sysroot_path = toolchain_root .. '/' .. triplet From 41a4fd68ea652b01375f2af5906ba23dcda83067 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 13:39:12 +0300 Subject: [PATCH 0618/1406] update --- lua/platformio/pio_setup.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index a427ccfb..ab003f1d 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -41,7 +41,8 @@ local function get_sysroot_triplet(bin_path) -- Search for the G++ compiler binary -- Matches triplet prefix from names like 'riscv32-esp-elf-g++' or 'xtensa-esp32-elf-g++.exe' - local triplet = name:match('^(.*)%-g%+%+.*$') + -- local triplet = name:match('^(.*)%-g%+%+.*$') + local triplet = name:match('^(.*)%-gcc.*$') if triplet then vim.notify("triplet= " .. triplet, vim.log.levels.INFO) From 4c84ff8f46f01595a1f1307690c532e41ecc08a6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 14:32:39 +0300 Subject: [PATCH 0619/1406] update --- lua/platformio/boilerplate.lua | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index b0565811..78eb09eb 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -79,11 +79,7 @@ clangdFileStatus=true, compilationDatabasePath=%s, ]], content = function(self) - return string.format( - self.template, - ("'-std=c++17','--target=" .. _G.metadata.triplet .. "','--sysroot=" .. _G.metadata.sysroot .. "'") or "'-std=c++17'", - vim.uv.cwd() - ) + return string.format(self.template, ('-std=c++17,--target=' .. _G.metadata.triplet .. ',--sysroot=' .. _G.metadata.sysroot) or '-std=c++17', vim.uv.cwd()) end, } From 4d5bc5e3563dacab7acb2c5cf3b7319e3a315f73 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 15:07:34 +0300 Subject: [PATCH 0620/1406] update --- lua/platformio/pio_setup.lua | 63 ++++++++++++++++++++++-------------- 1 file changed, 39 insertions(+), 24 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index ab003f1d..4acdd2e3 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -24,37 +24,51 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local debounce_timer = vim.uv.new_timer() +-- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) -- INFO: -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag -- stylua: ignore local function get_sysroot_triplet(bin_path) - -- Use Neovim's loop (uv) for file system scanning - local luv = vim.loop or vim.uv - - vim.notify("ccpath= " .. bin_path, vim.log.levels.INFO) - local handle = luv.fs_scandir(bin_path) - if not handle then return nil, 'Invalid path' end + local sep = package.config:sub(1, 1) + local handle = vim.loop.fs_scandir(bin_path) + if not handle then + return nil, 'Invalid path' + end + local triplet = nil while true do - local name = luv.fs_scandir_next(handle) - if not name then break end - - -- Search for the G++ compiler binary - -- Matches triplet prefix from names like 'riscv32-esp-elf-g++' or 'xtensa-esp32-elf-g++.exe' - -- local triplet = name:match('^(.*)%-g%+%+.*$') - local triplet = name:match('^(.*)%-gcc.*$') - - if triplet then - vim.notify("triplet= " .. triplet, vim.log.levels.INFO) - -- Get the toolchain root (parent of /bin) - local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') - local sysroot_path = toolchain_root .. '/' .. triplet - - -- Verify if the folder actually exists - if vim.fn.isdirectory(sysroot_path) == 1 then return triplet, sysroot_path end + local name = vim.loop.fs_scandir_next(handle) + if not name then + break + end + + -- This pattern looks for the dash followed by 'gcc' OR 'g++' + -- it captures everything before that dash. + -- %- is a literal dash + -- g[cc%+%+]+ matches 'gcc' or 'g++' + local match = name:match('^(.*)%-g[cc%+%+]+.*$') + + if match then + triplet = match + break end end - return nil, 'No valid triplet folder found' + + if not triplet then + return nil, 'No compiler found' + end + + local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') + local sysroot = toolchain_root .. sep .. triplet + + if vim.fn.isdirectory(sysroot) == 1 then + return { + triplet = triplet, + sysroot = sysroot, + query_driver = bin_path .. sep .. triplet .. '-*', + } + end + return nil, 'Sysroot folder missing' end @@ -429,10 +443,11 @@ local function start_pio_watcher() -- vim.schedule(function() boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - local triplet, sysroot = get_sysroot_triplet(_G.metadata.cc_path) + local triplet, sysroot, query_driver = get_sysroot_triplet(_G.metadata.cc_path) if triplet then _G.metadata.triplet = triplet _G.metadata.sysroot = sysroot + _G.metadata.driver_path = query_driver end boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) From 0f8814e9e73a13173852d82b5aafc651cd9f7fad Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 15:21:21 +0300 Subject: [PATCH 0621/1406] update --- lua/platformio/pio_setup.lua | 48 ++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 27 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 4acdd2e3..dfae3082 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -24,53 +24,47 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local debounce_timer = vim.uv.new_timer() --- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) -- INFO: -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag --- stylua: ignore +--- stylua: ignore local function get_sysroot_triplet(bin_path) local sep = package.config:sub(1, 1) - local handle = vim.loop.fs_scandir(bin_path) - if not handle then - return nil, 'Invalid path' - end + -- 1. Get a list of all files in the bin directory + local files = vim.fn.readdir(bin_path) local triplet = nil - while true do - local name = vim.loop.fs_scandir_next(handle) - if not name then - break - end - - -- This pattern looks for the dash followed by 'gcc' OR 'g++' - -- it captures everything before that dash. - -- %- is a literal dash - -- g[cc%+%+]+ matches 'gcc' or 'g++' - local match = name:match('^(.*)%-g[cc%+%+]+.*$') - if match then - triplet = match + -- 2. Find the first file that looks like a compiler + for _, name in ipairs(files) do + -- This pattern looks for the suffix "-gcc" + -- It captures everything before the "-" + triplet = name:match('^(.*)%-gcc') + if triplet then break end end if not triplet then - return nil, 'No compiler found' + return nil, 'No compiler binary found' end + -- 3. Construct Sysroot: The folder with the same name as the triplet + -- in the parent directory of 'bin' local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') local sysroot = toolchain_root .. sep .. triplet + -- 4. Verify the folder exists if vim.fn.isdirectory(sysroot) == 1 then + vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) return { triplet = triplet, sysroot = sysroot, query_driver = bin_path .. sep .. triplet .. '-*', } end - return nil, 'Sysroot folder missing' -end + return nil, 'Found triplet ' .. triplet .. ' but no matching folder.' +end -- INFO: -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag @@ -443,11 +437,11 @@ local function start_pio_watcher() -- vim.schedule(function() boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - local triplet, sysroot, query_driver = get_sysroot_triplet(_G.metadata.cc_path) - if triplet then - _G.metadata.triplet = triplet - _G.metadata.sysroot = sysroot - _G.metadata.driver_path = query_driver + local data = get_sysroot_triplet(_G.metadata.cc_path) + if data then + _G.metadata.triplet = data.triplet + _G.metadata.sysroot = data.sysroot + _G.metadata.driver_path = data.query_driver end boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) From d5f294a9620e3ca929a28799029bf9a27c06e8ef Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 15:30:06 +0300 Subject: [PATCH 0622/1406] update --- lua/platformio/pio_setup.lua | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index dfae3082..a1a21287 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -30,30 +30,28 @@ local debounce_timer = vim.uv.new_timer() local function get_sysroot_triplet(bin_path) local sep = package.config:sub(1, 1) - -- 1. Get a list of all files in the bin directory + -- 1. Read all files in the bin directory local files = vim.fn.readdir(bin_path) local triplet = nil - -- 2. Find the first file that looks like a compiler + -- 2. Extract triplet from any file containing '-gcc' for _, name in ipairs(files) do - -- This pattern looks for the suffix "-gcc" - -- It captures everything before the "-" - triplet = name:match('^(.*)%-gcc') - if triplet then + local match = name:match('^(.*)%-gcc') + if match then + triplet = match break end end if not triplet then - return nil, 'No compiler binary found' + return nil, 'No compiler found' end - -- 3. Construct Sysroot: The folder with the same name as the triplet - -- in the parent directory of 'bin' + -- 3. Get the toolchain root and sysroot folder local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') local sysroot = toolchain_root .. sep .. triplet - -- 4. Verify the folder exists + -- 4. Final verification if vim.fn.isdirectory(sysroot) == 1 then vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) return { @@ -62,8 +60,7 @@ local function get_sysroot_triplet(bin_path) query_driver = bin_path .. sep .. triplet .. '-*', } end - - return nil, 'Found triplet ' .. triplet .. ' but no matching folder.' + return nil, 'Sysroot folder missing: ' .. sysroot end -- INFO: From 3e527cb1f29a05b1d493cb6420951cdb9e36502a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 16:06:23 +0300 Subject: [PATCH 0623/1406] update --- lua/platformio/boilerplate.lua | 7 ++++++- lua/platformio/pio_setup.lua | 25 +++++++++++++------------ 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 78eb09eb..8c4aa1b2 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -1,5 +1,6 @@ local M = {} +local misc = require('platformio.utils.misc') local uv = vim.loop local boilerplate = {} @@ -79,7 +80,11 @@ clangdFileStatus=true, compilationDatabasePath=%s, ]], content = function(self) - return string.format(self.template, ('-std=c++17,--target=' .. _G.metadata.triplet .. ',--sysroot=' .. _G.metadata.sysroot) or '-std=c++17', vim.uv.cwd()) + return string.format( + self.template, + ('-std=c++17,--target=' .. _G.metadata.triplet .. ',--sysroot=' .. _G.metadata.sysroot) or '-std=c++17', + misc.normalize_path(vim.uv.cwd()) + ) end, } diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index a1a21287..89291ba8 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -24,19 +24,21 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local debounce_timer = vim.uv.new_timer() +-- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) -- INFO: -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag --- stylua: ignore local function get_sysroot_triplet(bin_path) - local sep = package.config:sub(1, 1) - - -- 1. Read all files in the bin directory - local files = vim.fn.readdir(bin_path) + -- Normalize to forward slashes for cross-platform compatibility + local normalized_bin = misc.normalize_path(bin_path) --bin_path:gsub("\\", "/") + local files = vim.fn.readdir(normalized_bin) local triplet = nil - -- 2. Extract triplet from any file containing '-gcc' for _, name in ipairs(files) do - local match = name:match('^(.*)%-gcc') + -- Pattern: ^(.*) matches the triplet + -- %- matches the hyphen + -- g[c%+][c%+] matches 'gcc' or 'g++' + local match = name:match('^(.*)%-g[c%+][c%+]') if match then triplet = match break @@ -47,20 +49,19 @@ local function get_sysroot_triplet(bin_path) return nil, 'No compiler found' end - -- 3. Get the toolchain root and sysroot folder - local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') - local sysroot = toolchain_root .. sep .. triplet + local toolchain_root = vim.fn.fnamemodify(normalized_bin, ':h') + local sysroot = toolchain_root .. '/' .. triplet - -- 4. Final verification if vim.fn.isdirectory(sysroot) == 1 then vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) return { triplet = triplet, sysroot = sysroot, - query_driver = bin_path .. sep .. triplet .. '-*', + -- The wildcard allows clangd to use both gcc and g++ + query_driver = normalized_bin .. '/' .. triplet .. '-*', } end - return nil, 'Sysroot folder missing: ' .. sysroot + return nil, 'Sysroot folder missing' end -- INFO: From e8558f29deab953b35911d44a6af4833f71ec1f9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 16:18:04 +0300 Subject: [PATCH 0624/1406] update --- lua/platformio/pio_setup.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 89291ba8..9af65b35 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -51,9 +51,10 @@ local function get_sysroot_triplet(bin_path) local toolchain_root = vim.fn.fnamemodify(normalized_bin, ':h') local sysroot = toolchain_root .. '/' .. triplet + vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) + vim.notify('toolchain_root= ' .. toolchain_root, vim.log.levels.INFO) if vim.fn.isdirectory(sysroot) == 1 then - vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) return { triplet = triplet, sysroot = sysroot, From 85897ac950072dd63bf8aad2f7fde804ed8ed212 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 16:19:11 +0300 Subject: [PATCH 0625/1406] update --- lua/platformio/pio_setup.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 9af65b35..d4e4c139 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -183,7 +183,7 @@ local pio_manager = (function() _G.metadata.cc_path = misc.normalize_path(env.cc_path) or '' _G.metadata.fallback_flags = fallback_flags - print(vim.inspect(_G.metadata)) + -- print(vim.inspect(_G.metadata)) if callback then vim.schedule(function() vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) @@ -381,7 +381,7 @@ function _G.get_pio_sdk_info() local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' print('get_pio_sdk_info(): final=' .. final) -- Normalize paths for the OS and ensure backslashes for Windows if needed - print(vim.inspect(_G.metadata)) + -- print(vim.inspect(_G.metadata)) return (misc.normalize_path(final)) -- return _G.metadata.driver_path -- return pio_info From fb82be5e34fb6dc72eac201baab27825989791f1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 16:38:07 +0300 Subject: [PATCH 0626/1406] update --- lua/platformio/pio_setup.lua | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index d4e4c139..484d4803 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -31,16 +31,21 @@ local debounce_timer = vim.uv.new_timer() local function get_sysroot_triplet(bin_path) -- Normalize to forward slashes for cross-platform compatibility local normalized_bin = misc.normalize_path(bin_path) --bin_path:gsub("\\", "/") + + vim.notify('cc_path= ' .. bin_path, vim.log.levels.INFO) + vim.notify('normalized_bin= ' .. normalized_bin, vim.log.levels.INFO) + local files = vim.fn.readdir(normalized_bin) local triplet = nil + vim.notify('cc_path= ' .. bin_path, vim.log.levels.INFO) for _, name in ipairs(files) do -- Pattern: ^(.*) matches the triplet -- %- matches the hyphen -- g[c%+][c%+] matches 'gcc' or 'g++' local match = name:match('^(.*)%-g[c%+][c%+]') if match then - triplet = match + triplet = misc.normalize_path(match) break end end From c3bbf1486912a570b2271b776572192a7815075a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 16:49:00 +0300 Subject: [PATCH 0627/1406] update --- lua/platformio/pio_setup.lua | 52 ++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 484d4803..0b4328f7 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -28,48 +28,48 @@ local debounce_timer = vim.uv.new_timer() -- INFO: -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag --- stylua: ignore -local function get_sysroot_triplet(bin_path) - -- Normalize to forward slashes for cross-platform compatibility - local normalized_bin = misc.normalize_path(bin_path) --bin_path:gsub("\\", "/") - - vim.notify('cc_path= ' .. bin_path, vim.log.levels.INFO) - vim.notify('normalized_bin= ' .. normalized_bin, vim.log.levels.INFO) +local function get_sysroot_triplet(compiler_full_path) + -- 1. Normalize and extract the directory portion (Head) + local normalized_path = compiler_full_path:gsub('\\', '/') + local bin_dir = vim.fn.fnamemodify(normalized_path, ':h') + + -- 2. Check if the directory exists before opening + if vim.fn.isdirectory(bin_dir) == 0 then + return nil, 'Directory not found: ' .. bin_dir + end - local files = vim.fn.readdir(normalized_bin) + -- 3. Read the directory safely + local files = vim.fn.readdir(bin_dir) local triplet = nil - vim.notify('cc_path= ' .. bin_path, vim.log.levels.INFO) + -- 4. Find the triplet (e.g., riscv32-esp-elf) from a file name for _, name in ipairs(files) do - -- Pattern: ^(.*) matches the triplet - -- %- matches the hyphen - -- g[c%+][c%+] matches 'gcc' or 'g++' local match = name:match('^(.*)%-g[c%+][c%+]') if match then - triplet = misc.normalize_path(match) + triplet = match break end end if not triplet then - return nil, 'No compiler found' + return nil, 'No triplet detected in ' .. bin_dir end - local toolchain_root = vim.fn.fnamemodify(normalized_bin, ':h') - local sysroot = toolchain_root .. '/' .. triplet vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) - vim.notify('toolchain_root= ' .. toolchain_root, vim.log.levels.INFO) - - if vim.fn.isdirectory(sysroot) == 1 then - return { - triplet = triplet, - sysroot = sysroot, - -- The wildcard allows clangd to use both gcc and g++ - query_driver = normalized_bin .. '/' .. triplet .. '-*', - } - end - return nil, 'Sysroot folder missing' + -- 5. Construct sysroot from the toolchain root (parent of bin) + local toolchain_root = vim.fn.fnamemodify(bin_dir, ':h') + local sysroot = toolchain_root .. '/' .. triplet + + return { + triplet = triplet, + sysroot = sysroot, + query_driver = normalized_path, + } end +-- USAGE: Pass the FULL path once. The function will extract the dir itself. +local result = get_sysroot_triplet('C:/Users/tom/.platformio/packages/toolchain-riscv32-esp/bin/riscv32-esp-elf-gcc.exe') + -- INFO: -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag -- stylua: ignore From 6c0c9c6a5edc8932b8c40172edc2e03cec34b7de Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 17:01:24 +0300 Subject: [PATCH 0628/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 8c4aa1b2..a21a019b 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -82,7 +82,7 @@ compilationDatabasePath=%s, content = function(self) return string.format( self.template, - ('-std=c++17,--target=' .. _G.metadata.triplet .. ',--sysroot=' .. _G.metadata.sysroot) or '-std=c++17', + ("'-std=c++17','--target=" .. _G.metadata.triplet .. "','--sysroot=" .. _G.metadata.sysroot) .. "'" or "'-std=c++17'", misc.normalize_path(vim.uv.cwd()) ) end, From 18d8cbeb72ec62a42db0e336d11bc38c7f180f5f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 17:29:20 +0300 Subject: [PATCH 0629/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index a21a019b..697cd89d 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -82,7 +82,7 @@ compilationDatabasePath=%s, content = function(self) return string.format( self.template, - ("'-std=c++17','--target=" .. _G.metadata.triplet .. "','--sysroot=" .. _G.metadata.sysroot) .. "'" or "'-std=c++17'", + ('"-std=c++17","--target=' .. _G.metadata.triplet .. '","--sysroot=' .. _G.metadata.sysroot) .. '"' or '"-std=c++17"', misc.normalize_path(vim.uv.cwd()) ) end, From 86cb5ca2121994e946848934f3911485c75bd975 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 17:40:11 +0300 Subject: [PATCH 0630/1406] update --- lua/platformio/boilerplate.lua | 6 +++++- lua/platformio/pio_setup.lua | 6 ++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 697cd89d..a9a975d3 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -129,10 +129,11 @@ clangd -- INFO: .clangd boilerplate['.clangd'] = { rewrite = false, - content = [[ + template = [[ CompileFlags: Add: - "--target=riscv32-esp-elf" + - "--sysroot=%s" Remove: - "-fno-fat-lto-objects" - "-fno%-fat%-lto%-objects" @@ -168,6 +169,9 @@ Diagnostics: - "hicpp-vararg" - "modernize-*" ]], + content = function(self) + return string.format(self.template, '"--sysroot=' .. _G.metadata.sysroot .. '"') + end, } -- INFO: .stylua.toml diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 0b4328f7..3640bcf9 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -448,6 +448,8 @@ local function start_pio_watcher() _G.metadata.driver_path = data.query_driver end boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) pio_generate_db() lsp.lsp_restart('clangd') @@ -470,8 +472,8 @@ function M.init() -- INFO: create clangd required files ----------------------------------------------------------------------------------------- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) + -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + -- boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) From cacd5fcc31a6001c3b433839389ac3b671c31298 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 17:50:35 +0300 Subject: [PATCH 0631/1406] update --- lua/platformio/boilerplate.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index a9a975d3..efffe4de 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -133,11 +133,11 @@ boilerplate['.clangd'] = { CompileFlags: Add: - "--target=riscv32-esp-elf" - - "--sysroot=%s" + - %q Remove: - "-fno-fat-lto-objects" - - "-fno%-fat%-lto%-objects" - - "-fno%-canonical%-system%-headers" + - "-fno%%-fat%%-lto%%-objects" + - "-fno%%-canonical%%-system%%-headers" - "-misc-definitions-in-headers" - "-fno-tree-switch-conversion" - "-mtext-section-literals" @@ -170,7 +170,7 @@ Diagnostics: - "modernize-*" ]], content = function(self) - return string.format(self.template, '"--sysroot=' .. _G.metadata.sysroot .. '"') + return string.format(self.template, '--sysroot=' .. _G.metadata.sysroot) end, } From d7b1ec65990cc8e8d71880e9451ade52b5be9912 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 18:42:39 +0300 Subject: [PATCH 0632/1406] update --- lua/platformio/boilerplate.lua | 5 +++-- lua/platformio/pio_setup.lua | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index efffe4de..8b40e6da 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -109,10 +109,11 @@ clangd --pch-storage=memory --pretty --ranking-model=decision_forest ---query-driver=%s +--query-driver=%q ]], content = function(self) - return string.format(self.template, _G.metadata.driver_path or '**') + return string.format(self.template, (_G.metadata.toolchain .. '/**/' .. _G.metadata.triplet) or '**') + -- return string.format(self.template, _G.metadata.driver_path or '**') -- return string.format(self.template, _G.get_pio_toolchain_pattern() or '**') -- return string.format(self.template, _G.get_pio_sdk_info() or '**') end, diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 3640bcf9..fb0798cd 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -10,6 +10,7 @@ _G.metadata = { driver_path = '', cc_path = '', triplet = '', + toolchain = '', sysroot = '', fallback_flags = {}, } @@ -63,12 +64,11 @@ local function get_sysroot_triplet(compiler_full_path) return { triplet = triplet, sysroot = sysroot, + toolchain_root = toolchain_root, query_driver = normalized_path, } end --- USAGE: Pass the FULL path once. The function will extract the dir itself. -local result = get_sysroot_triplet('C:/Users/tom/.platformio/packages/toolchain-riscv32-esp/bin/riscv32-esp-elf-gcc.exe') -- INFO: -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag @@ -446,6 +446,7 @@ local function start_pio_watcher() _G.metadata.triplet = data.triplet _G.metadata.sysroot = data.sysroot _G.metadata.driver_path = data.query_driver + _G.metadata.toolchain = data.toolchain_root end boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.g.platformioRootDir) From 91e4ca6f4800256b6407e17c1e527c83cb548131 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 19:18:01 +0300 Subject: [PATCH 0633/1406] update --- lua/platformio/boilerplate.lua | 6 +++--- lua/platformio/lspConfig/clangd.lua | 4 ++-- lua/platformio/utils/lsp.lua | 3 ++- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 8b40e6da..1236d766 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -109,11 +109,11 @@ clangd --pch-storage=memory --pretty --ranking-model=decision_forest ---query-driver=%q +--query-driver=%s ]], content = function(self) - return string.format(self.template, (_G.metadata.toolchain .. '/**/' .. _G.metadata.triplet) or '**') - -- return string.format(self.template, _G.metadata.driver_path or '**') + -- return string.format(self.template, (_G.metadata.toolchain .. '/**/' .. _G.metadata.triplet) or '**') + return string.format(self.template, _G.metadata.driver_path or '**') -- return string.format(self.template, _G.get_pio_toolchain_pattern() or '**') -- return string.format(self.template, _G.get_pio_sdk_info() or '**') end, diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index a58ea2e4..4c184b59 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -150,7 +150,7 @@ if vim.uv.fs_stat(fname) then end end -local clangd = { +_G.clangd = { cmd = cmd, filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, root_markers = { @@ -168,7 +168,7 @@ local clangd = { single_file_support = true, init_options = init_options, } -vim.lsp.config('clangd', clangd) +vim.lsp.config('clangd', _G.clangd) ---------------------------------------------------------------------------------------- -- INFO: configure clangd lsp server diff --git a/lua/platformio/utils/lsp.lua b/lua/platformio/utils/lsp.lua index 2ff24227..39709b56 100644 --- a/lua/platformio/utils/lsp.lua +++ b/lua/platformio/utils/lsp.lua @@ -19,7 +19,8 @@ function M.lsp_restart(name) local configc = c.config c:stop(true) vim.defer_fn(function() - vim.lsp.config(name, configc) + -- vim.lsp.config(name, configc) + vim.lsp.config(name, _G.clangd) vim.lsp.enable(name) vim.cmd('checktime') end, 600) From 3ddfb0c2579c29f4bc460a131207f46d55ef7411 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 15 Apr 2026 22:11:09 +0300 Subject: [PATCH 0634/1406] update --- lua/platformio/utils/lsp.lua | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/lua/platformio/utils/lsp.lua b/lua/platformio/utils/lsp.lua index 39709b56..0af1b9f8 100644 --- a/lua/platformio/utils/lsp.lua +++ b/lua/platformio/utils/lsp.lua @@ -1,6 +1,6 @@ local M = {} --- stylua: ignore +--- stylua: ignore function M.lsp_restart(name) if vim.fn.has('nvim-0.12') == 1 then -- local clients = vim.lsp.get_clients({ name = name }) @@ -18,12 +18,14 @@ function M.lsp_restart(name) for _, c in ipairs(clients) do local configc = c.config c:stop(true) - vim.defer_fn(function() - -- vim.lsp.config(name, configc) + vim.schedule_wrap(function() + -- vim.defer_fn(function() + -- -- vim.lsp.config(name, configc) vim.lsp.config(name, _G.clangd) vim.lsp.enable(name) vim.cmd('checktime') - end, 600) + -- end, 600) + end) end -- -- 1. Stop the specific client -- for _, client in ipairs(clients) do client:stop() end From 58db765f51140d32c3c736e578f2d2e6a2ade0e9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 14:55:49 +0300 Subject: [PATCH 0635/1406] update --- lua/platformio/boilerplate.lua | 182 ++++++++++++++++++---------- lua/platformio/lspConfig/clangd.lua | 140 ++++++++++++++------- lua/platformio/pio_setup.lua | 88 ++++++-------- lua/platformio/utils/lsp.lua | 72 +++++++++-- tmp.lua | 108 +++++++++++++++++ 5 files changed, 425 insertions(+), 165 deletions(-) create mode 100644 tmp.lua diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 1236d766..2955e619 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -1,6 +1,4 @@ -local M = {} - -local misc = require('platformio.utils.misc') +-- local misc = require('platformio.utils.misc') local uv = vim.loop local boilerplate = {} @@ -9,6 +7,7 @@ local boilerplate = {} --- stylua: ignore boilerplate['arduino'] = { rewrite = false, + read = false, content = [[ #include @@ -25,6 +24,7 @@ void loop() { -- INFO: platformio.ini boilerplate['platformio.ini'] = { rewrite = false, + read = false, template = [[ [platformio] core_dir = %s @@ -53,44 +53,65 @@ lib_ldf_mode = chain ;Library dependencies Finder ldf end, } --- INFO: enable_toolchain.py -boilerplate['enable_toolchain.py'] = { +-- ============================================================================= +-- DYNAMIC CLANGD CONFIGURATION TEMPLATE +-- ============================================================================= +-- Note: %q is used for paths to handle escaping and spaces automatically. +-- INFO: .clangd_config +boilerplate['.clangd_config'] = { rewrite = false, + read = true, content = [[ -from SCons.Script import DefaultEnvironment -env = DefaultEnvironment() -env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) - -#Import("env") - -# Safe retrieval with a default message -print(f"Toolchain Inclusion Status: {env.get('COMPILATIONDB_INCLUDE_TOOLCHAIN', 'Not Set')}") -print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") -]], +{ + cmd = { + "clangd", + "--all-scopes-completion", + "--background-index", + "--clang-tidy", + "--compile_args_from=filesystem", + "--enable-config", + "--completion-parse=always", + "--completion-style=detailed", + "--header-insertion=iwyu", + "--fallback-style=llvm", + "-j=12", + "--log=verbose", + "--offset-encoding=utf-8", + "--pch-storage=memory", + "--pretty", + "--ranking-model=decision_forest", + "--sync", + "--offset-encoding=utf-16", + "--query-driver=%s", -- will be assigned based op project + }, + filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, + root_markers = { + 'platformio.ini', + 'CMakeLists.txt', + '.clangd', + '.clang-tidy', + '.clang-format', + 'compile_commands.json', + 'compile_flags.txt', + 'configure.ac', + '.git', + }, + workspace_required = true, + single_file_support = true, + init_options = { + usePlaceholders = true, + completeUnimported = true, + fallbackFlags = {%s}, -- will be assigned based op project + clangdFileStatus = true, + compilationDatabasePath = %q, -- will be assigned based op project + } } - --- INFO: .clangd_init_options -boilerplate['.clangd_init_options'] = { - rewrite = true, - template = [[ -usePlaceholders=true, -completeUnimported=true, -fallbackFlags={%s}, -clangdFileStatus=true, -compilationDatabasePath=%s, ]], - content = function(self) - return string.format( - self.template, - ('"-std=c++17","--target=' .. _G.metadata.triplet .. '","--sysroot=' .. _G.metadata.sysroot) .. '"' or '"-std=c++17"', - misc.normalize_path(vim.uv.cwd()) - ) - end, } - -- INFO: .clangd_cmd boilerplate['.clangd_cmd'] = { rewrite = true, + read = false, template = [[ clangd --all-scopes-completion @@ -112,28 +133,18 @@ clangd --query-driver=%s ]], content = function(self) - -- return string.format(self.template, (_G.metadata.toolchain .. '/**/' .. _G.metadata.triplet) or '**') - return string.format(self.template, _G.metadata.driver_path or '**') - -- return string.format(self.template, _G.get_pio_toolchain_pattern() or '**') - -- return string.format(self.template, _G.get_pio_sdk_info() or '**') + return string.format(self.template, _G.metadata.query_driver or '**') end, - --header-insertion=iwyu - --header-insertion-decorators - --query-driver=%s/toolchain-*/**/bin/* - --query-driver=%s/.platformio/packages/*/bin/riscv32-esp-elf-* - --query-driver=%s/.platformio/**/packages/toolchain-*/**/bin/* - --query-driver = [[clangd --query-driver=]] .. vim.env.HOME .. [[/.platformio/packages/*]] - --query-driver=**/*riscv32-esp-elf-*,**/*gcc*,**/*g++* - --query-driver=**/.platformio/packages/toolchain*/**/bin/*gcc* } -- INFO: .clangd boilerplate['.clangd'] = { rewrite = false, + read = false, template = [[ CompileFlags: Add: - - "--target=riscv32-esp-elf" + - %q - %q Remove: - "-fno-fat-lto-objects" @@ -171,13 +182,16 @@ Diagnostics: - "modernize-*" ]], content = function(self) - return string.format(self.template, '--sysroot=' .. _G.metadata.sysroot) + local sysroot = '--sysroot=' .. _G.metadata.sysroot + local triplet = '--sysroot=' .. _G.metadata.triplet + return string.format(self.template, triplet, sysroot) end, } -- INFO: .stylua.toml boilerplate['.stylua.toml'] = { rewrite = false, + read = false, content = [[ syntax = "All" column_width = 132 @@ -197,6 +211,7 @@ enabled = false -- INFO: .clang-format boilerplate['.clang-format'] = { rewrite = false, + read = false, content = [[ --- Language: Cpp @@ -445,38 +460,77 @@ WhitespaceSensitiveMacros: ... ]], } - +-- stylua: ignore function M.boilerplate_gen(framework, src_path, filename) filename = filename or framework local entry = boilerplate[framework] - if not entry then - return - end + if not entry then return '' end -- local file_path = src_path .. '/' .. filename if vim.uv.fs_stat(file_path) then if not entry.rewrite then - return -- return if file exists and not rewritable + if entry.read then + local fr = io.open(file_path, 'r') + if fr then return (fr:read('*a')) end + end + return '' end end - if vim.fn.isdirectory(src_path) == 0 then - vim.fn.mkdir(src_path, 'p') - end + if vim.fn.isdirectory(src_path) == 0 then vim.fn.mkdir(src_path, 'p') end - ------------------------------------------------------------------------------------- local fd = assert(uv.fs_open(file_path, 'w', 420)) if not fd then print('failed to create file: ' .. file_path) - return + return '' end - -- local closeOnexit = type(exit_callback) == 'function' - -- local text = type(entry.content) == 'function' and entry:content() or entry.content - local text = type(entry.content) == 'function' and entry:content() or entry.content - if text then - uv.fs_write(fd, text, 0) - uv.fs_close(fd) - end + local template = type(entry.content) == 'function' and entry:content() or entry.content + uv.fs_write(fd, template, 0) + uv.fs_close(fd) + + if entry.read then + return template + else return '' end end + return M + +-- -- INFO: .clangd_init_options +-- boilerplate['.clangd_init_options'] = { +-- rewrite = true, +-- read = false, +-- template = [[ +-- usePlaceholders=true, +-- completeUnimported=true, +-- fallbackFlags={%s}, +-- clangdFileStatus=true, +-- compilationDatabasePath="%s", +-- ]], +-- content = function(self) +-- local f_flags = string.format('"--target=%s", "--sysroot=%s"', _G.metadata.triplet, _G.metadata.sysroot) +-- return string.format( +-- self.template, +-- ('"-std=c++17","--target=' .. _G.metadata.triplet .. '","--sysroot=' .. _G.metadata.sysroot) .. '"' or '"-std=c++17"', +-- misc.normalize_path(vim.uv.cwd()) +-- ) +-- end, +-- } +-- +-- -- INFO: enable_toolchain.py +-- boilerplate['enable_toolchain.py'] = { +-- rewrite = false, +-- read = false, +-- content = [[ +-- from SCons.Script import DefaultEnvironment +-- env = DefaultEnvironment() +-- env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) +-- +-- #Import("env") +-- +-- # Safe retrieval with a default message +-- print(f"Toolchain Inclusion Status: {env.get('COMPILATIONDB_INCLUDE_TOOLCHAIN', 'Not Set')}") +-- print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") +-- ]], +-- } +-- diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 4c184b59..4fe0cd1e 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -1,3 +1,19 @@ +local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +_G.metadata = { + envs = {}, + default_envs = {}, + core_dir = '', + packages_dir = '', + platforms_dir = '', + active_env = '', + query_driver = '', + cc_compiler = '', + triplet = '', + toolchain = '', + sysroot = '', + fallback_flags = {}, +} + local ok, result ok, result = pcall(require, 'fidget') if ok then @@ -124,51 +140,91 @@ vim.lsp.config('*', { ---------------------------------------------------------------------------------------- -- INFO: configure clangd lsp server ----------------------------------------------------------------------------------------- -local cmd = { 'clangd' } -local fname = string.format('%s/.clangd_cmd', vim.uv.cwd()) -if vim.uv.fs_stat(fname) then - ok, result = pcall(vim.fn.readfile, fname) - if ok then - cmd = result - -- print(vim.inspect(cmd)) - end -end -local init_options = { - usePlaceholders = true, - completeUnimported = true, - fallbackFlags = { '-std=c++17' }, - clangdFileStatus = true, - compilationDatabasePath = vim.uv.cwd(), -} -fname = string.format('%s/.clangd_init_options', vim.uv.cwd()) -if vim.uv.fs_stat(fname) then - ok, result = pcall(vim.fn.readfile, fname) - if ok then - init_options = result - -- print(vim.inspect(cmd)) - end -end +-- local cmd = { 'clangd' } +-- local fname = string.format('%s/.clangd_cmd', vim.uv.cwd()) +-- if vim.uv.fs_stat(fname) then +-- ok, result = pcall(vim.fn.readfile, fname) +-- if ok then +-- cmd = result +-- -- print(vim.inspect(cmd)) +-- end +-- end +-- +-- local init_options = { +-- usePlaceholders = true, +-- completeUnimported = true, +-- fallbackFlags = { '-std=c++17' }, +-- clangdFileStatus = true, +-- compilationDatabasePath = vim.uv.cwd(), +-- } +-- fname = string.format('%s/.clangd_init_options', vim.uv.cwd()) +-- if vim.uv.fs_stat(fname) then +-- ok, result = pcall(vim.fn.readfile, fname) +-- if ok then +-- init_options = result +-- -- print(vim.inspect(cmd)) +-- end +-- end +-- +-- _G.clangd = { +-- cmd = cmd, +-- filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, +-- root_markers = { +-- 'CMakeLists.txt', +-- '.clangd', +-- '.clang-tidy', +-- '.clang-format', +-- 'compile_commands.json', +-- 'compile_flags.txt', +-- 'configure.ac', +-- '.git', +-- vim.uv.cwd(), +-- }, +-- workspace_required = true, +-- single_file_support = true, +-- init_options = init_options, +-- } +-- vim.lsp.config('clangd', _G.clangd) +local clangd_config = { + -- on_new_config runs every time client started + -- stylua: ignore + on_new_config = function(new_config, new_root_dir) + -- Safety check for root_dir + if not new_root_dir then return end -_G.clangd = { - cmd = cmd, - filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, - root_markers = { - 'CMakeLists.txt', - '.clangd', - '.clang-tidy', - '.clang-format', - 'compile_commands.json', - 'compile_flags.txt', - 'configure.ac', - '.git', - vim.uv.cwd(), - }, - workspace_required = true, - single_file_support = true, - init_options = init_options, + -- Safe defaults (Standard clangd behavior) + local f_flags, q_driver = '', '--query-driver=**' + + if _G.metadata.cc_compiler ~= '' then + if _G.metadata.triplet and _G.metadata.triplet ~= '' then + q_driver = '--query-driver=' .. (_G.metadata.query_driver or '**') + f_flags = string.format('"--target=%s", "--sysroot=%s"', _G.metadata.triplet, _G.metadata.sysroot) + end + end + + -- Format the clangd_config string + local clangd_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) + local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) + + -- Load the string as a Lua table safely + local ok, table_config = pcall(function() return load('return ' .. formatted_str)() end) + + if ok and table_config then + -- This merges table_config INTO new_config, overwriting existing values + local merged = vim.tbl_deep_extend('force', new_config, table_config) + -- Since we can't reassign the reference, we have to copy the keys back + for k, v in pairs(merged) do new_config[k] = v end + else + -- If template loading fails, alert the user but keep default cmd + vim.notify('LSP Config Table Generation Failed', vim.log.levels.ERROR) + end + end, } -vim.lsp.config('clangd', _G.clangd) + +-- Apply and Enable +vim.lsp.config('clangd', clangd_config) +vim.lsp.enable('clangd') ---------------------------------------------------------------------------------------- -- INFO: configure clangd lsp server diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index fb0798cd..c5d78d11 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,20 +1,5 @@ M = {} -_G.metadata = { - envs = {}, - default_envs = {}, - core_dir = '', - packages_dir = '', - platforms_dir = '', - active_env = '', - driver_path = '', - cc_path = '', - triplet = '', - toolchain = '', - sysroot = '', - fallback_flags = {}, -} - local misc = require('platformio.utils.misc') local lsp = require('platformio.utils.lsp') local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen @@ -27,24 +12,25 @@ local debounce_timer = vim.uv.new_timer() -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) -- INFO: --- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag +-- ============================================================================= +-- UNIVERSAL TOOLCHAIN DETECTION +-- ============================================================================= --- stylua: ignore -local function get_sysroot_triplet(compiler_full_path) - -- 1. Normalize and extract the directory portion (Head) - local normalized_path = compiler_full_path:gsub('\\', '/') - local bin_dir = vim.fn.fnamemodify(normalized_path, ':h') - - -- 2. Check if the directory exists before opening - if vim.fn.isdirectory(bin_dir) == 0 then - return nil, 'Directory not found: ' .. bin_dir +local function get_sysroot_triplet(cc_compiler) + local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') + -- Early exit if path is nil or not a directory + if not bin_path or vim.fn.isdirectory(bin_path) == 0 then + return nil end - -- 3. Read the directory safely - local files = vim.fn.readdir(bin_dir) + -- Normalize backslashes to forward slashes for cross-platform consistency + bin_path = bin_path:gsub('\\', '/') + local files = vim.fn.readdir(bin_path) local triplet = nil - -- 4. Find the triplet (e.g., riscv32-esp-elf) from a file name + -- Loop through files to find the compiler and extract the triplet for _, name in ipairs(files) do + -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ local match = name:match('^(.*)%-g[c%+][c%+]') if match then triplet = match @@ -52,21 +38,27 @@ local function get_sysroot_triplet(compiler_full_path) end end + -- Return nil if no compiler was found in the bin directory if not triplet then - return nil, 'No triplet detected in ' .. bin_dir + return nil end - vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) - -- 5. Construct sysroot from the toolchain root (parent of bin) - local toolchain_root = vim.fn.fnamemodify(bin_dir, ':h') + -- toolchain_root is the parent of the 'bin' folder + local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') + -- sysroot folder is expected to have the same name as the triplet local sysroot = toolchain_root .. '/' .. triplet - return { - triplet = triplet, - sysroot = sysroot, - toolchain_root = toolchain_root, - query_driver = normalized_path, - } + vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) + -- Only return data if the sysroot folder actually exists on disk + if vim.fn.isdirectory(sysroot) == 1 then + return { + triplet = triplet, + sysroot = sysroot, + toolchain_root = toolchain_root, + query_driver = bin_path .. '/' .. triplet .. '-*', + } + end + return nil end @@ -184,8 +176,8 @@ local pio_manager = (function() -- end -- end - _G.metadata.driver_path = misc.normalize_path(env.cc_path:match('(.*[/\\])') .. '*') or '**' - _G.metadata.cc_path = misc.normalize_path(env.cc_path) or '' + -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' + _G.metadata.cc_compiler = misc.normalize_path(env.cc_compiler) or '' _G.metadata.fallback_flags = fallback_flags -- print(vim.inspect(_G.metadata)) @@ -339,7 +331,7 @@ end)() -- INFO: function _G.get_pio_sdk_info() - local pio_info = { includes = {}, cc_path = '' } + local pio_info = { includes = {}, cc_compiler = '' } if vim.fn.filereadable('platformio.ini') == 0 then return nil end @@ -379,7 +371,7 @@ function _G.get_pio_sdk_info() if packages_dir and packages_dir ~= '' and toolchain_pkg and toolchain_pkg ~= '' and cc_name ~= '' then local full_path = packages_dir .. '/' .. toolchain_pkg .. '/bin/' .. cc_name if vim.fn.executable(full_path) == 1 then - pio_info.cc_path = full_path + pio_info.cc_compiler = full_path end end @@ -388,7 +380,7 @@ function _G.get_pio_sdk_info() -- Normalize paths for the OS and ensure backslashes for Windows if needed -- print(vim.inspect(_G.metadata)) return (misc.normalize_path(final)) - -- return _G.metadata.driver_path + -- return _G.metadata.query_driver -- return pio_info end @@ -396,7 +388,7 @@ end -- LSP HELPER: Returns the glob pattern for clangd's --query-driver -- e.g., C:\Users\tom\.platformio\packages\toolchain-riscv32-esp\bin\* function _G.get_pio_toolchain_pattern() - return _G.metadata.driver_path + return _G.metadata.query_driver end -- INFO: @@ -439,13 +431,13 @@ local function start_pio_watcher() vim.schedule_wrap(function() pio_manager.refresh(function() -- vim.schedule(function() - boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - local data = get_sysroot_triplet(_G.metadata.cc_path) - if data then + local status, data = pcall(get_sysroot_triplet, _G.metadata.cc_compiler) + if status and data and data.triplet and data.triplet ~= '' then _G.metadata.triplet = data.triplet _G.metadata.sysroot = data.sysroot - _G.metadata.driver_path = data.query_driver + _G.metadata.query_driver = data.query_driver _G.metadata.toolchain = data.toolchain_root end boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) @@ -493,7 +485,7 @@ function M.init() if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then pio_manager.refresh(function() -- vim.schedule(function() - boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) pio_generate_db() lsp.lsp_restart('clangd') diff --git a/lua/platformio/utils/lsp.lua b/lua/platformio/utils/lsp.lua index 0af1b9f8..a436df84 100644 --- a/lua/platformio/utils/lsp.lua +++ b/lua/platformio/utils/lsp.lua @@ -1,5 +1,50 @@ local M = {} +-- -- Define your dynamic config +-- local clangd_config = { +-- cmd = { +-- 'clangd', +-- '--background-index', +-- '--clang-tidy', +-- '--query-driver=**', -- Placeholder index (#cmd) +-- }, +-- Important Detail: on_new_config behavior +-- +-- If you open a new project in a separate Neovim instance (or a separate tab with a different root), on_new_config runs automatically for that new project. +-- If you edit your config while staying in the same project, you must restart. +-- on_new_config = function(new_config, _) +-- -- 1. Safely run your detection function +-- local status, data = pcall(get_sysroot_triplet, 'C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/bin') +-- +-- if status and data then +-- -- 2. Modify the last item (#) of the cmd table +-- new_config.cmd[#new_config.cmd] = '--query-driver=' .. data.query_driver +-- +-- -- 3. Merge fallback flags into init_options +-- new_config.init_options = vim.tbl_deep_extend('force', new_config.init_options or {}, { +-- fallbackFlags = { +-- '--target=' .. data.triplet, +-- '--sysroot=' .. data.sysroot, +-- }, +-- }) +-- end +-- end, +-- } +-- vim.lsp.config("clangd", { +-- on_new_config = function(config, new_root_dir) +-- -- This is the only place you can safely change this: +-- config.cmd[#config.cmd] = "--query-driver=" .. my_detected_path +-- end, +-- }) +-- local function restart_clangd() +-- local clients = vim.lsp.get_clients({ name = "clangd" }) +-- for _, client in ipairs(clients) do +-- client.stop() -- Stops the process +-- end +-- -- Neovim 0.11+ will automatically try to restart enabled servers +-- -- if a valid buffer is open, or you can trigger a reload. +-- vim.cmd("edit") +-- end --- stylua: ignore function M.lsp_restart(name) if vim.fn.has('nvim-0.12') == 1 then @@ -15,17 +60,22 @@ function M.lsp_restart(name) end else local clients = vim.lsp.get_clients({ name = name }) - for _, c in ipairs(clients) do - local configc = c.config - c:stop(true) - vim.schedule_wrap(function() - -- vim.defer_fn(function() - -- -- vim.lsp.config(name, configc) - vim.lsp.config(name, _G.clangd) - vim.lsp.enable(name) - vim.cmd('checktime') - -- end, 600) - end) + for _, client in ipairs(clients) do + local clangd_config = client.config + client:stop(true) + -- -- Apply the config using the new 0.11+ API + vim.lsp.config('clangd', clangd_config) + vim.lsp.enable('clangd') + vim.cmd('checktime') + vim.cmd('edit') + -- vim.schedule_wrap(function() + -- -- vim.defer_fn(function() + -- -- -- vim.lsp.config(name, configc) + -- vim.lsp.config(name, _G.clangd) + -- vim.lsp.enable(name) + -- vim.cmd('checktime') + -- -- end, 600) + -- end) end -- -- 1. Stop the specific client -- for _, client in ipairs(clients) do client:stop() end diff --git a/tmp.lua b/tmp.lua new file mode 100644 index 00000000..c536630d --- /dev/null +++ b/tmp.lua @@ -0,0 +1,108 @@ +local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +-- 1. Define the template with 3 placeholders +-- ============================================================================= +-- DYNAMIC CLANGD CONFIGURATION TEMPLATE +-- ============================================================================= +-- Note: %q is used for paths to handle escaping and spaces automatically. +local clangd_template = [[ +{ + cmd = { + "clangd", + "--all-scopes-completion", + "--background-index", + "--clang-tidy", + "--compile_args_from=filesystem", + "--enable-config", + "--completion-parse=always", + "--completion-style=detailed", + "--header-insertion=iwyu", + "--fallback-style=llvm", + "-j=12", + "--log=verbose", + "--offset-encoding=utf-8", + "--pch-storage=memory", + "--pretty", + "--ranking-model=decision_forest", + "--sync", + "--offset-encoding=utf-16", + "--query-driver=%s", + }, + filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, + root_markers = { + 'platformio.ini', + 'CMakeLists.txt', + '.clangd', + '.clang-tidy', + '.clang-format', + 'compile_commands.json', + 'compile_flags.txt', + 'configure.ac', + '.git', + }, + workspace_required = true, + single_file_support = true, + init_options = { + usePlaceholders = true, + completeUnimported = true, + fallbackFlags = {%s}, + clangdFileStatus = true, + compilationDatabasePath = %q, + } +} +]] + +-- 2. Prepare the data +-- ============================================================================= +-- LSP SETUP (NEOVIM 0.11+) +-- ============================================================================= + +local clangd_config = { + -- on_new_config runs every time client started + -- stylua: ignore + on_new_config = function(new_config, new_root_dir) + -- Safety check for root_dir + if not new_root_dir then return end + + -- Safe defaults (Standard clangd behavior) + local f_flags, q_driver = '', '--query-driver=**' + + if _G.metadata.cc_compiler ~= '' then + if _G.metadata.triplet and _G.metadata.triplet ~= '' then + q_driver = '--query-driver=' .. (_G.metadata.query_driver or '**') + f_flags = string.format('"--target=%s", "--sysroot=%s"', _G.metadata.triplet, _G.metadata.sysroot) + end + end + + -- Format the clangd_config string + local clangd_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) + local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) + + -- Load the string as a Lua table safely + local ok, table_config = pcall(function() return load('return ' .. formatted_str)() end) + + if ok and table_config then + -- This merges table_config INTO new_config, overwriting existing values + local merged = vim.tbl_deep_extend('force', new_config, table_config) + -- Since we can't reassign the reference, we have to copy the keys back + for k, v in pairs(merged) do new_config[k] = v end + else + -- If template loading fails, alert the user but keep default cmd + vim.notify('LSP Config Table Generation Failed', vim.log.levels.ERROR) + end + end, +} + +-- Apply and Enable +vim.lsp.config('clangd', clangd_config) +vim.lsp.enable('clangd') +-- local q_driver = '--query-driver=' .. data.query_driver +-- local f_flags = string.format('"--target=%s", "--sysroot=%s"', data.triplet, data.sysroot) +-- local db_path = vim.uv.cwd() -- Using 0.11+ uv alias +-- +-- -- 3. Format the string +-- local formatted_str = string.format(clangd_template, q_driver, f_flags, db_path) +-- +-- -- 4. Load it into a real Lua table +-- local status, my_table = pcall(function() +-- return load('return ' .. formatted_str)() +-- end) From c75b2282caa3c29a94d0e3542dca6af08c1816c1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 15:14:16 +0300 Subject: [PATCH 0636/1406] update --- lua/platformio/pio_setup.lua | 71 ++++++++++++++++++------------------ 1 file changed, 35 insertions(+), 36 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index c5d78d11..b25ba15a 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -147,45 +147,44 @@ local pio_manager = (function() if int_obj.code == 0 and int_obj.stdout then local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) if ok and raw_data then - local _, env = next(raw_data) - if not env then - return - end - local fallback_flags = {} - -- 1. Process Includes - if env.includes then - for category, paths in pairs(env.includes) do - -- If it's a toolchain path, use -isystem to suppress warnings - -- and tell clangd these are standard libraries - if category == 'toolchain' then - local flag = '-isystem' - for _, path in ipairs(paths) do - table.insert(fallback_flags, flag .. path) + local _, data = next(raw_data) + if data then + local fallback_flags = {} + -- 1. Process Includes + if data.includes then + for category, paths in pairs(data.includes) do + -- If it's a toolchain path, use -isystem to suppress warnings + -- and tell clangd these are standard libraries + if category == 'toolchain' then + local flag = '-isystem' + for _, path in ipairs(paths) do + table.insert(fallback_flags, flag .. path) + end end + -- local flag = (category == 'toolchain') and '-isystem' or '-I' + -- for _, path in ipairs(paths) do + -- table.insert(fallback_flags, flag .. path) + -- end end - -- local flag = (category == 'toolchain') and '-isystem' or '-I' - -- for _, path in ipairs(paths) do - -- table.insert(fallback_flags, flag .. path) - -- end end - end - -- 2. Process Defines - -- if env.defines then - -- for _, define in ipairs(env.defines) do - -- table.insert(fallback_flags, '-D' .. define) - -- end - -- end - - -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' - _G.metadata.cc_compiler = misc.normalize_path(env.cc_compiler) or '' - _G.metadata.fallback_flags = fallback_flags - - -- print(vim.inspect(_G.metadata)) - if callback then - vim.schedule(function() - vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) - callback() - end) + -- 2. Process Defines + -- if env.defines then + -- for _, define in ipairs(env.defines) do + -- table.insert(fallback_flags, '-D' .. define) + -- end + -- end + + -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' + _G.metadata.cc_compiler = misc.normalize_path(data.cc_compiler) or '' + _G.metadata.fallback_flags = fallback_flags + + -- print(vim.inspect(_G.metadata)) + if callback then + vim.schedule(function() + vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) + callback() + end) + end end else vim.schedule(function() From 89014036557a268e8eba52d1ed83519b4340110f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 15:18:49 +0300 Subject: [PATCH 0637/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b25ba15a..a043e020 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -175,7 +175,7 @@ local pio_manager = (function() -- end -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' - _G.metadata.cc_compiler = misc.normalize_path(data.cc_compiler) or '' + _G.metadata.cc_compiler = misc.normalize_path(data.cc_path) or '' _G.metadata.fallback_flags = fallback_flags -- print(vim.inspect(_G.metadata)) From 21cf1efc2d2838a3552b9327535d3a71188886d5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 15:56:04 +0300 Subject: [PATCH 0638/1406] update --- lua/platformio/boilerplate.lua | 6 +++--- lua/platformio/lspConfig/clangd.lua | 6 ++++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 2955e619..e97be661 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -82,7 +82,7 @@ boilerplate['.clangd_config'] = { "--ranking-model=decision_forest", "--sync", "--offset-encoding=utf-16", - "--query-driver=%s", -- will be assigned based op project + "--query-driver=%s", }, filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, root_markers = { @@ -101,9 +101,9 @@ boilerplate['.clangd_config'] = { init_options = { usePlaceholders = true, completeUnimported = true, - fallbackFlags = {%s}, -- will be assigned based op project + fallbackFlags = {%s}, clangdFileStatus = true, - compilationDatabasePath = %q, -- will be assigned based op project + compilationDatabasePath = %q, } } ]], diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 4fe0cd1e..82cf01b7 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -207,14 +207,16 @@ local clangd_config = { local clangd_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) + print(formatted_str) -- Load the string as a Lua table safely - local ok, table_config = pcall(function() return load('return ' .. formatted_str)() end) + local cok, table_config = pcall(function() return load('return ' .. formatted_str)() end) - if ok and table_config then + if cok and table_config then -- This merges table_config INTO new_config, overwriting existing values local merged = vim.tbl_deep_extend('force', new_config, table_config) -- Since we can't reassign the reference, we have to copy the keys back for k, v in pairs(merged) do new_config[k] = v end + print(vim.inspect(new_config)) else -- If template loading fails, alert the user but keep default cmd vim.notify('LSP Config Table Generation Failed', vim.log.levels.ERROR) From 07a0500ecd5bd0f90358052b424f7a93d1031f52 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 16:01:53 +0300 Subject: [PATCH 0639/1406] update --- lua/platformio/lspConfig/clangd.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 82cf01b7..13a0dc4d 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -191,6 +191,7 @@ local clangd_config = { -- stylua: ignore on_new_config = function(new_config, new_root_dir) -- Safety check for root_dir + vim.notify("LSP Starting in: " .. (new_root_dir or "nil")) if not new_root_dir then return end -- Safe defaults (Standard clangd behavior) From 1df97d4299b113d07e5959f026249e1fd4cc4be7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 16:07:41 +0300 Subject: [PATCH 0640/1406] update --- lua/platformio/lspConfig/clangd.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 13a0dc4d..e144dc23 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -187,6 +187,8 @@ vim.lsp.config('*', { -- } -- vim.lsp.config('clangd', _G.clangd) local clangd_config = { + -- 1. ADD THIS: Provide a default cmd so validation passes + cmd = { 'clangd' }, -- on_new_config runs every time client started -- stylua: ignore on_new_config = function(new_config, new_root_dir) From 6893609ff6c23d66ad60b7be59c0861cf0f1c070 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 16:31:37 +0300 Subject: [PATCH 0641/1406] update --- lua/platformio/lspConfig/clangd.lua | 36 ++++++++++++++++++----------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index e144dc23..cd16e4fa 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -188,17 +188,21 @@ vim.lsp.config('*', { -- vim.lsp.config('clangd', _G.clangd) local clangd_config = { -- 1. ADD THIS: Provide a default cmd so validation passes - cmd = { 'clangd' }, + -- cmd = { 'clangd' }, -- on_new_config runs every time client started -- stylua: ignore - on_new_config = function(new_config, new_root_dir) - -- Safety check for root_dir + -- on_new_config = function(new_config, new_root_dir) + cmd = function(dispatchers) + -- 1. Use the current working directory or buffer's directory + local new_root_dir = vim.uv.cwd() vim.notify("LSP Starting in: " .. (new_root_dir or "nil")) + if not new_root_dir then return end -- Safe defaults (Standard clangd behavior) local f_flags, q_driver = '', '--query-driver=**' + -- 2. Run your toolchain detection if _G.metadata.cc_compiler ~= '' then if _G.metadata.triplet and _G.metadata.triplet ~= '' then q_driver = '--query-driver=' .. (_G.metadata.query_driver or '**') @@ -206,24 +210,30 @@ local clangd_config = { end end + -- 3. Format your template string -- Format the clangd_config string local clangd_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) print(formatted_str) - -- Load the string as a Lua table safely + + -- 4. Load the config table local cok, table_config = pcall(function() return load('return ' .. formatted_str)() end) - if cok and table_config then - -- This merges table_config INTO new_config, overwriting existing values - local merged = vim.tbl_deep_extend('force', new_config, table_config) - -- Since we can't reassign the reference, we have to copy the keys back - for k, v in pairs(merged) do new_config[k] = v end - print(vim.inspect(new_config)) - else + -- 5. Extract the final command list + local final_cmd = (ok and table_config) and table_config.cmd or { "clangd" } + -- 6. Launch the RPC client + return vim.lsp.rpc.start(final_cmd, dispatchers) + -- if cok and table_config then + -- -- This merges table_config INTO new_config, overwriting existing values + -- local merged = vim.tbl_deep_extend('force', new_config, table_config) + -- -- Since we can't reassign the reference, we have to copy the keys back + -- for k, v in pairs(merged) do new_config[k] = v end + -- print(vim.inspect(new_config)) + -- else -- If template loading fails, alert the user but keep default cmd - vim.notify('LSP Config Table Generation Failed', vim.log.levels.ERROR) - end + -- vim.notify('LSP Config Table Generation Failed', vim.log.levels.ERROR) + -- end end, } From e18b67e0cc529723f88ae35ea5853f4754c7fcba Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 16:52:23 +0300 Subject: [PATCH 0642/1406] update --- lua/platformio/lspConfig/attach.lua | 21 ++++++++++++++------- lua/platformio/lspConfig/clangd.lua | 2 +- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/lua/platformio/lspConfig/attach.lua b/lua/platformio/lspConfig/attach.lua index fc8aa51a..2a573853 100644 --- a/lua/platformio/lspConfig/attach.lua +++ b/lua/platformio/lspConfig/attach.lua @@ -11,18 +11,25 @@ vim.api.nvim_create_autocmd('LspAttach', { ------------------------------------------------------------------ if client.name == 'clangd' then - vim.api.nvim_buf_create_user_command(0, 'LspClangdSwitchSourceHeader', function() - local method_name = 'textDocument/switchSourceHeader' + local uri = vim.uri_from_bufnr(bufnr) + if not uri:match('^file://') then + return -- Stop here for non-file buffers (like git:// or nvim://) + end + vim.api.nvim_buf_create_user_command(bufnr, 'LspClangdSwitchSourceHeader', function() local params = vim.lsp.util.make_text_document_params(bufnr) - client.request(method_name, params, function(err, result) + client.request('textDocument/switchSourceHeader', params, function(err, result) if err then - error(tostring(err)) + vim.notify('Clangd Error: ' .. tostring(err), vim.log.levels.ERROR) + return end - if not result then - vim.notify('corresponding file cannot be determined') + if not result or result == '' then + vim.notify('Corresponding file cannot be determined', vim.log.levels.WARN) return end - vim.cmd.edit(vim.uri_to_fname(result)) + -- Use vim.schedule to ensure we aren't editing while the LSP is in a callback + vim.schedule(function() + vim.cmd.edit(vim.uri_to_fname(result)) + end) end, bufnr) end, { desc = 'Switch between source/header' }) -- piolsp.fix_pio_compile_commands() diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index cd16e4fa..e9dcf7ce 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -215,13 +215,13 @@ local clangd_config = { local clangd_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) - print(formatted_str) -- 4. Load the config table local cok, table_config = pcall(function() return load('return ' .. formatted_str)() end) -- 5. Extract the final command list local final_cmd = (ok and table_config) and table_config.cmd or { "clangd" } + print(vim.inspect(final_cmd)) -- 6. Launch the RPC client return vim.lsp.rpc.start(final_cmd, dispatchers) -- if cok and table_config then From 12c5d7d885b48ec1f46ef22868af3598ee7a147c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 17:41:43 +0300 Subject: [PATCH 0643/1406] update --- lua/platformio/lspConfig/clangd.lua | 129 ++++++++++++++++++---------- 1 file changed, 83 insertions(+), 46 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index e9dcf7ce..f4616d21 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -186,59 +186,96 @@ vim.lsp.config('*', { -- init_options = init_options, -- } -- vim.lsp.config('clangd', _G.clangd) -local clangd_config = { - -- 1. ADD THIS: Provide a default cmd so validation passes - -- cmd = { 'clangd' }, - -- on_new_config runs every time client started - -- stylua: ignore - -- on_new_config = function(new_config, new_root_dir) - cmd = function(dispatchers) - -- 1. Use the current working directory or buffer's directory - local new_root_dir = vim.uv.cwd() - vim.notify("LSP Starting in: " .. (new_root_dir or "nil")) - - if not new_root_dir then return end - - -- Safe defaults (Standard clangd behavior) - local f_flags, q_driver = '', '--query-driver=**' +-- local clangd_config = { +-- -- 1. ADD THIS: Provide a default cmd so validation passes +-- -- cmd = { 'clangd' }, +-- -- on_new_config runs every time client started +-- -- stylua: ignore +-- -- on_new_config = function(new_config, new_root_dir) +-- cmd = function(dispatchers) +-- -- 1. Use the current working directory or buffer's directory +-- local new_root_dir = vim.uv.cwd() or '.' +-- vim.notify("LSP Starting in: " .. (new_root_dir or "nil")) +-- +-- if not new_root_dir then return end +-- +-- -- Safe defaults (Standard clangd behavior) +-- local f_flags, q_driver = '', '--query-driver=**' +-- +-- -- 2. Run your toolchain detection +-- if _G.metadata.cc_compiler ~= '' then +-- if _G.metadata.triplet and _G.metadata.triplet ~= '' then +-- q_driver = '--query-driver=' .. (_G.metadata.query_driver or '**') +-- f_flags = string.format('"--target=%s", "--sysroot=%s"', _G.metadata.triplet, _G.metadata.sysroot) +-- end +-- end +-- +-- -- 3. Format your template string +-- -- Format the clangd_config string +-- local clangd_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) +-- local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) +-- +-- +-- -- 4. Load the config table +-- local cok, table_config = pcall(function() return load('return ' .. formatted_str)() end) +-- +-- -- 5. Extract the final command list +-- -- +-- -- +-- -- +-- -- +-- local final_cmd = (cok and table_config) and table_config.cmd or { "clangd" } +-- print(vim.inspect(final_cmd)) +-- -- 6. Launch the RPC client +-- return vim.lsp.rpc.start(final_cmd, dispatchers) +-- -- if cok and table_config then +-- -- -- This merges table_config INTO new_config, overwriting existing values +-- -- local merged = vim.tbl_deep_extend('force', new_config, table_config) +-- -- -- Since we can't reassign the reference, we have to copy the keys back +-- -- for k, v in pairs(merged) do new_config[k] = v end +-- -- print(vim.inspect(new_config)) +-- -- else +-- -- If template loading fails, alert the user but keep default cmd +-- -- vim.notify('LSP Config Table Generation Failed', vim.log.levels.ERROR) +-- -- end +-- end, +-- } - -- 2. Run your toolchain detection - if _G.metadata.cc_compiler ~= '' then - if _G.metadata.triplet and _G.metadata.triplet ~= '' then - q_driver = '--query-driver=' .. (_G.metadata.query_driver or '**') - f_flags = string.format('"--target=%s", "--sysroot=%s"', _G.metadata.triplet, _G.metadata.sysroot) - end - end +function _G.get_clangd_config() + local new_root_dir = vim.uv.cwd() or '.' + vim.notify('LSP Starting in: ' .. (new_root_dir or 'nil')) - -- 3. Format your template string - -- Format the clangd_config string - local clangd_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) - local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) + if not new_root_dir then + return + end + -- Safe defaults (Standard clangd behavior) + local f_flags, q_driver = '', '--query-driver=**' - -- 4. Load the config table - local cok, table_config = pcall(function() return load('return ' .. formatted_str)() end) + -- 2. Run your toolchain detection + if _G.metadata.cc_compiler ~= '' then + if _G.metadata.triplet and _G.metadata.triplet ~= '' then + q_driver = '--query-driver=' .. (_G.metadata.query_driver or '**') + f_flags = string.format('"--target=%s", "--sysroot=%s"', _G.metadata.triplet, _G.metadata.sysroot) + end + end - -- 5. Extract the final command list - local final_cmd = (ok and table_config) and table_config.cmd or { "clangd" } - print(vim.inspect(final_cmd)) - -- 6. Launch the RPC client - return vim.lsp.rpc.start(final_cmd, dispatchers) - -- if cok and table_config then - -- -- This merges table_config INTO new_config, overwriting existing values - -- local merged = vim.tbl_deep_extend('force', new_config, table_config) - -- -- Since we can't reassign the reference, we have to copy the keys back - -- for k, v in pairs(merged) do new_config[k] = v end - -- print(vim.inspect(new_config)) - -- else - -- If template loading fails, alert the user but keep default cmd - -- vim.notify('LSP Config Table Generation Failed', vim.log.levels.ERROR) - -- end - end, -} + -- 3. Format your template string + -- Format the clangd_config string + local clangd_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) + local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) + -- 4. Load the config table + local cok, table_config = pcall(function() + return load('return ' .. formatted_str)() + end) + if cok and table_config then + return table_config + end +end -- Apply and Enable -vim.lsp.config('clangd', clangd_config) +-- vim.lsp.config('clangd', clangd_config) +vim.lsp.config('clangd', _G.get_clangd_config()) vim.lsp.enable('clangd') ---------------------------------------------------------------------------------------- From 4c71b6c8d1bdd64774fd49210fbe67aefc071ffc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 17:53:04 +0300 Subject: [PATCH 0644/1406] update --- lua/platformio/lspConfig/clangd.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index f4616d21..fa5293fb 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -255,7 +255,7 @@ function _G.get_clangd_config() -- 2. Run your toolchain detection if _G.metadata.cc_compiler ~= '' then if _G.metadata.triplet and _G.metadata.triplet ~= '' then - q_driver = '--query-driver=' .. (_G.metadata.query_driver or '**') + q_driver = _G.metadata.query_driver or '**' f_flags = string.format('"--target=%s", "--sysroot=%s"', _G.metadata.triplet, _G.metadata.sysroot) end end @@ -269,6 +269,7 @@ function _G.get_clangd_config() local cok, table_config = pcall(function() return load('return ' .. formatted_str)() end) + if cok and table_config then return table_config end From c21fa6782a82ab39815d52567fd15e6fd5c1aade Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 18:02:46 +0300 Subject: [PATCH 0645/1406] update --- lua/platformio/lspConfig/clangd.lua | 2 +- lua/platformio/utils/lsp.lua | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index fa5293fb..9de51720 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -250,7 +250,7 @@ function _G.get_clangd_config() end -- Safe defaults (Standard clangd behavior) - local f_flags, q_driver = '', '--query-driver=**' + local f_flags, q_driver = '', '**' -- 2. Run your toolchain detection if _G.metadata.cc_compiler ~= '' then diff --git a/lua/platformio/utils/lsp.lua b/lua/platformio/utils/lsp.lua index a436df84..9a5fd6f5 100644 --- a/lua/platformio/utils/lsp.lua +++ b/lua/platformio/utils/lsp.lua @@ -64,8 +64,10 @@ function M.lsp_restart(name) local clangd_config = client.config client:stop(true) -- -- Apply the config using the new 0.11+ API - vim.lsp.config('clangd', clangd_config) + vim.lsp.config('clangd', _G.get_clangd_config()) vim.lsp.enable('clangd') + -- vim.lsp.config('clangd', clangd_config) + -- vim.lsp.enable('clangd') vim.cmd('checktime') vim.cmd('edit') -- vim.schedule_wrap(function() From b2bf566362e6d845497edb1ec79e7bd4b84c6038 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 18:48:33 +0300 Subject: [PATCH 0646/1406] update --- lua/platformio/lspConfig/clangd.lua | 2 +- lua/platformio/utils/lsp.lua | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 9de51720..d9792f50 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -395,5 +395,5 @@ local pyrefly = { vim.lsp.config('pyrefly', pyrefly) -- restart lsp -require('platformio.utils.lsp').lsp_restart('clangd') +-- require('platformio.utils.lsp').lsp_restart('clangd') ---------------------------------------------------------------------------------- diff --git a/lua/platformio/utils/lsp.lua b/lua/platformio/utils/lsp.lua index 9a5fd6f5..071aa31b 100644 --- a/lua/platformio/utils/lsp.lua +++ b/lua/platformio/utils/lsp.lua @@ -65,7 +65,8 @@ function M.lsp_restart(name) client:stop(true) -- -- Apply the config using the new 0.11+ API vim.lsp.config('clangd', _G.get_clangd_config()) - vim.lsp.enable('clangd') + vim.lsp.enable('clangd', false) + vim.lsp.enable('clangd', true) -- vim.lsp.config('clangd', clangd_config) -- vim.lsp.enable('clangd') vim.cmd('checktime') From 96e51dd89ae0cc6a89934fced1caf83635846ae5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 18:52:34 +0300 Subject: [PATCH 0647/1406] update --- lua/platformio/lspConfig/clangd.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index d9792f50..baadb60b 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -265,6 +265,7 @@ function _G.get_clangd_config() local clangd_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) + print(formatted_str) -- 4. Load the config table local cok, table_config = pcall(function() return load('return ' .. formatted_str)() From 6ef10b74551731316363487810c2765aedaf07ed Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 18:59:42 +0300 Subject: [PATCH 0648/1406] update --- lua/platformio/utils/lsp.lua | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/lsp.lua b/lua/platformio/utils/lsp.lua index 071aa31b..607fa15d 100644 --- a/lua/platformio/utils/lsp.lua +++ b/lua/platformio/utils/lsp.lua @@ -64,7 +64,9 @@ function M.lsp_restart(name) local clangd_config = client.config client:stop(true) -- -- Apply the config using the new 0.11+ API - vim.lsp.config('clangd', _G.get_clangd_config()) + local clangConfig = _G.get_clangd_config() + print(vim.inspect(clangConfig)) + vim.lsp.config('clangd', clangConfig) vim.lsp.enable('clangd', false) vim.lsp.enable('clangd', true) -- vim.lsp.config('clangd', clangd_config) From 43202dcff567d3e8910f0e0662dfcf3458592ffc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 19:04:48 +0300 Subject: [PATCH 0649/1406] update --- lua/platformio/lspConfig/clangd.lua | 2 +- lua/platformio/utils/lsp.lua | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index baadb60b..3ec3e267 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -265,7 +265,7 @@ function _G.get_clangd_config() local clangd_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) - print(formatted_str) + -- print(formatted_str) -- 4. Load the config table local cok, table_config = pcall(function() return load('return ' .. formatted_str)() diff --git a/lua/platformio/utils/lsp.lua b/lua/platformio/utils/lsp.lua index 607fa15d..7e2d2459 100644 --- a/lua/platformio/utils/lsp.lua +++ b/lua/platformio/utils/lsp.lua @@ -59,13 +59,13 @@ function M.lsp_restart(name) end end else + local clangConfig = _G.get_clangd_config() + print(vim.inspect(clangConfig)) local clients = vim.lsp.get_clients({ name = name }) for _, client in ipairs(clients) do local clangd_config = client.config client:stop(true) -- -- Apply the config using the new 0.11+ API - local clangConfig = _G.get_clangd_config() - print(vim.inspect(clangConfig)) vim.lsp.config('clangd', clangConfig) vim.lsp.enable('clangd', false) vim.lsp.enable('clangd', true) From df2d709cc1512ddf5c8c2d576f1dd01310402064 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 19:21:42 +0300 Subject: [PATCH 0650/1406] update --- lua/platformio/utils/lsp.lua | 45 +++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/lua/platformio/utils/lsp.lua b/lua/platformio/utils/lsp.lua index 7e2d2459..e46cdf6e 100644 --- a/lua/platformio/utils/lsp.lua +++ b/lua/platformio/utils/lsp.lua @@ -60,28 +60,31 @@ function M.lsp_restart(name) end else local clangConfig = _G.get_clangd_config() + vim.lsp.config('clangd', clangConfig) + vim.lsp.enable('clangd', false) + vim.lsp.enable('clangd', true) print(vim.inspect(clangConfig)) - local clients = vim.lsp.get_clients({ name = name }) - for _, client in ipairs(clients) do - local clangd_config = client.config - client:stop(true) - -- -- Apply the config using the new 0.11+ API - vim.lsp.config('clangd', clangConfig) - vim.lsp.enable('clangd', false) - vim.lsp.enable('clangd', true) - -- vim.lsp.config('clangd', clangd_config) - -- vim.lsp.enable('clangd') - vim.cmd('checktime') - vim.cmd('edit') - -- vim.schedule_wrap(function() - -- -- vim.defer_fn(function() - -- -- -- vim.lsp.config(name, configc) - -- vim.lsp.config(name, _G.clangd) - -- vim.lsp.enable(name) - -- vim.cmd('checktime') - -- -- end, 600) - -- end) - end + -- local clients = vim.lsp.get_clients({ name = name }) + -- for _, client in ipairs(clients) do + -- local clangd_config = client.config + -- client:stop(true) + -- -- -- Apply the config using the new 0.11+ API + -- vim.lsp.config('clangd', clangConfig) + -- vim.lsp.enable('clangd', false) + -- vim.lsp.enable('clangd', true) + -- -- vim.lsp.config('clangd', clangd_config) + -- -- vim.lsp.enable('clangd') + -- vim.cmd('checktime') + -- vim.cmd('edit') + -- -- vim.schedule_wrap(function() + -- -- -- vim.defer_fn(function() + -- -- -- -- vim.lsp.config(name, configc) + -- -- vim.lsp.config(name, _G.clangd) + -- -- vim.lsp.enable(name) + -- -- vim.cmd('checktime') + -- -- -- end, 600) + -- -- end) + -- end -- -- 1. Stop the specific client -- for _, client in ipairs(clients) do client:stop() end -- From 42198ae4c256cb60e50e325ccb8a1f559a7e8cc1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 21:43:40 +0300 Subject: [PATCH 0651/1406] update --- tmp.lua => lua/platformio/archived/tmp.lua | 0 lua/platformio/boilerplate.lua | 44 +- lua/platformio/lspConfig/clangd.lua | 144 +------ lua/platformio/pio_setup.lua | 21 +- lua/platformio/utils/lsp.lua | 124 +----- pio_setup.lua | 480 --------------------- 6 files changed, 15 insertions(+), 798 deletions(-) rename tmp.lua => lua/platformio/archived/tmp.lua (100%) delete mode 100644 pio_setup.lua diff --git a/tmp.lua b/lua/platformio/archived/tmp.lua similarity index 100% rename from tmp.lua rename to lua/platformio/archived/tmp.lua diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index e97be661..f6caefaa 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -68,15 +68,14 @@ boilerplate['.clangd_config'] = { "--all-scopes-completion", "--background-index", "--clang-tidy", - "--compile_args_from=filesystem", + "--compile_args_from=lsp", "--enable-config", "--completion-parse=always", "--completion-style=detailed", "--header-insertion=iwyu", "--fallback-style=llvm", "-j=12", - "--log=verbose", - "--offset-encoding=utf-8", + "--log=error", "--pch-storage=memory", "--pretty", "--ranking-model=decision_forest", @@ -495,42 +494,3 @@ function M.boilerplate_gen(framework, src_path, filename) end return M - --- -- INFO: .clangd_init_options --- boilerplate['.clangd_init_options'] = { --- rewrite = true, --- read = false, --- template = [[ --- usePlaceholders=true, --- completeUnimported=true, --- fallbackFlags={%s}, --- clangdFileStatus=true, --- compilationDatabasePath="%s", --- ]], --- content = function(self) --- local f_flags = string.format('"--target=%s", "--sysroot=%s"', _G.metadata.triplet, _G.metadata.sysroot) --- return string.format( --- self.template, --- ('"-std=c++17","--target=' .. _G.metadata.triplet .. '","--sysroot=' .. _G.metadata.sysroot) .. '"' or '"-std=c++17"', --- misc.normalize_path(vim.uv.cwd()) --- ) --- end, --- } --- --- -- INFO: enable_toolchain.py --- boilerplate['enable_toolchain.py'] = { --- rewrite = false, --- read = false, --- content = [[ --- from SCons.Script import DefaultEnvironment --- env = DefaultEnvironment() --- env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True) --- --- #Import("env") --- --- # Safe retrieval with a default message --- print(f"Toolchain Inclusion Status: {env.get('COMPILATIONDB_INCLUDE_TOOLCHAIN', 'Not Set')}") --- print(">>> SUCCESS: Toolchain inclusion forced in Global Environment") --- ]], --- } --- diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 3ec3e267..b00dd0fc 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -84,8 +84,6 @@ end) local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') if mok then mason_lspconfig.setup({ - -- ensure_installed = { 'clangd', 'pyrefly' }, - -- ensure_installed = { 'ccls', 'lua_ls', 'pyrefly', 'yamlls' }, ensure_installed = { 'clangd', 'lua_ls', 'pyrefly', 'yamlls' }, automatic_enable = true, -- this will automatically enable LSP servers after lsp.config }) @@ -102,7 +100,6 @@ local capabilities = vim.lsp.protocol.make_client_capabilities({ }) local bok, blink = pcall(require, 'blink.cmp') if bok then - -- capabilities = vim.tbl_deep_extend('force', capabilities, blink.get_lsp_capabilities({}, false)) capabilities = blink.get_lsp_capabilities(capabilities) end @@ -113,143 +110,15 @@ vim.lsp.config('*', { workspace_required = false, }) ----------------------------------------------------------------------------------------- --- INFO: configure ccls lsp server ------------------------------------------------------------------------------------------ --- vim.lsp.config('ccls', { --- filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, --- root_markers = { --- 'CMakeLists.txt', --- '.clangd', --- '.clang-tidy', --- '.clang-format', --- 'compile_commands.json', --- 'compile_flags.txt', --- 'configure.ac', --- '.git', --- vim.uv.cwd(), --- }, --- init_options = { --- diagnostics = { --- onChange = 100, --- }, --- }, --- }) --- vim.lsp.enable('ccls') - ---------------------------------------------------------------------------------------- -- INFO: configure clangd lsp server ----------------------------------------------------------------------------------------- - --- local cmd = { 'clangd' } --- local fname = string.format('%s/.clangd_cmd', vim.uv.cwd()) --- if vim.uv.fs_stat(fname) then --- ok, result = pcall(vim.fn.readfile, fname) --- if ok then --- cmd = result --- -- print(vim.inspect(cmd)) --- end --- end --- --- local init_options = { --- usePlaceholders = true, --- completeUnimported = true, --- fallbackFlags = { '-std=c++17' }, --- clangdFileStatus = true, --- compilationDatabasePath = vim.uv.cwd(), --- } --- fname = string.format('%s/.clangd_init_options', vim.uv.cwd()) --- if vim.uv.fs_stat(fname) then --- ok, result = pcall(vim.fn.readfile, fname) --- if ok then --- init_options = result --- -- print(vim.inspect(cmd)) --- end --- end --- --- _G.clangd = { --- cmd = cmd, --- filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, --- root_markers = { --- 'CMakeLists.txt', --- '.clangd', --- '.clang-tidy', --- '.clang-format', --- 'compile_commands.json', --- 'compile_flags.txt', --- 'configure.ac', --- '.git', --- vim.uv.cwd(), --- }, --- workspace_required = true, --- single_file_support = true, --- init_options = init_options, --- } --- vim.lsp.config('clangd', _G.clangd) --- local clangd_config = { --- -- 1. ADD THIS: Provide a default cmd so validation passes --- -- cmd = { 'clangd' }, --- -- on_new_config runs every time client started --- -- stylua: ignore --- -- on_new_config = function(new_config, new_root_dir) --- cmd = function(dispatchers) --- -- 1. Use the current working directory or buffer's directory --- local new_root_dir = vim.uv.cwd() or '.' --- vim.notify("LSP Starting in: " .. (new_root_dir or "nil")) --- --- if not new_root_dir then return end --- --- -- Safe defaults (Standard clangd behavior) --- local f_flags, q_driver = '', '--query-driver=**' --- --- -- 2. Run your toolchain detection --- if _G.metadata.cc_compiler ~= '' then --- if _G.metadata.triplet and _G.metadata.triplet ~= '' then --- q_driver = '--query-driver=' .. (_G.metadata.query_driver or '**') --- f_flags = string.format('"--target=%s", "--sysroot=%s"', _G.metadata.triplet, _G.metadata.sysroot) --- end --- end --- --- -- 3. Format your template string --- -- Format the clangd_config string --- local clangd_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) --- local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) --- --- --- -- 4. Load the config table --- local cok, table_config = pcall(function() return load('return ' .. formatted_str)() end) --- --- -- 5. Extract the final command list --- -- --- -- --- -- --- -- --- local final_cmd = (cok and table_config) and table_config.cmd or { "clangd" } --- print(vim.inspect(final_cmd)) --- -- 6. Launch the RPC client --- return vim.lsp.rpc.start(final_cmd, dispatchers) --- -- if cok and table_config then --- -- -- This merges table_config INTO new_config, overwriting existing values --- -- local merged = vim.tbl_deep_extend('force', new_config, table_config) --- -- -- Since we can't reassign the reference, we have to copy the keys back --- -- for k, v in pairs(merged) do new_config[k] = v end --- -- print(vim.inspect(new_config)) --- -- else --- -- If template loading fails, alert the user but keep default cmd --- -- vim.notify('LSP Config Table Generation Failed', vim.log.levels.ERROR) --- -- end --- end, --- } - +--stylua: ignore function _G.get_clangd_config() local new_root_dir = vim.uv.cwd() or '.' - vim.notify('LSP Starting in: ' .. (new_root_dir or 'nil')) - - if not new_root_dir then - return - end + if not new_root_dir then return end - -- Safe defaults (Standard clangd behavior) + -- 1. Safe defaults (Standard clangd behavior) local f_flags, q_driver = '', '**' -- 2. Run your toolchain detection @@ -261,22 +130,17 @@ function _G.get_clangd_config() end -- 3. Format your template string - -- Format the clangd_config string local clangd_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) - -- print(formatted_str) -- 4. Load the config table - local cok, table_config = pcall(function() - return load('return ' .. formatted_str)() - end) + local cok, table_config = pcall(function() return load('return ' .. formatted_str)() end) if cok and table_config then return table_config end end -- Apply and Enable --- vim.lsp.config('clangd', clangd_config) vim.lsp.config('clangd', _G.get_clangd_config()) vim.lsp.enable('clangd') diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index a043e020..3f0df012 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -383,13 +383,6 @@ function _G.get_pio_sdk_info() -- return pio_info end --- INFO: --- LSP HELPER: Returns the glob pattern for clangd's --query-driver --- e.g., C:\Users\tom\.platformio\packages\toolchain-riscv32-esp\bin\* -function _G.get_pio_toolchain_pattern() - return _G.metadata.query_driver -end - -- INFO: -- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync -- stylua: ignore @@ -430,8 +423,6 @@ local function start_pio_watcher() vim.schedule_wrap(function() pio_manager.refresh(function() -- vim.schedule(function() - -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - local status, data = pcall(get_sysroot_triplet, _G.metadata.cc_compiler) if status and data and data.triplet and data.triplet ~= '' then _G.metadata.triplet = data.triplet @@ -439,20 +430,14 @@ local function start_pio_watcher() _G.metadata.query_driver = data.query_driver _G.metadata.toolchain = data.toolchain_root end - boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) + -- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) + boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) pio_generate_db() lsp.lsp_restart('clangd') -- end) - end) - end) - ) - end - end - end) - ) + end) end)) end end end)) end ------------------------------------------------------------------------------------------------------ -- INFO: 6. Exported setup function diff --git a/lua/platformio/utils/lsp.lua b/lua/platformio/utils/lsp.lua index e46cdf6e..a34ed532 100644 --- a/lua/platformio/utils/lsp.lua +++ b/lua/platformio/utils/lsp.lua @@ -1,127 +1,15 @@ local M = {} --- -- Define your dynamic config --- local clangd_config = { --- cmd = { --- 'clangd', --- '--background-index', --- '--clang-tidy', --- '--query-driver=**', -- Placeholder index (#cmd) --- }, --- Important Detail: on_new_config behavior --- --- If you open a new project in a separate Neovim instance (or a separate tab with a different root), on_new_config runs automatically for that new project. --- If you edit your config while staying in the same project, you must restart. --- on_new_config = function(new_config, _) --- -- 1. Safely run your detection function --- local status, data = pcall(get_sysroot_triplet, 'C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/bin') --- --- if status and data then --- -- 2. Modify the last item (#) of the cmd table --- new_config.cmd[#new_config.cmd] = '--query-driver=' .. data.query_driver --- --- -- 3. Merge fallback flags into init_options --- new_config.init_options = vim.tbl_deep_extend('force', new_config.init_options or {}, { --- fallbackFlags = { --- '--target=' .. data.triplet, --- '--sysroot=' .. data.sysroot, --- }, --- }) --- end --- end, --- } --- vim.lsp.config("clangd", { --- on_new_config = function(config, new_root_dir) --- -- This is the only place you can safely change this: --- config.cmd[#config.cmd] = "--query-driver=" .. my_detected_path --- end, --- }) --- local function restart_clangd() --- local clients = vim.lsp.get_clients({ name = "clangd" }) --- for _, client in ipairs(clients) do --- client.stop() -- Stops the process --- end --- -- Neovim 0.11+ will automatically try to restart enabled servers --- -- if a valid buffer is open, or you can trigger a reload. --- vim.cmd("edit") --- end --- stylua: ignore function M.lsp_restart(name) - if vim.fn.has('nvim-0.12') == 1 then - -- local clients = vim.lsp.get_clients({ name = name }) - local clangd = vim.lsp.get_clients({ name = name })[1] - if clangd then - local ok, err = pcall(vim.cmd.lsp, { args = { 'restart', 'clangd' } }) - if not ok then - vim.notify('LSP ' .. name .. ' restart failed: ' .. err) - else - vim.notify('LSP ' .. name .. ' restarted' .. err) - end - end - else + vim.schedule_wrap(function() local clangConfig = _G.get_clangd_config() - vim.lsp.config('clangd', clangConfig) - vim.lsp.enable('clangd', false) - vim.lsp.enable('clangd', true) print(vim.inspect(clangConfig)) - -- local clients = vim.lsp.get_clients({ name = name }) - -- for _, client in ipairs(clients) do - -- local clangd_config = client.config - -- client:stop(true) - -- -- -- Apply the config using the new 0.11+ API - -- vim.lsp.config('clangd', clangConfig) - -- vim.lsp.enable('clangd', false) - -- vim.lsp.enable('clangd', true) - -- -- vim.lsp.config('clangd', clangd_config) - -- -- vim.lsp.enable('clangd') - -- vim.cmd('checktime') - -- vim.cmd('edit') - -- -- vim.schedule_wrap(function() - -- -- -- vim.defer_fn(function() - -- -- -- -- vim.lsp.config(name, configc) - -- -- vim.lsp.config(name, _G.clangd) - -- -- vim.lsp.enable(name) - -- -- vim.cmd('checktime') - -- -- -- end, 600) - -- -- end) - -- end - -- -- 1. Stop the specific client - -- for _, client in ipairs(clients) do client:stop() end - -- - -- -- 2. Reload all loaded buffers to trigger re-attachment for that client - -- -- (Note: 'checktime' is safer than 'bufdo edit' as it respects unsaved changes) - -- vim.cmd('checktime') - end + vim.lsp.config(name, clangConfig) + vim.lsp.enable(name, false) + vim.lsp.enable(name, true) + vim.cmd('checktime') + end) end --- function M.lsp_restarti() --- local bufnr = nvim_get_current_buf() --- local clients = lsp.get_clients({ bufnr = bufnr }) --- --- if #clients == 0 then --- -- I'm using my own implementation of `vim.lsp.enable()` --- -- To work with default one change group name from `MyLsp` to `nvim.lsp.enable` --- -- It is not tested with default one, so not sure if it would 100% work. --- api.nvim_exec_autocmds('FileType', { group = 'MyLsp', buffer = bufnr }) --- return --- end --- --- for _, c in ipairs(clients) do --- local attached_buffers = vim.tbl_keys(c.attached_buffers) ---@type integer[] --- local config = c.config --- lsp.stop_client(c.id, true) --- vim.defer_fn(function() --- local id = lsp.start(config) --- if id then --- for _, b in ipairs(attached_buffers) do --- lsp.buf_attach_client(b, id) --- end --- vim.notify(string.format('Lsp `%s` has been restarted.', config.name)) --- else --- vim.notify(string.format('Error restarting `%s`.', config.name), vim.log.levels.ERROR) --- end --- end, 600) --- end --- end - return M diff --git a/pio_setup.lua b/pio_setup.lua deleted file mode 100644 index c486df75..00000000 --- a/pio_setup.lua +++ /dev/null @@ -1,480 +0,0 @@ --- M = {} --- --- M.metadata = nil --- local misc = require('platformio.utils.misc') --- local lsp = require('platformio.utils.lsp') --- --- -- lua/pio_setup.lua --- -- This module manages PlatformIO project integration, LSP toolchain detection, --- -- and automatic sysroot patching for standard library headers (, etc.) --- --- local debounce_timer = vim.uv.new_timer() --- --- -- INFO: 1. The Core PIO Manager & Generic Extractor --- local pio_manager = (function() --- local cache = nil -- Stores the decoded platformio.ini JSON structure --- --- -- INFO: --- -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' --- -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } --- local function find_in_data(data, section_name, key_name) --- -- Safety check: Ensure data is a valid table from a successful JSON decode --- if type(data) ~= 'table' then --- return nil --- end --- --- for _, section in ipairs(data) do --- -- Each section must be a table with at least 2 elements: [1]=name, [2]=content --- if type(section) == 'table' and #section >= 2 then --- local s_id = section[1] -- Section header string --- local s_body = section[2] -- Table of key-value pairs --- --- if s_id == section_name and type(s_body) == 'table' then --- for _, kv in ipairs(s_body) do --- -- Each kv is a table: [1]=key, [2]=value --- if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then --- local val = kv[2] --- -- Treat empty strings or empty tables as nil to trigger fallback logic --- if val == nil or val == '' or (type(val) == 'table' and #val == 0) then --- return nil --- end --- return val --- end --- end --- end --- end --- end --- return nil --- end --- --- -- INFO: --- -- ASYNC REFRESH: Fetches the latest config from PlatformIO CLI --- local function refresh(callback) --- vim.schedule(function() --- vim.notify('PIO: Fetching Config...', vim.log.levels.INFO) --- end) --- -- INFO: --- local function execute_pio(attempts) --- -- Use Neovim's async system call to prevent UI freezing --- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) --- -- Error Checking: obj.code 0 means success --- if obj.code == 0 and obj.stdout then --- local ok, decoded = pcall(vim.json.decode, obj.stdout) --- if ok and decoded then --- cache = decoded --- vim.schedule(function() --- if not cache or type(cache) ~= 'table' then --- vim.notify('PIO: Fetching Config failed. Check platformio.ini syntax.', vim.log.levels.INFO) --- else --- vim.notify('PIO: Fetching Config successful', vim.log.levels.INFO) --- end --- end) --- if callback then --- vim.schedule(callback) --- end --- return --- end --- end --- --- -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save --- if attempts > 0 then --- vim.defer_fn(function() --- execute_pio(attempts - 1) --- end, 500) --- else --- vim.schedule(function() --- if obj.code ~= 0 then --- vim.notify('PIO: Config Error. Check platformio.ini syntax.', vim.log.levels.WARN) --- end --- end) --- end --- end) --- end --- execute_pio(1) --- end --- --- -- INFO: --- return { --- refresh = refresh, --- -- INFO: --- get = function(s, k) --- if not cache then --- return nil --- end --- local res = find_in_data(cache, s, k) --- --- -- FALLBACK: If default_envs is missing/empty, find the first hardware [env:xxx] block --- if k == 'default_envs' and not res then --- for _, section in ipairs(cache) do --- if type(section) == 'table' and type(section[1]) == 'string' then --- local name = section[1] --- if name:find('^env:') then --- local fallback = name:match('^env:(.+)') --- if fallback then --- vim.schedule(function() --- vim.notify('PIO: default_envs empty. Using: ' .. fallback, vim.log.levels.INFO) --- end) --- return fallback --- end --- end --- end --- end --- vim.schedule(function() --- vim.notify('PIO: Config Error. Check platformio.ini no env', vim.log.levels.WARN) --- end) --- elseif k == 'default_envs' and res and type(res) == 'table' then --- return res[1] --- else --- return res --- end --- end, --- } --- end)() --- --- -- INFO: --- function _G.get_pio_sdk_info() --- local pio_info = { includes = {}, cc_path = '' } --- if vim.fn.filereadable('platformio.ini') == 0 then --- return nil --- end --- --- local handle = io.popen('pio run -t envdump') --- if not handle then --- return nil --- end --- --- local packages_dir, cc_name, toolchain_pkg = '', '', '' --- --- for line in handle:lines() do --- -- 1. Get the global packages directory --- packages_dir = packages_dir ~= '' and packages_dir or line:match("'PROJECT_PACKAGES_DIR': '([^']+)'") --- --- -- 2. Get the compiler executable name (e.g., riscv32-esp-elf-gcc) --- cc_name = cc_name ~= '' and cc_name or line:match("'CC': '([^']+)'") --- --- -- 3. Find the specific toolchain package name from the PACKAGES list --- -- Matches lines like "- toolchain-riscv32-esp @ 14.2.0" --- local pkg = line:match('%- (toolchain%-[^ ]+)') --- if pkg then --- toolchain_pkg = pkg --- end --- --- -- 4. Collect include paths --- local path_list = line:match("'CPPPATH': %[(.+)%]") --- if path_list then --- for path in path_list:gmatch("'([^']+)'") do --- table.insert(pio_info.includes, '-I' .. path) --- end --- end --- end --- handle:close() --- --- -- Construct the absolute path: //bin/ --- if packages_dir and packages_dir ~= '' and toolchain_pkg and toolchain_pkg ~= '' and cc_name ~= '' then --- local full_path = packages_dir .. '/' .. toolchain_pkg .. '/bin/' .. cc_name --- if vim.fn.executable(full_path) == 1 then --- pio_info.cc_path = full_path --- end --- end --- --- local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' --- print('get_pio_sdk_info(): final=' .. final) --- -- Normalize paths for the OS and ensure backslashes for Windows if needed --- print(vim.inspect(M.metadata)) --- return (misc.normalize_path(final)) --- -- return M.metadata.driver_path --- -- return pio_info --- end --- --- -- INFO: --- -- LSP HELPER: Returns the glob pattern for clangd's --query-driver --- -- e.g., C:\Users\tom\.platformio\packages\toolchain-riscv32-esp\bin\* --- function _G.get_pio_toolchain_pattern() --- local ok_env, active_env = pcall(function() --- return vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') --- end) --- if not ok_env or not active_env then --- return '/**/bin/*' --- end --- --- local target_env = 'env:' .. active_env --- local platform = pio_manager.get(target_env, 'platform') --- -- Determine the packages directory (Windows vs Linux/Mac home folders) --- local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('USERPROFILE') or os.getenv('HOME') .. '/.platformio/packages') --- --- if not platform then --- return '/**/bin/*' --- end --- --- -- Use pio platform show to find which toolchain packages are associated with the platform --- local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') --- if not p_handle then --- return '/**/bin/*' --- end --- local raw_json = p_handle:read('*all') --- p_handle:close() --- --- local p_ok, p_data = pcall(vim.json.decode, raw_json) --- if not p_ok or not p_data or not p_data.packages then --- return '/**/bin/*' --- end --- --- local toolchain_folder = '' --- for _, pkg in ipairs(p_data.packages) do --- -- Skip ULP (low power) toolchains and find the primary one for the architecture --- if pkg.name and pkg.name:find('^toolchain%-') and not pkg.name:find('ulp') then --- local check_path = (packages_dir .. '/' .. pkg.name):gsub('\\', '/') --- if vim.fn.isdirectory(check_path) == 1 then --- toolchain_folder = pkg.name --- -- Verification: Match the toolchain name against the compiler used in compile_commands.json --- local db_path = vim.uv.cwd() .. '/compile_commands.json' --- local f = io.open(db_path, 'r') --- if f then --- local head = f:read(2048) -- Read enough to find the compiler path --- f:close() --- -- If the DB mentions "riscv32-esp", we ensure we picked the matching folder --- if head and head:find(pkg.name:gsub('toolchain%-', '')) then --- break --- end --- end --- end --- end --- end --- --- if toolchain_folder == '' then --- return '/**/bin/*' --- end --- --- local final = packages_dir .. toolchain_folder --- print('get_pio_toolchain 5: final=' .. final) --- -- Normalize paths for the OS and ensure backslashes for Windows if needed --- return (misc.normalize_path(final)) --- -- return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final --- end --- --- -- INFO: --- -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag --- -- stylua: ignore --- local function pio_generate_db() --- -- Check if we actually have an active environment before running --- local active_env = vim.g.pio_active_env or pio_manager.get('platformio', 'default_envs') --- --- if not active_env then --- -- Silent return or a minor info message --- vim.schedule(function() --- vim.notify('PIO: No board configured yet. Skipping DB generation.', vim.log.levels.INFO) --- end) --- return --- end --- --- vim.schedule(function() vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) end) --- --- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) --- if obj.code ~= 0 then return end --- --- -- Isolate the toolchain root from the pattern (e.g. .../toolchain-riscv32-esp) --- -- local pattern = _G.get_pio_toolchain_pattern() --- local pattern = _G.get_pio_sdk_info() --- --- local toolchain_root = nil --- if pattern then toolchain_root = pattern:match('(.-toolchain%-[^/\\]+)') end --- --- if not toolchain_root or vim.fn.isdirectory(toolchain_root) == 0 then return end --- --- -- FIND SYSROOT: Locate the internal folder that contains the /include directory --- -- This folder is necessary for clangd to find standard C++ headers like --- -- local sysroot_path = nil --- -- local subdirs = vim.fn.getcompletion(toolchain_root .. '/*', 'dir') --- -- for _, dir in ipairs(subdirs) do --- -- if vim.fn.isdirectory(dir .. '/include') == 1 then --- -- sysroot_path = dir:gsub('\\', '/') --- -- break --- -- end --- -- end --- --- local sysroot_path = nil --- local handle = vim.uv.fs_scandir(toolchain_root) --- if handle then --- while true do --- local name, type = vim.uv.fs_scandir_next(handle) --- if not name then break end --- -- Check if the entry is a directory (or a symlink to one) --- if type == "directory" or type == "link" then --- local full_path = toolchain_root .. '/' .. name --- -- Check if 'include' exists inside this directory --- local stat = vim.uv.fs_stat(full_path .. '/include') --- if stat and stat.type == "directory" then --- sysroot_path = full_path:gsub('\\', '/') --- break --- end --- end --- end --- end --- --- if sysroot_path then --- local db_path = vim.uv.cwd() .. '/compile_commands.json' --- local f = io.open(db_path, 'r') --- if not f then return end --- local content = f:read('*all') --- f:close() --- --- -- Inject the --sysroot flag into every command in the JSON file --- if content and content ~= '' then --- local patched = content:gsub('("-i")', '"--sysroot=' .. sysroot_path .. '", %1') --- local out = io.open(db_path, 'w') --- if out then --- out:write(patched) --- out:close() --- vim.schedule(function() --- vim.notify('PIO: Sync Complete!', vim.log.levels.INFO) --- end) --- end --- end --- end --- end) --- end --- --- -- INFO: --- -- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync --- local function start_pio_watcher() --- local platformioini = vim.uv.cwd() .. '/platformio.ini' --- if vim.fn.filereadable(platformioini) == 0 then --- return --- end --- --- local w = vim.uv.new_fs_event() --- if not w then --- return --- end --- w:start( --- platformioini, --- {}, --- vim.schedule_wrap(function(err, _, events) --- if err or not events or not events.change then --- return --- end --- --- if debounce_timer then --- -- DEBOUNCE: Stops and restarts the timer to ensure we only sync ONCE after typing stops --- debounce_timer:stop() --- debounce_timer:start( --- 500, --- 0, --- vim.schedule_wrap(function() --- pio_manager.refresh(function() --- local board_env = pio_manager.get('platformio', 'default_envs') --- if board_env then --- vim.system({ 'pio', 'project', 'metadata', '-e', board_env, '--json-output' }, { text = true }, function(obj) --- -- Error Checking: obj.code 0 means success --- if obj.code == 0 and obj.stdout then --- local ok, raw_data = pcall(vim.json.decode, obj.stdout) --- if ok and raw_data then --- local _, env = next(raw_data) --- if not env then --- return --- end --- local fallback_flags = {} --- -- 1. Process Includes --- if env.includes then --- for category, paths in pairs(env.includes) do --- -- If it's a toolchain path, use -isystem to suppress warnings --- -- and tell clangd these are standard libraries --- local flag = (category == 'toolchain') and '-isystem' or '-I' --- --- for _, path in ipairs(paths) do --- table.insert(fallback_flags, flag .. path) --- end --- end --- end --- -- 2. Process Defines --- if env.defines then --- for _, define in ipairs(env.defines) do --- table.insert(fallback_flags, '-D' .. define) --- end --- end --- M.metadata = { --- driver_path = env.cc_path:match('(.*[/\\])') .. '/*' or '**', --- cc_path = env.cc_path or '', --- fallback_flags = fallback_flags, --- } --- -- M.metadata = decoded --- vim.schedule(function() --- pio_generate_db() --- lsp.lsp_restart('clangd') --- vim.notify('PIO: Syncing Environment successful') --- end) --- else --- vim.schedule(function() --- vim.notify('PIO: Syncing Environment failed') --- end) --- end --- end --- end) --- -- pio_generate_db() --- -- lsp.lsp_restart('clangd') --- -- vim.notify('PIO: Syncing Environment...') --- end --- end) --- end) --- ) --- end --- end) --- ) --- end --- --- ------------------------------------------------------------------------------------------------------ --- -- INFO: 6. Exported setup function --- function M.init() --- local config = require('platformio').config --- if config.lspClangd.enabled == true then --- vim.notify('PIO setup initialize', vim.log.levels.INFO) --- ---------------------------------------------------------------------------------------- --- -- INFO: create clangd required files --- ----------------------------------------------------------------------------------------- --- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen --- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) --- --- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) --- boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) --- -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) --- -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') --- --- -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) --- --- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) --- --- boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) --- -- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) --- -- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) --- --------------------------------------------------------------------------------- --- --- require('platformio.lspConfig.clangd') --- if config.lspClangd.attach.enabled then --- require('platformio.lspConfig.attach') --- end --- if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then --- pio_manager.refresh(function() --- -- We check if we have data inside the refresh callback --- local env = pio_manager.get('platformio', 'default_envs') --- if env then --- pio_generate_db() --- start_pio_watcher() --- end --- -- pio_generate_db() --- start_pio_watcher() --- end) --- end --- end --- end --- --- -- local pio = require('pio_utils') --- -- --- -- require('lspconfig').clangd.setup({ --- -- on_new_config = function(new_config, _) --- -- if pio.data then --- -- new_config.cmd = { "clangd", "--query-driver=" .. pio.data.cc_path } --- -- new_config.init_options = { fallbackFlags = pio.data.fallback_flags } --- -- end --- -- end --- -- }) --- return M From d3ebdb70b22cb379715a20b53cff0615b695bf76 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 21:50:02 +0300 Subject: [PATCH 0652/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index f6caefaa..b74953d4 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -68,7 +68,7 @@ boilerplate['.clangd_config'] = { "--all-scopes-completion", "--background-index", "--clang-tidy", - "--compile_args_from=lsp", + "--compile_args_from=filesystem", "--enable-config", "--completion-parse=always", "--completion-style=detailed", From 99a284d239b4eef4b2c340bd7478991d1d58198d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 21:58:13 +0300 Subject: [PATCH 0653/1406] update --- lua/platformio/utils/lsp.lua | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/lua/platformio/utils/lsp.lua b/lua/platformio/utils/lsp.lua index a34ed532..e553ae2d 100644 --- a/lua/platformio/utils/lsp.lua +++ b/lua/platformio/utils/lsp.lua @@ -2,14 +2,14 @@ local M = {} --- stylua: ignore function M.lsp_restart(name) - vim.schedule_wrap(function() - local clangConfig = _G.get_clangd_config() - print(vim.inspect(clangConfig)) - vim.lsp.config(name, clangConfig) - vim.lsp.enable(name, false) - vim.lsp.enable(name, true) - vim.cmd('checktime') - end) + -- vim.schedule_wrap(function() + local clangConfig = _G.get_clangd_config() + print(vim.inspect(clangConfig)) + vim.lsp.config(name, clangConfig) + vim.lsp.enable(name, false) + vim.lsp.enable(name, true) + vim.cmd('checktime') + -- end) end return M From 336a4d5c78073e9ebd6786ffdab316acbcfe15a9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 22:14:18 +0300 Subject: [PATCH 0654/1406] update --- lua/platformio/lspConfig/clangd.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index b00dd0fc..a8125078 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -125,7 +125,8 @@ function _G.get_clangd_config() if _G.metadata.cc_compiler ~= '' then if _G.metadata.triplet and _G.metadata.triplet ~= '' then q_driver = _G.metadata.query_driver or '**' - f_flags = string.format('"--target=%s", "--sysroot=%s"', _G.metadata.triplet, _G.metadata.sysroot) + -- f_flags = string.format('"--target=%s", "--sysroot=%s"', _G.metadata.triplet, _G.metadata.sysroot) + f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) end end From 5ffaa59c6ac1d22ea80b33f24bd14df36b73fae8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 22:29:29 +0300 Subject: [PATCH 0655/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index b74953d4..a9b953f4 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -182,7 +182,7 @@ Diagnostics: ]], content = function(self) local sysroot = '--sysroot=' .. _G.metadata.sysroot - local triplet = '--sysroot=' .. _G.metadata.triplet + local triplet = '--target=' .. _G.metadata.triplet return string.format(self.template, triplet, sysroot) end, } From b24ea706a9aab3565319944d6b220261b559ed22 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 23:33:48 +0300 Subject: [PATCH 0656/1406] update --- lua/platformio/utils/pio.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f1b5374b..97ab7652 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -86,10 +86,10 @@ function M.fix_pio_compile_commands() -- print('PioFix0') -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path local path_map = {} - local pio_home = os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') + local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') if pio_home then -- Recursively find all binaries in PIO packages - local pio_packages = M.get_pio_dir('packages') .. '/*/bin/*' + local pio_packages = _G.metadata.toolchain .. '/bin' --M.get_pio_dir('packages') .. '/*/bin/*' local found_binaries = vim.fn.glob(pio_packages, false, true) for _, full_path in ipairs(found_binaries) do @@ -139,7 +139,7 @@ function M.fix_pio_compile_commands() out_file:write(formatted_json) out_file:close() vim.notify('compiledb: fixed', vim.log.levels.INFO) - lsp.lsp_restart('clangd') + -- lsp.lsp_restart('clangd') end end end From e614180691dae140845f214cd8775afd9888e537 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 16 Apr 2026 23:39:49 +0300 Subject: [PATCH 0657/1406] update --- lua/platformio/utils/lsp.lua | 2 +- lua/platformio/utils/pio.lua | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/lua/platformio/utils/lsp.lua b/lua/platformio/utils/lsp.lua index e553ae2d..58463023 100644 --- a/lua/platformio/utils/lsp.lua +++ b/lua/platformio/utils/lsp.lua @@ -4,7 +4,7 @@ local M = {} function M.lsp_restart(name) -- vim.schedule_wrap(function() local clangConfig = _G.get_clangd_config() - print(vim.inspect(clangConfig)) + -- print(vim.inspect(clangConfig)) vim.lsp.config(name, clangConfig) vim.lsp.enable(name, false) vim.lsp.enable(name, true) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 97ab7652..f0c4f4aa 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -83,7 +83,7 @@ function M.fix_pio_compile_commands() return end - -- print('PioFix0') + print('PioFix0') -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path local path_map = {} local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') @@ -96,7 +96,7 @@ function M.fix_pio_compile_commands() -- Extract filename (e.g., riscv32-esp-elf-gcc) local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = full_path - -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) + print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) end end @@ -111,11 +111,11 @@ function M.fix_pio_compile_commands() local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') if not is_abs then local short_name = first_token:gsub('%.exe$', '') - -- print('PioFix2: short_name=' .. short_name) + print('PioFix2: short_name=' .. short_name) -- Direct Query: Does this name exist in our discovered list? if path_map[short_name] then cmd_parts[1] = path_map[short_name] - -- print('PioFix3: full_name=' .. cmd_parts[1]) + print('PioFix3: full_name=' .. cmd_parts[1]) entry.command = table.concat(cmd_parts, ' ') modified = modified + 1 end From 8d6fafbfdeaaefab7c98cece335fd92937f064da Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 01:02:01 +0300 Subject: [PATCH 0658/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f0c4f4aa..1d379030 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -89,7 +89,7 @@ function M.fix_pio_compile_commands() local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') if pio_home then -- Recursively find all binaries in PIO packages - local pio_packages = _G.metadata.toolchain .. '/bin' --M.get_pio_dir('packages') .. '/*/bin/*' + local pio_packages = _G.metadata.toolchain .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' local found_binaries = vim.fn.glob(pio_packages, false, true) for _, full_path in ipairs(found_binaries) do From 63c494ed39be3b1b36668a663ec6c040e7073497 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 01:28:41 +0300 Subject: [PATCH 0659/1406] update --- plugin/platformio.lua | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 9294e53b..3bfb646e 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -101,12 +101,13 @@ end, {}) -- INFO: fix paths in compile_commands.json -- vim.api.nvim_create_user_command('PioFixPaths', require('platformio.piolsp').fix_pio_compile_commands, {}) vim.api.nvim_create_user_command('PioFixPaths', function() - pio.run_sequence({ - { - cmd = 'pio run -t compiledb', - cb = pio.handleDb, - }, - }) + pio.fix_pio_compile_commands() + -- pio.run_sequence({ + -- { + -- cmd = 'pio run -t compiledb', + -- cb = pio.handleDb, + -- }, + -- }) end, {}) ------------------------------------------------------ From 33a5cf52b51cb524d9143babe49957d641386ff1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 05:59:35 +0300 Subject: [PATCH 0660/1406] update --- mini_nvimPlatformio.lua | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index f4598f41..d00c8510 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -113,22 +113,27 @@ keymap('n', 'bp', 'BufferLineTogglePin', { desc = 'Toggle Pin' -- keymap('n', 'bd', 'bdelete', { desc = '[D]elete Buffer' }) keymap('n', 'bd', function() - -- local bufnr = vim.api.nvim_get_current_buf() + local bufnr = vim.api.nvim_get_current_buf() local bufs = vim.fn.getbufinfo({ buflisted = 1 }) + if #bufs <= 1 then - -- If it's the last buffer, create a new empty one first - -- This prevents focus from jumping to NvimTree - vim.cmd('enew | bd #') + -- Create a new empty buffer + vim.cmd('enew') else - -- Otherwise, go to the previous buffer and delete the old one - vim.cmd('bp | bd #') + -- Switch to the previous buffer + vim.cmd('bp') end - -- for _, cli in ipairs(vim.lsp.get_clients()) do - -- if cli.attached_buffers and vim.tbl_isempty(cli.attached_buffers) then - -- -- if vim.iter(cli.attached_buffers):count() == 0 then - -- print('bd: client stop') - -- cli:stop(true) - -- end + + -- Delete the buffer we started with (using pcall to ignore "No buffers deleted" errors) + pcall(vim.api.nvim_buf_delete, bufnr, { force = false }) + + -- if #bufs <= 1 then + -- -- If it's the last buffer, create a new empty one first + -- -- This prevents focus from jumping to NvimTree + -- vim.cmd('enew | bd #') + -- else + -- -- Otherwise, go to the previous buffer and delete the old one + -- vim.cmd('bp | bd #') -- end end, { desc = '[D]elete Buffer' }) From bcf761c0c2e5b47860a2305136592ea9eaeb8ce2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 06:14:05 +0300 Subject: [PATCH 0661/1406] update --- lua/platformio/boilerplate.lua | 1 - mini_nvimPlatformio.lua | 14 +++++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index a9b953f4..ec711ec5 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -74,7 +74,6 @@ boilerplate['.clangd_config'] = { "--completion-style=detailed", "--header-insertion=iwyu", "--fallback-style=llvm", - "-j=12", "--log=error", "--pch-storage=memory", "--pretty", diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index d00c8510..526fb1f3 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -226,7 +226,19 @@ local plugins = { 'nvim-tree/nvim-web-devicons', }, config = function() - require('nvim-tree').setup({}) + require('nvim-tree').setup({ + filesystem_watchers = { + ignore_dirs = { + '/.cache', -- Ignores clangd's heavy index folder + '/node_modules', -- Good practice for performance + '/.git', + }, + }, + -- Optional: If you also want to hide it from the tree view entirely + filters = { + custom = { '^\\.cache$' }, + }, + }) end, }, From e8edb9e537ce2acea36f42b0a0b1e153aef20748 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 06:21:35 +0300 Subject: [PATCH 0662/1406] update --- lua/platformio/lspConfig/clangd.lua | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index a8125078..575792a7 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -128,6 +128,12 @@ function _G.get_clangd_config() -- f_flags = string.format('"--target=%s", "--sysroot=%s"', _G.metadata.triplet, _G.metadata.sysroot) f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) end + -- 2. Add it to the PATH for this Neovim session + local current_path = vim.env.PATH + local pio_toolchain = _G.metadata.toolchain .. '/bin' + if not current_path:find(pio_toolchain, 1, true) then + vim.env.PATH = pio_toolchain .. (vim.fn.has("win32") == 1 and ";" or ":") .. current_path + end end -- 3. Format your template string From c18e352fe8fcd7f984e6d4493556bbb7504bc86f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 06:40:38 +0300 Subject: [PATCH 0663/1406] update --- lua/platformio/lspConfig/clangd.lua | 2 +- mini_nvimPlatformio.lua | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 575792a7..4e0ae730 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -128,7 +128,7 @@ function _G.get_clangd_config() -- f_flags = string.format('"--target=%s", "--sysroot=%s"', _G.metadata.triplet, _G.metadata.sysroot) f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) end - -- 2. Add it to the PATH for this Neovim session + -- 2.1 Add it to the PATH for this Neovim session local current_path = vim.env.PATH local pio_toolchain = _G.metadata.toolchain .. '/bin' if not current_path:find(pio_toolchain, 1, true) then diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 526fb1f3..8df17386 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -222,21 +222,20 @@ local plugins = { 'nvim-tree/nvim-tree.lua', version = '*', lazy = false, - dependencies = { - 'nvim-tree/nvim-web-devicons', - }, + dependencies = 'nvim-tree/nvim-web-devicons', config = function() require('nvim-tree').setup({ filesystem_watchers = { ignore_dirs = { '/.cache', -- Ignores clangd's heavy index folder + '/.pio', -- Ignores pio heavy index folder '/node_modules', -- Good practice for performance '/.git', }, }, -- Optional: If you also want to hide it from the tree view entirely filters = { - custom = { '^\\.cache$' }, + custom = { '^\\.cache$', '^\\.pio$' }, }, }) end, From cb651d8f30ce6248edd925845ff845dfb7a30b1f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 06:48:56 +0300 Subject: [PATCH 0664/1406] update --- lua/platformio/lspConfig/clangd.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 4e0ae730..80930294 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -129,10 +129,11 @@ function _G.get_clangd_config() f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) end -- 2.1 Add it to the PATH for this Neovim session - local current_path = vim.env.PATH + local current_path = vim.trim(vim.env.PATH) + local sep = (vim.fn.has("win32") == 1 and ";" or ":") local pio_toolchain = _G.metadata.toolchain .. '/bin' if not current_path:find(pio_toolchain, 1, true) then - vim.env.PATH = pio_toolchain .. (vim.fn.has("win32") == 1 and ";" or ":") .. current_path + vim.env.PATH = pio_toolchain .. sep .. current_path end end From 2ee0e7b12c8262d0e5850de6d80f9505a023d283 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 07:07:41 +0300 Subject: [PATCH 0665/1406] update --- lua/platformio/lspConfig/clangd.lua | 1 + mini_nvimPlatformio.lua | 5 ++--- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 80930294..d0458bff 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -128,6 +128,7 @@ function _G.get_clangd_config() -- f_flags = string.format('"--target=%s", "--sysroot=%s"', _G.metadata.triplet, _G.metadata.sysroot) f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) end + -- 2.1 Add it to the PATH for this Neovim session local current_path = vim.trim(vim.env.PATH) local sep = (vim.fn.has("win32") == 1 and ";" or ":") diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 8df17386..ca7b5ffe 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -354,9 +354,8 @@ vim.uv.os_setenv('PLATFORMIO_CORE_DIR', platformio_core_dir) vim.g.python_host_prog = pynvim_python vim.g.python3_host_prog = pynvim_python -vim.env.PATH = pynvim_bin - .. (isWindows and '; C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/bin/ ;' or ': C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/bin/ :') - .. vim.env.PATH +local sep = (vim.fn.has('win32') == 1 and ';' or ':') +vim.env.PATH = pynvim_bin .. sep .. vim.env.PATH vim.env.VIRTUAL_ENV = pynvim_env if vim.fn.isdirectory(platformio_core_dir) == 0 then From 635ac544c4299dd44f8e9db18f0e6384adf32cb9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 07:13:37 +0300 Subject: [PATCH 0666/1406] update --- lua/platformio/boilerplate.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index ec711ec5..98afd608 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -145,6 +145,8 @@ CompileFlags: - %q - %q Remove: + - "-target" + - "riscv32-esp-elf" - "-fno-fat-lto-objects" - "-fno%%-fat%%-lto%%-objects" - "-fno%%-canonical%%-system%%-headers" From 12a08ba85fd62ce19852ff3445a4f6be6dce56bf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 13:44:48 +0300 Subject: [PATCH 0667/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/lspConfig/clangd.lua | 13 +++++++------ lua/platformio/pio_setup.lua | 3 ++- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 98afd608..dfaee668 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -79,8 +79,8 @@ boilerplate['.clangd_config'] = { "--pretty", "--ranking-model=decision_forest", "--sync", + %q, "--offset-encoding=utf-16", - "--query-driver=%s", }, filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, root_markers = { diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index d0458bff..86cefd66 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -119,21 +119,22 @@ function _G.get_clangd_config() if not new_root_dir then return end -- 1. Safe defaults (Standard clangd behavior) - local f_flags, q_driver = '', '**' + local f_flags, q_driver = '', '--query-driver=**' -- 2. Run your toolchain detection if _G.metadata.cc_compiler ~= '' then if _G.metadata.triplet and _G.metadata.triplet ~= '' then - q_driver = _G.metadata.query_driver or '**' - -- f_flags = string.format('"--target=%s", "--sysroot=%s"', _G.metadata.triplet, _G.metadata.sysroot) - f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) + q_driver = '--query-driver=' .. _G.metadata.query_driver + f_flags = string.format([["--target=%s", "--sysroot=%s"]], _G.metadata.triplet, _G.metadata.sysroot) + -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) end -- 2.1 Add it to the PATH for this Neovim session - local current_path = vim.trim(vim.env.PATH) - local sep = (vim.fn.has("win32") == 1 and ";" or ":") + -- local current_path = vim.trim(vim.env.PATH) local pio_toolchain = _G.metadata.toolchain .. '/bin' + local current_path = vim.env.PATH if not current_path:find(pio_toolchain, 1, true) then + local sep = (vim.fn.has("win32") == 1 and ";" or ":") vim.env.PATH = pio_toolchain .. sep .. current_path end end diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 3f0df012..a013fad2 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -48,7 +48,7 @@ local function get_sysroot_triplet(cc_compiler) -- sysroot folder is expected to have the same name as the triplet local sysroot = toolchain_root .. '/' .. triplet - vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) + -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) -- Only return data if the sysroot folder actually exists on disk if vim.fn.isdirectory(sysroot) == 1 then return { @@ -182,6 +182,7 @@ local pio_manager = (function() if callback then vim.schedule(function() vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) + print(vim.inspect(_G.metadata.fallback_flags)) callback() end) end From efaa4ec23ee8102810125bdfb8d7da6556b2a979 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 13:55:30 +0300 Subject: [PATCH 0668/1406] update --- lua/platformio/lspConfig/clangd.lua | 2 +- lua/platformio/pio_setup.lua | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 86cefd66..38a0907e 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -125,7 +125,7 @@ function _G.get_clangd_config() if _G.metadata.cc_compiler ~= '' then if _G.metadata.triplet and _G.metadata.triplet ~= '' then q_driver = '--query-driver=' .. _G.metadata.query_driver - f_flags = string.format([["--target=%s", "--sysroot=%s"]], _G.metadata.triplet, _G.metadata.sysroot) + f_flags = string.format([["--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, _G.metadata.fallback_flags) -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) end diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index a013fad2..d519966e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -182,7 +182,6 @@ local pio_manager = (function() if callback then vim.schedule(function() vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) - print(vim.inspect(_G.metadata.fallback_flags)) callback() end) end From 562d39f7fa693527410fb1d4e44dbd94dc0a3f36 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 14:20:41 +0300 Subject: [PATCH 0669/1406] update --- lua/platformio/lspConfig/clangd.lua | 31 ++++++++++++++++++++--------- lua/platformio/pio_setup.lua | 2 +- 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 38a0907e..35bdb0c6 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -124,19 +124,32 @@ function _G.get_clangd_config() -- 2. Run your toolchain detection if _G.metadata.cc_compiler ~= '' then if _G.metadata.triplet and _G.metadata.triplet ~= '' then + + -- local formatted_paths = {} + -- for _, path in ipairs(_G.metadata.fallback_flags) do + -- -- Use %q to safely quote the string and -I to tell clangd it's an include + -- table.insert(formatted_paths, string.format('%q', path:gsub("\\", "/"))) + -- end + -- local include_flags = table.concat(formatted_paths, ", ") + local include_flags = table.concat(_G.metadata.fallback_flags, ", ") + q_driver = '--query-driver=' .. _G.metadata.query_driver - f_flags = string.format([["--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, _G.metadata.fallback_flags) + + f_flags = string.format([["--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, include_flags) + + print(include_flags) -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) - end - -- 2.1 Add it to the PATH for this Neovim session - -- local current_path = vim.trim(vim.env.PATH) - local pio_toolchain = _G.metadata.toolchain .. '/bin' - local current_path = vim.env.PATH - if not current_path:find(pio_toolchain, 1, true) then - local sep = (vim.fn.has("win32") == 1 and ";" or ":") - vim.env.PATH = pio_toolchain .. sep .. current_path + -- 2.1 Add it to the PATH for this Neovim session + -- local current_path = vim.trim(vim.env.PATH) + local pio_toolchain = _G.metadata.toolchain .. '/bin' + local current_path = vim.env.PATH + if not current_path:find(pio_toolchain, 1, true) then + local sep = (vim.fn.has("win32") == 1 and ";" or ":") + vim.env.PATH = pio_toolchain .. sep .. current_path + end end + end -- 3. Format your template string diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index d519966e..04b99b17 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -158,7 +158,7 @@ local pio_manager = (function() if category == 'toolchain' then local flag = '-isystem' for _, path in ipairs(paths) do - table.insert(fallback_flags, flag .. path) + table.insert(fallback_flags, flag .. string.format('%s', path:gsub('\\', '/'))) end end -- local flag = (category == 'toolchain') and '-isystem' or '-I' From b937c76bc50e7e0ee110f2883f4fb8e04fe23603 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 14:29:19 +0300 Subject: [PATCH 0670/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 04b99b17..85b001d5 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -158,7 +158,7 @@ local pio_manager = (function() if category == 'toolchain' then local flag = '-isystem' for _, path in ipairs(paths) do - table.insert(fallback_flags, flag .. string.format('%s', path:gsub('\\', '/'))) + table.insert(fallback_flags, flag .. string.format('%q', path:gsub('\\', '/'))) end end -- local flag = (category == 'toolchain') and '-isystem' or '-I' From 5a661ec7af24bda2f6b70bd2500f0a89f9b0efc1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 14:34:11 +0300 Subject: [PATCH 0671/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 85b001d5..94745cb1 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -158,7 +158,7 @@ local pio_manager = (function() if category == 'toolchain' then local flag = '-isystem' for _, path in ipairs(paths) do - table.insert(fallback_flags, flag .. string.format('%q', path:gsub('\\', '/'))) + table.insert(fallback_flags, string.format('%q', flag .. path:gsub('\\', '/'))) end end -- local flag = (category == 'toolchain') and '-isystem' or '-I' From 7d08522e5845509faa874e13113bfafec46d710c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 14:51:51 +0300 Subject: [PATCH 0672/1406] update --- lua/platformio/lspConfig/clangd.lua | 2 +- lua/platformio/pio_setup.lua | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 35bdb0c6..b6a9cfaa 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -133,7 +133,7 @@ function _G.get_clangd_config() -- local include_flags = table.concat(formatted_paths, ", ") local include_flags = table.concat(_G.metadata.fallback_flags, ", ") - q_driver = '--query-driver=' .. _G.metadata.query_driver + q_driver = '--query-driver=' .. _G.metadata.query_driver .. f_flags = string.format([["--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, include_flags) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 94745cb1..fffbc343 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -158,7 +158,8 @@ local pio_manager = (function() if category == 'toolchain' then local flag = '-isystem' for _, path in ipairs(paths) do - table.insert(fallback_flags, string.format('%q', flag .. path:gsub('\\', '/'))) + table.insert(fallback_flags, string.format('%q', flag)) + table.insert(fallback_flags, string.format('%q', path:gsub('\\', '/'))) end end -- local flag = (category == 'toolchain') and '-isystem' or '-I' From b515d7f7b60cef9e48edc1989f27875ac2af3bb7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 14:54:12 +0300 Subject: [PATCH 0673/1406] update --- lua/platformio/lspConfig/clangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index b6a9cfaa..35bdb0c6 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -133,7 +133,7 @@ function _G.get_clangd_config() -- local include_flags = table.concat(formatted_paths, ", ") local include_flags = table.concat(_G.metadata.fallback_flags, ", ") - q_driver = '--query-driver=' .. _G.metadata.query_driver .. + q_driver = '--query-driver=' .. _G.metadata.query_driver f_flags = string.format([["--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, include_flags) From 0ca9e4c88da0a0507384b1ef5ed36974b78c19d5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 15:21:03 +0300 Subject: [PATCH 0674/1406] update --- lua/platformio/boilerplate.lua | 20 +++++++++++--------- lua/platformio/pio_setup.lua | 10 +++++----- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index dfaee668..0c1915cc 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -135,15 +135,17 @@ clangd end, } +-- -- Add: +-- - %q +-- - %q -- INFO: .clangd +-- boilerplate['.clangd'] = { boilerplate['.clangd'] = { rewrite = false, read = false, - template = [[ + -- template = [[ + content = [[ CompileFlags: - Add: - - %q - - %q Remove: - "-target" - "riscv32-esp-elf" @@ -181,11 +183,11 @@ Diagnostics: - "hicpp-vararg" - "modernize-*" ]], - content = function(self) - local sysroot = '--sysroot=' .. _G.metadata.sysroot - local triplet = '--target=' .. _G.metadata.triplet - return string.format(self.template, triplet, sysroot) - end, + -- content = function(self) + -- local sysroot = '--sysroot=' .. _G.metadata.sysroot + -- local triplet = '--target=' .. _G.metadata.triplet + -- return string.format(self.template, triplet, sysroot) + -- end, } -- INFO: .stylua.toml diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index fffbc343..f1a12ab1 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -169,11 +169,11 @@ local pio_manager = (function() end end -- 2. Process Defines - -- if env.defines then - -- for _, define in ipairs(env.defines) do - -- table.insert(fallback_flags, '-D' .. define) - -- end - -- end + if env.defines then + for _, define in ipairs(env.defines) do + table.insert(fallback_flags, string.format('%q', '-D' .. define)) + end + end -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' _G.metadata.cc_compiler = misc.normalize_path(data.cc_path) or '' From e857675e64a503d196b9631d522c80c5ef2a2273 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 17:26:55 +0300 Subject: [PATCH 0675/1406] update --- lua/platformio/pio_setup.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index f1a12ab1..3bdae11f 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -169,8 +169,8 @@ local pio_manager = (function() end end -- 2. Process Defines - if env.defines then - for _, define in ipairs(env.defines) do + if data.defines then + for _, define in ipairs(data.defines) do table.insert(fallback_flags, string.format('%q', '-D' .. define)) end end From 154bbb27c0e816440c665bd947f09a765bfbd8ea Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 17:57:11 +0300 Subject: [PATCH 0676/1406] update --- lua/platformio/lspConfig/clangd.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 35bdb0c6..96acae33 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -135,7 +135,8 @@ function _G.get_clangd_config() q_driver = '--query-driver=' .. _G.metadata.query_driver - f_flags = string.format([["--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, include_flags) + -- f_flags = string.format([["--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, include_flags) + f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) print(include_flags) -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) From b65bf6945ccfbff00192600c841643f327083a89 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 18:09:06 +0300 Subject: [PATCH 0677/1406] update --- lua/platformio/boilerplate.lua | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 0c1915cc..31bd6b0a 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -138,6 +138,7 @@ clangd -- -- Add: -- - %q -- - %q +-- - "riscv32-esp-elf" -- INFO: .clangd -- boilerplate['.clangd'] = { boilerplate['.clangd'] = { @@ -146,9 +147,11 @@ boilerplate['.clangd'] = { -- template = [[ content = [[ CompileFlags: + Add: + - "--gcc-toolchain=C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp" Remove: - "-target" - - "riscv32-esp-elf" + - "--target=*" - "-fno-fat-lto-objects" - "-fno%%-fat%%-lto%%-objects" - "-fno%%-canonical%%-system%%-headers" From 2e3762c11dfe9d20746f4370858f70ad98d4a243 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 18:47:40 +0300 Subject: [PATCH 0678/1406] update --- lua/platformio/boilerplate.lua | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 31bd6b0a..063659e6 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -148,6 +148,12 @@ boilerplate['.clangd'] = { content = [[ CompileFlags: Add: + - "-IC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0" + - "-IC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0/riscv32-esp-elf" + - "-IC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include" + - "-IC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include-fixed" + - "-IC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/picolibc/include" + - "-IC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include" - "--gcc-toolchain=C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp" Remove: - "-target" From 5a2b48cb632128a68e3e75a0120f5a9b03a41f64 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 18:52:22 +0300 Subject: [PATCH 0679/1406] update --- lua/platformio/boilerplate.lua | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 063659e6..34fed7cd 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -148,12 +148,12 @@ boilerplate['.clangd'] = { content = [[ CompileFlags: Add: - - "-IC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0" - - "-IC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0/riscv32-esp-elf" - - "-IC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include" - - "-IC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include-fixed" - - "-IC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/picolibc/include" - - "-IC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include" + - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0" + - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0/riscv32-esp-elf" + - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include" + - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include-fixed" + - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/picolibc/include" + - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include" - "--gcc-toolchain=C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp" Remove: - "-target" From c4026e036ef0774191ac568537315101ee4ef91c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 18:59:33 +0300 Subject: [PATCH 0680/1406] update --- lua/platformio/lspConfig/clangd.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 96acae33..62462ade 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -138,7 +138,7 @@ function _G.get_clangd_config() -- f_flags = string.format([["--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, include_flags) f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) - print(include_flags) + -- print(include_flags) -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) -- 2.1 Add it to the PATH for this Neovim session @@ -155,7 +155,8 @@ function _G.get_clangd_config() -- 3. Format your template string local clangd_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) - local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) + -- local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) + local formatted_str = string.format(clangd_config, "", f_flags, new_root_dir) -- 4. Load the config table local cok, table_config = pcall(function() return load('return ' .. formatted_str)() end) From c957c9f1c2ea5f0aeb350e0fafefc44e21dff412 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 19:26:55 +0300 Subject: [PATCH 0681/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/lspConfig/clangd.lua | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 34fed7cd..d789ff9b 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -79,8 +79,8 @@ boilerplate['.clangd_config'] = { "--pretty", "--ranking-model=decision_forest", "--sync", - %q, "--offset-encoding=utf-16", + %s }, filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, root_markers = { diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 62462ade..9ab2d4d9 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -133,7 +133,9 @@ function _G.get_clangd_config() -- local include_flags = table.concat(formatted_paths, ", ") local include_flags = table.concat(_G.metadata.fallback_flags, ", ") - q_driver = '--query-driver=' .. _G.metadata.query_driver + -- q_driver = '--query-driver=' .. _G.metadata.query_driver + -- q_driver = string.format([['--query-driver=%s']], _G.metadata.query_driver) + q_driver = '' -- f_flags = string.format([["--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, include_flags) f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) @@ -156,7 +158,7 @@ function _G.get_clangd_config() -- 3. Format your template string local clangd_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) -- local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) - local formatted_str = string.format(clangd_config, "", f_flags, new_root_dir) + local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) -- 4. Load the config table local cok, table_config = pcall(function() return load('return ' .. formatted_str)() end) From d92f21be49879fcb2c157ea24d8eae8758c57bec Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 21:28:36 +0300 Subject: [PATCH 0682/1406] update --- lua/platformio/boilerplate.lua | 12 +-------- lua/platformio/lspConfig/clangd.lua | 38 ++++++++++------------------- lua/platformio/pio_setup.lua | 5 ++-- 3 files changed, 17 insertions(+), 38 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index d789ff9b..2e8ba558 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -80,7 +80,7 @@ boilerplate['.clangd_config'] = { "--ranking-model=decision_forest", "--sync", "--offset-encoding=utf-16", - %s + "--query-driver=%s" }, filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, root_markers = { @@ -147,17 +147,7 @@ boilerplate['.clangd'] = { -- template = [[ content = [[ CompileFlags: - Add: - - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0" - - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0/riscv32-esp-elf" - - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include" - - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include-fixed" - - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/picolibc/include" - - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include" - - "--gcc-toolchain=C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp" Remove: - - "-target" - - "--target=*" - "-fno-fat-lto-objects" - "-fno%%-fat%%-lto%%-objects" - "-fno%%-canonical%%-system%%-headers" diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 9ab2d4d9..aa672602 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -124,40 +124,28 @@ function _G.get_clangd_config() -- 2. Run your toolchain detection if _G.metadata.cc_compiler ~= '' then if _G.metadata.triplet and _G.metadata.triplet ~= '' then - - -- local formatted_paths = {} - -- for _, path in ipairs(_G.metadata.fallback_flags) do - -- -- Use %q to safely quote the string and -I to tell clangd it's an include - -- table.insert(formatted_paths, string.format('%q', path:gsub("\\", "/"))) - -- end - -- local include_flags = table.concat(formatted_paths, ", ") local include_flags = table.concat(_G.metadata.fallback_flags, ", ") - - -- q_driver = '--query-driver=' .. _G.metadata.query_driver - -- q_driver = string.format([['--query-driver=%s']], _G.metadata.query_driver) - q_driver = '' - - -- f_flags = string.format([["--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, include_flags) - f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) - - -- print(include_flags) + f_flags = string.format([["-std=c++17", "--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, include_flags) -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) + -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) + + q_driver = _G.metadata.query_driver -- use with "--query-driver=%s" + -- q_driver = '--query-driver=' .. _G.metadata.query_driver -- use with %q + -- q_driver = string.format([['--query-driver=%s']], _G.metadata.query_driver) -- use with %s + -- q_driver = '' -- use with %s ,not to use --query-driver -- 2.1 Add it to the PATH for this Neovim session - -- local current_path = vim.trim(vim.env.PATH) - local pio_toolchain = _G.metadata.toolchain .. '/bin' - local current_path = vim.env.PATH - if not current_path:find(pio_toolchain, 1, true) then - local sep = (vim.fn.has("win32") == 1 and ";" or ":") - vim.env.PATH = pio_toolchain .. sep .. current_path - end + -- local pio_toolchain = _G.metadata.toolchain .. '/bin' + -- local current_path = vim.env.PATH + -- if not current_path:find(pio_toolchain, 1, true) then + -- local sep = (vim.fn.has("win32") == 1 and ";" or ":") + -- vim.env.PATH = pio_toolchain .. sep .. current_path + -- end end - end -- 3. Format your template string local clangd_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) - -- local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) -- 4. Load the config table diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 3bdae11f..8f9b6f62 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -158,8 +158,9 @@ local pio_manager = (function() if category == 'toolchain' then local flag = '-isystem' for _, path in ipairs(paths) do - table.insert(fallback_flags, string.format('%q', flag)) - table.insert(fallback_flags, string.format('%q', path:gsub('\\', '/'))) + -- table.insert(fallback_flags, string.format('%q', flag)) + -- table.insert(fallback_flags, string.format('%q', path:gsub('\\', '/'))) + table.insert(fallback_flags, string.format('%q', flag .. path:gsub('\\', '/'))) end end -- local flag = (category == 'toolchain') and '-isystem' or '-I' From 339565634a910d39e5c57babe9ebf61551e4ddf5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 23:36:43 +0300 Subject: [PATCH 0683/1406] update --- lua/platformio/boilerplate.lua | 2 ++ lua/platformio/lspConfig/clangd.lua | 7 +++--- lua/platformio/pio_setup.lua | 39 +++++++++++++++-------------- lua/platformio/utils/pio.lua | 3 ++- 4 files changed, 28 insertions(+), 23 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 2e8ba558..05191cc6 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -46,6 +46,8 @@ monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dt ; pre:enable_toolchain.py ; enabled global env 'PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN' lib_ldf_mode = chain ;Library dependencies Finder ldf +build_flags = + -D COMPILATIONDB_INCLUDE_TOOLCHAIN ]], content = function(self) -- local pio = require('platformio.utils.pio') diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index aa672602..a39b502c 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -1,17 +1,17 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen _G.metadata = { envs = {}, + active_env = '', default_envs = {}, core_dir = '', packages_dir = '', platforms_dir = '', - active_env = '', query_driver = '', cc_compiler = '', triplet = '', toolchain = '', sysroot = '', - fallback_flags = {}, + fallbackFlags = {}, } local ok, result @@ -124,7 +124,7 @@ function _G.get_clangd_config() -- 2. Run your toolchain detection if _G.metadata.cc_compiler ~= '' then if _G.metadata.triplet and _G.metadata.triplet ~= '' then - local include_flags = table.concat(_G.metadata.fallback_flags, ", ") + local include_flags = table.concat(_G.metadata.fallbackFlags, ", ") f_flags = string.format([["-std=c++17", "--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, include_flags) -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) @@ -155,6 +155,7 @@ function _G.get_clangd_config() return table_config end end + -- Apply and Enable vim.lsp.config('clangd', _G.get_clangd_config()) vim.lsp.enable('clangd') diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 8f9b6f62..7ed39b0d 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -149,7 +149,7 @@ local pio_manager = (function() if ok and raw_data then local _, data = next(raw_data) if data then - local fallback_flags = {} + local fallbackFlags = {} -- 1. Process Includes if data.includes then for category, paths in pairs(data.includes) do @@ -158,27 +158,28 @@ local pio_manager = (function() if category == 'toolchain' then local flag = '-isystem' for _, path in ipairs(paths) do - -- table.insert(fallback_flags, string.format('%q', flag)) - -- table.insert(fallback_flags, string.format('%q', path:gsub('\\', '/'))) - table.insert(fallback_flags, string.format('%q', flag .. path:gsub('\\', '/'))) + -- table.insert(fallbackFlags, string.format('%q', flag)) + -- table.insert(fallbackFlags, string.format('%q', path:gsub('\\', '/'))) + table.insert(fallbackFlags, string.format('%q', flag .. path:gsub('\\', '/'))) end end -- local flag = (category == 'toolchain') and '-isystem' or '-I' -- for _, path in ipairs(paths) do - -- table.insert(fallback_flags, flag .. path) + -- table.insert(fallbackFlags, flag .. path) -- end end end -- 2. Process Defines if data.defines then for _, define in ipairs(data.defines) do - table.insert(fallback_flags, string.format('%q', '-D' .. define)) + table.insert(fallbackFlags, string.format('%q', '-D' .. define)) end end + -- get [cc_compiler]and [falbackFlags] -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' _G.metadata.cc_compiler = misc.normalize_path(data.cc_path) or '' - _G.metadata.fallback_flags = fallback_flags + _G.metadata.fallbackFlags = fallbackFlags -- print(vim.inspect(_G.metadata)) if callback then @@ -203,16 +204,10 @@ local pio_manager = (function() end) end - -- INFO: -- 1. Setup Base Paths + -- INFO: Setup Base Paths local home = os.getenv('HOME') or os.getenv('USERPROFILE') - -- INFO: -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) - local map = { - core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, - packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, - platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, - } - -- INFO: 3. Try to get explicit value from platformio.ini + -- INFO: Try to get explicit value from platformio.ini -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) @@ -238,7 +233,7 @@ local pio_manager = (function() for _, section in ipairs(decoded) do if type(section) == 'table' and #section >= 2 then local name, data = section[1], section[2] - -- 1. Extract Global PlatformIO Settings + -- 1. Extract Global PlatformIO Settings if available [core_dir][packages_dir][platforms_dir][default_envs] if name == 'platformio' then for _, kv in ipairs(data) do local key, val = kv[1], kv[2] @@ -247,7 +242,7 @@ local pio_manager = (function() _G.metadata[key] = val end end - -- 2. Extract all hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] + -- 2. Extract all hardware [envs] like [env:seeed_xiao_esp32c3], skipping generic [env] elseif name:match('^env:') then local env_name = name:match('^env:(.+)') _G.metadata.envs[env_name] = {} @@ -257,12 +252,19 @@ local pio_manager = (function() end end end + -- assign [active_env] if #_G.metadata.default_envs > 0 then _G.metadata.active_env = _G.metadata.default_envs[1] or '' - else + elseif _G.metadata.envs and #_G.metadata.envs > 0 then _G.metadata.active_env = next(_G.metadata.envs) or '' end + -- INFO: -- Define Mapping (key in INI, Env Var, Default Subfolder) + local map = { + core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, + packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, + platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, + } for _, kv in ipairs(map) do -- 4.0 Fallback Logic: INI -> Env Var -> Default local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') @@ -472,7 +474,6 @@ function M.init() pio_manager.refresh(function() -- vim.schedule(function() -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) pio_generate_db() lsp.lsp_restart('clangd') -- end) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 1d379030..e1fc5fb4 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -72,11 +72,12 @@ function M.fix_pio_compile_commands() local file = io.open(filename, 'r') if not file then return end + -- read compile_commands.json file to content local content = file:read('*a') file:close() if not content or content == '' then return end - -- Safe JSON decoding + -- JSON decoding content to data local ok, data = pcall(vim.json.decode, content) if not ok or type(data) ~= 'table' then vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) From fa98f9f88388380e1f2ec178e3a24ba70a47c9fa Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 17 Apr 2026 23:45:41 +0300 Subject: [PATCH 0684/1406] update --- lua/platformio/pio_setup.lua | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 7ed39b0d..c98f53b5 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -71,9 +71,9 @@ local function pio_generate_db() if obj.code ~= 0 then vim.schedule(function() if obj.code == 127 then - vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + vim.notify("PIO Manager db: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else - vim.notify('PIO Manager: Generating Compile Database failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + vim.notify('PIO Manager db: Generating Compile Database failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) end end) return @@ -136,9 +136,9 @@ local pio_manager = (function() -- Schedule notification to avoid error in the system callback thread vim.schedule(function() if int_obj.code == 127 then - vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + vim.notify("PIO Manager metadata: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else - vim.notify('PIO Manager: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + vim.notify('PIO Manager metadata: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) end end) return @@ -215,9 +215,9 @@ local pio_manager = (function() -- Schedule notification to avoid error in the system callback thread vim.schedule(function() if ext_obj.code == 127 then - vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + vim.notify("PIO Manager config: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else - vim.notify('PIO Manager: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + vim.notify('PIO Manager config: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) end end) return From 7da95e30975b8ef5c80dd0af2fea58600d896f79 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 00:23:25 +0300 Subject: [PATCH 0685/1406] update --- lua/platformio/pio_setup.lua | 28 +- pio_setup.lua | 485 +++++++++++++++++++++++++++++++++++ 2 files changed, 499 insertions(+), 14 deletions(-) create mode 100644 pio_setup.lua diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index c98f53b5..8ad1c32e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -426,21 +426,21 @@ local function start_pio_watcher() 0, vim.schedule_wrap(function() pio_manager.refresh(function() - -- vim.schedule(function() - local status, data = pcall(get_sysroot_triplet, _G.metadata.cc_compiler) - if status and data and data.triplet and data.triplet ~= '' then - _G.metadata.triplet = data.triplet - _G.metadata.sysroot = data.sysroot - _G.metadata.query_driver = data.query_driver - _G.metadata.toolchain = data.toolchain_root - end - -- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) + vim.schedule(function() + local status, data = pcall(get_sysroot_triplet, _G.metadata.cc_compiler) + if status and data and data.triplet and data.triplet ~= '' then + _G.metadata.triplet = data.triplet + _G.metadata.sysroot = data.sysroot + _G.metadata.query_driver = data.query_driver + _G.metadata.toolchain = data.toolchain_root + end + -- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) - pio_generate_db() - lsp.lsp_restart('clangd') - -- end) + pio_generate_db() + lsp.lsp_restart('clangd') + end) end) end)) end end end)) end ------------------------------------------------------------------------------------------------------ diff --git a/pio_setup.lua b/pio_setup.lua new file mode 100644 index 00000000..ab7f54d0 --- /dev/null +++ b/pio_setup.lua @@ -0,0 +1,485 @@ +-- M = {} +-- +-- local misc = require('platformio.utils.misc') +-- local lsp = require('platformio.utils.lsp') +-- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +-- +-- -- lua/pio_setup.lua +-- -- This module manages PlatformIO project integration, LSP toolchain detection, +-- -- and automatic sysroot patching for standard library headers (, etc.) +-- +-- local debounce_timer = vim.uv.new_timer() +-- +-- -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) +-- -- INFO: +-- -- ============================================================================= +-- -- UNIVERSAL TOOLCHAIN DETECTION +-- -- ============================================================================= +-- --- stylua: ignore +-- local function get_sysroot_triplet(cc_compiler) +-- local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') +-- -- Early exit if path is nil or not a directory +-- if not bin_path or vim.fn.isdirectory(bin_path) == 0 then +-- return nil +-- end +-- +-- -- Normalize backslashes to forward slashes for cross-platform consistency +-- bin_path = bin_path:gsub('\\', '/') +-- local files = vim.fn.readdir(bin_path) +-- local triplet = nil +-- +-- -- Loop through files to find the compiler and extract the triplet +-- for _, name in ipairs(files) do +-- -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ +-- local match = name:match('^(.*)%-g[c%+][c%+]') +-- if match then +-- triplet = match +-- break +-- end +-- end +-- +-- -- Return nil if no compiler was found in the bin directory +-- if not triplet then +-- return nil +-- end +-- +-- -- toolchain_root is the parent of the 'bin' folder +-- local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') +-- -- sysroot folder is expected to have the same name as the triplet +-- local sysroot = toolchain_root .. '/' .. triplet +-- +-- -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) +-- -- Only return data if the sysroot folder actually exists on disk +-- if vim.fn.isdirectory(sysroot) == 1 then +-- return { +-- triplet = triplet, +-- sysroot = sysroot, +-- toolchain_root = toolchain_root, +-- query_driver = bin_path .. '/' .. triplet .. '-*', +-- } +-- end +-- return nil +-- end +-- +-- +-- -- INFO: +-- -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag +-- -- stylua: ignore +-- local function pio_generate_db() +-- vim.schedule(function() vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) end) +-- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) +-- if obj.code ~= 0 then +-- vim.schedule(function() +-- if obj.code == 127 then +-- vim.notify("PIO Manager db: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) +-- else +-- vim.notify('PIO Manager db: Generating Compile Database failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) +-- end +-- end) +-- return +-- end +-- vim.schedule(function() vim.notify('PIO: Generating Compile Database successful', vim.log.levels.INFO) end) +-- end) +-- end +-- +-- -- INFO: 1. The Core PIO Manager & Generic Extractor +-- --- stylua: ignore +-- local pio_manager = (function() +-- local cache = nil -- Stores the decoded platformio.ini JSON structure +-- -- INFO: +-- local function find_in_data(data, section_name, key_name) +-- -- Safety check: Ensure data is a valid table from a successful JSON decode +-- if type(data) ~= 'table' then +-- return nil +-- end +-- +-- for _, section in ipairs(data) do +-- -- Each section must be a table with at least 2 elements: [1]=name, [2]=content +-- if type(section) == 'table' and #section >= 2 then +-- local s_id = section[1] -- Section header string +-- local s_body = section[2] -- Table of key-value pairs +-- +-- if s_id == section_name and type(s_body) == 'table' then +-- for _, kv in ipairs(s_body) do +-- -- Each kv is a table: [1]=key, [2]=value +-- if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then +-- local val = kv[2] +-- -- Treat empty strings or empty tables as nil to trigger fallback logic +-- if val == nil or val == '' or (type(val) == 'table' and #val == 0) then +-- return nil +-- end +-- return val +-- end +-- end +-- end +-- end +-- end +-- return nil +-- end +-- +-- -- INFO: ASYNC REFRESH: Fetches the latest config from PlatformIO CLI +-- --- stylua: ignore +-- local function refresh(callback) +-- vim.schedule(function() +-- vim.notify('PIO: Fetching Config ...', vim.log.levels.INFO) +-- end) +-- +-- -- INFO: get project metadata +-- local function get_metadata(attempts, env) +-- local active_env = env or _G.metadata.active_env +-- vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(int_obj) +-- vim.schedule(function() +-- vim.notify('PIO: Fetching metadata ...', vim.log.levels.INFO) +-- end) +-- +-- if int_obj.code ~= 0 then +-- -- Schedule notification to avoid error in the system callback thread +-- vim.schedule(function() +-- if int_obj.code == 127 then +-- vim.notify("PIO Manager metadata: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) +-- else +-- vim.notify('PIO Manager metadata: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) +-- end +-- end) +-- return +-- end +-- +-- if int_obj.code == 0 and int_obj.stdout then +-- local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) +-- if ok and raw_data then +-- local _, data = next(raw_data) +-- if data then +-- local fallbackFlags = {} +-- -- 1. Process Includes +-- if data.includes then +-- for category, paths in pairs(data.includes) do +-- -- If it's a toolchain path, use -isystem to suppress warnings +-- -- and tell clangd these are standard libraries +-- if category == 'toolchain' then +-- local flag = '-isystem' +-- for _, path in ipairs(paths) do +-- -- table.insert(fallbackFlags, string.format('%q', flag)) +-- -- table.insert(fallbackFlags, string.format('%q', path:gsub('\\', '/'))) +-- table.insert(fallbackFlags, string.format('%q', flag .. path:gsub('\\', '/'))) +-- end +-- end +-- -- local flag = (category == 'toolchain') and '-isystem' or '-I' +-- -- for _, path in ipairs(paths) do +-- -- table.insert(fallbackFlags, flag .. path) +-- -- end +-- end +-- end +-- -- 2. Process Defines +-- if data.defines then +-- for _, define in ipairs(data.defines) do +-- table.insert(fallbackFlags, string.format('%q', '-D' .. define)) +-- end +-- end +-- +-- -- get [cc_compiler]and [falbackFlags] +-- -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' +-- _G.metadata.cc_compiler = misc.normalize_path(data.cc_path) or '' +-- _G.metadata.fallbackFlags = fallbackFlags +-- +-- -- print(vim.inspect(_G.metadata)) +-- if callback then +-- vim.schedule(function() +-- vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) +-- callback() +-- end) +-- end +-- end +-- else +-- vim.schedule(function() +-- vim.notify('PIO: Syncing Environment failed', vim.log.levels.WARN) +-- end) +-- end +-- end +-- -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save +-- if attempts > 0 then +-- vim.defer_fn(function() +-- get_metadata(attempts - 1) +-- end, 500) +-- end +-- end) +-- end +-- +-- -- INFO: Setup Base Paths +-- local home = os.getenv('HOME') or os.getenv('USERPROFILE') +-- +-- -- INFO: Try to get explicit value from platformio.ini +-- -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' +-- -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } +-- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) +-- if ext_obj.code ~= 0 then +-- -- Schedule notification to avoid error in the system callback thread +-- vim.schedule(function() +-- if ext_obj.code == 127 then +-- vim.notify("PIO Manager config: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) +-- else +-- vim.notify('PIO Manager config: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) +-- end +-- end) +-- return +-- end +-- _G.metadata.core_dir = '' +-- _G.metadata.packages_dir = '' +-- _G.metadata.platforms_dir = '' +-- _G.metadata.active_env = '' +-- _G.metadata.default_envs = {} +-- _G.metadata.envs = {} +-- +-- local decoded = vim.json.decode(ext_obj.stdout) +-- for _, section in ipairs(decoded) do +-- if type(section) == 'table' and #section >= 2 then +-- local name, data = section[1], section[2] +-- -- 1. Extract Global PlatformIO Settings if available [core_dir][packages_dir][platforms_dir][default_envs] +-- if name == 'platformio' then +-- for _, kv in ipairs(data) do +-- local key, val = kv[1], kv[2] +-- if key ~= nil then +-- -- if _G.metadata[key] ~= nil then +-- _G.metadata[key] = val +-- end +-- end +-- -- 2. Extract all hardware [envs] like [env:seeed_xiao_esp32c3], skipping generic [env] +-- elseif name:match('^env:') then +-- local env_name = name:match('^env:(.+)') +-- _G.metadata.envs[env_name] = {} +-- for _, kv in ipairs(data) do +-- _G.metadata.envs[env_name][kv[1]] = kv[2] +-- end +-- end +-- end +-- end +-- -- assign [active_env] +-- if #_G.metadata.default_envs > 0 then +-- _G.metadata.active_env = _G.metadata.default_envs[1] or '' +-- elseif _G.metadata.envs and #_G.metadata.envs > 0 then +-- _G.metadata.active_env = next(_G.metadata.envs) or '' +-- end +-- +-- -- INFO: -- Define Mapping (key in INI, Env Var, Default Subfolder) +-- local map = { +-- core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, +-- packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, +-- platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, +-- } +-- for _, kv in ipairs(map) do +-- -- 4.0 Fallback Logic: INI -> Env Var -> Default +-- local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') +-- -- 5. Expand ${platformio.core_dir} +-- if type(result) == 'string' then +-- if result:find('${platformio.core_dir}', 1, true) then +-- result = result:gsub('%${platformio.core_dir}', _G.metadata.core_dir) +-- end +-- end +-- -- 6. Normalize Slashes for Windows +-- -- _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') +-- _G.metadata[kv.ini] = result:gsub('\\', '/'):gsub('//+', '/') +-- end +-- -- return _G.metadata[map[type].ini] +-- -- end +-- +-- if _G.metadata.active_env ~= '' then +-- vim.schedule(function() +-- vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) +-- end) +-- get_metadata(1, _G.metadata.active_env) +-- else +-- vim.schedule(function() +-- vim.notify('PIO: no [env:] found, add board first', vim.log.levels.ERROR) +-- end) +-- end +-- end) +-- end +-- +-- -- INFO: +-- return { +-- refresh = refresh, +-- -- INFO: +-- get = function(s, k) +-- if not cache then +-- return nil +-- end +-- local res = find_in_data(cache, s, k) +-- +-- -- FALLBACK: If default_envs is missing/empty, find the first hardware [env:xxx] block +-- if k == 'default_envs' and not res then +-- for _, section in ipairs(cache) do +-- if type(section) == 'table' and type(section[1]) == 'string' then +-- local name = section[1] +-- if name:find('^env:') then +-- local fallback = name:match('^env:(.+)') +-- if fallback then +-- vim.schedule(function() +-- vim.notify('PIO: default_envs empty. Using: ' .. fallback, vim.log.levels.INFO) +-- end) +-- return fallback +-- end +-- end +-- end +-- end +-- vim.schedule(function() +-- vim.notify('PIO: Config Error. Check platformio.ini no env', vim.log.levels.WARN) +-- end) +-- elseif k == 'default_envs' and res and type(res) == 'table' then +-- return res[1] +-- else +-- return res +-- end +-- end, +-- } +-- end)() +-- +-- -- INFO: +-- function _G.get_pio_sdk_info() +-- local pio_info = { includes = {}, cc_compiler = '' } +-- if vim.fn.filereadable('platformio.ini') == 0 then +-- return nil +-- end +-- +-- local handle = io.popen('pio run -t envdump') +-- if not handle then +-- return nil +-- end +-- +-- local packages_dir, cc_name, toolchain_pkg = '', '', '' +-- +-- for line in handle:lines() do +-- -- 1. Get the global packages directory +-- packages_dir = packages_dir ~= '' and packages_dir or line:match("'PROJECT_PACKAGES_DIR': '([^']+)'") +-- +-- -- 2. Get the compiler executable name (e.g., riscv32-esp-elf-gcc) +-- cc_name = cc_name ~= '' and cc_name or line:match("'CC': '([^']+)'") +-- +-- -- 3. Find the specific toolchain package name from the PACKAGES list +-- -- Matches lines like "- toolchain-riscv32-esp @ 14.2.0" +-- local pkg = line:match('%- (toolchain%-[^ ]+)') +-- if pkg then +-- toolchain_pkg = pkg +-- end +-- +-- -- 4. Collect include paths +-- local path_list = line:match("'CPPPATH': %[(.+)%]") +-- if path_list then +-- for path in path_list:gmatch("'([^']+)'") do +-- table.insert(pio_info.includes, '-I' .. path) +-- end +-- end +-- end +-- handle:close() +-- +-- -- Construct the absolute path: //bin/ +-- if packages_dir and packages_dir ~= '' and toolchain_pkg and toolchain_pkg ~= '' and cc_name ~= '' then +-- local full_path = packages_dir .. '/' .. toolchain_pkg .. '/bin/' .. cc_name +-- if vim.fn.executable(full_path) == 1 then +-- pio_info.cc_compiler = full_path +-- end +-- end +-- +-- local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' +-- print('get_pio_sdk_info(): final=' .. final) +-- -- Normalize paths for the OS and ensure backslashes for Windows if needed +-- -- print(vim.inspect(_G.metadata)) +-- return (misc.normalize_path(final)) +-- -- return _G.metadata.query_driver +-- -- return pio_info +-- end +-- +-- -- INFO: +-- -- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync +-- -- stylua: ignore +-- local function start_pio_watcher() +-- local dir_path = vim.uv.cwd() +-- if not dir_path then return end +-- +-- -- Create a directory watcher +-- local handle = vim.uv.new_fs_event() +-- if not handle then return end +-- +-- -- local last_trigger = 0 +-- -- Watch the directory for platformio.ini creation or changes +-- handle:start( +-- dir_path, +-- { +-- watch_entry = false, -- watch the file/dir itself +-- stat = false, -- use stat to detect changes (slower but more reliable on some FS) +-- recursive = false, -- watch subdirectories (if path is a directory) +-- }, +-- vim.schedule_wrap(function(err, filename, events) +-- if err or not events or not events.change then return end +-- -- Trigger only if the changed file is platformio.ini +-- if filename == 'platformio.ini' and (events.change or events.rename) then +-- -- -- ignore events within time +-- -- local current_time = vim.uv.now() +-- -- -- IGNORE events if they happen within 100ms of the last one +-- -- if current_time - last_trigger < 100 then +-- -- return +-- -- end +-- -- last_trigger = current_time +-- +-- if debounce_timer then +-- debounce_timer:stop() +-- debounce_timer:start( +-- 500, +-- 0, +-- vim.schedule_wrap(function() +-- pio_manager.refresh(function() +-- -- vim.schedule(function() +-- local status, data = pcall(get_sysroot_triplet, _G.metadata.cc_compiler) +-- if status and data and data.triplet and data.triplet ~= '' then +-- _G.metadata.triplet = data.triplet +-- _G.metadata.sysroot = data.sysroot +-- _G.metadata.query_driver = data.query_driver +-- _G.metadata.toolchain = data.toolchain_root +-- end +-- -- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) +-- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +-- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) +-- +-- pio_generate_db() +-- lsp.lsp_restart('clangd') +-- -- end) +-- end) end)) end end end)) +-- end +-- ------------------------------------------------------------------------------------------------------ +-- -- INFO: 6. Exported setup function +-- function M.init() +-- local config = require('platformio').config +-- if config.lspClangd.enabled == true then +-- vim.notify('PIO setup initialize', vim.log.levels.INFO) +-- ---------------------------------------------------------------------------------------- +-- -- INFO: create clangd required files +-- ----------------------------------------------------------------------------------------- +-- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) +-- -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +-- -- boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) +-- -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) +-- -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') +-- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) +-- boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) +-- --------------------------------------------------------------------------------- +-- +-- require('platformio.lspConfig.clangd') +-- if config.lspClangd.attach.enabled then +-- require('platformio.lspConfig.attach') +-- end +-- +-- -- Always start the watcher so it can catch a future 'pio init' +-- start_pio_watcher() +-- +-- -- If the file already exists, do an initial sync +-- if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then +-- pio_manager.refresh(function() +-- -- vim.schedule(function() +-- -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) +-- pio_generate_db() +-- lsp.lsp_restart('clangd') +-- -- end) +-- end) +-- end +-- end +-- end +-- +-- return M From 81e778f1cc072269a8c2a08e3bb8355b416d32e4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 00:33:08 +0300 Subject: [PATCH 0686/1406] update --- lua/platformio/pio_setup.lua | 79 ++++++++++++++++++------------------ 1 file changed, 39 insertions(+), 40 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 8ad1c32e..8f9b6f62 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -71,9 +71,9 @@ local function pio_generate_db() if obj.code ~= 0 then vim.schedule(function() if obj.code == 127 then - vim.notify("PIO Manager db: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else - vim.notify('PIO Manager db: Generating Compile Database failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + vim.notify('PIO Manager: Generating Compile Database failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) end end) return @@ -136,9 +136,9 @@ local pio_manager = (function() -- Schedule notification to avoid error in the system callback thread vim.schedule(function() if int_obj.code == 127 then - vim.notify("PIO Manager metadata: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else - vim.notify('PIO Manager metadata: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + vim.notify('PIO Manager: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) end end) return @@ -149,7 +149,7 @@ local pio_manager = (function() if ok and raw_data then local _, data = next(raw_data) if data then - local fallbackFlags = {} + local fallback_flags = {} -- 1. Process Includes if data.includes then for category, paths in pairs(data.includes) do @@ -158,28 +158,27 @@ local pio_manager = (function() if category == 'toolchain' then local flag = '-isystem' for _, path in ipairs(paths) do - -- table.insert(fallbackFlags, string.format('%q', flag)) - -- table.insert(fallbackFlags, string.format('%q', path:gsub('\\', '/'))) - table.insert(fallbackFlags, string.format('%q', flag .. path:gsub('\\', '/'))) + -- table.insert(fallback_flags, string.format('%q', flag)) + -- table.insert(fallback_flags, string.format('%q', path:gsub('\\', '/'))) + table.insert(fallback_flags, string.format('%q', flag .. path:gsub('\\', '/'))) end end -- local flag = (category == 'toolchain') and '-isystem' or '-I' -- for _, path in ipairs(paths) do - -- table.insert(fallbackFlags, flag .. path) + -- table.insert(fallback_flags, flag .. path) -- end end end -- 2. Process Defines if data.defines then for _, define in ipairs(data.defines) do - table.insert(fallbackFlags, string.format('%q', '-D' .. define)) + table.insert(fallback_flags, string.format('%q', '-D' .. define)) end end - -- get [cc_compiler]and [falbackFlags] -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' _G.metadata.cc_compiler = misc.normalize_path(data.cc_path) or '' - _G.metadata.fallbackFlags = fallbackFlags + _G.metadata.fallback_flags = fallback_flags -- print(vim.inspect(_G.metadata)) if callback then @@ -204,10 +203,16 @@ local pio_manager = (function() end) end - -- INFO: Setup Base Paths + -- INFO: -- 1. Setup Base Paths local home = os.getenv('HOME') or os.getenv('USERPROFILE') + -- INFO: -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) + local map = { + core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, + packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, + platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, + } - -- INFO: Try to get explicit value from platformio.ini + -- INFO: 3. Try to get explicit value from platformio.ini -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) @@ -215,9 +220,9 @@ local pio_manager = (function() -- Schedule notification to avoid error in the system callback thread vim.schedule(function() if ext_obj.code == 127 then - vim.notify("PIO Manager config: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else - vim.notify('PIO Manager config: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + vim.notify('PIO Manager: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) end end) return @@ -233,7 +238,7 @@ local pio_manager = (function() for _, section in ipairs(decoded) do if type(section) == 'table' and #section >= 2 then local name, data = section[1], section[2] - -- 1. Extract Global PlatformIO Settings if available [core_dir][packages_dir][platforms_dir][default_envs] + -- 1. Extract Global PlatformIO Settings if name == 'platformio' then for _, kv in ipairs(data) do local key, val = kv[1], kv[2] @@ -242,7 +247,7 @@ local pio_manager = (function() _G.metadata[key] = val end end - -- 2. Extract all hardware [envs] like [env:seeed_xiao_esp32c3], skipping generic [env] + -- 2. Extract all hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] elseif name:match('^env:') then local env_name = name:match('^env:(.+)') _G.metadata.envs[env_name] = {} @@ -252,19 +257,12 @@ local pio_manager = (function() end end end - -- assign [active_env] if #_G.metadata.default_envs > 0 then _G.metadata.active_env = _G.metadata.default_envs[1] or '' - elseif _G.metadata.envs and #_G.metadata.envs > 0 then + else _G.metadata.active_env = next(_G.metadata.envs) or '' end - -- INFO: -- Define Mapping (key in INI, Env Var, Default Subfolder) - local map = { - core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, - packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, - platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, - } for _, kv in ipairs(map) do -- 4.0 Fallback Logic: INI -> Env Var -> Default local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') @@ -426,21 +424,21 @@ local function start_pio_watcher() 0, vim.schedule_wrap(function() pio_manager.refresh(function() - vim.schedule(function() - local status, data = pcall(get_sysroot_triplet, _G.metadata.cc_compiler) - if status and data and data.triplet and data.triplet ~= '' then - _G.metadata.triplet = data.triplet - _G.metadata.sysroot = data.sysroot - _G.metadata.query_driver = data.query_driver - _G.metadata.toolchain = data.toolchain_root - end - -- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) + -- vim.schedule(function() + local status, data = pcall(get_sysroot_triplet, _G.metadata.cc_compiler) + if status and data and data.triplet and data.triplet ~= '' then + _G.metadata.triplet = data.triplet + _G.metadata.sysroot = data.sysroot + _G.metadata.query_driver = data.query_driver + _G.metadata.toolchain = data.toolchain_root + end + -- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) - pio_generate_db() - lsp.lsp_restart('clangd') - end) + pio_generate_db() + lsp.lsp_restart('clangd') + -- end) end) end)) end end end)) end ------------------------------------------------------------------------------------------------------ @@ -474,6 +472,7 @@ function M.init() pio_manager.refresh(function() -- vim.schedule(function() -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) pio_generate_db() lsp.lsp_restart('clangd') -- end) From b7e59dcc8b22ecd0f1065de78825d3fe9008bc50 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 04:51:23 +0300 Subject: [PATCH 0687/1406] update --- lua/platformio/archived/pio_setup.lua | 761 ++++++++++++++--------- lua/platformio/archived/pio_setupold.lua | 277 +++++++++ lua/platformio/pio_setup.lua | 3 +- 3 files changed, 763 insertions(+), 278 deletions(-) create mode 100644 lua/platformio/archived/pio_setupold.lua diff --git a/lua/platformio/archived/pio_setup.lua b/lua/platformio/archived/pio_setup.lua index 7f6be736..8f9b6f62 100644 --- a/lua/platformio/archived/pio_setup.lua +++ b/lua/platformio/archived/pio_setup.lua @@ -1,277 +1,484 @@ --- local misc = require('platformio.utils.misc') --- local lsp = require('platformio.utils.lsp') --- --- local debounce_timer = vim.uv.new_timer() --- --- -- INFO: 1. The Core PIO Manager & Generic Extractor --- --This manages the data cache and navigates your specific nested-list JSON structure. --- --- -- stylua: ignore --- local pio_manager = (function() --- local cache = nil --- --- -- INFO: 1 Generic extractor for nested structure: { { "name", { {"k","v"}, ... } }, ... } --- local function find_in_data(data, section_name, key_name) --- if not data or type(data) ~= 'table' then return nil end --- --- -- INFO: 1.0 SPECIFIC SEARCH: Look for a specific section (e.g., "platformio") --- if section_name then --- for _, section in ipairs(data) do --- if type(section) == 'table' and #section >= 2 then --- local s_id, s_body = section[1], section[2] --- if s_id == section_name and type(s_body) == "table" then --- for _, kv in ipairs(s_body) do --- if type(kv) == "table" and #kv >= 2 and kv[1] == key_name then --- local val = kv[2] --- if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then --- return val --- end --- end --- end --- end --- end --- end --- end --- --- -- INFO: 1.1 FALLBACK SEARCH (If we reach here, Step 1 failed or was skipped) --- local fallback_env_found = nil --- for _, section in ipairs(data) do --- if type(section) == 'table' and #section >= 2 then --- local s_id = section[1] --- local s_body = section[2] --- -- Look for hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] --- if type(s_id) == 'string' and s_id:find('^env:') then --- fallback_env_found = s_id:match('^env:(.+)') --- --- -- If we were looking for default_envs, we just found our fallback --- if key_name == 'default_envs' then --- vim.schedule(function() --- vim.notify("PIO: 'default_envs' empty. Falling back to: " .. fallback_env_found, vim.log.levels.INFO) --- end) --- return fallback_env_found --- end --- --- -- If looking for a key (like 'platform') inside this fallback env --- if type(s_body) == 'table' then --- for _, kv in ipairs(s_body) do --- if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then --- local val = kv[2] --- if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then --- vim.schedule(function() --- vim.notify("PIO: Using '" .. key_name .. "' from fallback env: " .. fallback_env_found, vim.log.levels.INFO) --- end) --- return val --- end --- end --- end --- end --- end --- end --- end --- --- -- INFO: 1.2 FINAL ERROR If even fallback fails --- if key_name == 'platform' or key_name == 'packages_dir' then --- vim.schedule(function() --- vim.notify("PIO: Critical key '" .. key_name .. "' not found anywhere!", vim.log.levels.INFO) --- end) --- end --- return nil --- end --- ------------------------------------------------------------------------------------------ --- --- -- INFO: 2. Asynchronous Refresh --- local function refresh(callback) --- -- Using vim.system to detect if the command exists --- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) --- if obj.code ~= 0 then --- -- Schedule notification to avoid error in the system callback thread --- vim.schedule(function() --- if obj.code == 127 then --- vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) --- else --- vim.notify('PIO Manager: Failed to fetch config (Error ' .. obj.code .. ')', vim.log.levels.WARN) --- end --- end) --- return --- end --- local ok, decoded = pcall(vim.json.decode, obj.stdout) --- if ok and decoded then --- cache = decoded --- if not cache or type(cache) ~= 'table' then --- print('no cahce') --- else --- print('cahced ok') --- end --- if callback then vim.schedule(callback) end --- end --- end) --- end --- return { --- refresh = refresh, --- get = function(s, k) --- return find_in_data(cache, s, k) --- end, --- } --- end)() --- --- ------------------------------------------------------------------------------------------------------ --- -- INFO: 2. Generic Toolchain & Sysroot Logic. These functions identify where the compiler and its C++ headers live. --- -- Gets the compiler glob for clangd --query-driver --- -- stylua: ignore --- function _G.get_pio_toolchain_pattern() --- local active_env = vim.g.pio_active_env or pio_manager.get("platformio", "default_envs") --- -- or pio_manager.get(nil, "default_envs") --- --- -- Handle default_envs being a list/table --- if type(active_env) == 'table' then active_env = active_env[1] end --- --- local target_env = active_env and ('env:' .. active_env) or nil --- local platform = pio_manager.get(target_env, 'platform') --- local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('HOME') or os.getenv('USERPROFILE') .. '/.platformio/packages') --- --- if not platform then return '/**/bin/*' end --- --- -- Sync call for toolchain name --- local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') --- if not p_handle then return '/**/bin/*' end --- --- local p_json = p_handle:read('*all') --- p_handle:close() --- local arch_glob = '/**/bin/*' --- local p_ok, p_data = pcall(vim.json.decode, p_json) --- if p_ok and p_data and type(p_data.packages) == 'table' then --- for pkg_name, _ in pairs(p_data.packages) do --- if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then --- local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') --- arch_glob = '/**/bin/*' .. arch .. '*' --- break --- end --- end --- end --- -- local final = (packages_dir:gsub('\\', '/') .. arch_glob):gsub('//+', '/') --- local final = packages_dir .. arch_glob --- print('toolchain 5: final=' .. final) --- return (misc.normalize_path(final)) --- -- return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final --- end --- --- -- INFO: 3. Patches compile_commands.json with --sysroot to fix --- -- Helper to generate the compilation database --- -- stylua: ignore --- local function pio_generate_db() --- -- This runs in the background so it doesn't freeze Neovim --- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) --- if obj.code ~= 0 then return end --- print('pio_generate_db 0') --- local pattern = _G.get_pio_toolchain_pattern() --- local toolchain_root = pattern:match('(.*toolchain%-[^/\\]+)') --- if not toolchain_root or vim.fn.isdirectory(toolchain_root) == 0 then --- return --- end --- --- -- Find subdirectory containing 'include' (the sysroot) --- local sysroot_path = nil --- local subdirs = vim.fn.getcompletion(toolchain_root .. '/*', 'dir') --- for _, dir in ipairs(subdirs) do --- if vim.fn.isdirectory(dir .. '/include') == 1 then --- sysroot_path = dir:gsub('\\', '/') --- break --- end --- end --- if sysroot_path then --- local db_path = vim.fn.getcwd() .. '/compile_commands.json' --- local f = io.open(db_path, 'r') --- if not f then return end --- local content = f:read('*all') --- f:close() --- --- -- patch sysroot --- local patched = content:gsub('("-i")', '"--sysroot=' .. sysroot_path .. '", %1') --- local out = io.open(db_path, 'w') --- if out then --- out:write(patched) --- out:close() --- vim.schedule(function() vim.notify('PIO: DB & Sysroot Patched') end) --- end --- end --- end) --- end --- --- ------------------------------------------------------------------------------------------------------ --- -- INFO: 4. Automation & File Watcher --- --This handles the background synchronization when you save your project. --- -- stylua: ignore --- local function start_pio_watcher() --- local path = vim.fn.getcwd() .. '/platformio.ini' --- if vim.fn.filereadable(path) == 0 then return end --- --- local w = vim.uv.new_fs_event() --- if not w then return end --- --- w:start( --- path, {}, --- vim.schedule_wrap(function(err, _, events) --- if err or not events.change then return end --- --- -- 1. Stop any existing timer (cancel previous "half-finished" events) --- if debounce_timer then --- debounce_timer:stop() --- --- -- 2. Start a 500ms window. Logic only runs if NO more events happen in this time. --- debounce_timer:start( 500, 0, --- vim.schedule_wrap(function() --- vim.notify('PIO: Config change detected. Refreshing...', vim.log.levels.INFO) --- --- pio_manager.refresh(function() --- pio_generate_db() --- -- 3. Only restart LSP if the pattern actually changed or DB was updated --- lsp.lsp_restart('clangd') --- end) --- end) --- ) --- end --- end) --- ) --- end --- --- ------------------------------------------------------------------------------------------------------ --- -- INFO: 6. Exported setup function --- return { --- init = function() --- local config = require('platformio').config --- if config.lspClangd.enabled == true then --- vim.notify('PIO setup initialize', vim.log.levels.INFO) --- ---------------------------------------------------------------------------------------- --- -- INFO: create clangd required files --- ----------------------------------------------------------------------------------------- --- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen --- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) --- --- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) --- boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) --- -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) --- -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') --- --- -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) --- --- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) --- --- boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) --- -- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) --- -- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) --- --------------------------------------------------------------------------------- --- --- -- vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) --- require('platformio.lspConfig.clangd') --- if config.lspClangd.attach.enabled then --- require('platformio.lspConfig.attach') --- end --- if vim.fn.filereadable(vim.fn.getcwd() .. '/platformio.ini') == 1 then --- pio_manager.refresh(function() --- pio_generate_db() --- start_pio_watcher() --- end) --- end --- end --- end, --- } +M = {} + +local misc = require('platformio.utils.misc') +local lsp = require('platformio.utils.lsp') +local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + +-- lua/pio_setup.lua +-- This module manages PlatformIO project integration, LSP toolchain detection, +-- and automatic sysroot patching for standard library headers (, etc.) + +local debounce_timer = vim.uv.new_timer() + +-- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) +-- INFO: +-- ============================================================================= +-- UNIVERSAL TOOLCHAIN DETECTION +-- ============================================================================= +--- stylua: ignore +local function get_sysroot_triplet(cc_compiler) + local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') + -- Early exit if path is nil or not a directory + if not bin_path or vim.fn.isdirectory(bin_path) == 0 then + return nil + end + + -- Normalize backslashes to forward slashes for cross-platform consistency + bin_path = bin_path:gsub('\\', '/') + local files = vim.fn.readdir(bin_path) + local triplet = nil + + -- Loop through files to find the compiler and extract the triplet + for _, name in ipairs(files) do + -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ + local match = name:match('^(.*)%-g[c%+][c%+]') + if match then + triplet = match + break + end + end + + -- Return nil if no compiler was found in the bin directory + if not triplet then + return nil + end + + -- toolchain_root is the parent of the 'bin' folder + local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') + -- sysroot folder is expected to have the same name as the triplet + local sysroot = toolchain_root .. '/' .. triplet + + -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) + -- Only return data if the sysroot folder actually exists on disk + if vim.fn.isdirectory(sysroot) == 1 then + return { + triplet = triplet, + sysroot = sysroot, + toolchain_root = toolchain_root, + query_driver = bin_path .. '/' .. triplet .. '-*', + } + end + return nil +end + + +-- INFO: +-- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag +-- stylua: ignore +local function pio_generate_db() + vim.schedule(function() vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) end) + vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) + if obj.code ~= 0 then + vim.schedule(function() + if obj.code == 127 then + vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + else + vim.notify('PIO Manager: Generating Compile Database failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + end + end) + return + end + vim.schedule(function() vim.notify('PIO: Generating Compile Database successful', vim.log.levels.INFO) end) + end) +end + +-- INFO: 1. The Core PIO Manager & Generic Extractor +--- stylua: ignore +local pio_manager = (function() + local cache = nil -- Stores the decoded platformio.ini JSON structure + -- INFO: + local function find_in_data(data, section_name, key_name) + -- Safety check: Ensure data is a valid table from a successful JSON decode + if type(data) ~= 'table' then + return nil + end + + for _, section in ipairs(data) do + -- Each section must be a table with at least 2 elements: [1]=name, [2]=content + if type(section) == 'table' and #section >= 2 then + local s_id = section[1] -- Section header string + local s_body = section[2] -- Table of key-value pairs + + if s_id == section_name and type(s_body) == 'table' then + for _, kv in ipairs(s_body) do + -- Each kv is a table: [1]=key, [2]=value + if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then + local val = kv[2] + -- Treat empty strings or empty tables as nil to trigger fallback logic + if val == nil or val == '' or (type(val) == 'table' and #val == 0) then + return nil + end + return val + end + end + end + end + end + return nil + end + + -- INFO: ASYNC REFRESH: Fetches the latest config from PlatformIO CLI + --- stylua: ignore + local function refresh(callback) + vim.schedule(function() + vim.notify('PIO: Fetching Config ...', vim.log.levels.INFO) + end) + + -- INFO: get project metadata + local function get_metadata(attempts, env) + local active_env = env or _G.metadata.active_env + vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(int_obj) + vim.schedule(function() + vim.notify('PIO: Fetching metadata ...', vim.log.levels.INFO) + end) + + if int_obj.code ~= 0 then + -- Schedule notification to avoid error in the system callback thread + vim.schedule(function() + if int_obj.code == 127 then + vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + else + vim.notify('PIO Manager: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + end + end) + return + end + + if int_obj.code == 0 and int_obj.stdout then + local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) + if ok and raw_data then + local _, data = next(raw_data) + if data then + local fallback_flags = {} + -- 1. Process Includes + if data.includes then + for category, paths in pairs(data.includes) do + -- If it's a toolchain path, use -isystem to suppress warnings + -- and tell clangd these are standard libraries + if category == 'toolchain' then + local flag = '-isystem' + for _, path in ipairs(paths) do + -- table.insert(fallback_flags, string.format('%q', flag)) + -- table.insert(fallback_flags, string.format('%q', path:gsub('\\', '/'))) + table.insert(fallback_flags, string.format('%q', flag .. path:gsub('\\', '/'))) + end + end + -- local flag = (category == 'toolchain') and '-isystem' or '-I' + -- for _, path in ipairs(paths) do + -- table.insert(fallback_flags, flag .. path) + -- end + end + end + -- 2. Process Defines + if data.defines then + for _, define in ipairs(data.defines) do + table.insert(fallback_flags, string.format('%q', '-D' .. define)) + end + end + + -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' + _G.metadata.cc_compiler = misc.normalize_path(data.cc_path) or '' + _G.metadata.fallback_flags = fallback_flags + + -- print(vim.inspect(_G.metadata)) + if callback then + vim.schedule(function() + vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) + callback() + end) + end + end + else + vim.schedule(function() + vim.notify('PIO: Syncing Environment failed', vim.log.levels.WARN) + end) + end + end + -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save + if attempts > 0 then + vim.defer_fn(function() + get_metadata(attempts - 1) + end, 500) + end + end) + end + + -- INFO: -- 1. Setup Base Paths + local home = os.getenv('HOME') or os.getenv('USERPROFILE') + -- INFO: -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) + local map = { + core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, + packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, + platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, + } + + -- INFO: 3. Try to get explicit value from platformio.ini + -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' + -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } + vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) + if ext_obj.code ~= 0 then + -- Schedule notification to avoid error in the system callback thread + vim.schedule(function() + if ext_obj.code == 127 then + vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + else + vim.notify('PIO Manager: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + end + end) + return + end + _G.metadata.core_dir = '' + _G.metadata.packages_dir = '' + _G.metadata.platforms_dir = '' + _G.metadata.active_env = '' + _G.metadata.default_envs = {} + _G.metadata.envs = {} + + local decoded = vim.json.decode(ext_obj.stdout) + for _, section in ipairs(decoded) do + if type(section) == 'table' and #section >= 2 then + local name, data = section[1], section[2] + -- 1. Extract Global PlatformIO Settings + if name == 'platformio' then + for _, kv in ipairs(data) do + local key, val = kv[1], kv[2] + if key ~= nil then + -- if _G.metadata[key] ~= nil then + _G.metadata[key] = val + end + end + -- 2. Extract all hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] + elseif name:match('^env:') then + local env_name = name:match('^env:(.+)') + _G.metadata.envs[env_name] = {} + for _, kv in ipairs(data) do + _G.metadata.envs[env_name][kv[1]] = kv[2] + end + end + end + end + if #_G.metadata.default_envs > 0 then + _G.metadata.active_env = _G.metadata.default_envs[1] or '' + else + _G.metadata.active_env = next(_G.metadata.envs) or '' + end + + for _, kv in ipairs(map) do + -- 4.0 Fallback Logic: INI -> Env Var -> Default + local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') + -- 5. Expand ${platformio.core_dir} + if type(result) == 'string' then + if result:find('${platformio.core_dir}', 1, true) then + result = result:gsub('%${platformio.core_dir}', _G.metadata.core_dir) + end + end + -- 6. Normalize Slashes for Windows + -- _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') + _G.metadata[kv.ini] = result:gsub('\\', '/'):gsub('//+', '/') + end + -- return _G.metadata[map[type].ini] + -- end + + if _G.metadata.active_env ~= '' then + vim.schedule(function() + vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) + end) + get_metadata(1, _G.metadata.active_env) + else + vim.schedule(function() + vim.notify('PIO: no [env:] found, add board first', vim.log.levels.ERROR) + end) + end + end) + end + + -- INFO: + return { + refresh = refresh, + -- INFO: + get = function(s, k) + if not cache then + return nil + end + local res = find_in_data(cache, s, k) + + -- FALLBACK: If default_envs is missing/empty, find the first hardware [env:xxx] block + if k == 'default_envs' and not res then + for _, section in ipairs(cache) do + if type(section) == 'table' and type(section[1]) == 'string' then + local name = section[1] + if name:find('^env:') then + local fallback = name:match('^env:(.+)') + if fallback then + vim.schedule(function() + vim.notify('PIO: default_envs empty. Using: ' .. fallback, vim.log.levels.INFO) + end) + return fallback + end + end + end + end + vim.schedule(function() + vim.notify('PIO: Config Error. Check platformio.ini no env', vim.log.levels.WARN) + end) + elseif k == 'default_envs' and res and type(res) == 'table' then + return res[1] + else + return res + end + end, + } +end)() + +-- INFO: +function _G.get_pio_sdk_info() + local pio_info = { includes = {}, cc_compiler = '' } + if vim.fn.filereadable('platformio.ini') == 0 then + return nil + end + + local handle = io.popen('pio run -t envdump') + if not handle then + return nil + end + + local packages_dir, cc_name, toolchain_pkg = '', '', '' + + for line in handle:lines() do + -- 1. Get the global packages directory + packages_dir = packages_dir ~= '' and packages_dir or line:match("'PROJECT_PACKAGES_DIR': '([^']+)'") + + -- 2. Get the compiler executable name (e.g., riscv32-esp-elf-gcc) + cc_name = cc_name ~= '' and cc_name or line:match("'CC': '([^']+)'") + + -- 3. Find the specific toolchain package name from the PACKAGES list + -- Matches lines like "- toolchain-riscv32-esp @ 14.2.0" + local pkg = line:match('%- (toolchain%-[^ ]+)') + if pkg then + toolchain_pkg = pkg + end + + -- 4. Collect include paths + local path_list = line:match("'CPPPATH': %[(.+)%]") + if path_list then + for path in path_list:gmatch("'([^']+)'") do + table.insert(pio_info.includes, '-I' .. path) + end + end + end + handle:close() + + -- Construct the absolute path: //bin/ + if packages_dir and packages_dir ~= '' and toolchain_pkg and toolchain_pkg ~= '' and cc_name ~= '' then + local full_path = packages_dir .. '/' .. toolchain_pkg .. '/bin/' .. cc_name + if vim.fn.executable(full_path) == 1 then + pio_info.cc_compiler = full_path + end + end + + local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' + print('get_pio_sdk_info(): final=' .. final) + -- Normalize paths for the OS and ensure backslashes for Windows if needed + -- print(vim.inspect(_G.metadata)) + return (misc.normalize_path(final)) + -- return _G.metadata.query_driver + -- return pio_info +end + +-- INFO: +-- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync +-- stylua: ignore +local function start_pio_watcher() + local dir_path = vim.uv.cwd() + if not dir_path then return end + + -- Create a directory watcher + local handle = vim.uv.new_fs_event() + if not handle then return end + + -- local last_trigger = 0 + -- Watch the directory for platformio.ini creation or changes + handle:start( + dir_path, + { + watch_entry = false, -- watch the file/dir itself + stat = false, -- use stat to detect changes (slower but more reliable on some FS) + recursive = false, -- watch subdirectories (if path is a directory) + }, + vim.schedule_wrap(function(err, filename, events) + if err or not events or not events.change then return end + -- Trigger only if the changed file is platformio.ini + if filename == 'platformio.ini' and (events.change or events.rename) then + -- -- ignore events within time + -- local current_time = vim.uv.now() + -- -- IGNORE events if they happen within 100ms of the last one + -- if current_time - last_trigger < 100 then + -- return + -- end + -- last_trigger = current_time + + if debounce_timer then + debounce_timer:stop() + debounce_timer:start( + 500, + 0, + vim.schedule_wrap(function() + pio_manager.refresh(function() + -- vim.schedule(function() + local status, data = pcall(get_sysroot_triplet, _G.metadata.cc_compiler) + if status and data and data.triplet and data.triplet ~= '' then + _G.metadata.triplet = data.triplet + _G.metadata.sysroot = data.sysroot + _G.metadata.query_driver = data.query_driver + _G.metadata.toolchain = data.toolchain_root + end + -- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) + + pio_generate_db() + lsp.lsp_restart('clangd') + -- end) + end) end)) end end end)) +end +------------------------------------------------------------------------------------------------------ +-- INFO: 6. Exported setup function +function M.init() + local config = require('platformio').config + if config.lspClangd.enabled == true then + vim.notify('PIO setup initialize', vim.log.levels.INFO) + ---------------------------------------------------------------------------------------- + -- INFO: create clangd required files + ----------------------------------------------------------------------------------------- + boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) + -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + -- boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) + -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) + -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') + boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) + boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) + --------------------------------------------------------------------------------- + + require('platformio.lspConfig.clangd') + if config.lspClangd.attach.enabled then + require('platformio.lspConfig.attach') + end + + -- Always start the watcher so it can catch a future 'pio init' + start_pio_watcher() + + -- If the file already exists, do an initial sync + if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then + pio_manager.refresh(function() + -- vim.schedule(function() + -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) + pio_generate_db() + lsp.lsp_restart('clangd') + -- end) + end) + end + end +end + +return M diff --git a/lua/platformio/archived/pio_setupold.lua b/lua/platformio/archived/pio_setupold.lua new file mode 100644 index 00000000..7f6be736 --- /dev/null +++ b/lua/platformio/archived/pio_setupold.lua @@ -0,0 +1,277 @@ +-- local misc = require('platformio.utils.misc') +-- local lsp = require('platformio.utils.lsp') +-- +-- local debounce_timer = vim.uv.new_timer() +-- +-- -- INFO: 1. The Core PIO Manager & Generic Extractor +-- --This manages the data cache and navigates your specific nested-list JSON structure. +-- +-- -- stylua: ignore +-- local pio_manager = (function() +-- local cache = nil +-- +-- -- INFO: 1 Generic extractor for nested structure: { { "name", { {"k","v"}, ... } }, ... } +-- local function find_in_data(data, section_name, key_name) +-- if not data or type(data) ~= 'table' then return nil end +-- +-- -- INFO: 1.0 SPECIFIC SEARCH: Look for a specific section (e.g., "platformio") +-- if section_name then +-- for _, section in ipairs(data) do +-- if type(section) == 'table' and #section >= 2 then +-- local s_id, s_body = section[1], section[2] +-- if s_id == section_name and type(s_body) == "table" then +-- for _, kv in ipairs(s_body) do +-- if type(kv) == "table" and #kv >= 2 and kv[1] == key_name then +-- local val = kv[2] +-- if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then +-- return val +-- end +-- end +-- end +-- end +-- end +-- end +-- end +-- +-- -- INFO: 1.1 FALLBACK SEARCH (If we reach here, Step 1 failed or was skipped) +-- local fallback_env_found = nil +-- for _, section in ipairs(data) do +-- if type(section) == 'table' and #section >= 2 then +-- local s_id = section[1] +-- local s_body = section[2] +-- -- Look for hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] +-- if type(s_id) == 'string' and s_id:find('^env:') then +-- fallback_env_found = s_id:match('^env:(.+)') +-- +-- -- If we were looking for default_envs, we just found our fallback +-- if key_name == 'default_envs' then +-- vim.schedule(function() +-- vim.notify("PIO: 'default_envs' empty. Falling back to: " .. fallback_env_found, vim.log.levels.INFO) +-- end) +-- return fallback_env_found +-- end +-- +-- -- If looking for a key (like 'platform') inside this fallback env +-- if type(s_body) == 'table' then +-- for _, kv in ipairs(s_body) do +-- if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then +-- local val = kv[2] +-- if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then +-- vim.schedule(function() +-- vim.notify("PIO: Using '" .. key_name .. "' from fallback env: " .. fallback_env_found, vim.log.levels.INFO) +-- end) +-- return val +-- end +-- end +-- end +-- end +-- end +-- end +-- end +-- +-- -- INFO: 1.2 FINAL ERROR If even fallback fails +-- if key_name == 'platform' or key_name == 'packages_dir' then +-- vim.schedule(function() +-- vim.notify("PIO: Critical key '" .. key_name .. "' not found anywhere!", vim.log.levels.INFO) +-- end) +-- end +-- return nil +-- end +-- ------------------------------------------------------------------------------------------ +-- +-- -- INFO: 2. Asynchronous Refresh +-- local function refresh(callback) +-- -- Using vim.system to detect if the command exists +-- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) +-- if obj.code ~= 0 then +-- -- Schedule notification to avoid error in the system callback thread +-- vim.schedule(function() +-- if obj.code == 127 then +-- vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) +-- else +-- vim.notify('PIO Manager: Failed to fetch config (Error ' .. obj.code .. ')', vim.log.levels.WARN) +-- end +-- end) +-- return +-- end +-- local ok, decoded = pcall(vim.json.decode, obj.stdout) +-- if ok and decoded then +-- cache = decoded +-- if not cache or type(cache) ~= 'table' then +-- print('no cahce') +-- else +-- print('cahced ok') +-- end +-- if callback then vim.schedule(callback) end +-- end +-- end) +-- end +-- return { +-- refresh = refresh, +-- get = function(s, k) +-- return find_in_data(cache, s, k) +-- end, +-- } +-- end)() +-- +-- ------------------------------------------------------------------------------------------------------ +-- -- INFO: 2. Generic Toolchain & Sysroot Logic. These functions identify where the compiler and its C++ headers live. +-- -- Gets the compiler glob for clangd --query-driver +-- -- stylua: ignore +-- function _G.get_pio_toolchain_pattern() +-- local active_env = vim.g.pio_active_env or pio_manager.get("platformio", "default_envs") +-- -- or pio_manager.get(nil, "default_envs") +-- +-- -- Handle default_envs being a list/table +-- if type(active_env) == 'table' then active_env = active_env[1] end +-- +-- local target_env = active_env and ('env:' .. active_env) or nil +-- local platform = pio_manager.get(target_env, 'platform') +-- local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('HOME') or os.getenv('USERPROFILE') .. '/.platformio/packages') +-- +-- if not platform then return '/**/bin/*' end +-- +-- -- Sync call for toolchain name +-- local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') +-- if not p_handle then return '/**/bin/*' end +-- +-- local p_json = p_handle:read('*all') +-- p_handle:close() +-- local arch_glob = '/**/bin/*' +-- local p_ok, p_data = pcall(vim.json.decode, p_json) +-- if p_ok and p_data and type(p_data.packages) == 'table' then +-- for pkg_name, _ in pairs(p_data.packages) do +-- if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then +-- local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') +-- arch_glob = '/**/bin/*' .. arch .. '*' +-- break +-- end +-- end +-- end +-- -- local final = (packages_dir:gsub('\\', '/') .. arch_glob):gsub('//+', '/') +-- local final = packages_dir .. arch_glob +-- print('toolchain 5: final=' .. final) +-- return (misc.normalize_path(final)) +-- -- return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final +-- end +-- +-- -- INFO: 3. Patches compile_commands.json with --sysroot to fix +-- -- Helper to generate the compilation database +-- -- stylua: ignore +-- local function pio_generate_db() +-- -- This runs in the background so it doesn't freeze Neovim +-- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) +-- if obj.code ~= 0 then return end +-- print('pio_generate_db 0') +-- local pattern = _G.get_pio_toolchain_pattern() +-- local toolchain_root = pattern:match('(.*toolchain%-[^/\\]+)') +-- if not toolchain_root or vim.fn.isdirectory(toolchain_root) == 0 then +-- return +-- end +-- +-- -- Find subdirectory containing 'include' (the sysroot) +-- local sysroot_path = nil +-- local subdirs = vim.fn.getcompletion(toolchain_root .. '/*', 'dir') +-- for _, dir in ipairs(subdirs) do +-- if vim.fn.isdirectory(dir .. '/include') == 1 then +-- sysroot_path = dir:gsub('\\', '/') +-- break +-- end +-- end +-- if sysroot_path then +-- local db_path = vim.fn.getcwd() .. '/compile_commands.json' +-- local f = io.open(db_path, 'r') +-- if not f then return end +-- local content = f:read('*all') +-- f:close() +-- +-- -- patch sysroot +-- local patched = content:gsub('("-i")', '"--sysroot=' .. sysroot_path .. '", %1') +-- local out = io.open(db_path, 'w') +-- if out then +-- out:write(patched) +-- out:close() +-- vim.schedule(function() vim.notify('PIO: DB & Sysroot Patched') end) +-- end +-- end +-- end) +-- end +-- +-- ------------------------------------------------------------------------------------------------------ +-- -- INFO: 4. Automation & File Watcher +-- --This handles the background synchronization when you save your project. +-- -- stylua: ignore +-- local function start_pio_watcher() +-- local path = vim.fn.getcwd() .. '/platformio.ini' +-- if vim.fn.filereadable(path) == 0 then return end +-- +-- local w = vim.uv.new_fs_event() +-- if not w then return end +-- +-- w:start( +-- path, {}, +-- vim.schedule_wrap(function(err, _, events) +-- if err or not events.change then return end +-- +-- -- 1. Stop any existing timer (cancel previous "half-finished" events) +-- if debounce_timer then +-- debounce_timer:stop() +-- +-- -- 2. Start a 500ms window. Logic only runs if NO more events happen in this time. +-- debounce_timer:start( 500, 0, +-- vim.schedule_wrap(function() +-- vim.notify('PIO: Config change detected. Refreshing...', vim.log.levels.INFO) +-- +-- pio_manager.refresh(function() +-- pio_generate_db() +-- -- 3. Only restart LSP if the pattern actually changed or DB was updated +-- lsp.lsp_restart('clangd') +-- end) +-- end) +-- ) +-- end +-- end) +-- ) +-- end +-- +-- ------------------------------------------------------------------------------------------------------ +-- -- INFO: 6. Exported setup function +-- return { +-- init = function() +-- local config = require('platformio').config +-- if config.lspClangd.enabled == true then +-- vim.notify('PIO setup initialize', vim.log.levels.INFO) +-- ---------------------------------------------------------------------------------------- +-- -- INFO: create clangd required files +-- ----------------------------------------------------------------------------------------- +-- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +-- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) +-- +-- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +-- boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) +-- -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) +-- -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') +-- +-- -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) +-- +-- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) +-- +-- boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) +-- -- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) +-- -- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) +-- --------------------------------------------------------------------------------- +-- +-- -- vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) +-- require('platformio.lspConfig.clangd') +-- if config.lspClangd.attach.enabled then +-- require('platformio.lspConfig.attach') +-- end +-- if vim.fn.filereadable(vim.fn.getcwd() .. '/platformio.ini') == 1 then +-- pio_manager.refresh(function() +-- pio_generate_db() +-- start_pio_watcher() +-- end) +-- end +-- end +-- end, +-- } diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 8f9b6f62..f40c7480 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -259,7 +259,8 @@ local pio_manager = (function() end if #_G.metadata.default_envs > 0 then _G.metadata.active_env = _G.metadata.default_envs[1] or '' - else + -- else + elseif _G.metadata.envs and #_G.metadata.envs > 0 then _G.metadata.active_env = next(_G.metadata.envs) or '' end From 8562aa34f3f2d01c524647eb5a66f981f79b04b2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 05:09:07 +0300 Subject: [PATCH 0688/1406] update --- lua/platformio/archived/pio_setup.lua | 968 +++++++++++++------------- lua/platformio/pio_setup.lua | 52 +- 2 files changed, 510 insertions(+), 510 deletions(-) diff --git a/lua/platformio/archived/pio_setup.lua b/lua/platformio/archived/pio_setup.lua index 8f9b6f62..f61f5c0c 100644 --- a/lua/platformio/archived/pio_setup.lua +++ b/lua/platformio/archived/pio_setup.lua @@ -1,484 +1,484 @@ -M = {} - -local misc = require('platformio.utils.misc') -local lsp = require('platformio.utils.lsp') -local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - --- lua/pio_setup.lua --- This module manages PlatformIO project integration, LSP toolchain detection, --- and automatic sysroot patching for standard library headers (, etc.) - -local debounce_timer = vim.uv.new_timer() - --- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) --- INFO: --- ============================================================================= --- UNIVERSAL TOOLCHAIN DETECTION --- ============================================================================= ---- stylua: ignore -local function get_sysroot_triplet(cc_compiler) - local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') - -- Early exit if path is nil or not a directory - if not bin_path or vim.fn.isdirectory(bin_path) == 0 then - return nil - end - - -- Normalize backslashes to forward slashes for cross-platform consistency - bin_path = bin_path:gsub('\\', '/') - local files = vim.fn.readdir(bin_path) - local triplet = nil - - -- Loop through files to find the compiler and extract the triplet - for _, name in ipairs(files) do - -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ - local match = name:match('^(.*)%-g[c%+][c%+]') - if match then - triplet = match - break - end - end - - -- Return nil if no compiler was found in the bin directory - if not triplet then - return nil - end - - -- toolchain_root is the parent of the 'bin' folder - local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') - -- sysroot folder is expected to have the same name as the triplet - local sysroot = toolchain_root .. '/' .. triplet - - -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) - -- Only return data if the sysroot folder actually exists on disk - if vim.fn.isdirectory(sysroot) == 1 then - return { - triplet = triplet, - sysroot = sysroot, - toolchain_root = toolchain_root, - query_driver = bin_path .. '/' .. triplet .. '-*', - } - end - return nil -end - - --- INFO: --- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag --- stylua: ignore -local function pio_generate_db() - vim.schedule(function() vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) end) - vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) - if obj.code ~= 0 then - vim.schedule(function() - if obj.code == 127 then - vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) - else - vim.notify('PIO Manager: Generating Compile Database failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) - end - end) - return - end - vim.schedule(function() vim.notify('PIO: Generating Compile Database successful', vim.log.levels.INFO) end) - end) -end - --- INFO: 1. The Core PIO Manager & Generic Extractor ---- stylua: ignore -local pio_manager = (function() - local cache = nil -- Stores the decoded platformio.ini JSON structure - -- INFO: - local function find_in_data(data, section_name, key_name) - -- Safety check: Ensure data is a valid table from a successful JSON decode - if type(data) ~= 'table' then - return nil - end - - for _, section in ipairs(data) do - -- Each section must be a table with at least 2 elements: [1]=name, [2]=content - if type(section) == 'table' and #section >= 2 then - local s_id = section[1] -- Section header string - local s_body = section[2] -- Table of key-value pairs - - if s_id == section_name and type(s_body) == 'table' then - for _, kv in ipairs(s_body) do - -- Each kv is a table: [1]=key, [2]=value - if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then - local val = kv[2] - -- Treat empty strings or empty tables as nil to trigger fallback logic - if val == nil or val == '' or (type(val) == 'table' and #val == 0) then - return nil - end - return val - end - end - end - end - end - return nil - end - - -- INFO: ASYNC REFRESH: Fetches the latest config from PlatformIO CLI - --- stylua: ignore - local function refresh(callback) - vim.schedule(function() - vim.notify('PIO: Fetching Config ...', vim.log.levels.INFO) - end) - - -- INFO: get project metadata - local function get_metadata(attempts, env) - local active_env = env or _G.metadata.active_env - vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(int_obj) - vim.schedule(function() - vim.notify('PIO: Fetching metadata ...', vim.log.levels.INFO) - end) - - if int_obj.code ~= 0 then - -- Schedule notification to avoid error in the system callback thread - vim.schedule(function() - if int_obj.code == 127 then - vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) - else - vim.notify('PIO Manager: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) - end - end) - return - end - - if int_obj.code == 0 and int_obj.stdout then - local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) - if ok and raw_data then - local _, data = next(raw_data) - if data then - local fallback_flags = {} - -- 1. Process Includes - if data.includes then - for category, paths in pairs(data.includes) do - -- If it's a toolchain path, use -isystem to suppress warnings - -- and tell clangd these are standard libraries - if category == 'toolchain' then - local flag = '-isystem' - for _, path in ipairs(paths) do - -- table.insert(fallback_flags, string.format('%q', flag)) - -- table.insert(fallback_flags, string.format('%q', path:gsub('\\', '/'))) - table.insert(fallback_flags, string.format('%q', flag .. path:gsub('\\', '/'))) - end - end - -- local flag = (category == 'toolchain') and '-isystem' or '-I' - -- for _, path in ipairs(paths) do - -- table.insert(fallback_flags, flag .. path) - -- end - end - end - -- 2. Process Defines - if data.defines then - for _, define in ipairs(data.defines) do - table.insert(fallback_flags, string.format('%q', '-D' .. define)) - end - end - - -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' - _G.metadata.cc_compiler = misc.normalize_path(data.cc_path) or '' - _G.metadata.fallback_flags = fallback_flags - - -- print(vim.inspect(_G.metadata)) - if callback then - vim.schedule(function() - vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) - callback() - end) - end - end - else - vim.schedule(function() - vim.notify('PIO: Syncing Environment failed', vim.log.levels.WARN) - end) - end - end - -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save - if attempts > 0 then - vim.defer_fn(function() - get_metadata(attempts - 1) - end, 500) - end - end) - end - - -- INFO: -- 1. Setup Base Paths - local home = os.getenv('HOME') or os.getenv('USERPROFILE') - -- INFO: -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) - local map = { - core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, - packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, - platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, - } - - -- INFO: 3. Try to get explicit value from platformio.ini - -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' - -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } - vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) - if ext_obj.code ~= 0 then - -- Schedule notification to avoid error in the system callback thread - vim.schedule(function() - if ext_obj.code == 127 then - vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) - else - vim.notify('PIO Manager: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) - end - end) - return - end - _G.metadata.core_dir = '' - _G.metadata.packages_dir = '' - _G.metadata.platforms_dir = '' - _G.metadata.active_env = '' - _G.metadata.default_envs = {} - _G.metadata.envs = {} - - local decoded = vim.json.decode(ext_obj.stdout) - for _, section in ipairs(decoded) do - if type(section) == 'table' and #section >= 2 then - local name, data = section[1], section[2] - -- 1. Extract Global PlatformIO Settings - if name == 'platformio' then - for _, kv in ipairs(data) do - local key, val = kv[1], kv[2] - if key ~= nil then - -- if _G.metadata[key] ~= nil then - _G.metadata[key] = val - end - end - -- 2. Extract all hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] - elseif name:match('^env:') then - local env_name = name:match('^env:(.+)') - _G.metadata.envs[env_name] = {} - for _, kv in ipairs(data) do - _G.metadata.envs[env_name][kv[1]] = kv[2] - end - end - end - end - if #_G.metadata.default_envs > 0 then - _G.metadata.active_env = _G.metadata.default_envs[1] or '' - else - _G.metadata.active_env = next(_G.metadata.envs) or '' - end - - for _, kv in ipairs(map) do - -- 4.0 Fallback Logic: INI -> Env Var -> Default - local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') - -- 5. Expand ${platformio.core_dir} - if type(result) == 'string' then - if result:find('${platformio.core_dir}', 1, true) then - result = result:gsub('%${platformio.core_dir}', _G.metadata.core_dir) - end - end - -- 6. Normalize Slashes for Windows - -- _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') - _G.metadata[kv.ini] = result:gsub('\\', '/'):gsub('//+', '/') - end - -- return _G.metadata[map[type].ini] - -- end - - if _G.metadata.active_env ~= '' then - vim.schedule(function() - vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) - end) - get_metadata(1, _G.metadata.active_env) - else - vim.schedule(function() - vim.notify('PIO: no [env:] found, add board first', vim.log.levels.ERROR) - end) - end - end) - end - - -- INFO: - return { - refresh = refresh, - -- INFO: - get = function(s, k) - if not cache then - return nil - end - local res = find_in_data(cache, s, k) - - -- FALLBACK: If default_envs is missing/empty, find the first hardware [env:xxx] block - if k == 'default_envs' and not res then - for _, section in ipairs(cache) do - if type(section) == 'table' and type(section[1]) == 'string' then - local name = section[1] - if name:find('^env:') then - local fallback = name:match('^env:(.+)') - if fallback then - vim.schedule(function() - vim.notify('PIO: default_envs empty. Using: ' .. fallback, vim.log.levels.INFO) - end) - return fallback - end - end - end - end - vim.schedule(function() - vim.notify('PIO: Config Error. Check platformio.ini no env', vim.log.levels.WARN) - end) - elseif k == 'default_envs' and res and type(res) == 'table' then - return res[1] - else - return res - end - end, - } -end)() - --- INFO: -function _G.get_pio_sdk_info() - local pio_info = { includes = {}, cc_compiler = '' } - if vim.fn.filereadable('platformio.ini') == 0 then - return nil - end - - local handle = io.popen('pio run -t envdump') - if not handle then - return nil - end - - local packages_dir, cc_name, toolchain_pkg = '', '', '' - - for line in handle:lines() do - -- 1. Get the global packages directory - packages_dir = packages_dir ~= '' and packages_dir or line:match("'PROJECT_PACKAGES_DIR': '([^']+)'") - - -- 2. Get the compiler executable name (e.g., riscv32-esp-elf-gcc) - cc_name = cc_name ~= '' and cc_name or line:match("'CC': '([^']+)'") - - -- 3. Find the specific toolchain package name from the PACKAGES list - -- Matches lines like "- toolchain-riscv32-esp @ 14.2.0" - local pkg = line:match('%- (toolchain%-[^ ]+)') - if pkg then - toolchain_pkg = pkg - end - - -- 4. Collect include paths - local path_list = line:match("'CPPPATH': %[(.+)%]") - if path_list then - for path in path_list:gmatch("'([^']+)'") do - table.insert(pio_info.includes, '-I' .. path) - end - end - end - handle:close() - - -- Construct the absolute path: //bin/ - if packages_dir and packages_dir ~= '' and toolchain_pkg and toolchain_pkg ~= '' and cc_name ~= '' then - local full_path = packages_dir .. '/' .. toolchain_pkg .. '/bin/' .. cc_name - if vim.fn.executable(full_path) == 1 then - pio_info.cc_compiler = full_path - end - end - - local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' - print('get_pio_sdk_info(): final=' .. final) - -- Normalize paths for the OS and ensure backslashes for Windows if needed - -- print(vim.inspect(_G.metadata)) - return (misc.normalize_path(final)) - -- return _G.metadata.query_driver - -- return pio_info -end - --- INFO: --- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync --- stylua: ignore -local function start_pio_watcher() - local dir_path = vim.uv.cwd() - if not dir_path then return end - - -- Create a directory watcher - local handle = vim.uv.new_fs_event() - if not handle then return end - - -- local last_trigger = 0 - -- Watch the directory for platformio.ini creation or changes - handle:start( - dir_path, - { - watch_entry = false, -- watch the file/dir itself - stat = false, -- use stat to detect changes (slower but more reliable on some FS) - recursive = false, -- watch subdirectories (if path is a directory) - }, - vim.schedule_wrap(function(err, filename, events) - if err or not events or not events.change then return end - -- Trigger only if the changed file is platformio.ini - if filename == 'platformio.ini' and (events.change or events.rename) then - -- -- ignore events within time - -- local current_time = vim.uv.now() - -- -- IGNORE events if they happen within 100ms of the last one - -- if current_time - last_trigger < 100 then - -- return - -- end - -- last_trigger = current_time - - if debounce_timer then - debounce_timer:stop() - debounce_timer:start( - 500, - 0, - vim.schedule_wrap(function() - pio_manager.refresh(function() - -- vim.schedule(function() - local status, data = pcall(get_sysroot_triplet, _G.metadata.cc_compiler) - if status and data and data.triplet and data.triplet ~= '' then - _G.metadata.triplet = data.triplet - _G.metadata.sysroot = data.sysroot - _G.metadata.query_driver = data.query_driver - _G.metadata.toolchain = data.toolchain_root - end - -- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) - - pio_generate_db() - lsp.lsp_restart('clangd') - -- end) - end) end)) end end end)) -end ------------------------------------------------------------------------------------------------------- --- INFO: 6. Exported setup function -function M.init() - local config = require('platformio').config - if config.lspClangd.enabled == true then - vim.notify('PIO setup initialize', vim.log.levels.INFO) - ---------------------------------------------------------------------------------------- - -- INFO: create clangd required files - ----------------------------------------------------------------------------------------- - boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) - -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - -- boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) - -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) - -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') - boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) - boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) - --------------------------------------------------------------------------------- - - require('platformio.lspConfig.clangd') - if config.lspClangd.attach.enabled then - require('platformio.lspConfig.attach') - end - - -- Always start the watcher so it can catch a future 'pio init' - start_pio_watcher() - - -- If the file already exists, do an initial sync - if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then - pio_manager.refresh(function() - -- vim.schedule(function() - -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) - pio_generate_db() - lsp.lsp_restart('clangd') - -- end) - end) - end - end -end - -return M +-- M = {} +-- +-- local misc = require('platformio.utils.misc') +-- local lsp = require('platformio.utils.lsp') +-- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +-- +-- -- lua/pio_setup.lua +-- -- This module manages PlatformIO project integration, LSP toolchain detection, +-- -- and automatic sysroot patching for standard library headers (, etc.) +-- +-- local debounce_timer = vim.uv.new_timer() +-- +-- -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) +-- -- INFO: +-- -- ============================================================================= +-- -- UNIVERSAL TOOLCHAIN DETECTION +-- -- ============================================================================= +-- --- stylua: ignore +-- local function get_sysroot_triplet(cc_compiler) +-- local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') +-- -- Early exit if path is nil or not a directory +-- if not bin_path or vim.fn.isdirectory(bin_path) == 0 then +-- return nil +-- end +-- +-- -- Normalize backslashes to forward slashes for cross-platform consistency +-- bin_path = bin_path:gsub('\\', '/') +-- local files = vim.fn.readdir(bin_path) +-- local triplet = nil +-- +-- -- Loop through files to find the compiler and extract the triplet +-- for _, name in ipairs(files) do +-- -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ +-- local match = name:match('^(.*)%-g[c%+][c%+]') +-- if match then +-- triplet = match +-- break +-- end +-- end +-- +-- -- Return nil if no compiler was found in the bin directory +-- if not triplet then +-- return nil +-- end +-- +-- -- toolchain_root is the parent of the 'bin' folder +-- local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') +-- -- sysroot folder is expected to have the same name as the triplet +-- local sysroot = toolchain_root .. '/' .. triplet +-- +-- -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) +-- -- Only return data if the sysroot folder actually exists on disk +-- if vim.fn.isdirectory(sysroot) == 1 then +-- return { +-- triplet = triplet, +-- sysroot = sysroot, +-- toolchain_root = toolchain_root, +-- query_driver = bin_path .. '/' .. triplet .. '-*', +-- } +-- end +-- return nil +-- end +-- +-- +-- -- INFO: +-- -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag +-- -- stylua: ignore +-- local function pio_generate_db() +-- vim.schedule(function() vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) end) +-- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) +-- if obj.code ~= 0 then +-- vim.schedule(function() +-- if obj.code == 127 then +-- vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) +-- else +-- vim.notify('PIO Manager: Generating Compile Database failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) +-- end +-- end) +-- return +-- end +-- vim.schedule(function() vim.notify('PIO: Generating Compile Database successful', vim.log.levels.INFO) end) +-- end) +-- end +-- +-- -- INFO: 1. The Core PIO Manager & Generic Extractor +-- --- stylua: ignore +-- local pio_manager = (function() +-- local cache = nil -- Stores the decoded platformio.ini JSON structure +-- -- INFO: +-- local function find_in_data(data, section_name, key_name) +-- -- Safety check: Ensure data is a valid table from a successful JSON decode +-- if type(data) ~= 'table' then +-- return nil +-- end +-- +-- for _, section in ipairs(data) do +-- -- Each section must be a table with at least 2 elements: [1]=name, [2]=content +-- if type(section) == 'table' and #section >= 2 then +-- local s_id = section[1] -- Section header string +-- local s_body = section[2] -- Table of key-value pairs +-- +-- if s_id == section_name and type(s_body) == 'table' then +-- for _, kv in ipairs(s_body) do +-- -- Each kv is a table: [1]=key, [2]=value +-- if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then +-- local val = kv[2] +-- -- Treat empty strings or empty tables as nil to trigger fallback logic +-- if val == nil or val == '' or (type(val) == 'table' and #val == 0) then +-- return nil +-- end +-- return val +-- end +-- end +-- end +-- end +-- end +-- return nil +-- end +-- +-- -- INFO: ASYNC REFRESH: Fetches the latest config from PlatformIO CLI +-- --- stylua: ignore +-- local function refresh(callback) +-- vim.schedule(function() +-- vim.notify('PIO: Fetching Config ...', vim.log.levels.INFO) +-- end) +-- +-- -- INFO: get project metadata +-- local function get_metadata(attempts, env) +-- local active_env = env or _G.metadata.active_env +-- vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(int_obj) +-- vim.schedule(function() +-- vim.notify('PIO: Fetching metadata ...', vim.log.levels.INFO) +-- end) +-- +-- if int_obj.code ~= 0 then +-- -- Schedule notification to avoid error in the system callback thread +-- vim.schedule(function() +-- if int_obj.code == 127 then +-- vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) +-- else +-- vim.notify('PIO Manager: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) +-- end +-- end) +-- return +-- end +-- +-- if int_obj.code == 0 and int_obj.stdout then +-- local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) +-- if ok and raw_data then +-- local _, data = next(raw_data) +-- if data then +-- local fallback_flags = {} +-- -- 1. Process Includes +-- if data.includes then +-- for category, paths in pairs(data.includes) do +-- -- If it's a toolchain path, use -isystem to suppress warnings +-- -- and tell clangd these are standard libraries +-- if category == 'toolchain' then +-- local flag = '-isystem' +-- for _, path in ipairs(paths) do +-- -- table.insert(fallback_flags, string.format('%q', flag)) +-- -- table.insert(fallback_flags, string.format('%q', path:gsub('\\', '/'))) +-- table.insert(fallback_flags, string.format('%q', flag .. path:gsub('\\', '/'))) +-- end +-- end +-- -- local flag = (category == 'toolchain') and '-isystem' or '-I' +-- -- for _, path in ipairs(paths) do +-- -- table.insert(fallback_flags, flag .. path) +-- -- end +-- end +-- end +-- -- 2. Process Defines +-- if data.defines then +-- for _, define in ipairs(data.defines) do +-- table.insert(fallback_flags, string.format('%q', '-D' .. define)) +-- end +-- end +-- +-- -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' +-- _G.metadata.cc_compiler = misc.normalize_path(data.cc_path) or '' +-- _G.metadata.fallback_flags = fallback_flags +-- +-- -- print(vim.inspect(_G.metadata)) +-- if callback then +-- vim.schedule(function() +-- vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) +-- callback() +-- end) +-- end +-- end +-- else +-- vim.schedule(function() +-- vim.notify('PIO: Syncing Environment failed', vim.log.levels.WARN) +-- end) +-- end +-- end +-- -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save +-- if attempts > 0 then +-- vim.defer_fn(function() +-- get_metadata(attempts - 1) +-- end, 500) +-- end +-- end) +-- end +-- +-- -- INFO: -- 1. Setup Base Paths +-- local home = os.getenv('HOME') or os.getenv('USERPROFILE') +-- -- INFO: -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) +-- local map = { +-- core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, +-- packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, +-- platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, +-- } +-- +-- -- INFO: 3. Try to get explicit value from platformio.ini +-- -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' +-- -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } +-- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) +-- if ext_obj.code ~= 0 then +-- -- Schedule notification to avoid error in the system callback thread +-- vim.schedule(function() +-- if ext_obj.code == 127 then +-- vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) +-- else +-- vim.notify('PIO Manager: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) +-- end +-- end) +-- return +-- end +-- _G.metadata.core_dir = '' +-- _G.metadata.packages_dir = '' +-- _G.metadata.platforms_dir = '' +-- _G.metadata.active_env = '' +-- _G.metadata.default_envs = {} +-- _G.metadata.envs = {} +-- +-- local decoded = vim.json.decode(ext_obj.stdout) +-- for _, section in ipairs(decoded) do +-- if type(section) == 'table' and #section >= 2 then +-- local name, data = section[1], section[2] +-- -- 1. Extract Global PlatformIO Settings +-- if name == 'platformio' then +-- for _, kv in ipairs(data) do +-- local key, val = kv[1], kv[2] +-- if key ~= nil then +-- -- if _G.metadata[key] ~= nil then +-- _G.metadata[key] = val +-- end +-- end +-- -- 2. Extract all hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] +-- elseif name:match('^env:') then +-- local env_name = name:match('^env:(.+)') +-- _G.metadata.envs[env_name] = {} +-- for _, kv in ipairs(data) do +-- _G.metadata.envs[env_name][kv[1]] = kv[2] +-- end +-- end +-- end +-- end +-- if #_G.metadata.default_envs > 0 then +-- _G.metadata.active_env = _G.metadata.default_envs[1] or '' +-- else +-- _G.metadata.active_env = next(_G.metadata.envs) or '' +-- end +-- +-- for _, kv in ipairs(map) do +-- -- 4.0 Fallback Logic: INI -> Env Var -> Default +-- local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') +-- -- 5. Expand ${platformio.core_dir} +-- if type(result) == 'string' then +-- if result:find('${platformio.core_dir}', 1, true) then +-- result = result:gsub('%${platformio.core_dir}', _G.metadata.core_dir) +-- end +-- end +-- -- 6. Normalize Slashes for Windows +-- -- _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') +-- _G.metadata[kv.ini] = result:gsub('\\', '/'):gsub('//+', '/') +-- end +-- -- return _G.metadata[map[type].ini] +-- -- end +-- +-- if _G.metadata.active_env ~= '' then +-- vim.schedule(function() +-- vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) +-- end) +-- get_metadata(1, _G.metadata.active_env) +-- else +-- vim.schedule(function() +-- vim.notify('PIO: no [env:] found, add board first', vim.log.levels.ERROR) +-- end) +-- end +-- end) +-- end +-- +-- -- INFO: +-- return { +-- refresh = refresh, +-- -- INFO: +-- get = function(s, k) +-- if not cache then +-- return nil +-- end +-- local res = find_in_data(cache, s, k) +-- +-- -- FALLBACK: If default_envs is missing/empty, find the first hardware [env:xxx] block +-- if k == 'default_envs' and not res then +-- for _, section in ipairs(cache) do +-- if type(section) == 'table' and type(section[1]) == 'string' then +-- local name = section[1] +-- if name:find('^env:') then +-- local fallback = name:match('^env:(.+)') +-- if fallback then +-- vim.schedule(function() +-- vim.notify('PIO: default_envs empty. Using: ' .. fallback, vim.log.levels.INFO) +-- end) +-- return fallback +-- end +-- end +-- end +-- end +-- vim.schedule(function() +-- vim.notify('PIO: Config Error. Check platformio.ini no env', vim.log.levels.WARN) +-- end) +-- elseif k == 'default_envs' and res and type(res) == 'table' then +-- return res[1] +-- else +-- return res +-- end +-- end, +-- } +-- end)() +-- +-- -- INFO: +-- function _G.get_pio_sdk_info() +-- local pio_info = { includes = {}, cc_compiler = '' } +-- if vim.fn.filereadable('platformio.ini') == 0 then +-- return nil +-- end +-- +-- local handle = io.popen('pio run -t envdump') +-- if not handle then +-- return nil +-- end +-- +-- local packages_dir, cc_name, toolchain_pkg = '', '', '' +-- +-- for line in handle:lines() do +-- -- 1. Get the global packages directory +-- packages_dir = packages_dir ~= '' and packages_dir or line:match("'PROJECT_PACKAGES_DIR': '([^']+)'") +-- +-- -- 2. Get the compiler executable name (e.g., riscv32-esp-elf-gcc) +-- cc_name = cc_name ~= '' and cc_name or line:match("'CC': '([^']+)'") +-- +-- -- 3. Find the specific toolchain package name from the PACKAGES list +-- -- Matches lines like "- toolchain-riscv32-esp @ 14.2.0" +-- local pkg = line:match('%- (toolchain%-[^ ]+)') +-- if pkg then +-- toolchain_pkg = pkg +-- end +-- +-- -- 4. Collect include paths +-- local path_list = line:match("'CPPPATH': %[(.+)%]") +-- if path_list then +-- for path in path_list:gmatch("'([^']+)'") do +-- table.insert(pio_info.includes, '-I' .. path) +-- end +-- end +-- end +-- handle:close() +-- +-- -- Construct the absolute path: //bin/ +-- if packages_dir and packages_dir ~= '' and toolchain_pkg and toolchain_pkg ~= '' and cc_name ~= '' then +-- local full_path = packages_dir .. '/' .. toolchain_pkg .. '/bin/' .. cc_name +-- if vim.fn.executable(full_path) == 1 then +-- pio_info.cc_compiler = full_path +-- end +-- end +-- +-- local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' +-- print('get_pio_sdk_info(): final=' .. final) +-- -- Normalize paths for the OS and ensure backslashes for Windows if needed +-- -- print(vim.inspect(_G.metadata)) +-- return (misc.normalize_path(final)) +-- -- return _G.metadata.query_driver +-- -- return pio_info +-- end +-- +-- -- INFO: +-- -- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync +-- -- stylua: ignore +-- local function start_pio_watcher() +-- local dir_path = vim.uv.cwd() +-- if not dir_path then return end +-- +-- -- Create a directory watcher +-- local handle = vim.uv.new_fs_event() +-- if not handle then return end +-- +-- -- local last_trigger = 0 +-- -- Watch the directory for platformio.ini creation or changes +-- handle:start( +-- dir_path, +-- { +-- watch_entry = false, -- watch the file/dir itself +-- stat = false, -- use stat to detect changes (slower but more reliable on some FS) +-- recursive = false, -- watch subdirectories (if path is a directory) +-- }, +-- vim.schedule_wrap(function(err, filename, events) +-- if err or not events or not events.change then return end +-- -- Trigger only if the changed file is platformio.ini +-- if filename == 'platformio.ini' and (events.change or events.rename) then +-- -- -- ignore events within time +-- -- local current_time = vim.uv.now() +-- -- -- IGNORE events if they happen within 100ms of the last one +-- -- if current_time - last_trigger < 100 then +-- -- return +-- -- end +-- -- last_trigger = current_time +-- +-- if debounce_timer then +-- debounce_timer:stop() +-- debounce_timer:start( +-- 500, +-- 0, +-- vim.schedule_wrap(function() +-- pio_manager.refresh(function() +-- -- vim.schedule(function() +-- local status, data = pcall(get_sysroot_triplet, _G.metadata.cc_compiler) +-- if status and data and data.triplet and data.triplet ~= '' then +-- _G.metadata.triplet = data.triplet +-- _G.metadata.sysroot = data.sysroot +-- _G.metadata.query_driver = data.query_driver +-- _G.metadata.toolchain = data.toolchain_root +-- end +-- -- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) +-- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +-- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) +-- +-- pio_generate_db() +-- lsp.lsp_restart('clangd') +-- -- end) +-- end) end)) end end end)) +-- end +-- ------------------------------------------------------------------------------------------------------ +-- -- INFO: 6. Exported setup function +-- function M.init() +-- local config = require('platformio').config +-- if config.lspClangd.enabled == true then +-- vim.notify('PIO setup initialize', vim.log.levels.INFO) +-- ---------------------------------------------------------------------------------------- +-- -- INFO: create clangd required files +-- ----------------------------------------------------------------------------------------- +-- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) +-- -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +-- -- boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) +-- -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) +-- -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') +-- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) +-- boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) +-- --------------------------------------------------------------------------------- +-- +-- require('platformio.lspConfig.clangd') +-- if config.lspClangd.attach.enabled then +-- require('platformio.lspConfig.attach') +-- end +-- +-- -- Always start the watcher so it can catch a future 'pio init' +-- start_pio_watcher() +-- +-- -- If the file already exists, do an initial sync +-- if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then +-- pio_manager.refresh(function() +-- -- vim.schedule(function() +-- -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) +-- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) +-- pio_generate_db() +-- lsp.lsp_restart('clangd') +-- -- end) +-- end) +-- end +-- end +-- end +-- +-- return M diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index f40c7480..e6dc5b8f 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -71,9 +71,9 @@ local function pio_generate_db() if obj.code ~= 0 then vim.schedule(function() if obj.code == 127 then - vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + vim.notify("PIO Manager db: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else - vim.notify('PIO Manager: Generating Compile Database failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + vim.notify('PIO Manager db: Generating Compile Database failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) end end) return @@ -136,9 +136,9 @@ local pio_manager = (function() -- Schedule notification to avoid error in the system callback thread vim.schedule(function() if int_obj.code == 127 then - vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + vim.notify("PIO Manager metadata: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else - vim.notify('PIO Manager: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + vim.notify('PIO Manager metadata: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) end end) return @@ -149,7 +149,7 @@ local pio_manager = (function() if ok and raw_data then local _, data = next(raw_data) if data then - local fallback_flags = {} + local fallbackFlags = {} -- 1. Process Includes if data.includes then for category, paths in pairs(data.includes) do @@ -158,27 +158,28 @@ local pio_manager = (function() if category == 'toolchain' then local flag = '-isystem' for _, path in ipairs(paths) do - -- table.insert(fallback_flags, string.format('%q', flag)) - -- table.insert(fallback_flags, string.format('%q', path:gsub('\\', '/'))) - table.insert(fallback_flags, string.format('%q', flag .. path:gsub('\\', '/'))) + -- table.insert(fallbackFlags, string.format('%q', flag)) + -- table.insert(fallbackFlags, string.format('%q', path:gsub('\\', '/'))) + table.insert(fallbackFlags, string.format('%q', flag .. path:gsub('\\', '/'))) end end -- local flag = (category == 'toolchain') and '-isystem' or '-I' -- for _, path in ipairs(paths) do - -- table.insert(fallback_flags, flag .. path) + -- table.insert(fallbackFlags, flag .. path) -- end end end -- 2. Process Defines if data.defines then for _, define in ipairs(data.defines) do - table.insert(fallback_flags, string.format('%q', '-D' .. define)) + table.insert(fallbackFlags, string.format('%q', '-D' .. define)) end end + -- get [cc_compiler]and [falbackFlags] -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' _G.metadata.cc_compiler = misc.normalize_path(data.cc_path) or '' - _G.metadata.fallback_flags = fallback_flags + _G.metadata.fallbackFlags = fallbackFlags -- print(vim.inspect(_G.metadata)) if callback then @@ -203,16 +204,10 @@ local pio_manager = (function() end) end - -- INFO: -- 1. Setup Base Paths + -- INFO: Setup Base Paths local home = os.getenv('HOME') or os.getenv('USERPROFILE') - -- INFO: -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) - local map = { - core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, - packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, - platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, - } - -- INFO: 3. Try to get explicit value from platformio.ini + -- INFO: Try to get explicit value from platformio.ini -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) @@ -220,9 +215,9 @@ local pio_manager = (function() -- Schedule notification to avoid error in the system callback thread vim.schedule(function() if ext_obj.code == 127 then - vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + vim.notify("PIO Manager config: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else - vim.notify('PIO Manager: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + vim.notify('PIO Manager config: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) end end) return @@ -238,7 +233,7 @@ local pio_manager = (function() for _, section in ipairs(decoded) do if type(section) == 'table' and #section >= 2 then local name, data = section[1], section[2] - -- 1. Extract Global PlatformIO Settings + -- 1. Extract Global PlatformIO Settings if available [core_dir][packages_dir][platforms_dir][default_envs] if name == 'platformio' then for _, kv in ipairs(data) do local key, val = kv[1], kv[2] @@ -247,7 +242,7 @@ local pio_manager = (function() _G.metadata[key] = val end end - -- 2. Extract all hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] + -- 2. Extract all hardware [envs] like [env:seeed_xiao_esp32c3], skipping generic [env] elseif name:match('^env:') then local env_name = name:match('^env:(.+)') _G.metadata.envs[env_name] = {} @@ -257,13 +252,19 @@ local pio_manager = (function() end end end + -- assign [active_env] if #_G.metadata.default_envs > 0 then _G.metadata.active_env = _G.metadata.default_envs[1] or '' - -- else - elseif _G.metadata.envs and #_G.metadata.envs > 0 then + elseif _G.metadata.envs and next(_G.metadata.envs) ~= '' then _G.metadata.active_env = next(_G.metadata.envs) or '' end + -- INFO: -- Define Mapping (key in INI, Env Var, Default Subfolder) + local map = { + core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, + packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, + platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, + } for _, kv in ipairs(map) do -- 4.0 Fallback Logic: INI -> Env Var -> Default local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') @@ -473,7 +474,6 @@ function M.init() pio_manager.refresh(function() -- vim.schedule(function() -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) pio_generate_db() lsp.lsp_restart('clangd') -- end) From 6bdff4a8ab85c2190342691151e42b6f86a716a3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 06:43:07 +0300 Subject: [PATCH 0689/1406] update --- lua/platformio/archived/pio_setup.lua | 6 +- lua/platformio/archived/pio_setupold.lua | 6 +- lua/platformio/archived/piolsp.lua | 2 +- lua/platformio/{lspConfig => lsp}/attach.lua | 2 +- lua/platformio/{lspConfig => lsp}/clangd.lua | 17 +--- lua/platformio/{lspConfig => lsp}/keymaps.lua | 0 lua/platformio/lsp/tools.lua | 16 ++++ lua/platformio/metadata.lua | 95 +++++++++++++++++++ lua/platformio/pioCommands.lua | 2 +- lua/platformio/pio_setup.lua | 28 +++++- lua/platformio/utils/pio.lua | 2 +- pio_setup.lua | 6 +- 12 files changed, 150 insertions(+), 32 deletions(-) rename lua/platformio/{lspConfig => lsp}/attach.lua (96%) rename lua/platformio/{lspConfig => lsp}/clangd.lua (94%) rename lua/platformio/{lspConfig => lsp}/keymaps.lua (100%) create mode 100644 lua/platformio/lsp/tools.lua create mode 100644 lua/platformio/metadata.lua diff --git a/lua/platformio/archived/pio_setup.lua b/lua/platformio/archived/pio_setup.lua index f61f5c0c..05203705 100644 --- a/lua/platformio/archived/pio_setup.lua +++ b/lua/platformio/archived/pio_setup.lua @@ -1,7 +1,7 @@ -- M = {} -- -- local misc = require('platformio.utils.misc') --- local lsp = require('platformio.utils.lsp') +-- local lsp = require('platformio.lsp.tools') -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -- -- -- lua/pio_setup.lua @@ -459,9 +459,9 @@ -- boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) -- --------------------------------------------------------------------------------- -- --- require('platformio.lspConfig.clangd') +-- require('platformio.lsp.clangd') -- if config.lspClangd.attach.enabled then --- require('platformio.lspConfig.attach') +-- require('platformio.lsp.attach') -- end -- -- -- Always start the watcher so it can catch a future 'pio init' diff --git a/lua/platformio/archived/pio_setupold.lua b/lua/platformio/archived/pio_setupold.lua index 7f6be736..d4ec21df 100644 --- a/lua/platformio/archived/pio_setupold.lua +++ b/lua/platformio/archived/pio_setupold.lua @@ -1,5 +1,5 @@ -- local misc = require('platformio.utils.misc') --- local lsp = require('platformio.utils.lsp') +-- local lsp = require('platformio.lsp.tools') -- -- local debounce_timer = vim.uv.new_timer() -- @@ -262,9 +262,9 @@ -- --------------------------------------------------------------------------------- -- -- -- vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) --- require('platformio.lspConfig.clangd') +-- require('platformio.lsp.clangd') -- if config.lspClangd.attach.enabled then --- require('platformio.lspConfig.attach') +-- require('platformio.lsp.attach') -- end -- if vim.fn.filereadable(vim.fn.getcwd() .. '/platformio.ini') == 1 then -- pio_manager.refresh(function() diff --git a/lua/platformio/archived/piolsp.lua b/lua/platformio/archived/piolsp.lua index c0c10560..42faa97f 100644 --- a/lua/platformio/archived/piolsp.lua +++ b/lua/platformio/archived/piolsp.lua @@ -1,6 +1,6 @@ local M = {} -local lsp = require('platformio.utils.lsp') +local lsp = require('platformio.lsp.tools') -- stylua: ignore function M.piolsp() diff --git a/lua/platformio/lspConfig/attach.lua b/lua/platformio/lsp/attach.lua similarity index 96% rename from lua/platformio/lspConfig/attach.lua rename to lua/platformio/lsp/attach.lua index 2a573853..aa804083 100644 --- a/lua/platformio/lspConfig/attach.lua +++ b/lua/platformio/lsp/attach.lua @@ -92,7 +92,7 @@ vim.api.nvim_create_autocmd('LspAttach', { ------------------------------------------------------------------ local config = require('platformio').config if config.lspClangd.attach.keymaps then - local lspkeymaps = require('platformio.lspConfig.keymaps') + local lspkeymaps = require('platformio.lsp.keymaps') lspkeymaps.lspKeymaps(client, bufnr) end end diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lsp/clangd.lua similarity index 94% rename from lua/platformio/lspConfig/clangd.lua rename to lua/platformio/lsp/clangd.lua index a39b502c..b5b10c83 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -1,19 +1,4 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -_G.metadata = { - envs = {}, - active_env = '', - default_envs = {}, - core_dir = '', - packages_dir = '', - platforms_dir = '', - query_driver = '', - cc_compiler = '', - triplet = '', - toolchain = '', - sysroot = '', - fallbackFlags = {}, -} - local ok, result ok, result = pcall(require, 'fidget') if ok then @@ -276,5 +261,5 @@ local pyrefly = { vim.lsp.config('pyrefly', pyrefly) -- restart lsp --- require('platformio.utils.lsp').lsp_restart('clangd') +-- require('platformio.lsp.tools').lsp_restart('clangd') ---------------------------------------------------------------------------------- diff --git a/lua/platformio/lspConfig/keymaps.lua b/lua/platformio/lsp/keymaps.lua similarity index 100% rename from lua/platformio/lspConfig/keymaps.lua rename to lua/platformio/lsp/keymaps.lua diff --git a/lua/platformio/lsp/tools.lua b/lua/platformio/lsp/tools.lua new file mode 100644 index 00000000..52ba6bbe --- /dev/null +++ b/lua/platformio/lsp/tools.lua @@ -0,0 +1,16 @@ +local M = {} + +--- stylua: ignore +function M.lsp_restart(name) + -- vim.schedule_wrap(function() + vim.notify('LSP restart.', vim.log.levels.WARN) + local clangConfig = _G.get_clangd_config() + -- print(vim.inspect(clangConfig)) + vim.lsp.config(name, clangConfig) + vim.lsp.enable(name, false) + vim.lsp.enable(name, true) + vim.cmd('checktime') + -- end) +end + +return M diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua new file mode 100644 index 00000000..2c6200e5 --- /dev/null +++ b/lua/platformio/metadata.lua @@ -0,0 +1,95 @@ +-- Global metadata initialization +_G.metadata = { + envs = {}, + active_env = '', + default_envs = {}, + core_dir = '', + packages_dir = '', + platforms_dir = '', + query_driver = '', + cc_compiler = '', + triplet = '', + toolchain = '', + sysroot = '', + fallbackFlags = {}, +} + +local M = {} +local last_saved_hash = nil +local config_path = vim.fn.getcwd() .. '/.project_config.json' + +-- 1. Optimized Save Function +function M.save_project_config(quiet) + if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then + return + end + + local current_data = vim.json.encode(_G.metadata) + local current_hash = vim.hash(current_data) -- Inline hashing + + -- Only write to disk if data actually changed + if current_hash ~= last_saved_hash then + local file = io.open(config_path, 'w') + if file then + file:write(current_data) + file:close() + last_saved_hash = current_hash + + if not quiet then + vim.notify('Project settings synced to disk', vim.log.levels.INFO, { + title = 'PlatformIO', + render = 'compact', + }) + end + end + end +end + +-- 2. Robust Load Function (Startup) +function M.load_project_config() + if vim.fn.filereadable(config_path) == 1 then + local file = io.open(config_path, 'r') + if file then + local content = file:read('*a') + file:close() + + local ok, decoded = pcall(vim.json.decode, content) + if ok and decoded then + _G.metadata = decoded + last_saved_hash = vim.hash(content) + vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { + title = 'PlatformIO Loaded', + }) + end + end + end +end + +-- 3. Environment Switcher UI +function M.switch_env() + if not _G.metadata.envs or next(_G.metadata.envs) == nil then + vim.notify('No environments found. Run PlatformIO Refresh first.', vim.log.levels.WARN) + return + end + + local options = vim.tbl_keys(_G.metadata.envs) + table.sort(options) + + vim.ui.select(options, { + prompt = 'Select PlatformIO Environment:', + format_item = function(item) + local indicator = (item == _G.metadata.active_env) and '● ' or '○ ' + return indicator .. item + end, + }, function(choice) + if choice then + _G.metadata.active_env = choice + -- Save immediately on user selection + M.save_project_config(false) + -- Force LSP to pick up new fallbackFlags/defines + vim.cmd('LspRestart clangd') + end + end) +end + +return M diff --git a/lua/platformio/pioCommands.lua b/lua/platformio/pioCommands.lua index 647cabfd..533435d9 100644 --- a/lua/platformio/pioCommands.lua +++ b/lua/platformio/pioCommands.lua @@ -5,7 +5,7 @@ local ToggleTerminal = require('platformio.utils.term').ToggleTerminal -- stylua: ignore function M.piolsp() - require('platformio.utils.lsp').lsp_restart('clangd') + require('platformio.lsp.tools').lsp_restart('clangd') -- local ok, err = pcall(vim.cmd.lsp, { args = { 'restart' } }) -- if ok then vim.notify('LSP restarted' .. err) -- else vim.notify('LSP restart failed: ' .. err) end diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index e6dc5b8f..1770d57c 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,7 +1,7 @@ M = {} local misc = require('platformio.utils.misc') -local lsp = require('platformio.utils.lsp') +local lsp = require('platformio.lsp.tools') local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -- lua/pio_setup.lua @@ -449,6 +449,28 @@ function M.init() local config = require('platformio').config if config.lspClangd.enabled == true then vim.notify('PIO setup initialize', vim.log.levels.INFO) + + -- -- activate meta save and upload and env switch + -- local metadata = require('platformio.utils.metadata') + -- metadata.load_project_config() + -- + -- local pio_group = vim.api.nvim_create_augroup('PioPersist', { clear = true }) + -- vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { + -- group = pio_group, + -- callback = function() + -- -- Pass 'true' to save silently in the background + -- metadata.save_project_config(true) + -- end, + -- desc = 'Automatically save PlatformIO project metadata', + -- }) + -- -- 5. Keybindings + -- -- Switch Environment + -- vim.keymap.set('n', 'pe', metadata.switch_env, { desc = 'PlatformIO: Switch Environment' }) + -- -- Manual Status Check + -- vim.keymap.set('n', 'ps', function() + -- metadata().save_project_config(false) + -- end, { desc = 'PlatformIO: Status' }) + ---------------------------------------------------------------------------------------- -- INFO: create clangd required files ----------------------------------------------------------------------------------------- @@ -461,9 +483,9 @@ function M.init() boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) --------------------------------------------------------------------------------- - require('platformio.lspConfig.clangd') + require('platformio.lsp.clangd') if config.lspClangd.attach.enabled then - require('platformio.lspConfig.attach') + require('platformio.lsp.attach') end -- Always start the watcher so it can catch a future 'pio init' diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index e1fc5fb4..3aed7531 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -3,7 +3,7 @@ local M = {} M.selected_framework = '' local misc = require('platformio.utils.misc') -local lsp = require('platformio.utils.lsp') +local lsp = require('platformio..lsp.tools') ------------------------------------------------------ -- stylua: ignore diff --git a/pio_setup.lua b/pio_setup.lua index ab7f54d0..9293e0a9 100644 --- a/pio_setup.lua +++ b/pio_setup.lua @@ -1,7 +1,7 @@ -- M = {} -- -- local misc = require('platformio.utils.misc') --- local lsp = require('platformio.utils.lsp') +-- local lsp = require('platformio.lsp.tools') -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -- -- -- lua/pio_setup.lua @@ -461,9 +461,9 @@ -- boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) -- --------------------------------------------------------------------------------- -- --- require('platformio.lspConfig.clangd') +-- require('platformio.lsp.clangd') -- if config.lspClangd.attach.enabled then --- require('platformio.lspConfig.attach') +-- require('platformio.lsp.attach') -- end -- -- -- Always start the watcher so it can catch a future 'pio init' From 6c9dfc0c4692f9e8fba2c2ecb108c0785dc40a84 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 06:50:34 +0300 Subject: [PATCH 0690/1406] update --- lua/platformio/lsp/clangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua index b5b10c83..0372c60c 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -107,7 +107,7 @@ function _G.get_clangd_config() local f_flags, q_driver = '', '--query-driver=**' -- 2. Run your toolchain detection - if _G.metadata.cc_compiler ~= '' then + if _G.metadata and _G.metadata.cc_compiler and _G.metadata.cc_compiler ~= '' then if _G.metadata.triplet and _G.metadata.triplet ~= '' then local include_flags = table.concat(_G.metadata.fallbackFlags, ", ") f_flags = string.format([["-std=c++17", "--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, include_flags) From c4952e032a3137eed273505c1025138e05f4c680 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 07:06:16 +0300 Subject: [PATCH 0691/1406] update --- lua/platformio/metadata.lua | 30 +++++++++++++++--------------- lua/platformio/pio_setup.lua | 16 ++++++++++++++++ 2 files changed, 31 insertions(+), 15 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 2c6200e5..79381056 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,18 +1,18 @@ --- Global metadata initialization -_G.metadata = { - envs = {}, - active_env = '', - default_envs = {}, - core_dir = '', - packages_dir = '', - platforms_dir = '', - query_driver = '', - cc_compiler = '', - triplet = '', - toolchain = '', - sysroot = '', - fallbackFlags = {}, -} +-- -- Global metadata initialization +-- _G.metadata = { +-- envs = {}, +-- active_env = '', +-- default_envs = {}, +-- core_dir = '', +-- packages_dir = '', +-- platforms_dir = '', +-- query_driver = '', +-- cc_compiler = '', +-- triplet = '', +-- toolchain = '', +-- sysroot = '', +-- fallbackFlags = {}, +-- } local M = {} local last_saved_hash = nil diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 1770d57c..f6dc19d3 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -450,6 +450,22 @@ function M.init() if config.lspClangd.enabled == true then vim.notify('PIO setup initialize', vim.log.levels.INFO) + if not _G.metadata then + _G.metadata = { + envs = {}, + active_env = '', + default_envs = {}, + core_dir = '', + packages_dir = '', + platforms_dir = '', + query_driver = '', + cc_compiler = '', + triplet = '', + toolchain = '', + sysroot = '', + fallbackFlags = {}, + } + end -- -- activate meta save and upload and env switch -- local metadata = require('platformio.utils.metadata') -- metadata.load_project_config() From d6feb90c1a604ae3f57f69a6f301c9ee86637038 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 07:23:33 +0300 Subject: [PATCH 0692/1406] update --- lua/platformio/lsp/tools.lua | 59 ++++++++++++++++++ lua/platformio/pio_setup.lua | 114 +++++++++++++++++------------------ 2 files changed, 116 insertions(+), 57 deletions(-) diff --git a/lua/platformio/lsp/tools.lua b/lua/platformio/lsp/tools.lua index 52ba6bbe..24928209 100644 --- a/lua/platformio/lsp/tools.lua +++ b/lua/platformio/lsp/tools.lua @@ -1,9 +1,68 @@ local M = {} +local lsp = require('platformio.lsp.tools') +-- INFO: +-- ============================================================================= +-- UNIVERSAL TOOLCHAIN DETECTION +-- ============================================================================= +--- stylua: ignore +function M.get_sysroot_triplet(cc_compiler) + local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') + -- Early exit if path is nil or not a directory + if not bin_path or vim.fn.isdirectory(bin_path) == 0 then + return nil + end + + -- Normalize backslashes to forward slashes for cross-platform consistency + bin_path = bin_path:gsub('\\', '/') + local files = vim.fn.readdir(bin_path) + local triplet = nil + + -- Loop through files to find the compiler and extract the triplet + for _, name in ipairs(files) do + -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ + local match = name:match('^(.*)%-g[c%+][c%+]') + if match then + triplet = match + break + end + end + + -- Return nil if no compiler was found in the bin directory + if not triplet then + return nil + end + + -- toolchain_root is the parent of the 'bin' folder + local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') + -- sysroot folder is expected to have the same name as the triplet + local sysroot = toolchain_root .. '/' .. triplet + + -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) + -- Only return data if the sysroot folder actually exists on disk + if vim.fn.isdirectory(sysroot) == 1 then + return { + triplet = triplet, + sysroot = sysroot, + toolchain_root = toolchain_root, + query_driver = bin_path .. '/' .. triplet .. '-*', + } + end + return nil +end --- stylua: ignore function M.lsp_restart(name) -- vim.schedule_wrap(function() vim.notify('LSP restart.', vim.log.levels.WARN) + + local status, data = pcall(lsp.get_sysroot_triplet, _G.metadata.cc_compiler) + if status and data and data.triplet and data.triplet ~= '' then + _G.metadata.triplet = data.triplet + _G.metadata.sysroot = data.sysroot + _G.metadata.query_driver = data.query_driver + _G.metadata.toolchain = data.toolchain_root + end + local clangConfig = _G.get_clangd_config() -- print(vim.inspect(clangConfig)) vim.lsp.config(name, clangConfig) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index f6dc19d3..99f72a7f 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -11,56 +11,56 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local debounce_timer = vim.uv.new_timer() -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) --- INFO: --- ============================================================================= --- UNIVERSAL TOOLCHAIN DETECTION --- ============================================================================= ---- stylua: ignore -local function get_sysroot_triplet(cc_compiler) - local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') - -- Early exit if path is nil or not a directory - if not bin_path or vim.fn.isdirectory(bin_path) == 0 then - return nil - end - - -- Normalize backslashes to forward slashes for cross-platform consistency - bin_path = bin_path:gsub('\\', '/') - local files = vim.fn.readdir(bin_path) - local triplet = nil - - -- Loop through files to find the compiler and extract the triplet - for _, name in ipairs(files) do - -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ - local match = name:match('^(.*)%-g[c%+][c%+]') - if match then - triplet = match - break - end - end - - -- Return nil if no compiler was found in the bin directory - if not triplet then - return nil - end - - -- toolchain_root is the parent of the 'bin' folder - local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') - -- sysroot folder is expected to have the same name as the triplet - local sysroot = toolchain_root .. '/' .. triplet - - -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) - -- Only return data if the sysroot folder actually exists on disk - if vim.fn.isdirectory(sysroot) == 1 then - return { - triplet = triplet, - sysroot = sysroot, - toolchain_root = toolchain_root, - query_driver = bin_path .. '/' .. triplet .. '-*', - } - end - return nil -end - +-- -- INFO: +-- -- ============================================================================= +-- -- UNIVERSAL TOOLCHAIN DETECTION +-- -- ============================================================================= +-- --- stylua: ignore +-- local function get_sysroot_triplet(cc_compiler) +-- local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') +-- -- Early exit if path is nil or not a directory +-- if not bin_path or vim.fn.isdirectory(bin_path) == 0 then +-- return nil +-- end +-- +-- -- Normalize backslashes to forward slashes for cross-platform consistency +-- bin_path = bin_path:gsub('\\', '/') +-- local files = vim.fn.readdir(bin_path) +-- local triplet = nil +-- +-- -- Loop through files to find the compiler and extract the triplet +-- for _, name in ipairs(files) do +-- -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ +-- local match = name:match('^(.*)%-g[c%+][c%+]') +-- if match then +-- triplet = match +-- break +-- end +-- end +-- +-- -- Return nil if no compiler was found in the bin directory +-- if not triplet then +-- return nil +-- end +-- +-- -- toolchain_root is the parent of the 'bin' folder +-- local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') +-- -- sysroot folder is expected to have the same name as the triplet +-- local sysroot = toolchain_root .. '/' .. triplet +-- +-- -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) +-- -- Only return data if the sysroot folder actually exists on disk +-- if vim.fn.isdirectory(sysroot) == 1 then +-- return { +-- triplet = triplet, +-- sysroot = sysroot, +-- toolchain_root = toolchain_root, +-- query_driver = bin_path .. '/' .. triplet .. '-*', +-- } +-- end +-- return nil +-- end +-- -- INFO: -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag @@ -427,13 +427,13 @@ local function start_pio_watcher() vim.schedule_wrap(function() pio_manager.refresh(function() -- vim.schedule(function() - local status, data = pcall(get_sysroot_triplet, _G.metadata.cc_compiler) - if status and data and data.triplet and data.triplet ~= '' then - _G.metadata.triplet = data.triplet - _G.metadata.sysroot = data.sysroot - _G.metadata.query_driver = data.query_driver - _G.metadata.toolchain = data.toolchain_root - end + -- local status, data = pcall(lsp.get_sysroot_triplet, _G.metadata.cc_compiler) + -- if status and data and data.triplet and data.triplet ~= '' then + -- _G.metadata.triplet = data.triplet + -- _G.metadata.sysroot = data.sysroot + -- _G.metadata.query_driver = data.query_driver + -- _G.metadata.toolchain = data.toolchain_root + -- end -- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) From c6d3904882cf3cd7797d92285748dc162c4c87cf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 07:32:42 +0300 Subject: [PATCH 0693/1406] update --- lua/platformio/init.lua | 16 ++++++++++++++++ lua/platformio/pio_setup.lua | 16 ---------------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index 8482bb33..ebce66d3 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -184,6 +184,22 @@ function M.setup(user_config) require('platformio.piomenu').piomenu(M.config) -- Load the PIO setup logic + if not _G.metadata then + _G.metadata = { + envs = {}, + active_env = '', + default_envs = {}, + core_dir = '', + packages_dir = '', + platforms_dir = '', + query_driver = '', + cc_compiler = '', + triplet = '', + toolchain = '', + sysroot = '', + fallbackFlags = {}, + } + end require('platformio.pio_setup').init() end diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 99f72a7f..8905abdb 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -450,22 +450,6 @@ function M.init() if config.lspClangd.enabled == true then vim.notify('PIO setup initialize', vim.log.levels.INFO) - if not _G.metadata then - _G.metadata = { - envs = {}, - active_env = '', - default_envs = {}, - core_dir = '', - packages_dir = '', - platforms_dir = '', - query_driver = '', - cc_compiler = '', - triplet = '', - toolchain = '', - sysroot = '', - fallbackFlags = {}, - } - end -- -- activate meta save and upload and env switch -- local metadata = require('platformio.utils.metadata') -- metadata.load_project_config() From 10d5ce3728b9bf8a7c2329fa60ef3bd75d3b81b1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 07:50:07 +0300 Subject: [PATCH 0694/1406] update --- lua/platformio/init.lua | 33 +++++++++++++------------ lua/platformio/metadata.lua | 48 ++++++++++++++++++++++++++----------- 2 files changed, 50 insertions(+), 31 deletions(-) diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index ebce66d3..a23cb981 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -1,3 +1,19 @@ +_G.metadata = _G.metadata + or { + envs = {}, + active_env = '', + default_envs = {}, + core_dir = '', + packages_dir = '', + platforms_dir = '', + query_driver = '', + cc_compiler = '', + triplet = '', + toolchain = '', + sysroot = '', + fallbackFlags = {}, + } + local M = {} M.config = { lspClangd = { @@ -183,23 +199,6 @@ function M.setup(user_config) require('platformio.piomenu').piomenu(M.config) - -- Load the PIO setup logic - if not _G.metadata then - _G.metadata = { - envs = {}, - active_env = '', - default_envs = {}, - core_dir = '', - packages_dir = '', - platforms_dir = '', - query_driver = '', - cc_compiler = '', - triplet = '', - toolchain = '', - sysroot = '', - fallbackFlags = {}, - } - end require('platformio.pio_setup').init() end diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 79381056..adf78285 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,23 +1,43 @@ -- -- Global metadata initialization --- _G.metadata = { --- envs = {}, --- active_env = '', --- default_envs = {}, --- core_dir = '', --- packages_dir = '', --- platforms_dir = '', --- query_driver = '', --- cc_compiler = '', --- triplet = '', --- toolchain = '', --- sysroot = '', --- fallbackFlags = {}, --- } +-- Load the PIO setup logic +-- if not _G.metadata then +-- _G.metadata = { +-- envs = {}, +-- active_env = '', +-- default_envs = {}, +-- core_dir = '', +-- packages_dir = '', +-- platforms_dir = '', +-- query_driver = '', +-- cc_compiler = '', +-- triplet = '', +-- toolchain = '', +-- sysroot = '', +-- fallbackFlags = {}, +-- } +-- end +-- _G.metadata = _G.metadata +-- or { +-- envs = {}, +-- active_env = '', +-- default_envs = {}, +-- core_dir = '', +-- packages_dir = '', +-- platforms_dir = '', +-- query_driver = '', +-- cc_compiler = '', +-- triplet = '', +-- toolchain = '', +-- sysroot = '', +-- fallbackFlags = {}, +-- } local M = {} local last_saved_hash = nil local config_path = vim.fn.getcwd() .. '/.project_config.json' +M.metadata = _G.metadata + -- 1. Optimized Save Function function M.save_project_config(quiet) if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then From c001d75f6c260ad2426856c3dc18fa42005829ea Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 07:52:54 +0300 Subject: [PATCH 0695/1406] update --- lua/platformio/init.lua | 16 ---------------- lua/platformio/pio_setup.lua | 16 ++++++++++++++++ 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index a23cb981..1d07641c 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -1,19 +1,3 @@ -_G.metadata = _G.metadata - or { - envs = {}, - active_env = '', - default_envs = {}, - core_dir = '', - packages_dir = '', - platforms_dir = '', - query_driver = '', - cc_compiler = '', - triplet = '', - toolchain = '', - sysroot = '', - fallbackFlags = {}, - } - local M = {} M.config = { lspClangd = { diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 8905abdb..84446052 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,3 +1,19 @@ +_G.metadata = _G.metadata + or { + envs = {}, + active_env = '', + default_envs = {}, + core_dir = '', + packages_dir = '', + platforms_dir = '', + query_driver = '', + cc_compiler = '', + triplet = '', + toolchain = '', + sysroot = '', + fallbackFlags = {}, + } + M = {} local misc = require('platformio.utils.misc') From cfe8c426c0210cd815f343e6d22016b9339e37d9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 08:02:45 +0300 Subject: [PATCH 0696/1406] update --- lua/platformio/pio_setup.lua | 54 +++++++++++++++++++++++++----------- 1 file changed, 38 insertions(+), 16 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 84446052..d1d906ac 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,25 +1,45 @@ -_G.metadata = _G.metadata - or { - envs = {}, - active_env = '', - default_envs = {}, - core_dir = '', - packages_dir = '', - platforms_dir = '', - query_driver = '', - cc_compiler = '', - triplet = '', - toolchain = '', - sysroot = '', - fallbackFlags = {}, - } - +-- _G.metadata = _G.metadata +-- or { +-- envs = {}, +-- active_env = '', +-- default_envs = {}, +-- core_dir = '', +-- packages_dir = '', +-- platforms_dir = '', +-- query_driver = '', +-- cc_compiler = '', +-- triplet = '', +-- toolchain = '', +-- sysroot = '', +-- fallbackFlags = {}, +-- } +-- M = {} local misc = require('platformio.utils.misc') local lsp = require('platformio.lsp.tools') local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +-- This function ensures metadata is NEVER nil when you call it +local function get_meta() + if not _G.metadata then + _G.metadata = { + envs = {}, + active_env = '', + default_envs = {}, + core_dir = '', + packages_dir = '', + platforms_dir = '', + query_driver = '', + cc_compiler = '', + triplet = '', + toolchain = '', + sysroot = '', + fallbackFlags = {}, + } + end + return _G.metadata +end -- lua/pio_setup.lua -- This module manages PlatformIO project integration, LSP toolchain detection, -- and automatic sysroot patching for standard library headers (, etc.) @@ -466,6 +486,8 @@ function M.init() if config.lspClangd.enabled == true then vim.notify('PIO setup initialize', vim.log.levels.INFO) + get_meta() + -- -- activate meta save and upload and env switch -- local metadata = require('platformio.utils.metadata') -- metadata.load_project_config() From 706a4cf5ed2c346f1f1c4b8f99aa274a779f3a20 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 08:07:33 +0300 Subject: [PATCH 0697/1406] update --- lua/platformio/lsp/tools.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lsp/tools.lua b/lua/platformio/lsp/tools.lua index 24928209..f1741175 100644 --- a/lua/platformio/lsp/tools.lua +++ b/lua/platformio/lsp/tools.lua @@ -1,5 +1,5 @@ local M = {} -local lsp = require('platformio.lsp.tools') + -- INFO: -- ============================================================================= -- UNIVERSAL TOOLCHAIN DETECTION @@ -55,7 +55,7 @@ function M.lsp_restart(name) -- vim.schedule_wrap(function() vim.notify('LSP restart.', vim.log.levels.WARN) - local status, data = pcall(lsp.get_sysroot_triplet, _G.metadata.cc_compiler) + local status, data = pcall(M.get_sysroot_triplet, _G.metadata.cc_compiler) if status and data and data.triplet and data.triplet ~= '' then _G.metadata.triplet = data.triplet _G.metadata.sysroot = data.sysroot From b60671b60cd215ed301ecef9f6966c7dabaf5f9b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 08:16:29 +0300 Subject: [PATCH 0698/1406] update --- plugin/platformio.lua | 4 ---- 1 file changed, 4 deletions(-) diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 3bfb646e..bb042383 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -6,10 +6,6 @@ -- +: At least one argument. -- -1: Zero or one argument (like ?, explicitly). --- Load the PIO logic -local pio_setup = require('platformio.pio_setup') -pio_setup.init() - local misc = require('platformio.utils.misc') local pio = require('platformio.utils.pio') local piolsserial = require('platformio.piolsserial') From 0e4c2457e4f4e230e9c1d51885306182f69ccecc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 08:36:20 +0300 Subject: [PATCH 0699/1406] update --- lua/platformio/metadata.lua | 30 +++++++++++--- lua/platformio/pio_setup.lua | 80 ++++++++++-------------------------- 2 files changed, 47 insertions(+), 63 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index adf78285..45a533d1 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -34,9 +34,28 @@ local M = {} local last_saved_hash = nil -local config_path = vim.fn.getcwd() .. '/.project_config.json' +local config_path = vim.fn.getcwd() .. '/.pioConfig.json' -M.metadata = _G.metadata +-- This function ensures metadata is NEVER nil when you call it +local function get_meta() + if not _G.metadata then + _G.metadata = { + envs = {}, + active_env = '', + default_envs = {}, + core_dir = '', + packages_dir = '', + platforms_dir = '', + query_driver = '', + cc_compiler = '', + triplet = '', + toolchain = '', + sysroot = '', + fallbackFlags = {}, + } + end + -- return _G.metadata +end -- 1. Optimized Save Function function M.save_project_config(quiet) @@ -77,9 +96,10 @@ function M.load_project_config() if ok and decoded then _G.metadata = decoded last_saved_hash = vim.hash(content) - vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { - title = 'PlatformIO Loaded', - }) + vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { title = 'PlatformIO: .pioCongig.json Loaded' }) + else + get_meta() + vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { title = 'PlatformIO: defautl Loaded' }) end end end diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index d1d906ac..df3d27d0 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,45 +1,9 @@ --- _G.metadata = _G.metadata --- or { --- envs = {}, --- active_env = '', --- default_envs = {}, --- core_dir = '', --- packages_dir = '', --- platforms_dir = '', --- query_driver = '', --- cc_compiler = '', --- triplet = '', --- toolchain = '', --- sysroot = '', --- fallbackFlags = {}, --- } --- M = {} local misc = require('platformio.utils.misc') local lsp = require('platformio.lsp.tools') local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen --- This function ensures metadata is NEVER nil when you call it -local function get_meta() - if not _G.metadata then - _G.metadata = { - envs = {}, - active_env = '', - default_envs = {}, - core_dir = '', - packages_dir = '', - platforms_dir = '', - query_driver = '', - cc_compiler = '', - triplet = '', - toolchain = '', - sysroot = '', - fallbackFlags = {}, - } - end - return _G.metadata -end -- lua/pio_setup.lua -- This module manages PlatformIO project integration, LSP toolchain detection, -- and automatic sysroot patching for standard library headers (, etc.) @@ -486,28 +450,28 @@ function M.init() if config.lspClangd.enabled == true then vim.notify('PIO setup initialize', vim.log.levels.INFO) - get_meta() - - -- -- activate meta save and upload and env switch - -- local metadata = require('platformio.utils.metadata') - -- metadata.load_project_config() - -- - -- local pio_group = vim.api.nvim_create_augroup('PioPersist', { clear = true }) - -- vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { - -- group = pio_group, - -- callback = function() - -- -- Pass 'true' to save silently in the background - -- metadata.save_project_config(true) - -- end, - -- desc = 'Automatically save PlatformIO project metadata', - -- }) - -- -- 5. Keybindings - -- -- Switch Environment - -- vim.keymap.set('n', 'pe', metadata.switch_env, { desc = 'PlatformIO: Switch Environment' }) - -- -- Manual Status Check - -- vim.keymap.set('n', 'ps', function() - -- metadata().save_project_config(false) - -- end, { desc = 'PlatformIO: Status' }) + -- get_meta() + + -- activate meta save and upload and env switch + local metadata = require('platformio.utils.metadata') + metadata.load_project_config() + + local pio_group = vim.api.nvim_create_augroup('PioPersist', { clear = true }) + vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { + group = pio_group, + callback = function() + -- Pass 'true' to save silently in the background + metadata.save_project_config(true) + end, + desc = 'Automatically save PlatformIO project metadata', + }) + -- 5. Keybindings + -- Switch Environment + vim.keymap.set('n', 'pe', metadata.switch_env, { desc = 'PlatformIO: Switch Environment' }) + -- Manual Status Check + vim.keymap.set('n', 'ps', function() + metadata().save_project_config(false) + end, { desc = 'PlatformIO: Status' }) ---------------------------------------------------------------------------------------- -- INFO: create clangd required files From 179047e76dd9dc0cdeb11d0db1276532579c0e42 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 08:38:22 +0300 Subject: [PATCH 0700/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index df3d27d0..8530fcc9 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -453,7 +453,7 @@ function M.init() -- get_meta() -- activate meta save and upload and env switch - local metadata = require('platformio.utils.metadata') + local metadata = require('platformio.metadata') metadata.load_project_config() local pio_group = vim.api.nvim_create_augroup('PioPersist', { clear = true }) From 9f65d41c9a12ba5ed8d88a6c3e239bced0bb1ef8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 08:40:24 +0300 Subject: [PATCH 0701/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 8530fcc9..c1b98fd9 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -95,7 +95,7 @@ local pio_manager = (function() for _, section in ipairs(data) do -- Each section must be a table with at least 2 elements: [1]=name, [2]=content - if type(section) == 'table' and #section >= 2 then + if section and type(section) == 'table' and #section >= 2 then local s_id = section[1] -- Section header string local s_body = section[2] -- Table of key-value pairs From 73e524af76dd61f8467a4d200f298f90a0677d57 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 08:44:39 +0300 Subject: [PATCH 0702/1406] update --- lua/platformio/pio_setup.lua | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index c1b98fd9..8f40be0a 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -222,12 +222,15 @@ local pio_manager = (function() end) return end - _G.metadata.core_dir = '' - _G.metadata.packages_dir = '' - _G.metadata.platforms_dir = '' - _G.metadata.active_env = '' - _G.metadata.default_envs = {} - _G.metadata.envs = {} + + if _G.metadata then + _G.metadata.core_dir = '' + _G.metadata.packages_dir = '' + _G.metadata.platforms_dir = '' + _G.metadata.active_env = '' + _G.metadata.default_envs = {} + _G.metadata.envs = {} + end local decoded = vim.json.decode(ext_obj.stdout) for _, section in ipairs(decoded) do From 295ca8179c11d465609c617a8de8c559f21c6db3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 08:50:28 +0300 Subject: [PATCH 0703/1406] update --- lua/platformio/init.lua | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index 1d07641c..8d0aa865 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -183,7 +183,9 @@ function M.setup(user_config) require('platformio.piomenu').piomenu(M.config) - require('platformio.pio_setup').init() + vim.schedule(function() + require('platformio.pio_setup').init() + end) end return M From 75c4b14adb1097d2bb1173ba41f5833a2e015c37 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 08:56:45 +0300 Subject: [PATCH 0704/1406] update --- lua/platformio/metadata.lua | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 45a533d1..76bb05a6 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -101,6 +101,9 @@ function M.load_project_config() get_meta() vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { title = 'PlatformIO: defautl Loaded' }) end + else + get_meta() + vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { title = 'PlatformIO: defautl Loaded' }) end end end From c8382b3458c9e03399d1affca179b96190e9cbcf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 09:03:42 +0300 Subject: [PATCH 0705/1406] update --- lua/platformio/metadata.lua | 51 +++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 25 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 76bb05a6..33cbac21 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -37,25 +37,26 @@ local last_saved_hash = nil local config_path = vim.fn.getcwd() .. '/.pioConfig.json' -- This function ensures metadata is NEVER nil when you call it -local function get_meta() - if not _G.metadata then - _G.metadata = { - envs = {}, - active_env = '', - default_envs = {}, - core_dir = '', - packages_dir = '', - platforms_dir = '', - query_driver = '', - cc_compiler = '', - triplet = '', - toolchain = '', - sysroot = '', - fallbackFlags = {}, - } - end - -- return _G.metadata -end +-- local function get_meta() +-- if not _G.metadata then +_G.metadata = _G.metadata + or { + envs = {}, + active_env = '', + default_envs = {}, + core_dir = '', + packages_dir = '', + platforms_dir = '', + query_driver = '', + cc_compiler = '', + triplet = '', + toolchain = '', + sysroot = '', + fallbackFlags = {}, + } +-- end +-- -- return _G.metadata +-- end -- 1. Optimized Save Function function M.save_project_config(quiet) @@ -97,13 +98,13 @@ function M.load_project_config() _G.metadata = decoded last_saved_hash = vim.hash(content) vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { title = 'PlatformIO: .pioCongig.json Loaded' }) - else - get_meta() - vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { title = 'PlatformIO: defautl Loaded' }) + -- else + -- get_meta() + -- vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { title = 'PlatformIO: defautl Loaded' }) end - else - get_meta() - vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { title = 'PlatformIO: defautl Loaded' }) + -- else + -- get_meta() + -- vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { title = 'PlatformIO: defautl Loaded' }) end end end From da726853733bd3bc341551fd39cf0a9f16a13cf8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 09:11:39 +0300 Subject: [PATCH 0706/1406] update --- lua/platformio/metadata.lua | 41 +----------------------------------- lua/platformio/pio_setup.lua | 8 +++---- 2 files changed, 4 insertions(+), 45 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 33cbac21..bc48fc11 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,44 +1,8 @@ --- -- Global metadata initialization --- Load the PIO setup logic --- if not _G.metadata then --- _G.metadata = { --- envs = {}, --- active_env = '', --- default_envs = {}, --- core_dir = '', --- packages_dir = '', --- platforms_dir = '', --- query_driver = '', --- cc_compiler = '', --- triplet = '', --- toolchain = '', --- sysroot = '', --- fallbackFlags = {}, --- } --- end --- _G.metadata = _G.metadata --- or { --- envs = {}, --- active_env = '', --- default_envs = {}, --- core_dir = '', --- packages_dir = '', --- platforms_dir = '', --- query_driver = '', --- cc_compiler = '', --- triplet = '', --- toolchain = '', --- sysroot = '', --- fallbackFlags = {}, --- } - local M = {} local last_saved_hash = nil local config_path = vim.fn.getcwd() .. '/.pioConfig.json' --- This function ensures metadata is NEVER nil when you call it --- local function get_meta() --- if not _G.metadata then +-- Global metadata initialization _G.metadata = _G.metadata or { envs = {}, @@ -54,9 +18,6 @@ _G.metadata = _G.metadata sysroot = '', fallbackFlags = {}, } --- end --- -- return _G.metadata --- end -- 1. Optimized Save Function function M.save_project_config(quiet) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 8f40be0a..f50da8ad 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -453,8 +453,6 @@ function M.init() if config.lspClangd.enabled == true then vim.notify('PIO setup initialize', vim.log.levels.INFO) - -- get_meta() - -- activate meta save and upload and env switch local metadata = require('platformio.metadata') metadata.load_project_config() @@ -470,11 +468,11 @@ function M.init() }) -- 5. Keybindings -- Switch Environment - vim.keymap.set('n', 'pe', metadata.switch_env, { desc = 'PlatformIO: Switch Environment' }) + vim.keymap.set('n', '\\e', metadata.switch_env, { desc = 'PlatformIO: Switch Environment' }) -- Manual Status Check - vim.keymap.set('n', 'ps', function() + vim.keymap.set('n', '\\s', function() metadata().save_project_config(false) - end, { desc = 'PlatformIO: Status' }) + end, { desc = 'PlatformIO: config status' }) ---------------------------------------------------------------------------------------- -- INFO: create clangd required files From 8002d79294177ce1b0571d8b87624fe25b77d780 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 09:35:30 +0300 Subject: [PATCH 0707/1406] update --- lua/platformio/metadata.lua | 79 +++++++++++++++++++++++------------- lua/platformio/pio_setup.lua | 18 ++++---- 2 files changed, 59 insertions(+), 38 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index bc48fc11..67c4e650 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -2,22 +2,37 @@ local M = {} local last_saved_hash = nil local config_path = vim.fn.getcwd() .. '/.pioConfig.json' --- Global metadata initialization -_G.metadata = _G.metadata - or { - envs = {}, - active_env = '', - default_envs = {}, - core_dir = '', - packages_dir = '', - platforms_dir = '', - query_driver = '', - cc_compiler = '', - triplet = '', - toolchain = '', - sysroot = '', - fallbackFlags = {}, - } +-- -- Global metadata initialization +-- _G.metadata = _G.metadata +-- or { +-- envs = {}, +-- active_env = '', +-- default_envs = {}, +-- core_dir = '', +-- packages_dir = '', +-- platforms_dir = '', +-- query_driver = '', +-- cc_compiler = '', +-- triplet = '', +-- toolchain = '', +-- sysroot = '', +-- fallbackFlags = {}, +-- } + +local default_metadata = { + envs = {}, + active_env = '', + default_envs = {}, + core_dir = '', + packages_dir = '', + platforms_dir = '', + query_driver = '', + cc_compiler = '', + triplet = '', + toolchain = '', + sysroot = '', + fallbackFlags = {}, +} -- 1. Optimized Save Function function M.save_project_config(quiet) @@ -48,28 +63,36 @@ end -- 2. Robust Load Function (Startup) function M.load_project_config() - if vim.fn.filereadable(config_path) == 1 then - local file = io.open(config_path, 'r') + local path = vim.fn.getcwd() .. '/.project_config.json' + local success = false + + -- 1. Attempt to read and decode + if vim.fn.filereadable(path) == 1 then + local file = io.open(path, 'r') if file then local content = file:read('*a') file:close() - local ok, decoded = pcall(vim.json.decode, content) - if ok and decoded then + if ok and type(decoded) == 'table' then _G.metadata = decoded last_saved_hash = vim.hash(content) - vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { title = 'PlatformIO: .pioCongig.json Loaded' }) - -- else - -- get_meta() - -- vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { title = 'PlatformIO: defautl Loaded' }) + success = true end - -- else - -- get_meta() - -- vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { title = 'PlatformIO: defautl Loaded' }) end end -end + -- 2. Fallback: If loading failed or file didn't exist, use defaults + if not success then + -- We use vim.deepcopy to ensure we don't accidentally edit the 'default' template + _G.metadata = vim.deepcopy(default_metadata) + last_saved_hash = vim.hash(vim.json.encode(_G.metadata)) + + -- Optional: Notify only if we are actually in a PIO project + if vim.fn.filereadable('platformio.ini') == 1 then + vim.notify('Initialized new project metadata', vim.log.levels.INFO, { title = 'PlatformIO' }) + end + end +end -- 3. Environment Switcher UI function M.switch_env() if not _G.metadata.envs or next(_G.metadata.envs) == nil then diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index f50da8ad..38fd48d6 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -223,14 +223,12 @@ local pio_manager = (function() return end - if _G.metadata then - _G.metadata.core_dir = '' - _G.metadata.packages_dir = '' - _G.metadata.platforms_dir = '' - _G.metadata.active_env = '' - _G.metadata.default_envs = {} - _G.metadata.envs = {} - end + _G.metadata.core_dir = '' + _G.metadata.packages_dir = '' + _G.metadata.platforms_dir = '' + _G.metadata.active_env = '' + _G.metadata.default_envs = {} + _G.metadata.envs = {} local decoded = vim.json.decode(ext_obj.stdout) for _, section in ipairs(decoded) do @@ -468,11 +466,11 @@ function M.init() }) -- 5. Keybindings -- Switch Environment - vim.keymap.set('n', '\\e', metadata.switch_env, { desc = 'PlatformIO: Switch Environment' }) + vim.keymap.set('n', '\\e', metadata.switch_env, { desc = 'Switch environment' }) -- Manual Status Check vim.keymap.set('n', '\\s', function() metadata().save_project_config(false) - end, { desc = 'PlatformIO: config status' }) + end, { desc = 'Config status' }) ---------------------------------------------------------------------------------------- -- INFO: create clangd required files From fa236f4a628a82959e9fd8116d2a09f5ed5a9eaa Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 09:51:45 +0300 Subject: [PATCH 0708/1406] update --- lua/platformio/metadata.lua | 37 +++++++++++++++++++++++++++---------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 67c4e650..47721d54 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -35,15 +35,22 @@ local default_metadata = { } -- 1. Optimized Save Function + +-- Performance-proof: Uses guaranteed Vimscript sha256 via Lua bridge +local function get_safe_hash(data) + -- sha256 is built into Neovim's core and never nil + return vim.fn.sha256(data) +end + function M.save_project_config(quiet) if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then return end local current_data = vim.json.encode(_G.metadata) - local current_hash = vim.hash(current_data) -- Inline hashing + local current_hash = get_safe_hash(current_data) - -- Only write to disk if data actually changed + -- Only write if data actually changed if current_hash ~= last_saved_hash then local file = io.open(config_path, 'w') if file then @@ -66,33 +73,43 @@ function M.load_project_config() local path = vim.fn.getcwd() .. '/.project_config.json' local success = false - -- 1. Attempt to read and decode + -- 1. Try to read existing file if vim.fn.filereadable(path) == 1 then local file = io.open(path, 'r') if file then local content = file:read('*a') file:close() local ok, decoded = pcall(vim.json.decode, content) + if ok and type(decoded) == 'table' then _G.metadata = decoded - last_saved_hash = vim.hash(content) + last_saved_hash = vim.fn.sha256(content) success = true end end end - -- 2. Fallback: If loading failed or file didn't exist, use defaults + -- 2. If no file OR read failed, initialize defaults AND save to disk if not success then - -- We use vim.deepcopy to ensure we don't accidentally edit the 'default' template + -- Use vim.deepcopy to prevent reference bugs _G.metadata = vim.deepcopy(default_metadata) - last_saved_hash = vim.hash(vim.json.encode(_G.metadata)) - -- Optional: Notify only if we are actually in a PIO project - if vim.fn.filereadable('platformio.ini') == 1 then - vim.notify('Initialized new project metadata', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- Immediately persist the defaults so the file exists + local encoded = vim.json.encode(_G.metadata) + local file = io.open(path, 'w') + if file then + file:write(encoded) + file:close() + last_saved_hash = vim.fn.sha256(encoded) + + -- Only notify if we are actually in a PlatformIO project + if vim.fn.filereadable('platformio.ini') == 1 then + vim.notify('Created new .project_config.json', vim.log.levels.INFO, { title = 'PlatformIO' }) + end end end end + -- 3. Environment Switcher UI function M.switch_env() if not _G.metadata.envs or next(_G.metadata.envs) == nil then From 6f1adc8bd874642e845a1c7ed29ccd1366929c45 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 09:57:21 +0300 Subject: [PATCH 0709/1406] update --- lua/platformio/metadata.lua | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 47721d54..4e5960cf 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,3 +1,9 @@ +-- Performance-proof: Uses guaranteed Vimscript sha256 via Lua bridge +local function get_safe_hash(data) + -- sha256 is built into Neovim's core and never nil + return vim.fn.sha256(data) +end + local M = {} local last_saved_hash = nil local config_path = vim.fn.getcwd() .. '/.pioConfig.json' @@ -36,12 +42,6 @@ local default_metadata = { -- 1. Optimized Save Function --- Performance-proof: Uses guaranteed Vimscript sha256 via Lua bridge -local function get_safe_hash(data) - -- sha256 is built into Neovim's core and never nil - return vim.fn.sha256(data) -end - function M.save_project_config(quiet) if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then return From 42e15fa7f50d24d928d0d990e557e000345440e3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 10:10:08 +0300 Subject: [PATCH 0710/1406] update --- lua/platformio/metadata.lua | 45 ++++++++++++++++--------------------- 1 file changed, 19 insertions(+), 26 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 4e5960cf..c5887fc4 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -25,21 +25,6 @@ local config_path = vim.fn.getcwd() .. '/.pioConfig.json' -- fallbackFlags = {}, -- } -local default_metadata = { - envs = {}, - active_env = '', - default_envs = {}, - core_dir = '', - packages_dir = '', - platforms_dir = '', - query_driver = '', - cc_compiler = '', - triplet = '', - toolchain = '', - sysroot = '', - fallbackFlags = {}, -} - -- 1. Optimized Save Function function M.save_project_config(quiet) @@ -69,42 +54,50 @@ function M.save_project_config(quiet) end -- 2. Robust Load Function (Startup) +local default_metadata = { + envs = {}, + active_env = '', + default_envs = {}, + core_dir = '', + packages_dir = '', + platforms_dir = '', + query_driver = '', + cc_compiler = '', + triplet = '', + toolchain = '', + sysroot = '', + fallbackFlags = {}, +} + function M.load_project_config() local path = vim.fn.getcwd() .. '/.project_config.json' local success = false - -- 1. Try to read existing file if vim.fn.filereadable(path) == 1 then local file = io.open(path, 'r') if file then local content = file:read('*a') file:close() local ok, decoded = pcall(vim.json.decode, content) - if ok and type(decoded) == 'table' then _G.metadata = decoded - last_saved_hash = vim.fn.sha256(content) + last_saved_hash = get_safe_hash(content) success = true end end end - -- 2. If no file OR read failed, initialize defaults AND save to disk + -- If no file or failed to read, write defaults immediately if not success then - -- Use vim.deepcopy to prevent reference bugs _G.metadata = vim.deepcopy(default_metadata) - - -- Immediately persist the defaults so the file exists local encoded = vim.json.encode(_G.metadata) local file = io.open(path, 'w') if file then file:write(encoded) file:close() - last_saved_hash = vim.fn.sha256(encoded) - - -- Only notify if we are actually in a PlatformIO project + last_saved_hash = get_safe_hash(encoded) if vim.fn.filereadable('platformio.ini') == 1 then - vim.notify('Created new .project_config.json', vim.log.levels.INFO, { title = 'PlatformIO' }) + vim.notify('Initialized new project settings', vim.log.levels.INFO, { title = 'PlatformIO' }) end end end From 7ff8acd679b537e98590e805c6aa6af6997e4415 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 10:27:05 +0300 Subject: [PATCH 0711/1406] update --- lua/platformio/metadata.lua | 268 +++++++++++++++++++++++++---------- lua/platformio/pio_setup.lua | 2 +- 2 files changed, 196 insertions(+), 74 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index c5887fc4..850c5635 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,45 +1,45 @@ --- Performance-proof: Uses guaranteed Vimscript sha256 via Lua bridge -local function get_safe_hash(data) - -- sha256 is built into Neovim's core and never nil - return vim.fn.sha256(data) -end +-- Global metadata initialization +_G.metadata = _G.metadata + or { + envs = {}, + active_env = '', + default_envs = {}, + core_dir = '', + packages_dir = '', + platforms_dir = '', + query_driver = '', + cc_compiler = '', + triplet = '', + toolchain = '', + sysroot = '', + fallbackFlags = {}, + } local M = {} local last_saved_hash = nil -local config_path = vim.fn.getcwd() .. '/.pioConfig.json' - --- -- Global metadata initialization --- _G.metadata = _G.metadata --- or { --- envs = {}, --- active_env = '', --- default_envs = {}, --- core_dir = '', --- packages_dir = '', --- platforms_dir = '', --- query_driver = '', --- cc_compiler = '', --- triplet = '', --- toolchain = '', --- sysroot = '', --- fallbackFlags = {}, --- } +local config_path = vim.fn.getcwd() .. '/.project_config.json' --- 1. Optimized Save Function +-- Helper: Performance-friendly hashing for change detection +local function get_current_hash() + if not _G.metadata then + return nil + end + return vim.hash(vim.json.encode(_G.metadata)) +end +-- 1. Optimized Save Function function M.save_project_config(quiet) if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then return end - local current_data = vim.json.encode(_G.metadata) - local current_hash = get_safe_hash(current_data) + local current_hash = get_current_hash() - -- Only write if data actually changed + -- Performance check: Only write to disk if data changed if current_hash ~= last_saved_hash then local file = io.open(config_path, 'w') if file then - file:write(current_data) + file:write(vim.json.encode(_G.metadata)) file:close() last_saved_hash = current_hash @@ -53,60 +53,30 @@ function M.save_project_config(quiet) end end --- 2. Robust Load Function (Startup) -local default_metadata = { - envs = {}, - active_env = '', - default_envs = {}, - core_dir = '', - packages_dir = '', - platforms_dir = '', - query_driver = '', - cc_compiler = '', - triplet = '', - toolchain = '', - sysroot = '', - fallbackFlags = {}, -} - +-- 2. Robust Load Function function M.load_project_config() - local path = vim.fn.getcwd() .. '/.project_config.json' - local success = false - - if vim.fn.filereadable(path) == 1 then - local file = io.open(path, 'r') + if vim.fn.filereadable(config_path) == 1 then + local file = io.open(config_path, 'r') if file then local content = file:read('*a') file:close() + local ok, decoded = pcall(vim.json.decode, content) - if ok and type(decoded) == 'table' then + if ok and decoded then _G.metadata = decoded - last_saved_hash = get_safe_hash(content) - success = true - end - end - end - - -- If no file or failed to read, write defaults immediately - if not success then - _G.metadata = vim.deepcopy(default_metadata) - local encoded = vim.json.encode(_G.metadata) - local file = io.open(path, 'w') - if file then - file:write(encoded) - file:close() - last_saved_hash = get_safe_hash(encoded) - if vim.fn.filereadable('platformio.ini') == 1 then - vim.notify('Initialized new project settings', vim.log.levels.INFO, { title = 'PlatformIO' }) + last_saved_hash = vim.hash(content) + vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { + title = 'PlatformIO Loaded', + }) end end end end --- 3. Environment Switcher UI +-- 3. The "Pick Environment" UI (Instant Switch & Save) function M.switch_env() if not _G.metadata.envs or next(_G.metadata.envs) == nil then - vim.notify('No environments found. Run PlatformIO Refresh first.', vim.log.levels.WARN) + vim.notify('No environments found in metadata', vim.log.levels.ERROR) return end @@ -116,18 +86,170 @@ function M.switch_env() vim.ui.select(options, { prompt = 'Select PlatformIO Environment:', format_item = function(item) - local indicator = (item == _G.metadata.active_env) and '● ' or '○ ' - return indicator .. item + return ' ' .. item .. (item == _G.metadata.active_env and ' (current)' or '') end, }, function(choice) if choice then _G.metadata.active_env = choice - -- Save immediately on user selection + -- Immediately save the change M.save_project_config(false) - -- Force LSP to pick up new fallbackFlags/defines + -- Trigger LSP restart or internal refresh here if needed vim.cmd('LspRestart clangd') end end) end +-- 4. Setup Startup and Autocmds +M.load_project_config() + +local group = vim.api.nvim_create_augroup('PioPersist', { clear = true }) + +-- Autosave only on important events to keep performance high +vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { + group = group, + callback = function() + M.save_project_config(true) + end, +}) + +-- 5. Keybindings +vim.keymap.set('n', 'pe', M.switch_env, { desc = 'PlatformIO: Switch Environment' }) +vim.keymap.set('n', 'ps', function() + M.save_project_config(false) +end, { desc = 'PlatformIO: Manual Save/Status' }) + return M + +-- -- Performance-proof: Uses guaranteed Vimscript sha256 via Lua bridge +-- local function get_safe_hash(data) +-- -- sha256 is built into Neovim's core and never nil +-- return vim.fn.sha256(data) +-- end +-- +-- local M = {} +-- local last_saved_hash = nil +-- local config_path = vim.fn.getcwd() .. '/.pioConfig.json' +-- +-- -- -- Global metadata initialization +-- -- _G.metadata = _G.metadata +-- -- or { +-- -- envs = {}, +-- -- active_env = '', +-- -- default_envs = {}, +-- -- core_dir = '', +-- -- packages_dir = '', +-- -- platforms_dir = '', +-- -- query_driver = '', +-- -- cc_compiler = '', +-- -- triplet = '', +-- -- toolchain = '', +-- -- sysroot = '', +-- -- fallbackFlags = {}, +-- -- } +-- +-- -- 1. Optimized Save Function +-- +-- function M.save_project_config(quiet) +-- if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then +-- return +-- end +-- +-- local current_data = vim.json.encode(_G.metadata) +-- local current_hash = get_safe_hash(current_data) +-- +-- -- Only write if data actually changed +-- if current_hash ~= last_saved_hash then +-- local file = io.open(config_path, 'w') +-- if file then +-- file:write(current_data) +-- file:close() +-- last_saved_hash = current_hash +-- +-- if not quiet then +-- vim.notify('Project settings synced to disk', vim.log.levels.INFO, { +-- title = 'PlatformIO', +-- render = 'compact', +-- }) +-- end +-- end +-- end +-- end +-- +-- -- 2. Robust Load Function (Startup) +-- local default_metadata = { +-- envs = {}, +-- active_env = '', +-- default_envs = {}, +-- core_dir = '', +-- packages_dir = '', +-- platforms_dir = '', +-- query_driver = '', +-- cc_compiler = '', +-- triplet = '', +-- toolchain = '', +-- sysroot = '', +-- fallbackFlags = {}, +-- } +-- +-- function M.load_project_config() +-- local path = vim.fn.getcwd() .. '/.project_config.json' +-- local success = false +-- +-- if vim.fn.filereadable(path) == 1 then +-- local file = io.open(path, 'r') +-- if file then +-- local content = file:read('*a') +-- file:close() +-- local ok, decoded = pcall(vim.json.decode, content) +-- if ok and type(decoded) == 'table' then +-- _G.metadata = decoded +-- last_saved_hash = get_safe_hash(content) +-- success = true +-- end +-- end +-- end +-- +-- -- If no file or failed to read, write defaults immediately +-- if not success then +-- _G.metadata = vim.deepcopy(default_metadata) +-- local encoded = vim.json.encode(_G.metadata) +-- local file = io.open(path, 'w') +-- if file then +-- file:write(encoded) +-- file:close() +-- last_saved_hash = get_safe_hash(encoded) +-- if vim.fn.filereadable('platformio.ini') == 1 then +-- vim.notify('Initialized new project settings', vim.log.levels.INFO, { title = 'PlatformIO' }) +-- end +-- end +-- end +-- end +-- +-- -- 3. Environment Switcher UI +-- function M.switch_env() +-- if not _G.metadata.envs or next(_G.metadata.envs) == nil then +-- vim.notify('No environments found. Run PlatformIO Refresh first.', vim.log.levels.WARN) +-- return +-- end +-- +-- local options = vim.tbl_keys(_G.metadata.envs) +-- table.sort(options) +-- +-- vim.ui.select(options, { +-- prompt = 'Select PlatformIO Environment:', +-- format_item = function(item) +-- local indicator = (item == _G.metadata.active_env) and '● ' or '○ ' +-- return indicator .. item +-- end, +-- }, function(choice) +-- if choice then +-- _G.metadata.active_env = choice +-- -- Save immediately on user selection +-- M.save_project_config(false) +-- -- Force LSP to pick up new fallbackFlags/defines +-- vim.cmd('LspRestart clangd') +-- end +-- end) +-- end +-- +-- return M diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 38fd48d6..b76c1d1d 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -469,7 +469,7 @@ function M.init() vim.keymap.set('n', '\\e', metadata.switch_env, { desc = 'Switch environment' }) -- Manual Status Check vim.keymap.set('n', '\\s', function() - metadata().save_project_config(false) + metadata.save_project_config(false) end, { desc = 'Config status' }) ---------------------------------------------------------------------------------------- From a3f754bd8793cb4235d9073f1f19410f23876ca4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 10:30:26 +0300 Subject: [PATCH 0712/1406] update --- lua/platformio/metadata.lua | 390 ++++++++++++++++++------------------ 1 file changed, 195 insertions(+), 195 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 850c5635..2fe804f4 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,167 +1,45 @@ --- Global metadata initialization -_G.metadata = _G.metadata - or { - envs = {}, - active_env = '', - default_envs = {}, - core_dir = '', - packages_dir = '', - platforms_dir = '', - query_driver = '', - cc_compiler = '', - triplet = '', - toolchain = '', - sysroot = '', - fallbackFlags = {}, - } - -local M = {} -local last_saved_hash = nil -local config_path = vim.fn.getcwd() .. '/.project_config.json' - --- Helper: Performance-friendly hashing for change detection -local function get_current_hash() - if not _G.metadata then - return nil - end - return vim.hash(vim.json.encode(_G.metadata)) -end - --- 1. Optimized Save Function -function M.save_project_config(quiet) - if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then - return - end - - local current_hash = get_current_hash() - - -- Performance check: Only write to disk if data changed - if current_hash ~= last_saved_hash then - local file = io.open(config_path, 'w') - if file then - file:write(vim.json.encode(_G.metadata)) - file:close() - last_saved_hash = current_hash - - if not quiet then - vim.notify('Project settings synced to disk', vim.log.levels.INFO, { - title = 'PlatformIO', - render = 'compact', - }) - end - end - end -end - --- 2. Robust Load Function -function M.load_project_config() - if vim.fn.filereadable(config_path) == 1 then - local file = io.open(config_path, 'r') - if file then - local content = file:read('*a') - file:close() - - local ok, decoded = pcall(vim.json.decode, content) - if ok and decoded then - _G.metadata = decoded - last_saved_hash = vim.hash(content) - vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { - title = 'PlatformIO Loaded', - }) - end - end - end -end - --- 3. The "Pick Environment" UI (Instant Switch & Save) -function M.switch_env() - if not _G.metadata.envs or next(_G.metadata.envs) == nil then - vim.notify('No environments found in metadata', vim.log.levels.ERROR) - return - end - - local options = vim.tbl_keys(_G.metadata.envs) - table.sort(options) - - vim.ui.select(options, { - prompt = 'Select PlatformIO Environment:', - format_item = function(item) - return ' ' .. item .. (item == _G.metadata.active_env and ' (current)' or '') - end, - }, function(choice) - if choice then - _G.metadata.active_env = choice - -- Immediately save the change - M.save_project_config(false) - -- Trigger LSP restart or internal refresh here if needed - vim.cmd('LspRestart clangd') - end - end) -end - --- 4. Setup Startup and Autocmds -M.load_project_config() - -local group = vim.api.nvim_create_augroup('PioPersist', { clear = true }) - --- Autosave only on important events to keep performance high -vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { - group = group, - callback = function() - M.save_project_config(true) - end, -}) - --- 5. Keybindings -vim.keymap.set('n', 'pe', M.switch_env, { desc = 'PlatformIO: Switch Environment' }) -vim.keymap.set('n', 'ps', function() - M.save_project_config(false) -end, { desc = 'PlatformIO: Manual Save/Status' }) - -return M - --- -- Performance-proof: Uses guaranteed Vimscript sha256 via Lua bridge --- local function get_safe_hash(data) --- -- sha256 is built into Neovim's core and never nil --- return vim.fn.sha256(data) --- end +-- -- Global metadata initialization +-- _G.metadata = _G.metadata +-- or { +-- envs = {}, +-- active_env = '', +-- default_envs = {}, +-- core_dir = '', +-- packages_dir = '', +-- platforms_dir = '', +-- query_driver = '', +-- cc_compiler = '', +-- triplet = '', +-- toolchain = '', +-- sysroot = '', +-- fallbackFlags = {}, +-- } -- -- local M = {} -- local last_saved_hash = nil --- local config_path = vim.fn.getcwd() .. '/.pioConfig.json' --- --- -- -- Global metadata initialization --- -- _G.metadata = _G.metadata --- -- or { --- -- envs = {}, --- -- active_env = '', --- -- default_envs = {}, --- -- core_dir = '', --- -- packages_dir = '', --- -- platforms_dir = '', --- -- query_driver = '', --- -- cc_compiler = '', --- -- triplet = '', --- -- toolchain = '', --- -- sysroot = '', --- -- fallbackFlags = {}, --- -- } +-- local config_path = vim.fn.getcwd() .. '/.project_config.json' -- --- -- 1. Optimized Save Function +-- -- Helper: Performance-friendly hashing for change detection +-- local function get_current_hash() +-- if not _G.metadata then +-- return nil +-- end +-- return vim.hash(vim.json.encode(_G.metadata)) +-- end -- +-- -- 1. Optimized Save Function -- function M.save_project_config(quiet) -- if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then -- return -- end -- --- local current_data = vim.json.encode(_G.metadata) --- local current_hash = get_safe_hash(current_data) +-- local current_hash = get_current_hash() -- --- -- Only write if data actually changed +-- -- Performance check: Only write to disk if data changed -- if current_hash ~= last_saved_hash then -- local file = io.open(config_path, 'w') -- if file then --- file:write(current_data) +-- file:write(vim.json.encode(_G.metadata)) -- file:close() -- last_saved_hash = current_hash -- @@ -175,60 +53,30 @@ return M -- end -- end -- --- -- 2. Robust Load Function (Startup) --- local default_metadata = { --- envs = {}, --- active_env = '', --- default_envs = {}, --- core_dir = '', --- packages_dir = '', --- platforms_dir = '', --- query_driver = '', --- cc_compiler = '', --- triplet = '', --- toolchain = '', --- sysroot = '', --- fallbackFlags = {}, --- } --- +-- -- 2. Robust Load Function -- function M.load_project_config() --- local path = vim.fn.getcwd() .. '/.project_config.json' --- local success = false --- --- if vim.fn.filereadable(path) == 1 then --- local file = io.open(path, 'r') +-- if vim.fn.filereadable(config_path) == 1 then +-- local file = io.open(config_path, 'r') -- if file then -- local content = file:read('*a') -- file:close() +-- -- local ok, decoded = pcall(vim.json.decode, content) --- if ok and type(decoded) == 'table' then +-- if ok and decoded then -- _G.metadata = decoded --- last_saved_hash = get_safe_hash(content) --- success = true --- end --- end --- end --- --- -- If no file or failed to read, write defaults immediately --- if not success then --- _G.metadata = vim.deepcopy(default_metadata) --- local encoded = vim.json.encode(_G.metadata) --- local file = io.open(path, 'w') --- if file then --- file:write(encoded) --- file:close() --- last_saved_hash = get_safe_hash(encoded) --- if vim.fn.filereadable('platformio.ini') == 1 then --- vim.notify('Initialized new project settings', vim.log.levels.INFO, { title = 'PlatformIO' }) +-- last_saved_hash = vim.hash(content) +-- vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { +-- title = 'PlatformIO Loaded', +-- }) -- end -- end -- end -- end -- --- -- 3. Environment Switcher UI +-- -- 3. The "Pick Environment" UI (Instant Switch & Save) -- function M.switch_env() -- if not _G.metadata.envs or next(_G.metadata.envs) == nil then --- vim.notify('No environments found. Run PlatformIO Refresh first.', vim.log.levels.WARN) +-- vim.notify('No environments found in metadata', vim.log.levels.ERROR) -- return -- end -- @@ -238,18 +86,170 @@ return M -- vim.ui.select(options, { -- prompt = 'Select PlatformIO Environment:', -- format_item = function(item) --- local indicator = (item == _G.metadata.active_env) and '● ' or '○ ' --- return indicator .. item +-- return ' ' .. item .. (item == _G.metadata.active_env and ' (current)' or '') -- end, -- }, function(choice) -- if choice then -- _G.metadata.active_env = choice --- -- Save immediately on user selection +-- -- Immediately save the change -- M.save_project_config(false) --- -- Force LSP to pick up new fallbackFlags/defines +-- -- Trigger LSP restart or internal refresh here if needed -- vim.cmd('LspRestart clangd') -- end -- end) -- end -- +-- -- 4. Setup Startup and Autocmds +-- M.load_project_config() +-- +-- local group = vim.api.nvim_create_augroup('PioPersist', { clear = true }) +-- +-- -- Autosave only on important events to keep performance high +-- vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { +-- group = group, +-- callback = function() +-- M.save_project_config(true) +-- end, +-- }) +-- +-- -- 5. Keybindings +-- vim.keymap.set('n', 'pe', M.switch_env, { desc = 'PlatformIO: Switch Environment' }) +-- vim.keymap.set('n', 'ps', function() +-- M.save_project_config(false) +-- end, { desc = 'PlatformIO: Manual Save/Status' }) +-- -- return M +-- +-- Performance-proof: Uses guaranteed Vimscript sha256 via Lua bridge +local function get_safe_hash(data) + -- sha256 is built into Neovim's core and never nil + return vim.fn.sha256(data) +end + +local M = {} +local last_saved_hash = nil +local config_path = vim.fn.getcwd() .. '/.pioConfig.json' + +-- -- Global metadata initialization +-- _G.metadata = _G.metadata +-- or { +-- envs = {}, +-- active_env = '', +-- default_envs = {}, +-- core_dir = '', +-- packages_dir = '', +-- platforms_dir = '', +-- query_driver = '', +-- cc_compiler = '', +-- triplet = '', +-- toolchain = '', +-- sysroot = '', +-- fallbackFlags = {}, +-- } + +-- 1. Optimized Save Function + +function M.save_project_config(quiet) + if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then + return + end + + local current_data = vim.json.encode(_G.metadata) + local current_hash = get_safe_hash(current_data) + + -- Only write if data actually changed + if current_hash ~= last_saved_hash then + local file = io.open(config_path, 'w') + if file then + file:write(current_data) + file:close() + last_saved_hash = current_hash + + if not quiet then + vim.notify('Project settings synced to disk', vim.log.levels.INFO, { + title = 'PlatformIO', + render = 'compact', + }) + end + end + end +end + +-- 2. Robust Load Function (Startup) +local default_metadata = { + envs = {}, + active_env = '', + default_envs = {}, + core_dir = '', + packages_dir = '', + platforms_dir = '', + query_driver = '', + cc_compiler = '', + triplet = '', + toolchain = '', + sysroot = '', + fallbackFlags = {}, +} + +function M.load_project_config() + local path = vim.fn.getcwd() .. '/.project_config.json' + local success = false + + if vim.fn.filereadable(path) == 1 then + local file = io.open(path, 'r') + if file then + local content = file:read('*a') + file:close() + local ok, decoded = pcall(vim.json.decode, content) + if ok and type(decoded) == 'table' then + _G.metadata = decoded + last_saved_hash = get_safe_hash(content) + success = true + end + end + end + + -- If no file or failed to read, write defaults immediately + if not success then + _G.metadata = vim.deepcopy(default_metadata) + local encoded = vim.json.encode(_G.metadata) + local file = io.open(path, 'w') + if file then + file:write(encoded) + file:close() + last_saved_hash = get_safe_hash(encoded) + if vim.fn.filereadable('platformio.ini') == 1 then + vim.notify('Initialized new project settings', vim.log.levels.INFO, { title = 'PlatformIO' }) + end + end + end +end + +-- 3. Environment Switcher UI +function M.switch_env() + if not _G.metadata.envs or next(_G.metadata.envs) == nil then + vim.notify('No environments found. Run PlatformIO Refresh first.', vim.log.levels.WARN) + return + end + + local options = vim.tbl_keys(_G.metadata.envs) + table.sort(options) + + vim.ui.select(options, { + prompt = 'Select PlatformIO Environment:', + format_item = function(item) + local indicator = (item == _G.metadata.active_env) and '● ' or '○ ' + return indicator .. item + end, + }, function(choice) + if choice then + _G.metadata.active_env = choice + -- Save immediately on user selection + M.save_project_config(false) + -- Force LSP to pick up new fallbackFlags/defines + vim.cmd('LspRestart clangd') + end + end) +end + +return M From 331f03617e2a4eb43e6c303e35190c6e4b6324c0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 10:39:13 +0300 Subject: [PATCH 0713/1406] update --- lua/platformio/metadata.lua | 272 ++++++++--------------------------- lua/platformio/pio_setup.lua | 12 +- metadata.lua | 255 ++++++++++++++++++++++++++++++++ 3 files changed, 320 insertions(+), 219 deletions(-) create mode 100644 metadata.lua diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 2fe804f4..fc46d897 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,202 +1,35 @@ --- -- Global metadata initialization --- _G.metadata = _G.metadata --- or { --- envs = {}, --- active_env = '', --- default_envs = {}, --- core_dir = '', --- packages_dir = '', --- platforms_dir = '', --- query_driver = '', --- cc_compiler = '', --- triplet = '', --- toolchain = '', --- sysroot = '', --- fallbackFlags = {}, --- } --- --- local M = {} --- local last_saved_hash = nil --- local config_path = vim.fn.getcwd() .. '/.project_config.json' --- --- -- Helper: Performance-friendly hashing for change detection --- local function get_current_hash() --- if not _G.metadata then --- return nil --- end --- return vim.hash(vim.json.encode(_G.metadata)) --- end --- --- -- 1. Optimized Save Function --- function M.save_project_config(quiet) --- if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then --- return --- end --- --- local current_hash = get_current_hash() --- --- -- Performance check: Only write to disk if data changed --- if current_hash ~= last_saved_hash then --- local file = io.open(config_path, 'w') --- if file then --- file:write(vim.json.encode(_G.metadata)) --- file:close() --- last_saved_hash = current_hash --- --- if not quiet then --- vim.notify('Project settings synced to disk', vim.log.levels.INFO, { --- title = 'PlatformIO', --- render = 'compact', --- }) --- end --- end --- end --- end --- --- -- 2. Robust Load Function --- function M.load_project_config() --- if vim.fn.filereadable(config_path) == 1 then --- local file = io.open(config_path, 'r') --- if file then --- local content = file:read('*a') --- file:close() --- --- local ok, decoded = pcall(vim.json.decode, content) --- if ok and decoded then --- _G.metadata = decoded --- last_saved_hash = vim.hash(content) --- vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { --- title = 'PlatformIO Loaded', --- }) --- end --- end --- end --- end --- --- -- 3. The "Pick Environment" UI (Instant Switch & Save) --- function M.switch_env() --- if not _G.metadata.envs or next(_G.metadata.envs) == nil then --- vim.notify('No environments found in metadata', vim.log.levels.ERROR) --- return --- end --- --- local options = vim.tbl_keys(_G.metadata.envs) --- table.sort(options) --- --- vim.ui.select(options, { --- prompt = 'Select PlatformIO Environment:', --- format_item = function(item) --- return ' ' .. item .. (item == _G.metadata.active_env and ' (current)' or '') --- end, --- }, function(choice) --- if choice then --- _G.metadata.active_env = choice --- -- Immediately save the change --- M.save_project_config(false) --- -- Trigger LSP restart or internal refresh here if needed --- vim.cmd('LspRestart clangd') --- end --- end) --- end --- --- -- 4. Setup Startup and Autocmds --- M.load_project_config() --- --- local group = vim.api.nvim_create_augroup('PioPersist', { clear = true }) --- --- -- Autosave only on important events to keep performance high --- vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { --- group = group, --- callback = function() --- M.save_project_config(true) --- end, --- }) --- --- -- 5. Keybindings --- vim.keymap.set('n', 'pe', M.switch_env, { desc = 'PlatformIO: Switch Environment' }) --- vim.keymap.set('n', 'ps', function() --- M.save_project_config(false) --- end, { desc = 'PlatformIO: Manual Save/Status' }) --- --- return M --- --- Performance-proof: Uses guaranteed Vimscript sha256 via Lua bridge -local function get_safe_hash(data) - -- sha256 is built into Neovim's core and never nil - return vim.fn.sha256(data) -end +-- 1. Initialize Global Table immediately (Prevents nil errors) +_G.metadata = _G.metadata + or { + envs = {}, + active_env = '', + default_envs = {}, + core_dir = '', + packages_dir = '', + platforms_dir = '', + query_driver = '', + cc_compiler = '', + triplet = '', + toolchain = '', + sysroot = '', + fallbackFlags = {}, + } local M = {} -local last_saved_hash = nil -local config_path = vim.fn.getcwd() .. '/.pioConfig.json' - --- -- Global metadata initialization --- _G.metadata = _G.metadata --- or { --- envs = {}, --- active_env = '', --- default_envs = {}, --- core_dir = '', --- packages_dir = '', --- platforms_dir = '', --- query_driver = '', --- cc_compiler = '', --- triplet = '', --- toolchain = '', --- sysroot = '', --- fallbackFlags = {}, --- } - --- 1. Optimized Save Function - -function M.save_project_config(quiet) - if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then - return - end - - local current_data = vim.json.encode(_G.metadata) - local current_hash = get_safe_hash(current_data) +local last_saved_hash = '' +local config_path = vim.fn.getcwd() .. '/.project_config.json' - -- Only write if data actually changed - if current_hash ~= last_saved_hash then - local file = io.open(config_path, 'w') - if file then - file:write(current_data) - file:close() - last_saved_hash = current_hash - - if not quiet then - vim.notify('Project settings synced to disk', vim.log.levels.INFO, { - title = 'PlatformIO', - render = 'compact', - }) - end - end - end +-- Helper: Performance-proof hashing using built-in Vimscript (never nil) +local function get_safe_hash(data) + return vim.fn.sha256(data) end --- 2. Robust Load Function (Startup) -local default_metadata = { - envs = {}, - active_env = '', - default_envs = {}, - core_dir = '', - packages_dir = '', - platforms_dir = '', - query_driver = '', - cc_compiler = '', - triplet = '', - toolchain = '', - sysroot = '', - fallbackFlags = {}, -} - +-- 2. Self-Healing Load & Auto-Create function M.load_project_config() - local path = vim.fn.getcwd() .. '/.project_config.json' local success = false - if vim.fn.filereadable(path) == 1 then - local file = io.open(path, 'r') + if vim.fn.filereadable(config_path) == 1 then + local file = io.open(config_path, 'r') if file then local content = file:read('*a') file:close() @@ -209,47 +42,56 @@ function M.load_project_config() end end - -- If no file or failed to read, write defaults immediately + -- If file is missing or corrupted, initialize and force-save if not success then - _G.metadata = vim.deepcopy(default_metadata) + -- Use the global table we initialized at the top local encoded = vim.json.encode(_G.metadata) - local file = io.open(path, 'w') + local file = io.open(config_path, 'w') if file then file:write(encoded) file:close() last_saved_hash = get_safe_hash(encoded) if vim.fn.filereadable('platformio.ini') == 1 then - vim.notify('Initialized new project settings', vim.log.levels.INFO, { title = 'PlatformIO' }) + vim.notify('New project config created', vim.log.levels.INFO, { title = 'PlatformIO' }) end end end end --- 3. Environment Switcher UI -function M.switch_env() - if not _G.metadata.envs or next(_G.metadata.envs) == nil then - vim.notify('No environments found. Run PlatformIO Refresh first.', vim.log.levels.WARN) +-- 3. Performance-Proof Save (Hash Check) +function M.save_project_config(quiet) + if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then return end - local options = vim.tbl_keys(_G.metadata.envs) - table.sort(options) + local current_data = vim.json.encode(_G.metadata) + local current_hash = get_safe_hash(current_data) - vim.ui.select(options, { - prompt = 'Select PlatformIO Environment:', - format_item = function(item) - local indicator = (item == _G.metadata.active_env) and '● ' or '○ ' - return indicator .. item - end, - }, function(choice) - if choice then - _G.metadata.active_env = choice - -- Save immediately on user selection - M.save_project_config(false) - -- Force LSP to pick up new fallbackFlags/defines - vim.cmd('LspRestart clangd') + -- Only write if data actually changed since last load/save + if current_hash ~= last_saved_hash then + local file = io.open(config_path, 'w') + if file then + file:write(current_data) + file:close() + last_saved_hash = current_hash + + if not quiet then + vim.notify('Settings synced to disk', vim.log.levels.INFO, { + title = 'PlatformIO', + render = 'compact', + }) + end end - end) + end +end + +-- 4. Fixed Status Function (Fixes line 472 error) +function M.show_status() + -- Ensure we access the table, NOT call it + local meta = _G.metadata + local env = meta.active_env ~= '' and meta.active_env or 'None' + + vim.notify(string.format('Environment: %s\nTarget: %s', env, meta.triplet or 'Unknown'), vim.log.levels.INFO, { title = 'PlatformIO Status' }) end return M diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b76c1d1d..265a133d 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -464,14 +464,18 @@ function M.init() end, desc = 'Automatically save PlatformIO project metadata', }) + -- 5. Keybindings -- Switch Environment vim.keymap.set('n', '\\e', metadata.switch_env, { desc = 'Switch environment' }) - -- Manual Status Check - vim.keymap.set('n', '\\s', function() - metadata.save_project_config(false) - end, { desc = 'Config status' }) + -- write + -- vim.keymap.set('n', '\\s', function() + -- metadata.save_project_config(false) + -- end, { desc = 'Config status' }) + + -- Manual Status Check + vim.keymap.set('n', 'ps', metadata.show_status, { desc = 'PIO Status' }) ---------------------------------------------------------------------------------------- -- INFO: create clangd required files ----------------------------------------------------------------------------------------- diff --git a/metadata.lua b/metadata.lua new file mode 100644 index 00000000..2fe804f4 --- /dev/null +++ b/metadata.lua @@ -0,0 +1,255 @@ +-- -- Global metadata initialization +-- _G.metadata = _G.metadata +-- or { +-- envs = {}, +-- active_env = '', +-- default_envs = {}, +-- core_dir = '', +-- packages_dir = '', +-- platforms_dir = '', +-- query_driver = '', +-- cc_compiler = '', +-- triplet = '', +-- toolchain = '', +-- sysroot = '', +-- fallbackFlags = {}, +-- } +-- +-- local M = {} +-- local last_saved_hash = nil +-- local config_path = vim.fn.getcwd() .. '/.project_config.json' +-- +-- -- Helper: Performance-friendly hashing for change detection +-- local function get_current_hash() +-- if not _G.metadata then +-- return nil +-- end +-- return vim.hash(vim.json.encode(_G.metadata)) +-- end +-- +-- -- 1. Optimized Save Function +-- function M.save_project_config(quiet) +-- if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then +-- return +-- end +-- +-- local current_hash = get_current_hash() +-- +-- -- Performance check: Only write to disk if data changed +-- if current_hash ~= last_saved_hash then +-- local file = io.open(config_path, 'w') +-- if file then +-- file:write(vim.json.encode(_G.metadata)) +-- file:close() +-- last_saved_hash = current_hash +-- +-- if not quiet then +-- vim.notify('Project settings synced to disk', vim.log.levels.INFO, { +-- title = 'PlatformIO', +-- render = 'compact', +-- }) +-- end +-- end +-- end +-- end +-- +-- -- 2. Robust Load Function +-- function M.load_project_config() +-- if vim.fn.filereadable(config_path) == 1 then +-- local file = io.open(config_path, 'r') +-- if file then +-- local content = file:read('*a') +-- file:close() +-- +-- local ok, decoded = pcall(vim.json.decode, content) +-- if ok and decoded then +-- _G.metadata = decoded +-- last_saved_hash = vim.hash(content) +-- vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { +-- title = 'PlatformIO Loaded', +-- }) +-- end +-- end +-- end +-- end +-- +-- -- 3. The "Pick Environment" UI (Instant Switch & Save) +-- function M.switch_env() +-- if not _G.metadata.envs or next(_G.metadata.envs) == nil then +-- vim.notify('No environments found in metadata', vim.log.levels.ERROR) +-- return +-- end +-- +-- local options = vim.tbl_keys(_G.metadata.envs) +-- table.sort(options) +-- +-- vim.ui.select(options, { +-- prompt = 'Select PlatformIO Environment:', +-- format_item = function(item) +-- return ' ' .. item .. (item == _G.metadata.active_env and ' (current)' or '') +-- end, +-- }, function(choice) +-- if choice then +-- _G.metadata.active_env = choice +-- -- Immediately save the change +-- M.save_project_config(false) +-- -- Trigger LSP restart or internal refresh here if needed +-- vim.cmd('LspRestart clangd') +-- end +-- end) +-- end +-- +-- -- 4. Setup Startup and Autocmds +-- M.load_project_config() +-- +-- local group = vim.api.nvim_create_augroup('PioPersist', { clear = true }) +-- +-- -- Autosave only on important events to keep performance high +-- vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { +-- group = group, +-- callback = function() +-- M.save_project_config(true) +-- end, +-- }) +-- +-- -- 5. Keybindings +-- vim.keymap.set('n', 'pe', M.switch_env, { desc = 'PlatformIO: Switch Environment' }) +-- vim.keymap.set('n', 'ps', function() +-- M.save_project_config(false) +-- end, { desc = 'PlatformIO: Manual Save/Status' }) +-- +-- return M +-- +-- Performance-proof: Uses guaranteed Vimscript sha256 via Lua bridge +local function get_safe_hash(data) + -- sha256 is built into Neovim's core and never nil + return vim.fn.sha256(data) +end + +local M = {} +local last_saved_hash = nil +local config_path = vim.fn.getcwd() .. '/.pioConfig.json' + +-- -- Global metadata initialization +-- _G.metadata = _G.metadata +-- or { +-- envs = {}, +-- active_env = '', +-- default_envs = {}, +-- core_dir = '', +-- packages_dir = '', +-- platforms_dir = '', +-- query_driver = '', +-- cc_compiler = '', +-- triplet = '', +-- toolchain = '', +-- sysroot = '', +-- fallbackFlags = {}, +-- } + +-- 1. Optimized Save Function + +function M.save_project_config(quiet) + if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then + return + end + + local current_data = vim.json.encode(_G.metadata) + local current_hash = get_safe_hash(current_data) + + -- Only write if data actually changed + if current_hash ~= last_saved_hash then + local file = io.open(config_path, 'w') + if file then + file:write(current_data) + file:close() + last_saved_hash = current_hash + + if not quiet then + vim.notify('Project settings synced to disk', vim.log.levels.INFO, { + title = 'PlatformIO', + render = 'compact', + }) + end + end + end +end + +-- 2. Robust Load Function (Startup) +local default_metadata = { + envs = {}, + active_env = '', + default_envs = {}, + core_dir = '', + packages_dir = '', + platforms_dir = '', + query_driver = '', + cc_compiler = '', + triplet = '', + toolchain = '', + sysroot = '', + fallbackFlags = {}, +} + +function M.load_project_config() + local path = vim.fn.getcwd() .. '/.project_config.json' + local success = false + + if vim.fn.filereadable(path) == 1 then + local file = io.open(path, 'r') + if file then + local content = file:read('*a') + file:close() + local ok, decoded = pcall(vim.json.decode, content) + if ok and type(decoded) == 'table' then + _G.metadata = decoded + last_saved_hash = get_safe_hash(content) + success = true + end + end + end + + -- If no file or failed to read, write defaults immediately + if not success then + _G.metadata = vim.deepcopy(default_metadata) + local encoded = vim.json.encode(_G.metadata) + local file = io.open(path, 'w') + if file then + file:write(encoded) + file:close() + last_saved_hash = get_safe_hash(encoded) + if vim.fn.filereadable('platformio.ini') == 1 then + vim.notify('Initialized new project settings', vim.log.levels.INFO, { title = 'PlatformIO' }) + end + end + end +end + +-- 3. Environment Switcher UI +function M.switch_env() + if not _G.metadata.envs or next(_G.metadata.envs) == nil then + vim.notify('No environments found. Run PlatformIO Refresh first.', vim.log.levels.WARN) + return + end + + local options = vim.tbl_keys(_G.metadata.envs) + table.sort(options) + + vim.ui.select(options, { + prompt = 'Select PlatformIO Environment:', + format_item = function(item) + local indicator = (item == _G.metadata.active_env) and '● ' or '○ ' + return indicator .. item + end, + }, function(choice) + if choice then + _G.metadata.active_env = choice + -- Save immediately on user selection + M.save_project_config(false) + -- Force LSP to pick up new fallbackFlags/defines + vim.cmd('LspRestart clangd') + end + end) +end + +return M From 71070a0a25106153643e4da7dfa82ce4dfd84931 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 10:42:59 +0300 Subject: [PATCH 0714/1406] update --- lua/platformio/pio_setup.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 265a133d..a3c067c9 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -467,7 +467,7 @@ function M.init() -- 5. Keybindings -- Switch Environment - vim.keymap.set('n', '\\e', metadata.switch_env, { desc = 'Switch environment' }) + vim.keymap.set('n', '\\e', metadata.switch_env(), { desc = 'Switch environment' }) -- write -- vim.keymap.set('n', '\\s', function() @@ -475,7 +475,7 @@ function M.init() -- end, { desc = 'Config status' }) -- Manual Status Check - vim.keymap.set('n', 'ps', metadata.show_status, { desc = 'PIO Status' }) + vim.keymap.set('n', 'ps', metadata.show_status(), { desc = 'PIO Status' }) ---------------------------------------------------------------------------------------- -- INFO: create clangd required files ----------------------------------------------------------------------------------------- From 049c1f526652ef281b21c2c544bce2829129b04c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 10:49:47 +0300 Subject: [PATCH 0715/1406] update --- lua/platformio/metadata.lua | 11 +++++++++++ lua/platformio/pio_setup.lua | 11 ----------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index fc46d897..77c51529 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -94,4 +94,15 @@ function M.show_status() vim.notify(string.format('Environment: %s\nTarget: %s', env, meta.triplet or 'Unknown'), vim.log.levels.INFO, { title = 'PlatformIO Status' }) end +-- 5. Keybindings +-- Switch Environment +vim.keymap.set('n', '\\e', metadata.switch_env(), { desc = 'Switch environment' }) + +-- write +-- vim.keymap.set('n', '\\s', function() +-- metadata.save_project_config(false) +-- end, { desc = 'Config status' }) + +-- Manual Status Check +vim.keymap.set('n', 'ps', metadata.show_status(), { desc = 'PIO Status' }) return M diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index a3c067c9..6f5c0a85 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -465,17 +465,6 @@ function M.init() desc = 'Automatically save PlatformIO project metadata', }) - -- 5. Keybindings - -- Switch Environment - vim.keymap.set('n', '\\e', metadata.switch_env(), { desc = 'Switch environment' }) - - -- write - -- vim.keymap.set('n', '\\s', function() - -- metadata.save_project_config(false) - -- end, { desc = 'Config status' }) - - -- Manual Status Check - vim.keymap.set('n', 'ps', metadata.show_status(), { desc = 'PIO Status' }) ---------------------------------------------------------------------------------------- -- INFO: create clangd required files ----------------------------------------------------------------------------------------- From 076df2dede905dd35c157ea1e047d6b4300086e5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 10:58:49 +0300 Subject: [PATCH 0716/1406] update --- lua/platformio/metadata.lua | 16 +++++++++++++--- lua/platformio/pio_setup.lua | 10 ---------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 77c51529..e7400725 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -94,15 +94,25 @@ function M.show_status() vim.notify(string.format('Environment: %s\nTarget: %s', env, meta.triplet or 'Unknown'), vim.log.levels.INFO, { title = 'PlatformIO Status' }) end +local pio_group = vim.api.nvim_create_augroup('PioPersist', { clear = true }) +vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { + group = pio_group, + callback = function() + -- Pass 'true' to save silently in the background + M.save_project_config(true) + end, + desc = 'Automatically save PlatformIO project metadata', +}) + -- 5. Keybindings -- Switch Environment -vim.keymap.set('n', '\\e', metadata.switch_env(), { desc = 'Switch environment' }) +vim.keymap.set('n', '\\e', M.switch_env(), { desc = 'Switch environment' }) -- write -- vim.keymap.set('n', '\\s', function() --- metadata.save_project_config(false) +-- M.save_project_config(false) -- end, { desc = 'Config status' }) -- Manual Status Check -vim.keymap.set('n', 'ps', metadata.show_status(), { desc = 'PIO Status' }) +vim.keymap.set('n', 'ps', M.show_status(), { desc = 'PIO Status' }) return M diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 6f5c0a85..e659d87b 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -455,16 +455,6 @@ function M.init() local metadata = require('platformio.metadata') metadata.load_project_config() - local pio_group = vim.api.nvim_create_augroup('PioPersist', { clear = true }) - vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { - group = pio_group, - callback = function() - -- Pass 'true' to save silently in the background - metadata.save_project_config(true) - end, - desc = 'Automatically save PlatformIO project metadata', - }) - ---------------------------------------------------------------------------------------- -- INFO: create clangd required files ----------------------------------------------------------------------------------------- From 42bfaba951620474b2b41baee7f83f7b42e42534 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 11:02:05 +0300 Subject: [PATCH 0717/1406] update --- lua/platformio/metadata.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index e7400725..fad894b2 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -106,7 +106,7 @@ vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { -- 5. Keybindings -- Switch Environment -vim.keymap.set('n', '\\e', M.switch_env(), { desc = 'Switch environment' }) +vim.keymap.set('n', '\\e', M.switch_env, { desc = 'Switch environment' }) -- write -- vim.keymap.set('n', '\\s', function() @@ -114,5 +114,5 @@ vim.keymap.set('n', '\\e', M.switch_env(), { desc = 'Switch environment' -- end, { desc = 'Config status' }) -- Manual Status Check -vim.keymap.set('n', 'ps', M.show_status(), { desc = 'PIO Status' }) +vim.keymap.set('n', 'ps', M.show_status, { desc = 'PIO Status' }) return M From 1470b1a2232bba07139605d3aef1b3fb8b9e2e20 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 11:06:44 +0300 Subject: [PATCH 0718/1406] update --- lua/platformio/metadata.lua | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index fad894b2..345cd865 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -106,7 +106,9 @@ vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { -- 5. Keybindings -- Switch Environment -vim.keymap.set('n', '\\e', M.switch_env, { desc = 'Switch environment' }) +vim.keymap.set('n', '\\e', function() + M.switch_env() +end, { desc = 'Switch environment' }) -- write -- vim.keymap.set('n', '\\s', function() @@ -114,5 +116,7 @@ vim.keymap.set('n', '\\e', M.switch_env, { desc = 'Switch environment' } -- end, { desc = 'Config status' }) -- Manual Status Check -vim.keymap.set('n', 'ps', M.show_status, { desc = 'PIO Status' }) +vim.keymap.set('n', 'ps', function() + M.show_status() +end, { desc = 'PIO Status' }) return M From 16c364b1a3e33010e56b5fb9b8641db3f2d16bfe Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 11:17:37 +0300 Subject: [PATCH 0719/1406] update --- lua/platformio/metadata.lua | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 345cd865..565038de 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -106,9 +106,9 @@ vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { -- 5. Keybindings -- Switch Environment -vim.keymap.set('n', '\\e', function() - M.switch_env() -end, { desc = 'Switch environment' }) +-- vim.keymap.set('n', '\\e', function() +-- M.switch_env() +-- end, { desc = 'Switch environment' }) -- write -- vim.keymap.set('n', '\\s', function() @@ -119,4 +119,5 @@ end, { desc = 'Switch environment' }) vim.keymap.set('n', 'ps', function() M.show_status() end, { desc = 'PIO Status' }) + return M From 2f4a72e7b57e33254945ec06d8861fca3b170897 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 11:24:46 +0300 Subject: [PATCH 0720/1406] update --- lua/platformio/metadata.lua | 29 +++- metadata.lua | 268 ++++++++++-------------------------- 2 files changed, 101 insertions(+), 196 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 565038de..12ca43a0 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -104,7 +104,34 @@ vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { desc = 'Automatically save PlatformIO project metadata', }) --- 5. Keybindings +-- 5. Environment Switcher UI +function M.switch_env() + if not _G.metadata.envs or next(_G.metadata.envs) == nil then + vim.notify('No environments found. Run PlatformIO Refresh first.', vim.log.levels.WARN) + return + end + + local options = vim.tbl_keys(_G.metadata.envs) + table.sort(options) + + vim.ui.select(options, { + prompt = 'Select PlatformIO Environment:', + format_item = function(item) + local indicator = (item == _G.metadata.active_env) and '● ' or '○ ' + return indicator .. item + end, + }, function(choice) + if choice then + _G.metadata.active_env = choice + -- Save immediately on user selection + M.save_project_config(false) + -- Force LSP to pick up new fallbackFlags/defines + vim.cmd('LspRestart clangd') + end + end) +end + +-- 6. Keybindings -- Switch Environment -- vim.keymap.set('n', '\\e', function() -- M.switch_env() diff --git a/metadata.lua b/metadata.lua index 2fe804f4..f89054d9 100644 --- a/metadata.lua +++ b/metadata.lua @@ -1,45 +1,45 @@ --- -- Global metadata initialization --- _G.metadata = _G.metadata --- or { --- envs = {}, --- active_env = '', --- default_envs = {}, --- core_dir = '', --- packages_dir = '', --- platforms_dir = '', --- query_driver = '', --- cc_compiler = '', --- triplet = '', --- toolchain = '', --- sysroot = '', --- fallbackFlags = {}, --- } +-- -- Performance-proof: Uses guaranteed Vimscript sha256 via Lua bridge +-- local function get_safe_hash(data) +-- -- sha256 is built into Neovim's core and never nil +-- return vim.fn.sha256(data) +-- end -- -- local M = {} -- local last_saved_hash = nil --- local config_path = vim.fn.getcwd() .. '/.project_config.json' --- --- -- Helper: Performance-friendly hashing for change detection --- local function get_current_hash() --- if not _G.metadata then --- return nil --- end --- return vim.hash(vim.json.encode(_G.metadata)) --- end +-- local config_path = vim.fn.getcwd() .. '/.pioConfig.json' +-- +-- -- -- Global metadata initialization +-- -- _G.metadata = _G.metadata +-- -- or { +-- -- envs = {}, +-- -- active_env = '', +-- -- default_envs = {}, +-- -- core_dir = '', +-- -- packages_dir = '', +-- -- platforms_dir = '', +-- -- query_driver = '', +-- -- cc_compiler = '', +-- -- triplet = '', +-- -- toolchain = '', +-- -- sysroot = '', +-- -- fallbackFlags = {}, +-- -- } -- -- -- 1. Optimized Save Function +-- -- function M.save_project_config(quiet) -- if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then -- return -- end -- --- local current_hash = get_current_hash() +-- local current_data = vim.json.encode(_G.metadata) +-- local current_hash = get_safe_hash(current_data) -- --- -- Performance check: Only write to disk if data changed +-- -- Only write if data actually changed -- if current_hash ~= last_saved_hash then -- local file = io.open(config_path, 'w') -- if file then --- file:write(vim.json.encode(_G.metadata)) +-- file:write(current_data) -- file:close() -- last_saved_hash = current_hash -- @@ -53,30 +53,60 @@ -- end -- end -- --- -- 2. Robust Load Function +-- -- 2. Robust Load Function (Startup) +-- local default_metadata = { +-- envs = {}, +-- active_env = '', +-- default_envs = {}, +-- core_dir = '', +-- packages_dir = '', +-- platforms_dir = '', +-- query_driver = '', +-- cc_compiler = '', +-- triplet = '', +-- toolchain = '', +-- sysroot = '', +-- fallbackFlags = {}, +-- } +-- -- function M.load_project_config() --- if vim.fn.filereadable(config_path) == 1 then --- local file = io.open(config_path, 'r') +-- local path = vim.fn.getcwd() .. '/.project_config.json' +-- local success = false +-- +-- if vim.fn.filereadable(path) == 1 then +-- local file = io.open(path, 'r') -- if file then -- local content = file:read('*a') -- file:close() --- -- local ok, decoded = pcall(vim.json.decode, content) --- if ok and decoded then +-- if ok and type(decoded) == 'table' then -- _G.metadata = decoded --- last_saved_hash = vim.hash(content) --- vim.notify('Environment: ' .. (_G.metadata.active_env or 'None'), vim.log.levels.INFO, { --- title = 'PlatformIO Loaded', --- }) +-- last_saved_hash = get_safe_hash(content) +-- success = true +-- end +-- end +-- end +-- +-- -- If no file or failed to read, write defaults immediately +-- if not success then +-- _G.metadata = vim.deepcopy(default_metadata) +-- local encoded = vim.json.encode(_G.metadata) +-- local file = io.open(path, 'w') +-- if file then +-- file:write(encoded) +-- file:close() +-- last_saved_hash = get_safe_hash(encoded) +-- if vim.fn.filereadable('platformio.ini') == 1 then +-- vim.notify('Initialized new project settings', vim.log.levels.INFO, { title = 'PlatformIO' }) -- end -- end -- end -- end -- --- -- 3. The "Pick Environment" UI (Instant Switch & Save) +-- -- 3. Environment Switcher UI -- function M.switch_env() -- if not _G.metadata.envs or next(_G.metadata.envs) == nil then --- vim.notify('No environments found in metadata', vim.log.levels.ERROR) +-- vim.notify('No environments found. Run PlatformIO Refresh first.', vim.log.levels.WARN) -- return -- end -- @@ -86,170 +116,18 @@ -- vim.ui.select(options, { -- prompt = 'Select PlatformIO Environment:', -- format_item = function(item) --- return ' ' .. item .. (item == _G.metadata.active_env and ' (current)' or '') +-- local indicator = (item == _G.metadata.active_env) and '● ' or '○ ' +-- return indicator .. item -- end, -- }, function(choice) -- if choice then -- _G.metadata.active_env = choice --- -- Immediately save the change +-- -- Save immediately on user selection -- M.save_project_config(false) --- -- Trigger LSP restart or internal refresh here if needed +-- -- Force LSP to pick up new fallbackFlags/defines -- vim.cmd('LspRestart clangd') -- end -- end) -- end -- --- -- 4. Setup Startup and Autocmds --- M.load_project_config() --- --- local group = vim.api.nvim_create_augroup('PioPersist', { clear = true }) --- --- -- Autosave only on important events to keep performance high --- vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { --- group = group, --- callback = function() --- M.save_project_config(true) --- end, --- }) --- --- -- 5. Keybindings --- vim.keymap.set('n', 'pe', M.switch_env, { desc = 'PlatformIO: Switch Environment' }) --- vim.keymap.set('n', 'ps', function() --- M.save_project_config(false) --- end, { desc = 'PlatformIO: Manual Save/Status' }) --- -- return M --- --- Performance-proof: Uses guaranteed Vimscript sha256 via Lua bridge -local function get_safe_hash(data) - -- sha256 is built into Neovim's core and never nil - return vim.fn.sha256(data) -end - -local M = {} -local last_saved_hash = nil -local config_path = vim.fn.getcwd() .. '/.pioConfig.json' - --- -- Global metadata initialization --- _G.metadata = _G.metadata --- or { --- envs = {}, --- active_env = '', --- default_envs = {}, --- core_dir = '', --- packages_dir = '', --- platforms_dir = '', --- query_driver = '', --- cc_compiler = '', --- triplet = '', --- toolchain = '', --- sysroot = '', --- fallbackFlags = {}, --- } - --- 1. Optimized Save Function - -function M.save_project_config(quiet) - if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then - return - end - - local current_data = vim.json.encode(_G.metadata) - local current_hash = get_safe_hash(current_data) - - -- Only write if data actually changed - if current_hash ~= last_saved_hash then - local file = io.open(config_path, 'w') - if file then - file:write(current_data) - file:close() - last_saved_hash = current_hash - - if not quiet then - vim.notify('Project settings synced to disk', vim.log.levels.INFO, { - title = 'PlatformIO', - render = 'compact', - }) - end - end - end -end - --- 2. Robust Load Function (Startup) -local default_metadata = { - envs = {}, - active_env = '', - default_envs = {}, - core_dir = '', - packages_dir = '', - platforms_dir = '', - query_driver = '', - cc_compiler = '', - triplet = '', - toolchain = '', - sysroot = '', - fallbackFlags = {}, -} - -function M.load_project_config() - local path = vim.fn.getcwd() .. '/.project_config.json' - local success = false - - if vim.fn.filereadable(path) == 1 then - local file = io.open(path, 'r') - if file then - local content = file:read('*a') - file:close() - local ok, decoded = pcall(vim.json.decode, content) - if ok and type(decoded) == 'table' then - _G.metadata = decoded - last_saved_hash = get_safe_hash(content) - success = true - end - end - end - - -- If no file or failed to read, write defaults immediately - if not success then - _G.metadata = vim.deepcopy(default_metadata) - local encoded = vim.json.encode(_G.metadata) - local file = io.open(path, 'w') - if file then - file:write(encoded) - file:close() - last_saved_hash = get_safe_hash(encoded) - if vim.fn.filereadable('platformio.ini') == 1 then - vim.notify('Initialized new project settings', vim.log.levels.INFO, { title = 'PlatformIO' }) - end - end - end -end - --- 3. Environment Switcher UI -function M.switch_env() - if not _G.metadata.envs or next(_G.metadata.envs) == nil then - vim.notify('No environments found. Run PlatformIO Refresh first.', vim.log.levels.WARN) - return - end - - local options = vim.tbl_keys(_G.metadata.envs) - table.sort(options) - - vim.ui.select(options, { - prompt = 'Select PlatformIO Environment:', - format_item = function(item) - local indicator = (item == _G.metadata.active_env) and '● ' or '○ ' - return indicator .. item - end, - }, function(choice) - if choice then - _G.metadata.active_env = choice - -- Save immediately on user selection - M.save_project_config(false) - -- Force LSP to pick up new fallbackFlags/defines - vim.cmd('LspRestart clangd') - end - end) -end - -return M From 392b7415f60c25fe0f1f3ceefeb0e38a25844955 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 11:43:45 +0300 Subject: [PATCH 0721/1406] update --- lua/platformio/metadata.lua | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 12ca43a0..fd7c8fe0 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -133,17 +133,17 @@ end -- 6. Keybindings -- Switch Environment --- vim.keymap.set('n', '\\e', function() --- M.switch_env() --- end, { desc = 'Switch environment' }) +vim.keymap.set('n', '\\e', function() + M.switch_env() +end, { desc = 'Switch environment' }) -- write --- vim.keymap.set('n', '\\s', function() --- M.save_project_config(false) --- end, { desc = 'Config status' }) +vim.keymap.set('n', '\\s', function() + M.save_project_config(false) +end, { desc = 'Config status' }) -- Manual Status Check -vim.keymap.set('n', 'ps', function() +vim.keymap.set('n', '\\s', function() M.show_status() end, { desc = 'PIO Status' }) From 8d26d4d4743d6c7959946a637abf95f689d973ce Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 11:47:54 +0300 Subject: [PATCH 0722/1406] update --- lua/platformio/metadata.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index fd7c8fe0..ad7f4c99 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -135,16 +135,16 @@ end -- Switch Environment vim.keymap.set('n', '\\e', function() M.switch_env() -end, { desc = 'Switch environment' }) +end, { desc = 'Switch [E]nvironment' }) -- write -vim.keymap.set('n', '\\s', function() +vim.keymap.set('n', '\\w', function() M.save_project_config(false) -end, { desc = 'Config status' }) +end, { desc = 'config [W]rite' }) -- Manual Status Check vim.keymap.set('n', '\\s', function() M.show_status() -end, { desc = 'PIO Status' }) +end, { desc = 'config [S]tatus' }) return M From 8a3f00903718ddfa4a91bfad52ff01b0766326be Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 12:30:34 +0300 Subject: [PATCH 0723/1406] update --- lua/platformio/metadata.lua | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index ad7f4c99..ac133904 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -106,31 +106,47 @@ vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { -- 5. Environment Switcher UI function M.switch_env() + -- 1. Safety check for metadata if not _G.metadata.envs or next(_G.metadata.envs) == nil then - vim.notify('No environments found. Run PlatformIO Refresh first.', vim.log.levels.WARN) + vim.notify('No environments found. Please refresh PlatformIO data.', vim.log.levels.WARN) return end + -- 2. Prepare the list of environments local options = vim.tbl_keys(_G.metadata.envs) table.sort(options) + -- 3. Open the selection UI vim.ui.select(options, { prompt = 'Select PlatformIO Environment:', format_item = function(item) - local indicator = (item == _G.metadata.active_env) and '● ' or '○ ' - return indicator .. item + local icon = (item == _G.metadata.active_env) and ' ' or '○ ' + return icon .. item end, }, function(choice) if choice then + -- Update active environment _G.metadata.active_env = choice - -- Save immediately on user selection - M.save_project_config(false) - -- Force LSP to pick up new fallbackFlags/defines - vim.cmd('LspRestart clangd') + + -- 4. Persist change to disk (silently) + M.save_project_config(true) + + -- 5. Notify the user with the new board info + local board = _G.metadata.envs[choice].board or 'unknown' + vim.notify(string.format('Switched to %s\nBoard: %s', choice, board), vim.log.levels.INFO, { title = 'PlatformIO' }) + + -- 6. RESTART LSP (Crucial for refreshing includes/defines) + -- We wrap in pcall in case clangd isn't actually running yet + pcall(function() + vim.cmd('LspRestart clangd') + end) end end) end +-- -- Force LSP to pick up new fallbackFlags/defines +-- local lspTools = require('platformio.lsp.tools') +-- lspTools.lsp_restart() -- 6. Keybindings -- Switch Environment vim.keymap.set('n', '\\e', function() From 15a52af1bda5d88f830dabcdaaa64077e0f9ddbb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 12:41:27 +0300 Subject: [PATCH 0724/1406] update --- lua/platformio/utils/pio.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 3aed7531..c38332c2 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -84,7 +84,7 @@ function M.fix_pio_compile_commands() return end - print('PioFix0') + -- print('PioFix0') -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path local path_map = {} local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') @@ -97,7 +97,7 @@ function M.fix_pio_compile_commands() -- Extract filename (e.g., riscv32-esp-elf-gcc) local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = full_path - print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) + -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) end end @@ -112,11 +112,11 @@ function M.fix_pio_compile_commands() local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') if not is_abs then local short_name = first_token:gsub('%.exe$', '') - print('PioFix2: short_name=' .. short_name) + -- print('PioFix2: short_name=' .. short_name) -- Direct Query: Does this name exist in our discovered list? if path_map[short_name] then cmd_parts[1] = path_map[short_name] - print('PioFix3: full_name=' .. cmd_parts[1]) + -- print('PioFix3: full_name=' .. cmd_parts[1]) entry.command = table.concat(cmd_parts, ' ') modified = modified + 1 end From 91ae01d5c9121cb8a93bdcaf179562b91be57996 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 12:45:16 +0300 Subject: [PATCH 0725/1406] update --- lua/platformio/metadata.lua | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index ac133904..08331b76 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -138,15 +138,14 @@ function M.switch_env() -- 6. RESTART LSP (Crucial for refreshing includes/defines) -- We wrap in pcall in case clangd isn't actually running yet pcall(function() - vim.cmd('LspRestart clangd') + -- Force LSP to pick up new fallbackFlags/defines + local lspTools = require('platformio.lsp.tools') + lspTools.lsp_restart() end) end end) end --- -- Force LSP to pick up new fallbackFlags/defines --- local lspTools = require('platformio.lsp.tools') --- lspTools.lsp_restart() -- 6. Keybindings -- Switch Environment vim.keymap.set('n', '\\e', function() From 849339293746cb4e561bfb9043fada4f2b77506a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 16:37:44 +0300 Subject: [PATCH 0726/1406] update --- lua/platformio/metadata.lua | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 08331b76..d7bb8c56 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -15,6 +15,15 @@ _G.metadata = _G.metadata fallbackFlags = {}, } +_G.get_pio_status = function() + if _G.metadata and _G.metadata.active_env ~= '' then + return ' [ ' .. _G.metadata.active_env .. '] ' + end + return '' +end + +vim.o.statusline = '%f %m %r %= %{v:lua.get_pio_status()} %y %p%% %l:%c' + local M = {} local last_saved_hash = '' local config_path = vim.fn.getcwd() .. '/.project_config.json' From dc6a6453ded7fa7468d4411d66cd6fe2d2ef4406 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 16:58:46 +0300 Subject: [PATCH 0727/1406] update --- lua/platformio/metadata.lua | 3 ++- mini_nvimPlatformio.lua | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index d7bb8c56..6864b55c 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -17,7 +17,8 @@ _G.metadata = _G.metadata _G.get_pio_status = function() if _G.metadata and _G.metadata.active_env ~= '' then - return ' [ ' .. _G.metadata.active_env .. '] ' + -- return ' [ ' .. _G.metadata.active_env .. '] ' + return '%#PioStatus# [ ' .. _G.metadata.active_env .. '] %*' end return '' end diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index ca7b5ffe..927d362e 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -53,6 +53,8 @@ else vim.opt.shellquote = '' vim.opt.shellxquote = '' end +-- Define a custom highlight group +vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#A6E22E', bold = true }) ---------------------------------------------------------------------------------------- -- INFO: Set diagnostic config From 6e4e22837b0a6ec5f975d646188b3b5ba7a09626 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 17:05:17 +0300 Subject: [PATCH 0728/1406] update --- lua/platformio/metadata.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 6864b55c..3e6972f8 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -15,16 +15,16 @@ _G.metadata = _G.metadata fallbackFlags = {}, } +-- Move the %#PioStatus# and %* outside of the curly braces +vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' + _G.get_pio_status = function() if _G.metadata and _G.metadata.active_env ~= '' then - -- return ' [ ' .. _G.metadata.active_env .. '] ' - return '%#PioStatus# [ ' .. _G.metadata.active_env .. '] %*' + return ' [ ' .. _G.metadata.active_env .. '] ' end return '' end -vim.o.statusline = '%f %m %r %= %{v:lua.get_pio_status()} %y %p%% %l:%c' - local M = {} local last_saved_hash = '' local config_path = vim.fn.getcwd() .. '/.project_config.json' From 22a67a17e2feec866b476a1a0f93461c118dc8c4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 19:10:24 +0300 Subject: [PATCH 0729/1406] update --- lua/platformio/lsp/tools.lua | 23 +- lua/platformio/pio_setup.lua | 221 ++++++++-------- pio_setup.lua | 84 +----- pio_setupold.lua | 485 +++++++++++++++++++++++++++++++++++ 4 files changed, 624 insertions(+), 189 deletions(-) create mode 100644 pio_setupold.lua diff --git a/lua/platformio/lsp/tools.lua b/lua/platformio/lsp/tools.lua index f1741175..4fe55a22 100644 --- a/lua/platformio/lsp/tools.lua +++ b/lua/platformio/lsp/tools.lua @@ -7,6 +7,7 @@ local M = {} --- stylua: ignore function M.get_sysroot_triplet(cc_compiler) local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') + -- Early exit if path is nil or not a directory if not bin_path or vim.fn.isdirectory(bin_path) == 0 then return nil @@ -36,15 +37,20 @@ function M.get_sysroot_triplet(cc_compiler) local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') -- sysroot folder is expected to have the same name as the triplet local sysroot = toolchain_root .. '/' .. triplet + local query_driver = bin_path .. '/' .. triplet .. '-*' -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) -- Only return data if the sysroot folder actually exists on disk if vim.fn.isdirectory(sysroot) == 1 then + _G.metadata.triplet = triplet + _G.metadata.sysroot = sysroot + _G.metadata.toolchain = toolchain_root + _G.metadata.query_driver = query_driver return { triplet = triplet, sysroot = sysroot, toolchain_root = toolchain_root, - query_driver = bin_path .. '/' .. triplet .. '-*', + query_driver = query_driver, } end return nil @@ -55,13 +61,14 @@ function M.lsp_restart(name) -- vim.schedule_wrap(function() vim.notify('LSP restart.', vim.log.levels.WARN) - local status, data = pcall(M.get_sysroot_triplet, _G.metadata.cc_compiler) - if status and data and data.triplet and data.triplet ~= '' then - _G.metadata.triplet = data.triplet - _G.metadata.sysroot = data.sysroot - _G.metadata.query_driver = data.query_driver - _G.metadata.toolchain = data.toolchain_root - end + -- local status, data = pcall(M.get_sysroot_triplet, _G.metadata.cc_compiler) + pcall(M.get_sysroot_triplet, _G.metadata.cc_compiler) + -- if status and data and data.triplet and data.triplet ~= '' then + -- _G.metadata.triplet = data.triplet + -- _G.metadata.sysroot = data.sysroot + -- _G.metadata.query_driver = data.query_driver + -- _G.metadata.toolchain = data.toolchain_root + -- end local clangConfig = _G.get_clangd_config() -- print(vim.inspect(clangConfig)) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index e659d87b..3e0686b6 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -4,64 +4,8 @@ local misc = require('platformio.utils.misc') local lsp = require('platformio.lsp.tools') local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen --- lua/pio_setup.lua --- This module manages PlatformIO project integration, LSP toolchain detection, --- and automatic sysroot patching for standard library headers (, etc.) - local debounce_timer = vim.uv.new_timer() --- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) --- -- INFO: --- -- ============================================================================= --- -- UNIVERSAL TOOLCHAIN DETECTION --- -- ============================================================================= --- --- stylua: ignore --- local function get_sysroot_triplet(cc_compiler) --- local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') --- -- Early exit if path is nil or not a directory --- if not bin_path or vim.fn.isdirectory(bin_path) == 0 then --- return nil --- end --- --- -- Normalize backslashes to forward slashes for cross-platform consistency --- bin_path = bin_path:gsub('\\', '/') --- local files = vim.fn.readdir(bin_path) --- local triplet = nil --- --- -- Loop through files to find the compiler and extract the triplet --- for _, name in ipairs(files) do --- -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ --- local match = name:match('^(.*)%-g[c%+][c%+]') --- if match then --- triplet = match --- break --- end --- end --- --- -- Return nil if no compiler was found in the bin directory --- if not triplet then --- return nil --- end --- --- -- toolchain_root is the parent of the 'bin' folder --- local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') --- -- sysroot folder is expected to have the same name as the triplet --- local sysroot = toolchain_root .. '/' .. triplet --- --- -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) --- -- Only return data if the sysroot folder actually exists on disk --- if vim.fn.isdirectory(sysroot) == 1 then --- return { --- triplet = triplet, --- sysroot = sysroot, --- toolchain_root = toolchain_root, --- query_driver = bin_path .. '/' .. triplet .. '-*', --- } --- end --- return nil --- end --- - -- INFO: -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag -- stylua: ignore @@ -390,60 +334,131 @@ end -- INFO: -- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync +--- stylua: ignore +---------------------------------------------------------------------------------------------- + +local last_ini_hash = nil + +-- Helper to safely read file content +local function safe_read_file(path) + local f = io.open(path, 'r') + if not f then + return nil + end + local content = f:read('*a') + f:close() + return content +end + +local function wait_and_refresh() + -- Check if handle is valid before proceeding + if not pio_manager or not lsp then + vim.notify('PIO Manager or LSP module not found', vim.log.levels.ERROR) + return + end + + -- Check for lockfile (adjust path if your project uses different build dir) + local lock_file = vim.uv.cwd() .. '/.pio/build/lockfile' + if vim.fn.filereadable(lock_file) == 1 then + vim.defer_fn(wait_and_refresh, 1000) + return + end + + pio_manager.refresh(function() + pcall(function() + boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd]], _G.metadata.core_dir) + -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') + pio_generate_db() + lsp.lsp_restart('clangd') + end) + vim.notify('Build finished: Config reloaded', vim.log.levels.INFO, { title = 'PlatformIO' }) + end) +end + -- stylua: ignore -local function start_pio_watcher() - local dir_path = vim.uv.cwd() - if not dir_path then return end +function M.start_pio_watcher() + local cwd = vim.uv.cwd() + if not cwd then return end + + local ini_path = cwd .. '/platformio.ini' + if vim.fn.filereadable(ini_path) == 0 then return end + + -- Initial hash setup + local init_content = safe_read_file(ini_path) + if init_content then last_ini_hash = vim.fn.sha256(init_content) end - -- Create a directory watcher local handle = vim.uv.new_fs_event() - if not handle then return end + if not handle then vim.notify('Failed to create FS watcher', vim.log.levels.ERROR) return + end - -- local last_trigger = 0 - -- Watch the directory for platformio.ini creation or changes handle:start( - dir_path, - { - watch_entry = false, -- watch the file/dir itself - stat = false, -- use stat to detect changes (slower but more reliable on some FS) - recursive = false, -- watch subdirectories (if path is a directory) - }, + cwd, + { recursive = false }, vim.schedule_wrap(function(err, filename, events) - if err or not events or not events.change then return end - -- Trigger only if the changed file is platformio.ini - if filename == 'platformio.ini' and (events.change or events.rename) then - -- -- ignore events within time - -- local current_time = vim.uv.now() - -- -- IGNORE events if they happen within 100ms of the last one - -- if current_time - last_trigger < 100 then - -- return - -- end - -- last_trigger = current_time + -- 1. Check for UV errors or nil filenames + if err then + vim.notify('Watcher error: ' .. tostring(err), vim.log.levels.ERROR) + return + end + if filename ~= 'platformio.ini' or not events then return end + -- 2. Safe read with pcall (Windows may lock the file during 'pio run') + local ok, new_content = pcall(safe_read_file, ini_path) + if not ok or not new_content then return end + + -- 3. Content check + local new_hash = vim.fn.sha256(new_content) + if new_hash ~= last_ini_hash then + last_ini_hash = new_hash + + -- 4. Check for timer nil if debounce_timer then debounce_timer:stop() - debounce_timer:start( - 500, - 0, - vim.schedule_wrap(function() - pio_manager.refresh(function() - -- vim.schedule(function() - -- local status, data = pcall(lsp.get_sysroot_triplet, _G.metadata.cc_compiler) - -- if status and data and data.triplet and data.triplet ~= '' then - -- _G.metadata.triplet = data.triplet - -- _G.metadata.sysroot = data.sysroot - -- _G.metadata.query_driver = data.query_driver - -- _G.metadata.toolchain = data.toolchain_root - -- end - -- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) - - pio_generate_db() - lsp.lsp_restart('clangd') - -- end) - end) end)) end end end)) + debounce_timer:start(500, 0, vim.schedule_wrap(wait_and_refresh)) + end + end + end) + ) end + +---------------------------------------------------------------------------------------------- +-- local function start_pio_watcher() +-- local dir_path = vim.uv.cwd() +-- if not dir_path then return end +-- +-- -- Create a directory watcher +-- local handle = vim.uv.new_fs_event() +-- if not handle then return end +-- +-- -- local last_trigger = 0 +-- -- Watch the directory for platformio.ini creation or changes +-- handle:start( +-- dir_path, +-- { +-- watch_entry = false, -- watch the file/dir itself +-- stat = false, -- use stat to detect changes (slower but more reliable on some FS) +-- recursive = false, -- watch subdirectories (if path is a directory) +-- }, +-- vim.schedule_wrap(function(err, filename, events) +-- if err or not events or not events.change then return end +-- -- Trigger only if the changed file is platformio.ini +-- if filename == 'platformio.ini' and (events.change or events.rename) then +-- if debounce_timer then +-- debounce_timer:stop() +-- debounce_timer:start( +-- 500, +-- 0, +-- vim.schedule_wrap(function() +-- pio_manager.refresh(function() +-- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +-- boilerplate_gen([[.clangd]], _G.metadata.core_dir) +-- -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') +-- pio_generate_db() +-- lsp.lsp_restart('clangd') +-- -- end) +-- end) end)) end end end)) +-- end ------------------------------------------------------------------------------------------------------ -- INFO: 6. Exported setup function function M.init() @@ -459,10 +474,6 @@ function M.init() -- INFO: create clangd required files ----------------------------------------------------------------------------------------- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) - -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - -- boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) - -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) - -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) --------------------------------------------------------------------------------- @@ -473,7 +484,7 @@ function M.init() end -- Always start the watcher so it can catch a future 'pio init' - start_pio_watcher() + M.start_pio_watcher() -- If the file already exists, do an initial sync if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then diff --git a/pio_setup.lua b/pio_setup.lua index 9293e0a9..d36bca00 100644 --- a/pio_setup.lua +++ b/pio_setup.lua @@ -4,64 +4,8 @@ -- local lsp = require('platformio.lsp.tools') -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -- --- -- lua/pio_setup.lua --- -- This module manages PlatformIO project integration, LSP toolchain detection, --- -- and automatic sysroot patching for standard library headers (, etc.) --- -- local debounce_timer = vim.uv.new_timer() -- --- -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) --- -- INFO: --- -- ============================================================================= --- -- UNIVERSAL TOOLCHAIN DETECTION --- -- ============================================================================= --- --- stylua: ignore --- local function get_sysroot_triplet(cc_compiler) --- local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') --- -- Early exit if path is nil or not a directory --- if not bin_path or vim.fn.isdirectory(bin_path) == 0 then --- return nil --- end --- --- -- Normalize backslashes to forward slashes for cross-platform consistency --- bin_path = bin_path:gsub('\\', '/') --- local files = vim.fn.readdir(bin_path) --- local triplet = nil --- --- -- Loop through files to find the compiler and extract the triplet --- for _, name in ipairs(files) do --- -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ --- local match = name:match('^(.*)%-g[c%+][c%+]') --- if match then --- triplet = match --- break --- end --- end --- --- -- Return nil if no compiler was found in the bin directory --- if not triplet then --- return nil --- end --- --- -- toolchain_root is the parent of the 'bin' folder --- local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') --- -- sysroot folder is expected to have the same name as the triplet --- local sysroot = toolchain_root .. '/' .. triplet --- --- -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) --- -- Only return data if the sysroot folder actually exists on disk --- if vim.fn.isdirectory(sysroot) == 1 then --- return { --- triplet = triplet, --- sysroot = sysroot, --- toolchain_root = toolchain_root, --- query_driver = bin_path .. '/' .. triplet .. '-*', --- } --- end --- return nil --- end --- --- -- -- INFO: -- -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag -- -- stylua: ignore @@ -95,7 +39,7 @@ -- -- for _, section in ipairs(data) do -- -- Each section must be a table with at least 2 elements: [1]=name, [2]=content --- if type(section) == 'table' and #section >= 2 then +-- if section and type(section) == 'table' and #section >= 2 then -- local s_id = section[1] -- Section header string -- local s_body = section[2] -- Table of key-value pairs -- @@ -222,6 +166,7 @@ -- end) -- return -- end +-- -- _G.metadata.core_dir = '' -- _G.metadata.packages_dir = '' -- _G.metadata.platforms_dir = '' @@ -255,7 +200,7 @@ -- -- assign [active_env] -- if #_G.metadata.default_envs > 0 then -- _G.metadata.active_env = _G.metadata.default_envs[1] or '' --- elseif _G.metadata.envs and #_G.metadata.envs > 0 then +-- elseif _G.metadata.envs and next(_G.metadata.envs) ~= '' then -- _G.metadata.active_env = next(_G.metadata.envs) or '' -- end -- @@ -411,14 +356,6 @@ -- if err or not events or not events.change then return end -- -- Trigger only if the changed file is platformio.ini -- if filename == 'platformio.ini' and (events.change or events.rename) then --- -- -- ignore events within time --- -- local current_time = vim.uv.now() --- -- -- IGNORE events if they happen within 100ms of the last one --- -- if current_time - last_trigger < 100 then --- -- return --- -- end --- -- last_trigger = current_time --- -- if debounce_timer then -- debounce_timer:stop() -- debounce_timer:start( @@ -426,18 +363,8 @@ -- 0, -- vim.schedule_wrap(function() -- pio_manager.refresh(function() --- -- vim.schedule(function() --- local status, data = pcall(get_sysroot_triplet, _G.metadata.cc_compiler) --- if status and data and data.triplet and data.triplet ~= '' then --- _G.metadata.triplet = data.triplet --- _G.metadata.sysroot = data.sysroot --- _G.metadata.query_driver = data.query_driver --- _G.metadata.toolchain = data.toolchain_root --- end --- -- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) --- -- pio_generate_db() -- lsp.lsp_restart('clangd') -- -- end) @@ -449,6 +376,11 @@ -- local config = require('platformio').config -- if config.lspClangd.enabled == true then -- vim.notify('PIO setup initialize', vim.log.levels.INFO) +-- +-- -- activate meta save and upload and env switch +-- local metadata = require('platformio.metadata') +-- metadata.load_project_config() +-- -- ---------------------------------------------------------------------------------------- -- -- INFO: create clangd required files -- ----------------------------------------------------------------------------------------- diff --git a/pio_setupold.lua b/pio_setupold.lua new file mode 100644 index 00000000..9293e0a9 --- /dev/null +++ b/pio_setupold.lua @@ -0,0 +1,485 @@ +-- M = {} +-- +-- local misc = require('platformio.utils.misc') +-- local lsp = require('platformio.lsp.tools') +-- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +-- +-- -- lua/pio_setup.lua +-- -- This module manages PlatformIO project integration, LSP toolchain detection, +-- -- and automatic sysroot patching for standard library headers (, etc.) +-- +-- local debounce_timer = vim.uv.new_timer() +-- +-- -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) +-- -- INFO: +-- -- ============================================================================= +-- -- UNIVERSAL TOOLCHAIN DETECTION +-- -- ============================================================================= +-- --- stylua: ignore +-- local function get_sysroot_triplet(cc_compiler) +-- local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') +-- -- Early exit if path is nil or not a directory +-- if not bin_path or vim.fn.isdirectory(bin_path) == 0 then +-- return nil +-- end +-- +-- -- Normalize backslashes to forward slashes for cross-platform consistency +-- bin_path = bin_path:gsub('\\', '/') +-- local files = vim.fn.readdir(bin_path) +-- local triplet = nil +-- +-- -- Loop through files to find the compiler and extract the triplet +-- for _, name in ipairs(files) do +-- -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ +-- local match = name:match('^(.*)%-g[c%+][c%+]') +-- if match then +-- triplet = match +-- break +-- end +-- end +-- +-- -- Return nil if no compiler was found in the bin directory +-- if not triplet then +-- return nil +-- end +-- +-- -- toolchain_root is the parent of the 'bin' folder +-- local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') +-- -- sysroot folder is expected to have the same name as the triplet +-- local sysroot = toolchain_root .. '/' .. triplet +-- +-- -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) +-- -- Only return data if the sysroot folder actually exists on disk +-- if vim.fn.isdirectory(sysroot) == 1 then +-- return { +-- triplet = triplet, +-- sysroot = sysroot, +-- toolchain_root = toolchain_root, +-- query_driver = bin_path .. '/' .. triplet .. '-*', +-- } +-- end +-- return nil +-- end +-- +-- +-- -- INFO: +-- -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag +-- -- stylua: ignore +-- local function pio_generate_db() +-- vim.schedule(function() vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) end) +-- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) +-- if obj.code ~= 0 then +-- vim.schedule(function() +-- if obj.code == 127 then +-- vim.notify("PIO Manager db: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) +-- else +-- vim.notify('PIO Manager db: Generating Compile Database failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) +-- end +-- end) +-- return +-- end +-- vim.schedule(function() vim.notify('PIO: Generating Compile Database successful', vim.log.levels.INFO) end) +-- end) +-- end +-- +-- -- INFO: 1. The Core PIO Manager & Generic Extractor +-- --- stylua: ignore +-- local pio_manager = (function() +-- local cache = nil -- Stores the decoded platformio.ini JSON structure +-- -- INFO: +-- local function find_in_data(data, section_name, key_name) +-- -- Safety check: Ensure data is a valid table from a successful JSON decode +-- if type(data) ~= 'table' then +-- return nil +-- end +-- +-- for _, section in ipairs(data) do +-- -- Each section must be a table with at least 2 elements: [1]=name, [2]=content +-- if type(section) == 'table' and #section >= 2 then +-- local s_id = section[1] -- Section header string +-- local s_body = section[2] -- Table of key-value pairs +-- +-- if s_id == section_name and type(s_body) == 'table' then +-- for _, kv in ipairs(s_body) do +-- -- Each kv is a table: [1]=key, [2]=value +-- if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then +-- local val = kv[2] +-- -- Treat empty strings or empty tables as nil to trigger fallback logic +-- if val == nil or val == '' or (type(val) == 'table' and #val == 0) then +-- return nil +-- end +-- return val +-- end +-- end +-- end +-- end +-- end +-- return nil +-- end +-- +-- -- INFO: ASYNC REFRESH: Fetches the latest config from PlatformIO CLI +-- --- stylua: ignore +-- local function refresh(callback) +-- vim.schedule(function() +-- vim.notify('PIO: Fetching Config ...', vim.log.levels.INFO) +-- end) +-- +-- -- INFO: get project metadata +-- local function get_metadata(attempts, env) +-- local active_env = env or _G.metadata.active_env +-- vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(int_obj) +-- vim.schedule(function() +-- vim.notify('PIO: Fetching metadata ...', vim.log.levels.INFO) +-- end) +-- +-- if int_obj.code ~= 0 then +-- -- Schedule notification to avoid error in the system callback thread +-- vim.schedule(function() +-- if int_obj.code == 127 then +-- vim.notify("PIO Manager metadata: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) +-- else +-- vim.notify('PIO Manager metadata: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) +-- end +-- end) +-- return +-- end +-- +-- if int_obj.code == 0 and int_obj.stdout then +-- local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) +-- if ok and raw_data then +-- local _, data = next(raw_data) +-- if data then +-- local fallbackFlags = {} +-- -- 1. Process Includes +-- if data.includes then +-- for category, paths in pairs(data.includes) do +-- -- If it's a toolchain path, use -isystem to suppress warnings +-- -- and tell clangd these are standard libraries +-- if category == 'toolchain' then +-- local flag = '-isystem' +-- for _, path in ipairs(paths) do +-- -- table.insert(fallbackFlags, string.format('%q', flag)) +-- -- table.insert(fallbackFlags, string.format('%q', path:gsub('\\', '/'))) +-- table.insert(fallbackFlags, string.format('%q', flag .. path:gsub('\\', '/'))) +-- end +-- end +-- -- local flag = (category == 'toolchain') and '-isystem' or '-I' +-- -- for _, path in ipairs(paths) do +-- -- table.insert(fallbackFlags, flag .. path) +-- -- end +-- end +-- end +-- -- 2. Process Defines +-- if data.defines then +-- for _, define in ipairs(data.defines) do +-- table.insert(fallbackFlags, string.format('%q', '-D' .. define)) +-- end +-- end +-- +-- -- get [cc_compiler]and [falbackFlags] +-- -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' +-- _G.metadata.cc_compiler = misc.normalize_path(data.cc_path) or '' +-- _G.metadata.fallbackFlags = fallbackFlags +-- +-- -- print(vim.inspect(_G.metadata)) +-- if callback then +-- vim.schedule(function() +-- vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) +-- callback() +-- end) +-- end +-- end +-- else +-- vim.schedule(function() +-- vim.notify('PIO: Syncing Environment failed', vim.log.levels.WARN) +-- end) +-- end +-- end +-- -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save +-- if attempts > 0 then +-- vim.defer_fn(function() +-- get_metadata(attempts - 1) +-- end, 500) +-- end +-- end) +-- end +-- +-- -- INFO: Setup Base Paths +-- local home = os.getenv('HOME') or os.getenv('USERPROFILE') +-- +-- -- INFO: Try to get explicit value from platformio.ini +-- -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' +-- -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } +-- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) +-- if ext_obj.code ~= 0 then +-- -- Schedule notification to avoid error in the system callback thread +-- vim.schedule(function() +-- if ext_obj.code == 127 then +-- vim.notify("PIO Manager config: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) +-- else +-- vim.notify('PIO Manager config: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) +-- end +-- end) +-- return +-- end +-- _G.metadata.core_dir = '' +-- _G.metadata.packages_dir = '' +-- _G.metadata.platforms_dir = '' +-- _G.metadata.active_env = '' +-- _G.metadata.default_envs = {} +-- _G.metadata.envs = {} +-- +-- local decoded = vim.json.decode(ext_obj.stdout) +-- for _, section in ipairs(decoded) do +-- if type(section) == 'table' and #section >= 2 then +-- local name, data = section[1], section[2] +-- -- 1. Extract Global PlatformIO Settings if available [core_dir][packages_dir][platforms_dir][default_envs] +-- if name == 'platformio' then +-- for _, kv in ipairs(data) do +-- local key, val = kv[1], kv[2] +-- if key ~= nil then +-- -- if _G.metadata[key] ~= nil then +-- _G.metadata[key] = val +-- end +-- end +-- -- 2. Extract all hardware [envs] like [env:seeed_xiao_esp32c3], skipping generic [env] +-- elseif name:match('^env:') then +-- local env_name = name:match('^env:(.+)') +-- _G.metadata.envs[env_name] = {} +-- for _, kv in ipairs(data) do +-- _G.metadata.envs[env_name][kv[1]] = kv[2] +-- end +-- end +-- end +-- end +-- -- assign [active_env] +-- if #_G.metadata.default_envs > 0 then +-- _G.metadata.active_env = _G.metadata.default_envs[1] or '' +-- elseif _G.metadata.envs and #_G.metadata.envs > 0 then +-- _G.metadata.active_env = next(_G.metadata.envs) or '' +-- end +-- +-- -- INFO: -- Define Mapping (key in INI, Env Var, Default Subfolder) +-- local map = { +-- core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, +-- packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, +-- platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, +-- } +-- for _, kv in ipairs(map) do +-- -- 4.0 Fallback Logic: INI -> Env Var -> Default +-- local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') +-- -- 5. Expand ${platformio.core_dir} +-- if type(result) == 'string' then +-- if result:find('${platformio.core_dir}', 1, true) then +-- result = result:gsub('%${platformio.core_dir}', _G.metadata.core_dir) +-- end +-- end +-- -- 6. Normalize Slashes for Windows +-- -- _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') +-- _G.metadata[kv.ini] = result:gsub('\\', '/'):gsub('//+', '/') +-- end +-- -- return _G.metadata[map[type].ini] +-- -- end +-- +-- if _G.metadata.active_env ~= '' then +-- vim.schedule(function() +-- vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) +-- end) +-- get_metadata(1, _G.metadata.active_env) +-- else +-- vim.schedule(function() +-- vim.notify('PIO: no [env:] found, add board first', vim.log.levels.ERROR) +-- end) +-- end +-- end) +-- end +-- +-- -- INFO: +-- return { +-- refresh = refresh, +-- -- INFO: +-- get = function(s, k) +-- if not cache then +-- return nil +-- end +-- local res = find_in_data(cache, s, k) +-- +-- -- FALLBACK: If default_envs is missing/empty, find the first hardware [env:xxx] block +-- if k == 'default_envs' and not res then +-- for _, section in ipairs(cache) do +-- if type(section) == 'table' and type(section[1]) == 'string' then +-- local name = section[1] +-- if name:find('^env:') then +-- local fallback = name:match('^env:(.+)') +-- if fallback then +-- vim.schedule(function() +-- vim.notify('PIO: default_envs empty. Using: ' .. fallback, vim.log.levels.INFO) +-- end) +-- return fallback +-- end +-- end +-- end +-- end +-- vim.schedule(function() +-- vim.notify('PIO: Config Error. Check platformio.ini no env', vim.log.levels.WARN) +-- end) +-- elseif k == 'default_envs' and res and type(res) == 'table' then +-- return res[1] +-- else +-- return res +-- end +-- end, +-- } +-- end)() +-- +-- -- INFO: +-- function _G.get_pio_sdk_info() +-- local pio_info = { includes = {}, cc_compiler = '' } +-- if vim.fn.filereadable('platformio.ini') == 0 then +-- return nil +-- end +-- +-- local handle = io.popen('pio run -t envdump') +-- if not handle then +-- return nil +-- end +-- +-- local packages_dir, cc_name, toolchain_pkg = '', '', '' +-- +-- for line in handle:lines() do +-- -- 1. Get the global packages directory +-- packages_dir = packages_dir ~= '' and packages_dir or line:match("'PROJECT_PACKAGES_DIR': '([^']+)'") +-- +-- -- 2. Get the compiler executable name (e.g., riscv32-esp-elf-gcc) +-- cc_name = cc_name ~= '' and cc_name or line:match("'CC': '([^']+)'") +-- +-- -- 3. Find the specific toolchain package name from the PACKAGES list +-- -- Matches lines like "- toolchain-riscv32-esp @ 14.2.0" +-- local pkg = line:match('%- (toolchain%-[^ ]+)') +-- if pkg then +-- toolchain_pkg = pkg +-- end +-- +-- -- 4. Collect include paths +-- local path_list = line:match("'CPPPATH': %[(.+)%]") +-- if path_list then +-- for path in path_list:gmatch("'([^']+)'") do +-- table.insert(pio_info.includes, '-I' .. path) +-- end +-- end +-- end +-- handle:close() +-- +-- -- Construct the absolute path: //bin/ +-- if packages_dir and packages_dir ~= '' and toolchain_pkg and toolchain_pkg ~= '' and cc_name ~= '' then +-- local full_path = packages_dir .. '/' .. toolchain_pkg .. '/bin/' .. cc_name +-- if vim.fn.executable(full_path) == 1 then +-- pio_info.cc_compiler = full_path +-- end +-- end +-- +-- local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' +-- print('get_pio_sdk_info(): final=' .. final) +-- -- Normalize paths for the OS and ensure backslashes for Windows if needed +-- -- print(vim.inspect(_G.metadata)) +-- return (misc.normalize_path(final)) +-- -- return _G.metadata.query_driver +-- -- return pio_info +-- end +-- +-- -- INFO: +-- -- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync +-- -- stylua: ignore +-- local function start_pio_watcher() +-- local dir_path = vim.uv.cwd() +-- if not dir_path then return end +-- +-- -- Create a directory watcher +-- local handle = vim.uv.new_fs_event() +-- if not handle then return end +-- +-- -- local last_trigger = 0 +-- -- Watch the directory for platformio.ini creation or changes +-- handle:start( +-- dir_path, +-- { +-- watch_entry = false, -- watch the file/dir itself +-- stat = false, -- use stat to detect changes (slower but more reliable on some FS) +-- recursive = false, -- watch subdirectories (if path is a directory) +-- }, +-- vim.schedule_wrap(function(err, filename, events) +-- if err or not events or not events.change then return end +-- -- Trigger only if the changed file is platformio.ini +-- if filename == 'platformio.ini' and (events.change or events.rename) then +-- -- -- ignore events within time +-- -- local current_time = vim.uv.now() +-- -- -- IGNORE events if they happen within 100ms of the last one +-- -- if current_time - last_trigger < 100 then +-- -- return +-- -- end +-- -- last_trigger = current_time +-- +-- if debounce_timer then +-- debounce_timer:stop() +-- debounce_timer:start( +-- 500, +-- 0, +-- vim.schedule_wrap(function() +-- pio_manager.refresh(function() +-- -- vim.schedule(function() +-- local status, data = pcall(get_sysroot_triplet, _G.metadata.cc_compiler) +-- if status and data and data.triplet and data.triplet ~= '' then +-- _G.metadata.triplet = data.triplet +-- _G.metadata.sysroot = data.sysroot +-- _G.metadata.query_driver = data.query_driver +-- _G.metadata.toolchain = data.toolchain_root +-- end +-- -- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) +-- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +-- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) +-- +-- pio_generate_db() +-- lsp.lsp_restart('clangd') +-- -- end) +-- end) end)) end end end)) +-- end +-- ------------------------------------------------------------------------------------------------------ +-- -- INFO: 6. Exported setup function +-- function M.init() +-- local config = require('platformio').config +-- if config.lspClangd.enabled == true then +-- vim.notify('PIO setup initialize', vim.log.levels.INFO) +-- ---------------------------------------------------------------------------------------- +-- -- INFO: create clangd required files +-- ----------------------------------------------------------------------------------------- +-- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) +-- -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +-- -- boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) +-- -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) +-- -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') +-- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) +-- boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) +-- --------------------------------------------------------------------------------- +-- +-- require('platformio.lsp.clangd') +-- if config.lspClangd.attach.enabled then +-- require('platformio.lsp.attach') +-- end +-- +-- -- Always start the watcher so it can catch a future 'pio init' +-- start_pio_watcher() +-- +-- -- If the file already exists, do an initial sync +-- if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then +-- pio_manager.refresh(function() +-- -- vim.schedule(function() +-- -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) +-- pio_generate_db() +-- lsp.lsp_restart('clangd') +-- -- end) +-- end) +-- end +-- end +-- end +-- +-- return M From 49bd97588f91fbde04d88ee3f2804a5ac4a4c648 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 20:41:19 +0300 Subject: [PATCH 0730/1406] update --- lua/platformio/pio_setup.lua | 276 +++++++++++++++++------------------ 1 file changed, 138 insertions(+), 138 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 3e0686b6..55488da5 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -10,32 +10,32 @@ local debounce_timer = vim.uv.new_timer() -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag -- stylua: ignore local function pio_generate_db() - vim.schedule(function() vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) end) + vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) - if obj.code ~= 0 then - vim.schedule(function() + vim.schedule(function() + if obj.code ~= 0 then if obj.code == 127 then vim.notify("PIO Manager db: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else vim.notify('PIO Manager db: Generating Compile Database failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) end + return + end + vim.schedule(function() + vim.notify('PIO: Generating Compile Database successful', vim.log.levels.INFO) end) - return - end - vim.schedule(function() vim.notify('PIO: Generating Compile Database successful', vim.log.levels.INFO) end) + end) end) end -- INFO: 1. The Core PIO Manager & Generic Extractor ---- stylua: ignore +-- stylua: ignore local pio_manager = (function() local cache = nil -- Stores the decoded platformio.ini JSON structure -- INFO: local function find_in_data(data, section_name, key_name) -- Safety check: Ensure data is a valid table from a successful JSON decode - if type(data) ~= 'table' then - return nil - end + if type(data) ~= 'table' then return nil end for _, section in ipairs(data) do -- Each section must be a table with at least 2 elements: [1]=name, [2]=content @@ -74,77 +74,77 @@ local pio_manager = (function() vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(int_obj) vim.schedule(function() vim.notify('PIO: Fetching metadata ...', vim.log.levels.INFO) - end) - if int_obj.code ~= 0 then - -- Schedule notification to avoid error in the system callback thread - vim.schedule(function() - if int_obj.code == 127 then - vim.notify("PIO Manager metadata: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) - else - vim.notify('PIO Manager metadata: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) - end - end) - return - end + if int_obj.code ~= 0 then + -- Schedule notification to avoid error in the system callback thread + vim.schedule(function() + if int_obj.code == 127 then + vim.notify("PIO Manager metadata: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + else + vim.notify('PIO Manager metadata: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + end + end) + return + end - if int_obj.code == 0 and int_obj.stdout then - local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) - if ok and raw_data then - local _, data = next(raw_data) - if data then - local fallbackFlags = {} - -- 1. Process Includes - if data.includes then - for category, paths in pairs(data.includes) do - -- If it's a toolchain path, use -isystem to suppress warnings - -- and tell clangd these are standard libraries - if category == 'toolchain' then - local flag = '-isystem' - for _, path in ipairs(paths) do - -- table.insert(fallbackFlags, string.format('%q', flag)) - -- table.insert(fallbackFlags, string.format('%q', path:gsub('\\', '/'))) - table.insert(fallbackFlags, string.format('%q', flag .. path:gsub('\\', '/'))) + if int_obj.code == 0 and int_obj.stdout then + local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) + if ok and raw_data then + local _, data = next(raw_data) + if data then + local fallbackFlags = {} + -- 1. Process Includes + if data.includes then + for category, paths in pairs(data.includes) do + -- If it's a toolchain path, use -isystem to suppress warnings + -- and tell clangd these are standard libraries + if category == 'toolchain' then + local flag = '-isystem' + for _, path in ipairs(paths) do + -- table.insert(fallbackFlags, string.format('%q', flag)) + -- table.insert(fallbackFlags, string.format('%q', path:gsub('\\', '/'))) + table.insert(fallbackFlags, string.format('%q', flag .. path:gsub('\\', '/'))) + end end + -- local flag = (category == 'toolchain') and '-isystem' or '-I' + -- for _, path in ipairs(paths) do + -- table.insert(fallbackFlags, flag .. path) + -- end end - -- local flag = (category == 'toolchain') and '-isystem' or '-I' - -- for _, path in ipairs(paths) do - -- table.insert(fallbackFlags, flag .. path) - -- end end - end - -- 2. Process Defines - if data.defines then - for _, define in ipairs(data.defines) do - table.insert(fallbackFlags, string.format('%q', '-D' .. define)) + -- 2. Process Defines + if data.defines then + for _, define in ipairs(data.defines) do + table.insert(fallbackFlags, string.format('%q', '-D' .. define)) + end end - end - -- get [cc_compiler]and [falbackFlags] - -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' - _G.metadata.cc_compiler = misc.normalize_path(data.cc_path) or '' - _G.metadata.fallbackFlags = fallbackFlags - - -- print(vim.inspect(_G.metadata)) - if callback then - vim.schedule(function() - vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) - callback() - end) + -- get [cc_compiler]and [falbackFlags] + -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' + _G.metadata.cc_compiler = misc.normalize_path(data.cc_path) or '' + _G.metadata.fallbackFlags = fallbackFlags + + -- print(vim.inspect(_G.metadata)) + if callback then + vim.schedule(function() + vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) + callback() + end) + end end + else + vim.schedule(function() + vim.notify('PIO: Syncing Environment failed', vim.log.levels.WARN) + end) end - else - vim.schedule(function() - vim.notify('PIO: Syncing Environment failed', vim.log.levels.WARN) - end) end - end - -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save - if attempts > 0 then - vim.defer_fn(function() - get_metadata(attempts - 1) - end, 500) - end + -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save + if attempts > 0 then + vim.defer_fn(function() + get_metadata(attempts - 1) + end, 500) + end + end) end) end @@ -155,87 +155,87 @@ local pio_manager = (function() -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) - if ext_obj.code ~= 0 then - -- Schedule notification to avoid error in the system callback thread - vim.schedule(function() + vim.schedule(function() + if ext_obj.code ~= 0 then + -- Schedule notification to avoid error in the system callback thread if ext_obj.code == 127 then vim.notify("PIO Manager config: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else vim.notify('PIO Manager config: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) end - end) - return - end + return + end - _G.metadata.core_dir = '' - _G.metadata.packages_dir = '' - _G.metadata.platforms_dir = '' - _G.metadata.active_env = '' - _G.metadata.default_envs = {} - _G.metadata.envs = {} - - local decoded = vim.json.decode(ext_obj.stdout) - for _, section in ipairs(decoded) do - if type(section) == 'table' and #section >= 2 then - local name, data = section[1], section[2] - -- 1. Extract Global PlatformIO Settings if available [core_dir][packages_dir][platforms_dir][default_envs] - if name == 'platformio' then - for _, kv in ipairs(data) do - local key, val = kv[1], kv[2] - if key ~= nil then - -- if _G.metadata[key] ~= nil then - _G.metadata[key] = val + _G.metadata.core_dir = '' + _G.metadata.packages_dir = '' + _G.metadata.platforms_dir = '' + _G.metadata.active_env = '' + _G.metadata.default_envs = {} + _G.metadata.envs = {} + + local decoded = vim.json.decode(ext_obj.stdout) + for _, section in ipairs(decoded) do + if type(section) == 'table' and #section >= 2 then + local name, data = section[1], section[2] + -- 1. Extract Global PlatformIO Settings if available [core_dir][packages_dir][platforms_dir][default_envs] + if name == 'platformio' then + for _, kv in ipairs(data) do + local key, val = kv[1], kv[2] + if key ~= nil then + -- if _G.metadata[key] ~= nil then + _G.metadata[key] = val + end + end + -- 2. Extract all hardware [envs] like [env:seeed_xiao_esp32c3], skipping generic [env] + elseif name:match('^env:') then + local env_name = name:match('^env:(.+)') + _G.metadata.envs[env_name] = {} + for _, kv in ipairs(data) do + _G.metadata.envs[env_name][kv[1]] = kv[2] end - end - -- 2. Extract all hardware [envs] like [env:seeed_xiao_esp32c3], skipping generic [env] - elseif name:match('^env:') then - local env_name = name:match('^env:(.+)') - _G.metadata.envs[env_name] = {} - for _, kv in ipairs(data) do - _G.metadata.envs[env_name][kv[1]] = kv[2] end end end - end - -- assign [active_env] - if #_G.metadata.default_envs > 0 then - _G.metadata.active_env = _G.metadata.default_envs[1] or '' - elseif _G.metadata.envs and next(_G.metadata.envs) ~= '' then - _G.metadata.active_env = next(_G.metadata.envs) or '' - end + -- assign [active_env] + if #_G.metadata.default_envs > 0 then + _G.metadata.active_env = _G.metadata.default_envs[1] or '' + elseif _G.metadata.envs and next(_G.metadata.envs) ~= '' then + _G.metadata.active_env = next(_G.metadata.envs) or '' + end - -- INFO: -- Define Mapping (key in INI, Env Var, Default Subfolder) - local map = { - core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, - packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, - platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, - } - for _, kv in ipairs(map) do - -- 4.0 Fallback Logic: INI -> Env Var -> Default - local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') - -- 5. Expand ${platformio.core_dir} - if type(result) == 'string' then - if result:find('${platformio.core_dir}', 1, true) then - result = result:gsub('%${platformio.core_dir}', _G.metadata.core_dir) + -- INFO: -- Define Mapping (key in INI, Env Var, Default Subfolder) + local map = { + core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, + packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, + platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, + } + for _, kv in ipairs(map) do + -- 4.0 Fallback Logic: INI -> Env Var -> Default + local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') + -- 5. Expand ${platformio.core_dir} + if type(result) == 'string' then + if result:find('${platformio.core_dir}', 1, true) then + result = result:gsub('%${platformio.core_dir}', _G.metadata.core_dir) + end end + -- 6. Normalize Slashes for Windows + -- _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') + _G.metadata[kv.ini] = result:gsub('\\', '/'):gsub('//+', '/') end - -- 6. Normalize Slashes for Windows - -- _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') - _G.metadata[kv.ini] = result:gsub('\\', '/'):gsub('//+', '/') - end - -- return _G.metadata[map[type].ini] - -- end + -- return _G.metadata[map[type].ini] + -- end - if _G.metadata.active_env ~= '' then - vim.schedule(function() - vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) - end) - get_metadata(1, _G.metadata.active_env) - else - vim.schedule(function() - vim.notify('PIO: no [env:] found, add board first', vim.log.levels.ERROR) - end) - end + if _G.metadata.active_env ~= '' then + vim.schedule(function() + vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) + end) + get_metadata(1, _G.metadata.active_env) + else + vim.schedule(function() + vim.notify('PIO: no [env:] found, add board first', vim.log.levels.ERROR) + end) + end + end) end) end From 12fadd42800b95becebc7cedada02d92964d9e21 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 22:09:35 +0300 Subject: [PATCH 0731/1406] update --- lua/platformio/pio_setup.lua | 132 +++++++++++++++++++---------------- 1 file changed, 70 insertions(+), 62 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 55488da5..b01acb46 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -5,14 +5,18 @@ local lsp = require('platformio.lsp.tools') local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local debounce_timer = vim.uv.new_timer() +local last_ini_hash = '' +local is_ignoring_watcher = false -- INFO: -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag -- stylua: ignore local function pio_generate_db() - vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) + is_ignoring_watcher = true -- Mute watcher + vim.notify('PIO: Generating Compile DB...', vim.log.levels.INFO) vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) vim.schedule(function() + is_ignoring_watcher = false -- Unmute if obj.code ~= 0 then if obj.code == 127 then vim.notify("PIO Manager db: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) @@ -21,9 +25,7 @@ local function pio_generate_db() end return end - vim.schedule(function() - vim.notify('PIO: Generating Compile Database successful', vim.log.levels.INFO) - end) + vim.notify('PIO: Generating Compile Database successful', vim.log.levels.INFO) end) end) end @@ -337,85 +339,91 @@ end --- stylua: ignore ---------------------------------------------------------------------------------------------- -local last_ini_hash = nil +-- local last_ini_hash = "" +-- local is_ignoring_watcher = false --- Helper to safely read file content -local function safe_read_file(path) - local f = io.open(path, 'r') - if not f then - return nil +-- Safe hashing: uses sha256 to avoid 'nil' errors found with vim.hash +local function get_safe_hash(data) + if not data then + return '' end - local content = f:read('*a') - f:close() - return content + return vim.fn.sha256(data) end +-- 4. Execute Compiledb (Using vim.system + Muting) +function M.run_compiledb() + is_ignoring_watcher = true -- Mute watcher -local function wait_and_refresh() - -- Check if handle is valid before proceeding - if not pio_manager or not lsp then - vim.notify('PIO Manager or LSP module not found', vim.log.levels.ERROR) - return - end - - -- Check for lockfile (adjust path if your project uses different build dir) - local lock_file = vim.uv.cwd() .. '/.pio/build/lockfile' - if vim.fn.filereadable(lock_file) == 1 then - vim.defer_fn(wait_and_refresh, 1000) - return - end + vim.notify('Generating Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) - pio_manager.refresh(function() - pcall(function() - boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], _G.metadata.core_dir) - -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') - pio_generate_db() - lsp.lsp_restart('clangd') + vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) + vim.schedule(function() + is_ignoring_watcher = false -- Unmute + if obj.code == 0 then + vim.notify('Compiledb updated', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- Manual refresh once finished + pio_manager.refresh(function() + boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) + pio_generate_db() + lsp.lsp_restart('clangd') + end) + else + vim.notify('Compiledb failed: ' .. (obj.stderr or 'Unknown error'), vim.log.levels.ERROR) + end end) - vim.notify('Build finished: Config reloaded', vim.log.levels.INFO, { title = 'PlatformIO' }) end) end --- stylua: ignore +-- 5. Bulletproof Watcher (Content-aware & Lock-aware) function M.start_pio_watcher() - local cwd = vim.uv.cwd() - if not cwd then return end - - local ini_path = cwd .. '/platformio.ini' - if vim.fn.filereadable(ini_path) == 0 then return end + local dir_path = vim.uv.cwd() + local ini_path = dir_path .. '/platformio.ini' + if not dir_path or vim.fn.filereadable(ini_path) == 0 then + return + end - -- Initial hash setup - local init_content = safe_read_file(ini_path) - if init_content then last_ini_hash = vim.fn.sha256(init_content) end + -- Seed the initial hash + local init_f = io.open(ini_path, 'r') + if init_f then + last_ini_hash = get_safe_hash(init_f:read('*a')) + init_f:close() + end local handle = vim.uv.new_fs_event() - if not handle then vim.notify('Failed to create FS watcher', vim.log.levels.ERROR) return + if not handle then + return end handle:start( - cwd, + dir_path, { recursive = false }, - vim.schedule_wrap(function(err, filename, events) - -- 1. Check for UV errors or nil filenames - if err then - vim.notify('Watcher error: ' .. tostring(err), vim.log.levels.ERROR) + vim.schedule_wrap(function(err, filename) + if err or is_ignoring_watcher or filename ~= 'platformio.ini' then return end - if filename ~= 'platformio.ini' or not events then return end - - -- 2. Safe read with pcall (Windows may lock the file during 'pio run') - local ok, new_content = pcall(safe_read_file, ini_path) - if not ok or not new_content then return end - -- 3. Content check - local new_hash = vim.fn.sha256(new_content) - if new_hash ~= last_ini_hash then - last_ini_hash = new_hash + -- Safe read (pcall handles Windows file locks during build) + local ok, content = pcall(function() + local f = io.open(ini_path, 'r') + if not f then + return nil + end + local data = f:read('*a') + f:close() + return data + end) - -- 4. Check for timer nil - if debounce_timer then - debounce_timer:stop() - debounce_timer:start(500, 0, vim.schedule_wrap(wait_and_refresh)) + if ok and content then + local new_hash = get_safe_hash(content) + if new_hash ~= last_ini_hash then + last_ini_hash = new_hash + -- Trigger refresh via your manager + pio_manager.refresh(function() + boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) + pio_generate_db() + lsp.lsp_restart('clangd') + end) end end end) From 8fe8576e87c9a3399a8a9d4b901c1f7acb4db7a1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 22:32:19 +0300 Subject: [PATCH 0732/1406] update --- lua/platformio/pio_setup.lua | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b01acb46..82164fbd 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -13,7 +13,7 @@ local is_ignoring_watcher = false -- stylua: ignore local function pio_generate_db() is_ignoring_watcher = true -- Mute watcher - vim.notify('PIO: Generating Compile DB...', vim.log.levels.INFO) + vim.schedule(function() vim.notify('PIO: Generating Compile DB ...', vim.log.levels.INFO) end) vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) vim.schedule(function() is_ignoring_watcher = false -- Unmute @@ -21,11 +21,11 @@ local function pio_generate_db() if obj.code == 127 then vim.notify("PIO Manager db: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) else - vim.notify('PIO Manager db: Generating Compile Database failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + vim.notify('PIO Manager db: Generating Compile DB failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) end return end - vim.notify('PIO: Generating Compile Database successful', vim.log.levels.INFO) + vim.notify('PIO: Generating Compile DB successful', vim.log.levels.INFO) end) end) end @@ -129,7 +129,7 @@ local pio_manager = (function() -- print(vim.inspect(_G.metadata)) if callback then vim.schedule(function() - vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) + vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) callback() end) end @@ -229,7 +229,7 @@ local pio_manager = (function() if _G.metadata.active_env ~= '' then vim.schedule(function() - vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) + vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) end) get_metadata(1, _G.metadata.active_env) else @@ -351,6 +351,9 @@ local function get_safe_hash(data) end -- 4. Execute Compiledb (Using vim.system + Muting) function M.run_compiledb() + if is_ignoring_watcher then + return + end is_ignoring_watcher = true -- Mute watcher vim.notify('Generating Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) From 665c54d9d5ba714f859e61f996a346ddb8551f3f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 22:47:13 +0300 Subject: [PATCH 0733/1406] update --- lua/platformio/boilerplate.lua | 17 ++++++++++++++++- lua/platformio/pio_setup.lua | 1 + 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 05191cc6..8350599d 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -42,7 +42,7 @@ monitor_speed = 9600 monitor_rts = 1 ; 1 combination to reset esp32c6 (Table 32.3-2. CDC-ACM Settings with RTS and DTR) monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dtr=0 -;extra_scripts = +extra_scripts = post:generate_compileDB.py ; pre:enable_toolchain.py ; enabled global env 'PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN' lib_ldf_mode = chain ;Library dependencies Finder ldf @@ -211,6 +211,21 @@ enabled = false ]], } +-- INFO: generate_compileDB.py +boilerplate['generate_compileDB.py'] = { + rewrite = false, + read = false, + content = [[ +import subprocess +from SCons.Script import COMMAND_LINE_TARGETS + +# Only run if we are NOT already generating the compilation database +if "compiledb" not in COMMAND_LINE_TARGETS: + print("Regenerating compile_commands.json...") + subprocess.run(["pio", "run", "-t", "compiledb"]) +]], +} + -- INFO: .clang-format boilerplate['.clang-format'] = { rewrite = false, diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 82164fbd..991670a0 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -487,6 +487,7 @@ function M.init() boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) + boilerplate_gen([[generate_compileDB.py]], vim.g.platformioRootDir) --------------------------------------------------------------------------------- require('platformio.lsp.clangd') From 9b7fe0f3a2a940005819e2c9a9a0ab359bcc8999 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 23:20:25 +0300 Subject: [PATCH 0734/1406] update --- lua/platformio/pio_setup.lua | 137 +++++++++++++++++------------------ tmp.lua | 90 +++++++++++++++++++++++ 2 files changed, 157 insertions(+), 70 deletions(-) create mode 100644 tmp.lua diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 991670a0..29e6fbdd 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -5,18 +5,16 @@ local lsp = require('platformio.lsp.tools') local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local debounce_timer = vim.uv.new_timer() -local last_ini_hash = '' -local is_ignoring_watcher = false +local last_hash = '' +local is_busy = false -- INFO: -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag -- stylua: ignore local function pio_generate_db() - is_ignoring_watcher = true -- Mute watcher vim.schedule(function() vim.notify('PIO: Generating Compile DB ...', vim.log.levels.INFO) end) vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) vim.schedule(function() - is_ignoring_watcher = false -- Unmute if obj.code ~= 0 then if obj.code == 127 then vim.notify("PIO Manager db: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) @@ -339,98 +337,97 @@ end --- stylua: ignore ---------------------------------------------------------------------------------------------- --- local last_ini_hash = "" --- local is_ignoring_watcher = false +local dir_path = vim.uv.cwd() +local ini_file = vim.fs.joinpath(dir_path, 'platformio.ini') +local config_file = vim.fs.joinpath(dir_path, '.project_config.json') +-- 1. Helper: Unified hashing for change detection +local function get_hash(path) + if vim.fn.filereadable(path) == 0 then + return nil + end + local ok, data = pcall(vim.fn.readfile, path) -- readfile is safer than io.open + return ok and vim.fn.sha256(table.concat(data, '\n')) or nil +end --- Safe hashing: uses sha256 to avoid 'nil' errors found with vim.hash -local function get_safe_hash(data) - if not data then - return '' +-- 2. Smart Save/Load: Uses JSON and Hashing +function M.sync_config(force_load) + if force_load then + if vim.fn.filereadable(config_file) == 1 then + local data = table.concat(vim.fn.readfile(config_file), '') + _G.metadata = vim.json.decode(data) + last_hash = vim.fn.sha256(data) + end + else + local current_data = vim.json.encode(_G.metadata) + local current_hash = vim.fn.sha256(current_data) + if current_hash ~= last_hash then + vim.fn.writefile({ current_data }, config_file) + last_hash = current_hash + end end - return vim.fn.sha256(data) end --- 4. Execute Compiledb (Using vim.system + Muting) + +-- 3. Robust Execution: Mutes watcher and handles LSP restart function M.run_compiledb() - if is_ignoring_watcher then + if is_busy then return end - is_ignoring_watcher = true -- Mute watcher - - vim.notify('Generating Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) + is_busy = true + vim.notify('Building Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) - vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) + vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) vim.schedule(function() - is_ignoring_watcher = false -- Unmute + is_busy = false if obj.code == 0 then - vim.notify('Compiledb updated', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- Manual refresh once finished - pio_manager.refresh(function() - boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) - pio_generate_db() - lsp.lsp_restart('clangd') - end) + vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- Use pcall in case M.refresh is defined elsewhere + -- pio_manager.refresh(function() + -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) + -- pio_generate_db() + lsp.lsp_restart('clangd') + -- end) + -- else - vim.notify('Compiledb failed: ' .. (obj.stderr or 'Unknown error'), vim.log.levels.ERROR) + vim.notify('Build Failed', vim.log.levels.ERROR, { title = 'PlatformIO' }) end end) end) end --- 5. Bulletproof Watcher (Content-aware & Lock-aware) -function M.start_pio_watcher() - local dir_path = vim.uv.cwd() - local ini_path = dir_path .. '/platformio.ini' - if not dir_path or vim.fn.filereadable(ini_path) == 0 then +-- 4. Simple Watcher: Only triggers if the FILE CONTENT changed +function M.start_watcher() + if not dir_path or vim.fn.filereadable(ini_file) == 0 then return end - - -- Seed the initial hash - local init_f = io.open(ini_path, 'r') - if init_f then - last_ini_hash = get_safe_hash(init_f:read('*a')) - init_f:close() - end + local current_ini_hash = get_hash(ini_file) local handle = vim.uv.new_fs_event() - if not handle then - return - end - - handle:start( - dir_path, - { recursive = false }, - vim.schedule_wrap(function(err, filename) - if err or is_ignoring_watcher or filename ~= 'platformio.ini' then - return - end - - -- Safe read (pcall handles Windows file locks during build) - local ok, content = pcall(function() - local f = io.open(ini_path, 'r') - if not f then - return nil + if handle then + handle:start( + dir_path, + { recursive = false }, + vim.schedule_wrap(function(err, fname) + if err or is_busy or fname ~= 'platformio.ini' then + return end - local data = f:read('*a') - f:close() - return data - end) - if ok and content then - local new_hash = get_safe_hash(content) - if new_hash ~= last_ini_hash then - last_ini_hash = new_hash - -- Trigger refresh via your manager + local new_hash = get_hash(ini_file) + if new_hash and new_hash ~= current_ini_hash then + current_ini_hash = new_hash + M.run_compiledb() -- Smart: Auto-update DB if config changes pio_manager.refresh(function() boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) - pio_generate_db() - lsp.lsp_restart('clangd') + -- pio_generate_db() + -- M.run_compiledb() + M.run_compiledb() -- Smart: Auto-update DB if config changes + -- lsp.lsp_restart('clangd') end) end - end - end) - ) + end) + ) + end end ---------------------------------------------------------------------------------------------- diff --git a/tmp.lua b/tmp.lua new file mode 100644 index 00000000..1124c5c7 --- /dev/null +++ b/tmp.lua @@ -0,0 +1,90 @@ +-- local function get_safe_hash(data) +-- if not data then +-- return '' +-- end +-- return vim.fn.sha256(data) +-- end +-- -- 4. Execute Compiledb (Using vim.system + Muting) +-- function M.run_compiledb() +-- if is_ignoring_watcher then +-- return +-- end +-- is_ignoring_watcher = true -- Mute watcher +-- +-- vim.notify('Generating Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) +-- +-- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) +-- vim.schedule(function() +-- is_ignoring_watcher = false -- Unmute +-- if obj.code == 0 then +-- vim.notify('Compiledb updated', vim.log.levels.INFO, { title = 'PlatformIO' }) +-- -- Manual refresh once finished +-- pio_manager.refresh(function() +-- -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +-- -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) +-- -- pio_generate_db() +-- lsp.lsp_restart('clangd') +-- end) +-- else +-- vim.notify('Compiledb failed: ' .. (obj.stderr or 'Unknown error'), vim.log.levels.ERROR) +-- end +-- end) +-- end) +-- end +-- +-- -- 5. Bulletproof Watcher (Content-aware & Lock-aware) +-- function M.start_pio_watcher() +-- local dir_path = vim.uv.cwd() +-- local ini_path = dir_path .. '/platformio.ini' +-- if not dir_path or vim.fn.filereadable(ini_path) == 0 then +-- return +-- end +-- +-- -- Seed the initial hash +-- local init_f = io.open(ini_path, 'r') +-- if init_f then +-- last_ini_hash = get_safe_hash(init_f:read('*a')) +-- init_f:close() +-- end +-- +-- local handle = vim.uv.new_fs_event() +-- if not handle then +-- return +-- end +-- +-- handle:start( +-- dir_path, +-- { recursive = false }, +-- vim.schedule_wrap(function(err, filename) +-- if err or is_ignoring_watcher or filename ~= 'platformio.ini' then +-- return +-- end +-- +-- -- Safe read (pcall handles Windows file locks during build) +-- local ok, content = pcall(function() +-- local f = io.open(ini_path, 'r') +-- if not f then +-- return nil +-- end +-- local data = f:read('*a') +-- f:close() +-- return data +-- end) +-- +-- if ok and content then +-- local new_hash = get_safe_hash(content) +-- if new_hash ~= last_ini_hash then +-- last_ini_hash = new_hash +-- -- Trigger refresh via your manager +-- pio_manager.refresh(function() +-- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +-- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) +-- -- pio_generate_db() +-- M.run_compiledb() +-- lsp.lsp_restart('clangd') +-- end) +-- end +-- end +-- end) +-- ) +-- end From abc4edd1bb2850e1bc038ab2bc8702df8962d2fc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 23:23:02 +0300 Subject: [PATCH 0735/1406] update --- lua/platformio/pio_setup.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 29e6fbdd..f600e80e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -493,7 +493,8 @@ function M.init() end -- Always start the watcher so it can catch a future 'pio init' - M.start_pio_watcher() + -- M.start_pio_watcher() + M.start_watcher() -- If the file already exists, do an initial sync if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then From 0bbc7fc796450e807cb48deeaa2867d09f156c65 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 23:34:58 +0300 Subject: [PATCH 0736/1406] update --- lua/platformio/boilerplate.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 8350599d..1c334a53 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -42,7 +42,8 @@ monitor_speed = 9600 monitor_rts = 1 ; 1 combination to reset esp32c6 (Table 32.3-2. CDC-ACM Settings with RTS and DTR) monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dtr=0 -extra_scripts = post:generate_compileDB.py +extra_scripts = +;post:generate_compileDB.py ; pre:enable_toolchain.py ; enabled global env 'PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN' lib_ldf_mode = chain ;Library dependencies Finder ldf From 5ed86b1bc9f409f3368a84844d90d79f1db87363 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 18 Apr 2026 23:44:55 +0300 Subject: [PATCH 0737/1406] update --- lua/platformio/pio_setup.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index f600e80e..8aa2c6e5 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -501,8 +501,9 @@ function M.init() pio_manager.refresh(function() -- vim.schedule(function() -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - pio_generate_db() - lsp.lsp_restart('clangd') + -- pio_generate_db() + M.run_compiledb() -- Smart: Auto-update DB if config changes + -- lsp.lsp_restart('clangd') -- end) end) end From 44c3e52a0752c2dde85f00b65b385ff7bdd27392 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 01:13:45 +0300 Subject: [PATCH 0738/1406] update --- lua/platformio/metadata.lua | 31 ++++++++++++++++++++++++++----- lua/platformio/pio_setup.lua | 30 +++++------------------------- lua/platformio/utils/pio.lua | 3 +++ 3 files changed, 34 insertions(+), 30 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 3e6972f8..6ad9b8aa 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,6 +1,7 @@ -- 1. Initialize Global Table immediately (Prevents nil errors) _G.metadata = _G.metadata or { + is_busy = false, envs = {}, active_env = '', default_envs = {}, @@ -29,11 +30,31 @@ local M = {} local last_saved_hash = '' local config_path = vim.fn.getcwd() .. '/.project_config.json' --- Helper: Performance-proof hashing using built-in Vimscript (never nil) -local function get_safe_hash(data) +local function getHash(data) return vim.fn.sha256(data) end +-- local last_hash = '' +-- local dir_path = vim.uv.cwd() +-- local config_file = vim.fs.joinpath(dir_path, '.project_config.json') +-- +-- function M.sync_config(force_load) +-- if force_load then +-- if vim.fn.filereadable(config_file) == 1 then +-- local data = table.concat(vim.fn.readfile(config_file), '') +-- _G.metadata = vim.json.decode(data) +-- last_hash = getHash(data) +-- end +-- else +-- local current_data = vim.json.encode(_G.metadata) +-- local current_hash = getHash(current_data) +-- if current_hash ~= last_hash then +-- vim.fn.writefile({ current_data }, config_file) +-- last_hash = current_hash +-- end +-- end +-- end + -- 2. Self-Healing Load & Auto-Create function M.load_project_config() local success = false @@ -46,7 +67,7 @@ function M.load_project_config() local ok, decoded = pcall(vim.json.decode, content) if ok and type(decoded) == 'table' then _G.metadata = decoded - last_saved_hash = get_safe_hash(content) + last_saved_hash = getHash(content) success = true end end @@ -60,7 +81,7 @@ function M.load_project_config() if file then file:write(encoded) file:close() - last_saved_hash = get_safe_hash(encoded) + last_saved_hash = getHash(encoded) if vim.fn.filereadable('platformio.ini') == 1 then vim.notify('New project config created', vim.log.levels.INFO, { title = 'PlatformIO' }) end @@ -75,7 +96,7 @@ function M.save_project_config(quiet) end local current_data = vim.json.encode(_G.metadata) - local current_hash = get_safe_hash(current_data) + local current_hash = getHash(current_data) -- Only write if data actually changed since last load/save if current_hash ~= last_saved_hash then diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 8aa2c6e5..29ee9199 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -4,9 +4,7 @@ local misc = require('platformio.utils.misc') local lsp = require('platformio.lsp.tools') local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -local debounce_timer = vim.uv.new_timer() -local last_hash = '' -local is_busy = false +-- local debounce_timer = vim.uv.new_timer() -- INFO: -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag @@ -339,7 +337,6 @@ end local dir_path = vim.uv.cwd() local ini_file = vim.fs.joinpath(dir_path, 'platformio.ini') -local config_file = vim.fs.joinpath(dir_path, '.project_config.json') -- 1. Helper: Unified hashing for change detection local function get_hash(path) if vim.fn.filereadable(path) == 0 then @@ -350,34 +347,17 @@ local function get_hash(path) end -- 2. Smart Save/Load: Uses JSON and Hashing -function M.sync_config(force_load) - if force_load then - if vim.fn.filereadable(config_file) == 1 then - local data = table.concat(vim.fn.readfile(config_file), '') - _G.metadata = vim.json.decode(data) - last_hash = vim.fn.sha256(data) - end - else - local current_data = vim.json.encode(_G.metadata) - local current_hash = vim.fn.sha256(current_data) - if current_hash ~= last_hash then - vim.fn.writefile({ current_data }, config_file) - last_hash = current_hash - end - end -end - -- 3. Robust Execution: Mutes watcher and handles LSP restart function M.run_compiledb() - if is_busy then + if _G.metadata.isBusy then return end - is_busy = true + _G.metadata.isBusy = true vim.notify('Building Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) vim.schedule(function() - is_busy = false + _G.metadata.isBusy = false if obj.code == 0 then vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) -- Use pcall in case M.refresh is defined elsewhere @@ -408,7 +388,7 @@ function M.start_watcher() dir_path, { recursive = false }, vim.schedule_wrap(function(err, fname) - if err or is_busy or fname ~= 'platformio.ini' then + if err or _G.metadata.isBusy or fname ~= 'platformio.ini' then return end diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index c38332c2..69f15a2e 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -171,10 +171,12 @@ function M.dispatcher(_, _, data) -- 4. Store the last element as the new partial buffer for the next call pio_buffer = data[#data] local task = table.remove(M.queue, 1) + _G.metadata.isBusy = false if task then vim.schedule(task) end elseif status == 'FAILED' then M.queue = {} -- Clear queue on any other status (failure) pio_buffer = '' + _G.metadata.isBusy = false vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) end break @@ -203,6 +205,7 @@ M.run_sequence = function(tasks) end full_cmd = full_cmd .. ' || ' .. failure local ToggleTerminal = require('platformio.utils.term').ToggleTerminal + _G.metadata.isBusy = true ToggleTerminal(full_cmd, 'float') end From c5c4d95312c3e200ffcdbbdb222077f5e701fe8f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 01:42:05 +0300 Subject: [PATCH 0739/1406] update --- lua/platformio/pio_setup.lua | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 29ee9199..b0636421 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -349,9 +349,9 @@ end -- 2. Smart Save/Load: Uses JSON and Hashing -- 3. Robust Execution: Mutes watcher and handles LSP restart function M.run_compiledb() - if _G.metadata.isBusy then - return - end + -- if _G.metadata.isBusy then + -- return + -- end _G.metadata.isBusy = true vim.notify('Building Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) @@ -387,10 +387,16 @@ function M.start_watcher() handle:start( dir_path, { recursive = false }, - vim.schedule_wrap(function(err, fname) - if err or _G.metadata.isBusy or fname ~= 'platformio.ini' then + vim.schedule_wrap(function(err, fname, events) + if err or fname ~= 'platformio.ini' or _G.metadata.isBusy or not events or not (events.change or events.renamce) then return end + -- -- Trigger only if the changed file is platformio.ini + -- if filename == 'platformio.ini' and (events.change or events.rename) then + -- if filename == 'platformio.ini' and (events.change or events.rename) then + -- if err or _G.metadata.isBusy or fname ~= 'platformio.ini' then + -- return + -- end local new_hash = get_hash(ini_file) if new_hash and new_hash ~= current_ini_hash then From 1f88f859fdd432f692b1fd65c15f15f865fee4a9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 01:48:21 +0300 Subject: [PATCH 0740/1406] update --- lua/platformio/pioinit.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index bb2ca26a..c1d3d911 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -64,10 +64,10 @@ local function pick_framework(board_details) cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', cb = pio.handlePioinit, }, - -- { - -- cmd = 'pio run -t compiledb', - -- cb = pio.handleDb, - -- }, + { + cmd = 'pio run -t compiledb', + cb = pio.handleDb, + }, }) end) return true From 9256cb1a98ea9fb10c8b2450c7663ffaa41c0814 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 02:08:07 +0300 Subject: [PATCH 0741/1406] update --- lua/platformio/pio_setup.lua | 5 +++-- lua/platformio/utils/pio.lua | 11 ++++++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b0636421..191223be 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -403,8 +403,6 @@ function M.start_watcher() current_ini_hash = new_hash M.run_compiledb() -- Smart: Auto-update DB if config changes pio_manager.refresh(function() - boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) -- pio_generate_db() -- M.run_compiledb() M.run_compiledb() -- Smart: Auto-update DB if config changes @@ -467,6 +465,8 @@ function M.init() ---------------------------------------------------------------------------------------- -- INFO: create clangd required files ----------------------------------------------------------------------------------------- + boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) @@ -488,6 +488,7 @@ function M.init() -- vim.schedule(function() -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) -- pio_generate_db() + -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) M.run_compiledb() -- Smart: Auto-update DB if config changes -- lsp.lsp_restart('clangd') -- end) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 69f15a2e..b0175220 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -2,6 +2,7 @@ local M = {} M.selected_framework = '' +local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local misc = require('platformio.utils.misc') local lsp = require('platformio..lsp.tools') @@ -214,15 +215,19 @@ end function M.handleDb() vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) misc.gitignore_lsp_configs('compile_commands.json') - M.fix_pio_compile_commands() - lsp.lsp_restart('clangd') + local pio_manager = require('platformio.utils.pio').pio_manager + pio_manager.refresh(function() + boilerplate_gen([[.clangd]], _G.metadata.core_dir) + M.fix_pio_compile_commands() + lsp.lsp_restart('clangd') + end) end ------------------------------------------------------ -- Handle after poioinit execution -- stylua: ignore function M.handlePioinit() - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') vim.notify('Pioinit: Success', vim.log.levels.INFO) From 7cfa14b044f8dc2ce73b01f2fe4b9f39aac18f8f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 02:20:44 +0300 Subject: [PATCH 0742/1406] update --- lua/platformio/pio_setup.lua | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 191223be..863fac50 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,7 +1,7 @@ M = {} local misc = require('platformio.utils.misc') -local lsp = require('platformio.lsp.tools') +local lsp_restart = require('platformio.lsp.tools').lsp_restart local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -- local debounce_timer = vim.uv.new_timer() @@ -365,7 +365,7 @@ function M.run_compiledb() -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) -- pio_generate_db() - lsp.lsp_restart('clangd') + lsp_restart('clangd') -- end) -- else @@ -401,12 +401,11 @@ function M.start_watcher() local new_hash = get_hash(ini_file) if new_hash and new_hash ~= current_ini_hash then current_ini_hash = new_hash - M.run_compiledb() -- Smart: Auto-update DB if config changes pio_manager.refresh(function() -- pio_generate_db() -- M.run_compiledb() M.run_compiledb() -- Smart: Auto-update DB if config changes - -- lsp.lsp_restart('clangd') + -- lsp_restart('clangd') end) end end) @@ -447,7 +446,7 @@ end -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) -- -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') -- pio_generate_db() --- lsp.lsp_restart('clangd') +-- lsp_restart('clangd') -- -- end) -- end) end)) end end end)) -- end @@ -490,7 +489,7 @@ function M.init() -- pio_generate_db() -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) M.run_compiledb() -- Smart: Auto-update DB if config changes - -- lsp.lsp_restart('clangd') + -- lsp_restart('clangd') -- end) end) end From bb43540c0ce8f6430465cb9aeb7b810e111daaff Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 02:25:13 +0300 Subject: [PATCH 0743/1406] update --- lua/platformio/utils/pio.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index b0175220..902e380c 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -2,7 +2,6 @@ local M = {} M.selected_framework = '' -local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen local misc = require('platformio.utils.misc') local lsp = require('platformio..lsp.tools') @@ -217,6 +216,7 @@ function M.handleDb() misc.gitignore_lsp_configs('compile_commands.json') local pio_manager = require('platformio.utils.pio').pio_manager pio_manager.refresh(function() + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], _G.metadata.core_dir) M.fix_pio_compile_commands() lsp.lsp_restart('clangd') @@ -229,6 +229,7 @@ end function M.handlePioinit() -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') vim.notify('Pioinit: Success', vim.log.levels.INFO) end From 9b3d720857f3a0deec107e03d3c9232abe1953f8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 02:35:12 +0300 Subject: [PATCH 0744/1406] update --- lua/platformio/boilerplate.lua | 3 ++- lua/platformio/utils/pio.lua | 15 +++++++++------ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 1c334a53..4f60b602 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -52,7 +52,8 @@ build_flags = ]], content = function(self) -- local pio = require('platformio.utils.pio') - return string.format(self.template, require('platformio.utils.pio').get_pio_dir('core')) + -- return string.format(self.template, require('platformio.utils.pio').get_pio_dir('core')) + return string.format(self.template, _G.metadata.core_dir) end, } diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 902e380c..7fe5ac40 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -3,7 +3,7 @@ local M = {} M.selected_framework = '' local misc = require('platformio.utils.misc') -local lsp = require('platformio..lsp.tools') +local lsp = require('platformio.lsp.tools') ------------------------------------------------------ -- stylua: ignore @@ -227,11 +227,14 @@ end -- Handle after poioinit execution -- stylua: ignore function M.handlePioinit() - -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - vim.notify('Pioinit: Success', vim.log.levels.INFO) + local pio_manager = require('platformio.utils.pio').pio_manager + pio_manager.refresh(function() + -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + vim.notify('Pioinit: Success', vim.log.levels.INFO) + end) end -- Handle after poioinit execution -- stylua: ignore From b1f3765ecb5110ca3d37c24fd2ebf47203de549e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 02:47:40 +0300 Subject: [PATCH 0745/1406] update --- lua/platformio/utils/pio.lua | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 7fe5ac40..dfbee135 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -214,7 +214,7 @@ end function M.handleDb() vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) misc.gitignore_lsp_configs('compile_commands.json') - local pio_manager = require('platformio.utils.pio').pio_manager + local pio_manager = require('platformio.pio_setup').pio_manager pio_manager.refresh(function() local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], _G.metadata.core_dir) @@ -225,15 +225,17 @@ end ------------------------------------------------------ -- Handle after poioinit execution --- stylua: ignore +--- stylua: ignore function M.handlePioinit() - local pio_manager = require('platformio.utils.pio').pio_manager - pio_manager.refresh(function() - -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - vim.notify('Pioinit: Success', vim.log.levels.INFO) + -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + vim.schedule(function() + local pio_manager = require('platformio.pio_setup').pio_manager + pio_manager.refresh(function() + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + vim.notify('Pioinit: Success', vim.log.levels.INFO) + end) end) end -- Handle after poioinit execution From 6e8a0e9f42bf91faefa7032bf04ad39c1dc25832 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 02:52:20 +0300 Subject: [PATCH 0746/1406] update --- lua/platformio/utils/pio.lua | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index dfbee135..740159c6 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -229,14 +229,14 @@ end function M.handlePioinit() -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - vim.schedule(function() - local pio_manager = require('platformio.pio_setup').pio_manager - pio_manager.refresh(function() - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - vim.notify('Pioinit: Success', vim.log.levels.INFO) - end) + -- vim.schedule(function() + local pio_manager = require('platformio.pio_setup').pio_manager + pio_manager.refresh(function() + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + vim.notify('Pioinit: Success', vim.log.levels.INFO) end) + -- end) end -- Handle after poioinit execution -- stylua: ignore From 27a5030252c1b79a7e7fe19a1eb816363b1acd4f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 03:02:56 +0300 Subject: [PATCH 0747/1406] update --- lua/platformio/pio_setup.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 863fac50..85e7c8a0 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -28,7 +28,7 @@ end -- INFO: 1. The Core PIO Manager & Generic Extractor -- stylua: ignore -local pio_manager = (function() +M.pio_manager = (function() local cache = nil -- Stores the decoded platformio.ini JSON structure -- INFO: local function find_in_data(data, section_name, key_name) @@ -401,7 +401,7 @@ function M.start_watcher() local new_hash = get_hash(ini_file) if new_hash and new_hash ~= current_ini_hash then current_ini_hash = new_hash - pio_manager.refresh(function() + M.pio_manager.refresh(function() -- pio_generate_db() -- M.run_compiledb() M.run_compiledb() -- Smart: Auto-update DB if config changes @@ -483,7 +483,7 @@ function M.init() -- If the file already exists, do an initial sync if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then - pio_manager.refresh(function() + M.pio_manager.refresh(function() -- vim.schedule(function() -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) -- pio_generate_db() From f500627c7d4d673838f8c3403e440e20508092e6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 04:21:47 +0300 Subject: [PATCH 0748/1406] update --- lua/platformio/pio_setup.lua | 154 +++++++++++++++++------------------ lua/platformio/utils/pio.lua | 14 +++- 2 files changed, 85 insertions(+), 83 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 85e7c8a0..65a33146 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -6,25 +6,6 @@ local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -- local debounce_timer = vim.uv.new_timer() --- INFO: --- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag --- stylua: ignore -local function pio_generate_db() - vim.schedule(function() vim.notify('PIO: Generating Compile DB ...', vim.log.levels.INFO) end) - vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) - vim.schedule(function() - if obj.code ~= 0 then - if obj.code == 127 then - vim.notify("PIO Manager db: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) - else - vim.notify('PIO Manager db: Generating Compile DB failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) - end - return - end - vim.notify('PIO: Generating Compile DB successful', vim.log.levels.INFO) - end) - end) -end -- INFO: 1. The Core PIO Manager & Generic Extractor -- stylua: ignore @@ -275,68 +256,88 @@ M.pio_manager = (function() } end)() --- INFO: -function _G.get_pio_sdk_info() - local pio_info = { includes = {}, cc_compiler = '' } - if vim.fn.filereadable('platformio.ini') == 0 then - return nil - end - - local handle = io.popen('pio run -t envdump') - if not handle then - return nil - end - - local packages_dir, cc_name, toolchain_pkg = '', '', '' - - for line in handle:lines() do - -- 1. Get the global packages directory - packages_dir = packages_dir ~= '' and packages_dir or line:match("'PROJECT_PACKAGES_DIR': '([^']+)'") - - -- 2. Get the compiler executable name (e.g., riscv32-esp-elf-gcc) - cc_name = cc_name ~= '' and cc_name or line:match("'CC': '([^']+)'") - - -- 3. Find the specific toolchain package name from the PACKAGES list - -- Matches lines like "- toolchain-riscv32-esp @ 14.2.0" - local pkg = line:match('%- (toolchain%-[^ ]+)') - if pkg then - toolchain_pkg = pkg - end - - -- 4. Collect include paths - local path_list = line:match("'CPPPATH': %[(.+)%]") - if path_list then - for path in path_list:gmatch("'([^']+)'") do - table.insert(pio_info.includes, '-I' .. path) - end - end - end - handle:close() - - -- Construct the absolute path: //bin/ - if packages_dir and packages_dir ~= '' and toolchain_pkg and toolchain_pkg ~= '' and cc_name ~= '' then - local full_path = packages_dir .. '/' .. toolchain_pkg .. '/bin/' .. cc_name - if vim.fn.executable(full_path) == 1 then - pio_info.cc_compiler = full_path - end - end - - local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' - print('get_pio_sdk_info(): final=' .. final) - -- Normalize paths for the OS and ensure backslashes for Windows if needed - -- print(vim.inspect(_G.metadata)) - return (misc.normalize_path(final)) - -- return _G.metadata.query_driver - -- return pio_info -end +-- -- INFO: +-- function _G.get_pio_sdk_info() +-- local pio_info = { includes = {}, cc_compiler = '' } +-- if vim.fn.filereadable('platformio.ini') == 0 then +-- return nil +-- end +-- +-- local handle = io.popen('pio run -t envdump') +-- if not handle then +-- return nil +-- end +-- +-- local packages_dir, cc_name, toolchain_pkg = '', '', '' +-- +-- for line in handle:lines() do +-- -- 1. Get the global packages directory +-- packages_dir = packages_dir ~= '' and packages_dir or line:match("'PROJECT_PACKAGES_DIR': '([^']+)'") +-- +-- -- 2. Get the compiler executable name (e.g., riscv32-esp-elf-gcc) +-- cc_name = cc_name ~= '' and cc_name or line:match("'CC': '([^']+)'") +-- +-- -- 3. Find the specific toolchain package name from the PACKAGES list +-- -- Matches lines like "- toolchain-riscv32-esp @ 14.2.0" +-- local pkg = line:match('%- (toolchain%-[^ ]+)') +-- if pkg then +-- toolchain_pkg = pkg +-- end +-- +-- -- 4. Collect include paths +-- local path_list = line:match("'CPPPATH': %[(.+)%]") +-- if path_list then +-- for path in path_list:gmatch("'([^']+)'") do +-- table.insert(pio_info.includes, '-I' .. path) +-- end +-- end +-- end +-- handle:close() +-- +-- -- Construct the absolute path: //bin/ +-- if packages_dir and packages_dir ~= '' and toolchain_pkg and toolchain_pkg ~= '' and cc_name ~= '' then +-- local full_path = packages_dir .. '/' .. toolchain_pkg .. '/bin/' .. cc_name +-- if vim.fn.executable(full_path) == 1 then +-- pio_info.cc_compiler = full_path +-- end +-- end +-- +-- local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' +-- print('get_pio_sdk_info(): final=' .. final) +-- -- Normalize paths for the OS and ensure backslashes for Windows if needed +-- -- print(vim.inspect(_G.metadata)) +-- return (misc.normalize_path(final)) +-- -- return _G.metadata.query_driver +-- -- return pio_info +-- end -- INFO: -- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync --- stylua: ignore ---------------------------------------------------------------------------------------------- +-- INFO: +-- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag +-- stylua: ignore +-- local function pio_generate_db() +-- vim.schedule(function() vim.notify('PIO: Generating Compile DB ...', vim.log.levels.INFO) end) +-- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) +-- vim.schedule(function() +-- if obj.code ~= 0 then +-- if obj.code == 127 then +-- vim.notify("PIO Manager db: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) +-- else +-- vim.notify('PIO Manager db: Generating Compile DB failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) +-- end +-- return +-- end +-- vim.notify('PIO: Generating Compile DB successful', vim.log.levels.INFO) +-- end) +-- end) +-- end local dir_path = vim.uv.cwd() local ini_file = vim.fs.joinpath(dir_path, 'platformio.ini') + -- 1. Helper: Unified hashing for change detection local function get_hash(path) if vim.fn.filereadable(path) == 0 then @@ -381,6 +382,7 @@ function M.start_watcher() return end local current_ini_hash = get_hash(ini_file) + _G.metadata.isBusy = false local handle = vim.uv.new_fs_event() if handle then @@ -391,12 +393,6 @@ function M.start_watcher() if err or fname ~= 'platformio.ini' or _G.metadata.isBusy or not events or not (events.change or events.renamce) then return end - -- -- Trigger only if the changed file is platformio.ini - -- if filename == 'platformio.ini' and (events.change or events.rename) then - -- if filename == 'platformio.ini' and (events.change or events.rename) then - -- if err or _G.metadata.isBusy or fname ~= 'platformio.ini' then - -- return - -- end local new_hash = get_hash(ini_file) if new_hash and new_hash ~= current_ini_hash then diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 740159c6..8d306651 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -171,13 +171,19 @@ function M.dispatcher(_, _, data) -- 4. Store the last element as the new partial buffer for the next call pio_buffer = data[#data] local task = table.remove(M.queue, 1) - _G.metadata.isBusy = false - if task then vim.schedule(task) end + vim.schedule(function() + if task then + task() + _G.metadata.isBusy = false + end + end) elseif status == 'FAILED' then M.queue = {} -- Clear queue on any other status (failure) pio_buffer = '' - _G.metadata.isBusy = false - vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) + vim.schedule(function() + _G.metadata.isBusy = false + vim.notify('PIO Sequence: Aborted', 4) + end) end break end From 39c2e4c26d85a7fa4a212a2ce973a86afdb13187 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 06:08:50 +0300 Subject: [PATCH 0749/1406] update --- lua/platformio/utils/pio.lua | 39 +++++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 8d306651..6251c51f 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -154,20 +154,24 @@ local pio_buffer = '' -- Persistent stream buffer ------------------------------------------------------ -- The Dispatcher (The Brain) --- stylua: ignore +--- stylua: ignore function M.dispatcher(_, _, data) - if #M.queue == 0 then return end + if #M.queue == 0 then + return + end - -- 1. attach partial buffer from previous data last line to 1st line + -- 1. attach partial buffer from previous data last line to 1st line pio_buffer = pio_buffer .. data[1] -- 2. If the chunk has more than one element, we've encountered newlines if #data > 1 then -- 3. Process any "middle" lines which are guaranteed to be complete - for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end + for i = 2, #data - 1 do + pio_buffer = pio_buffer .. data[i] + end for status in pio_buffer:gmatch('___DONE___:(%a+)') do if status then - if status == 'SUCCESS' then + if status == 'PASS' then -- 4. Store the last element as the new partial buffer for the next call pio_buffer = data[#data] local task = table.remove(M.queue, 1) @@ -177,11 +181,12 @@ function M.dispatcher(_, _, data) _G.metadata.isBusy = false end end) + elseif status == 'LAST' then + _G.metadata.isBusy = false elseif status == 'FAILED' then M.queue = {} -- Clear queue on any other status (failure) pio_buffer = '' vim.schedule(function() - _G.metadata.isBusy = false vim.notify('PIO Sequence: Aborted', 4) end) end @@ -189,27 +194,33 @@ function M.dispatcher(_, _, data) end end end - if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end + if #pio_buffer > 10000 then + pio_buffer = pio_buffer:sub(-5000) + end end ------------------------------------------------------ --- stylua: ignore +--- stylua: ignore M.run_sequence = function(tasks) -- Reset local state for new run M.queue = {} pio_buffer = '' local full_cmd = '' - local success = 'echo ___DONE___":"SUCCESS' - local failure = 'echo ___DONE___":"FAILED' + local pass = 'echo _DONE_":"PASS' + local last = 'echo _DONE_":"LAST' + local failure = 'echo _DONE_":"FAIL' for _, task in ipairs(tasks) do table.insert(M.queue, task.cb) - local part = string.format('%s && %s', task.cmd, success) - if full_cmd == '' then full_cmd = part - else full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands + local part = string.format('%s && %s', task.cmd, pass) + if full_cmd == '' then + full_cmd = part + else + full_cmd = full_cmd .. ' && ' .. part + end -- Chain multiple commands end - full_cmd = full_cmd .. ' || ' .. failure + full_cmd = full_cmd .. ' && ' .. last .. ' || ' .. failure local ToggleTerminal = require('platformio.utils.term').ToggleTerminal _G.metadata.isBusy = true ToggleTerminal(full_cmd, 'float') From f8753e7cb02d3f033f1f43ea4bcd430ccc8aa43d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 06:14:44 +0300 Subject: [PATCH 0750/1406] update --- lua/platformio/utils/pio.lua | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 6251c51f..7a6937dd 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -178,12 +178,11 @@ function M.dispatcher(_, _, data) vim.schedule(function() if task then task() - _G.metadata.isBusy = false end end) elseif status == 'LAST' then _G.metadata.isBusy = false - elseif status == 'FAILED' then + elseif status == 'FAIL' then M.queue = {} -- Clear queue on any other status (failure) pio_buffer = '' vim.schedule(function() From b15d1493688cc3b87a4d8d693400851387c58b82 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 06:17:29 +0300 Subject: [PATCH 0751/1406] update --- lua/platformio/utils/pio.lua | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 7a6937dd..48658a67 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -175,11 +175,9 @@ function M.dispatcher(_, _, data) -- 4. Store the last element as the new partial buffer for the next call pio_buffer = data[#data] local task = table.remove(M.queue, 1) - vim.schedule(function() - if task then - task() - end - end) + if task then + vim.schedule(task) + end elseif status == 'LAST' then _G.metadata.isBusy = false elseif status == 'FAIL' then From 04bb61f9c915be6c97e88e2ea32bb759ef489434 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 06:22:04 +0300 Subject: [PATCH 0752/1406] update --- lua/platformio/utils/pio.lua | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 48658a67..b2cf90bd 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -169,15 +169,17 @@ function M.dispatcher(_, _, data) pio_buffer = pio_buffer .. data[i] end - for status in pio_buffer:gmatch('___DONE___:(%a+)') do + for status in pio_buffer:gmatch('_DONE_:(%a+)') do if status then if status == 'PASS' then -- 4. Store the last element as the new partial buffer for the next call pio_buffer = data[#data] local task = table.remove(M.queue, 1) - if task then - vim.schedule(task) - end + vim.schedule(function() + if task then + task() + end + end) elseif status == 'LAST' then _G.metadata.isBusy = false elseif status == 'FAIL' then From d06eb3294323a201a74cac17c1c854df3a2b8879 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 06:32:28 +0300 Subject: [PATCH 0753/1406] update --- lua/platformio/utils/pio.lua | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index b2cf90bd..f75dd79b 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -175,11 +175,11 @@ function M.dispatcher(_, _, data) -- 4. Store the last element as the new partial buffer for the next call pio_buffer = data[#data] local task = table.remove(M.queue, 1) - vim.schedule(function() - if task then - task() - end - end) + -- vim.schedule(function() + if task then + vim.schedule(task()) + end + -- end) elseif status == 'LAST' then _G.metadata.isBusy = false elseif status == 'FAIL' then From 294de13d670d291be87c77c04901a8818e2c61e7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 06:38:05 +0300 Subject: [PATCH 0754/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f75dd79b..8b45728c 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -177,7 +177,7 @@ function M.dispatcher(_, _, data) local task = table.remove(M.queue, 1) -- vim.schedule(function() if task then - vim.schedule(task()) + vim.schedule(task) end -- end) elseif status == 'LAST' then From 24a201ea33aced33b809b5e192833b1598a5ca0b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 07:21:02 +0300 Subject: [PATCH 0755/1406] update --- lua/platformio/utils/pio.lua | 40 +++++++++++++++--------------------- 1 file changed, 16 insertions(+), 24 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 8b45728c..160f7f23 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -154,20 +154,16 @@ local pio_buffer = '' -- Persistent stream buffer ------------------------------------------------------ -- The Dispatcher (The Brain) ---- stylua: ignore +-- stylua: ignore function M.dispatcher(_, _, data) - if #M.queue == 0 then - return - end + if #M.queue == 0 then return end -- 1. attach partial buffer from previous data last line to 1st line pio_buffer = pio_buffer .. data[1] -- 2. If the chunk has more than one element, we've encountered newlines if #data > 1 then -- 3. Process any "middle" lines which are guaranteed to be complete - for i = 2, #data - 1 do - pio_buffer = pio_buffer .. data[i] - end + for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end for status in pio_buffer:gmatch('_DONE_:(%a+)') do if status then @@ -175,27 +171,22 @@ function M.dispatcher(_, _, data) -- 4. Store the last element as the new partial buffer for the next call pio_buffer = data[#data] local task = table.remove(M.queue, 1) - -- vim.schedule(function() - if task then - vim.schedule(task) - end - -- end) + if task then vim.schedule(task) end elseif status == 'LAST' then _G.metadata.isBusy = false + M.queue = {} -- Clear queue on any other status + pio_buffer = '' + vim.schedule(function() vim.notify('PIO Sequence: Finished', 4) end) elseif status == 'FAIL' then M.queue = {} -- Clear queue on any other status (failure) pio_buffer = '' - vim.schedule(function() - vim.notify('PIO Sequence: Aborted', 4) - end) + vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) end break end end end - if #pio_buffer > 10000 then - pio_buffer = pio_buffer:sub(-5000) - end + if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end end ------------------------------------------------------ @@ -233,6 +224,7 @@ function M.handleDb() local pio_manager = require('platformio.pio_setup').pio_manager pio_manager.refresh(function() local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') boilerplate_gen([[.clangd]], _G.metadata.core_dir) M.fix_pio_compile_commands() lsp.lsp_restart('clangd') @@ -246,12 +238,12 @@ function M.handlePioinit() -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) -- vim.schedule(function() - local pio_manager = require('platformio.pio_setup').pio_manager - pio_manager.refresh(function() - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - vim.notify('Pioinit: Success', vim.log.levels.INFO) - end) + -- local pio_manager = require('platformio.pio_setup').pio_manager + -- pio_manager.refresh(function() + -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + -- boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + vim.notify('Pioinit: Success', vim.log.levels.INFO) + -- end) -- end) end -- Handle after poioinit execution From cfa558076b9495c5f51623fe5d97e05666627e16 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 10:57:34 +0300 Subject: [PATCH 0756/1406] update --- lua/platformio/metadata.lua | 11 ++++- lua/platformio/utils/pio.lua | 75 ++++------------------------------- lua/platformio/utils/term.lua | 2 +- 3 files changed, 18 insertions(+), 70 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 6ad9b8aa..6063773c 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -168,10 +168,17 @@ function M.switch_env() -- 6. RESTART LSP (Crucial for refreshing includes/defines) -- We wrap in pcall in case clangd isn't actually running yet + + local pio_manager = require('platformio.pio_setup').pio_manager + pio_manager.refresh(function() + M.fix_pio_compile_commands() + lsp_restart('clangd') + end) + pcall(function() -- Force LSP to pick up new fallbackFlags/defines - local lspTools = require('platformio.lsp.tools') - lspTools.lsp_restart() + local lsp_restart = require('platformio.lsp.tools').lsp_restart + lsp_restart() end) end end) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 160f7f23..94721d1e 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -3,67 +3,7 @@ local M = {} M.selected_framework = '' local misc = require('platformio.utils.misc') -local lsp = require('platformio.lsp.tools') - ------------------------------------------------------- --- stylua: ignore -function M.get_pio_dir(type) - -- 1. Setup Base Paths - local home = os.getenv('HOME') or os.getenv('USERPROFILE') - - -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) - local map = { - core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, - packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/packages' }, - platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/platforms' }, - } - - local core_ini, dir_ini = nil, nil - local core_map, dir_map = map['core'], map[type] - if not core_map and not dir_map then - return nil - end - - -- 3. Try to get explicit value from platformio.ini - local handle = io.popen('pio project config --json-output') - if handle then - local json_str = handle:read('*all') - local _, config = pcall(vim.json.decode, json_str) - for _, section in ipairs(config) do - if section[1] == 'platformio' then - for _, kv in ipairs(section[2]) do - if kv[1] == dir_map.ini then - dir_ini = tostring(kv[2]):match('([^,%s]+)') - end - if kv[1] == core_map.ini then - core_ini = kv[2] - end - end - break - end - end - handle:close() - end - - -- 4.0 Fallback Logic: INI -> Env Var -> Default - local core_dir = core_ini or os.getenv('PLATFORMIO_CORE_DIR' or (home .. map['core'].sub)):gsub('[\\/]+$', '') - core_dir = misc.normalize_path(core_dir) --core_dir:gsub('\\', '/'):gsub('//+', '/') - - if type == 'core' then - return core_dir - end - - local result = dir_ini or os.getenv(dir_map.env) or (core_dir .. dir_map.sub) - - -- 5. Expand ${platformio.core_dir} - if result:find('${platformio.core_dir}', 1, true) then - result = result:gsub('%${platformio.core_dir}', core_dir) - end - - -- 6. Normalize Slashes for Windows - result = misc.normalize_path(result) --result:gsub('\\', '/'):gsub('//+', '/') - return result -end +local lsp_restart = require('platformio.lsp.tools').lsp_restart ------------------------------------------------------ -- stylua: ignore @@ -140,22 +80,22 @@ function M.fix_pio_compile_commands() out_file:write(formatted_json) out_file:close() vim.notify('compiledb: fixed', vim.log.levels.INFO) - -- lsp.lsp_restart('clangd') + -- lsp_restart('clangd') end end end end ------------------------------------------------------ --- INFO: Dispatcher +-- INFO: ToggleTerminal commands sequencer M.queue = {} local pio_buffer = '' -- Persistent stream buffer ------------------------------------------------------ --- The Dispatcher (The Brain) +-- INFO: ToggleTerminal commands stdout filter -- stylua: ignore -function M.dispatcher(_, _, data) +function M.stdoutFilter(_, _, data) if #M.queue == 0 then return end -- 1. attach partial buffer from previous data last line to 1st line @@ -190,6 +130,7 @@ function M.dispatcher(_, _, data) end ------------------------------------------------------ +-- INFO: ToggleTerminal commands Sequencer --- stylua: ignore M.run_sequence = function(tasks) -- Reset local state for new run @@ -227,7 +168,7 @@ function M.handleDb() boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') boilerplate_gen([[.clangd]], _G.metadata.core_dir) M.fix_pio_compile_commands() - lsp.lsp_restart('clangd') + lsp_restart('clangd') end) end @@ -251,7 +192,7 @@ end function M.handlePiolib() vim.notify('Piolib: Success', vim.log.levels.INFO) end --- INFO: endDispatcher +-- INFO: end commands sequencer ------------------------------------------------------ return M diff --git a/lua/platformio/utils/term.lua b/lua/platformio/utils/term.lua index 7a8d8981..5eb1a9ad 100644 --- a/lua/platformio/utils/term.lua +++ b/lua/platformio/utils/term.lua @@ -245,7 +245,7 @@ function M.ToggleTerminal(command, direction) -- INFO: on_stdout -- on_stdout = stdout_callback, - on_stdout = pio.dispatcher, + on_stdout = pio.stdoutFilter, -- INFO: on_create() { on_create = function(t) From 0725fe7731e7577cec11afecf4609c1cba80358c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 11:34:01 +0300 Subject: [PATCH 0757/1406] update --- lua/platformio/archived/piolsp.lua | 8 +- lua/platformio/lsp/attach.lua | 8 -- lua/platformio/metadata.lua | 3 +- lua/platformio/pioCommands.lua | 4 - lua/platformio/piolib.lua | 1 - lua/platformio/utils/pio.lua | 178 ++++++++++++++++++----------- plugin/platformio.lua | 9 +- 7 files changed, 117 insertions(+), 94 deletions(-) diff --git a/lua/platformio/archived/piolsp.lua b/lua/platformio/archived/piolsp.lua index 42faa97f..7b5312ac 100644 --- a/lua/platformio/archived/piolsp.lua +++ b/lua/platformio/archived/piolsp.lua @@ -1,14 +1,10 @@ local M = {} -local lsp = require('platformio.lsp.tools') +local lsp_restart = require('platformio.lsp.tools').lsp_restart -- stylua: ignore function M.piolsp() - lsp.lsp_restart() - -- local ok, err = pcall(vim.cmd.lsp, { args = { 'restart' } }) - -- if ok then vim.notify('LSP restarted' .. err) - -- else vim.notify('LSP restart failed: ' .. err) end - -- M.fix_pio_compile_commands() + lsp_restart() end return M diff --git a/lua/platformio/lsp/attach.lua b/lua/platformio/lsp/attach.lua index aa804083..9b4d4c51 100644 --- a/lua/platformio/lsp/attach.lua +++ b/lua/platformio/lsp/attach.lua @@ -32,7 +32,6 @@ vim.api.nvim_create_autocmd('LspAttach', { end) end, bufnr) end, { desc = 'Switch between source/header' }) - -- piolsp.fix_pio_compile_commands() end -- use lsp completion if no blink @@ -100,13 +99,6 @@ vim.api.nvim_create_autocmd('LspAttach', { ------------------------------------------------------------------ vim.cmd([[autocmd FileType * set formatoptions-=ro]]) -- - -- -- Optional: Auto-run every time you attach an LSP to a C/C++ file - -- vim.api.nvim_create_autocmd('LspAttach', { - -- pattern = { '*.c', '*.cpp', '*.h', '*.hpp' }, - -- callback = function() - -- piolsp.fix_pio_compile_commands() - -- end, - -- }) end, }) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 6063773c..b579c0d9 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -171,7 +171,8 @@ function M.switch_env() local pio_manager = require('platformio.pio_setup').pio_manager pio_manager.refresh(function() - M.fix_pio_compile_commands() + M.compile_commands() + local lsp_restart = require('platformio.tools').lsp_restart lsp_restart('clangd') end) diff --git a/lua/platformio/pioCommands.lua b/lua/platformio/pioCommands.lua index 533435d9..61d939b6 100644 --- a/lua/platformio/pioCommands.lua +++ b/lua/platformio/pioCommands.lua @@ -6,10 +6,6 @@ local ToggleTerminal = require('platformio.utils.term').ToggleTerminal -- stylua: ignore function M.piolsp() require('platformio.lsp.tools').lsp_restart('clangd') - -- local ok, err = pcall(vim.cmd.lsp, { args = { 'restart' } }) - -- if ok then vim.notify('LSP restarted' .. err) - -- else vim.notify('LSP restart failed: ' .. err) end - -- M.fix_pio_compile_commands() end function M.piocmd(cmd_table, direction) diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 71af53d0..1d5e980d 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -10,7 +10,6 @@ local actions = require('telescope.actions') local action_state = require('telescope.actions.state') local misc = require('platformio.utils.misc') local previewers = require('telescope.previewers') --- local piolsp = require('platformio.piolsp') --.piolsp local libentry_maker = function(opts) local displayer = entry_display.create({ diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 94721d1e..1447f11a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -7,85 +7,131 @@ local lsp_restart = require('platformio.lsp.tools').lsp_restart ------------------------------------------------------ -- stylua: ignore -function M.fix_pio_compile_commands() +function M.compile_commandsFix() local filename = vim.uv.cwd() .. '/compile_commands.json' - local file = io.open(filename, 'r') - if not file then return end - - -- read compile_commands.json file to content - local content = file:read('*a') - file:close() - if not content or content == '' then return end - - -- JSON decoding content to data - local ok, data = pcall(vim.json.decode, content) - if not ok or type(data) ~= 'table' then - vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) - return - end + local content = vim.fn.readfile(filename) + if #content == 0 then return end + + local ok, data = pcall(vim.json.decode, table.concat(content, "\n")) + if not ok or type(data) ~= 'table' then return end - -- print('PioFix0') - -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path + -- 1. Build Path Map (Scan toolchain) local path_map = {} - local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') - if pio_home then - -- Recursively find all binaries in PIO packages - local pio_packages = _G.metadata.toolchain .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' - local found_binaries = vim.fn.glob(pio_packages, false, true) - - for _, full_path in ipairs(found_binaries) do - -- Extract filename (e.g., riscv32-esp-elf-gcc) - local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') - path_map[name] = full_path - -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) - end + + local pio_binaries = _G.metadata.query_driver or "/bin/*" + -- local pio_binaries = (_G.metadata.toolchain or "") .. '/bin/*' + for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do + local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') + path_map[name] = full_path end - -- PHASE 2: Update JSON using the Map - local modified = 0 + -- 2. Update Entries + local modified = false for _, entry in ipairs(data) do - if type(entry.command) == 'string' then - local cmd_parts = vim.split(entry.command, ' ') - local first_token = cmd_parts[1] - if first_token then - -- Check if it's already a short name (not an absolute path) - local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') - if not is_abs then - local short_name = first_token:gsub('%.exe$', '') - -- print('PioFix2: short_name=' .. short_name) - -- Direct Query: Does this name exist in our discovered list? - if path_map[short_name] then - cmd_parts[1] = path_map[short_name] - -- print('PioFix3: full_name=' .. cmd_parts[1]) - entry.command = table.concat(cmd_parts, ' ') - modified = modified + 1 - end - end + local cmd = entry.command or "" + local first_token = cmd:match("^%S+") -- Get first word before space + + if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then + local short_name = first_token:gsub('%.exe$', '') + if path_map[short_name] then + -- Swap first token with full path safely + entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) + modified = true end end end - -- PHASE 3: Save and Refresh - -- Safe JSON encoding - if modified > 0 then - local out_file = io.open(filename, 'w') - if out_file then - local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) - if encode_ok and json_str then - -- 1. Format the string using python's json.tool - -- The second argument to vim.fn.system() is the "stdin" passed to the command - local formatted_json = vim.fn.system('python -m json.tool', json_str) - - -- out_file:write(json_str) - out_file:write(formatted_json) - out_file:close() - vim.notify('compiledb: fixed', vim.log.levels.INFO) - -- lsp_restart('clangd') - end + -- 3. Save with Formatting + if modified then + local json_str = vim.json.encode(data) + -- Use python to format, then write file + local formatted = vim.fn.system('python -m json.tool', json_str) + if vim.v.shell_error == 0 then + vim.fn.writefile(vim.split(formatted, "\n"), filename) + vim.notify('compiledb: paths fixed', vim.log.levels.INFO) end end end +-- function M.compile_commandsFix() +-- local filename = vim.uv.cwd() .. '/compile_commands.json' +-- local file = io.open(filename, 'r') +-- if not file then return end +-- +-- -- read compile_commands.json file to content +-- local content = file:read('*a') +-- file:close() +-- if not content or content == '' then return end +-- +-- -- JSON decoding content to data +-- local ok, data = pcall(vim.json.decode, content) +-- if not ok or type(data) ~= 'table' then +-- vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) +-- return +-- end +-- +-- -- print('PioFix0') +-- -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path +-- local path_map = {} +-- local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') +-- if pio_home then +-- -- Recursively find all binaries in PIO packages +-- local pio_packages = _G.metadata.toolchain .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' +-- local found_binaries = vim.fn.glob(pio_packages, false, true) +-- +-- for _, full_path in ipairs(found_binaries) do +-- -- Extract filename (e.g., riscv32-esp-elf-gcc) +-- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') +-- path_map[name] = full_path +-- -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) +-- end +-- end +-- +-- -- PHASE 2: Update JSON using the Map +-- local modified = 0 +-- for _, entry in ipairs(data) do +-- if type(entry.command) == 'string' then +-- local cmd_parts = vim.split(entry.command, ' ') +-- local first_token = cmd_parts[1] +-- if first_token then +-- -- Check if it's already a short name (not an absolute path) +-- local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') +-- if not is_abs then +-- local short_name = first_token:gsub('%.exe$', '') +-- -- print('PioFix2: short_name=' .. short_name) +-- -- Direct Query: Does this name exist in our discovered list? +-- if path_map[short_name] then +-- cmd_parts[1] = path_map[short_name] +-- -- print('PioFix3: full_name=' .. cmd_parts[1]) +-- entry.command = table.concat(cmd_parts, ' ') +-- modified = modified + 1 +-- end +-- end +-- end +-- end +-- end +-- +-- -- PHASE 3: Save and Refresh +-- -- Safe JSON encoding +-- if modified > 0 then +-- local out_file = io.open(filename, 'w') +-- if out_file then +-- local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) +-- if encode_ok and json_str then +-- -- 1. Format the string using python's json.tool +-- -- The second argument to vim.fn.system() is the "stdin" passed to the command +-- local formatted_json = vim.fn.system('python -m json.tool', json_str) +-- +-- -- out_file:write(json_str) +-- out_file:write(formatted_json) +-- out_file:close() +-- vim.notify('compiledb: fixed', vim.log.levels.INFO) +-- -- lsp_restart('clangd') +-- end +-- end +-- end +-- end + ------------------------------------------------------ -- INFO: ToggleTerminal commands sequencer @@ -167,7 +213,7 @@ function M.handleDb() local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') boilerplate_gen([[.clangd]], _G.metadata.core_dir) - M.fix_pio_compile_commands() + M.compile_commandsFix() lsp_restart('clangd') end) end diff --git a/plugin/platformio.lua b/plugin/platformio.lua index bb042383..c38d4372 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -95,15 +95,8 @@ end, {}) ------------------------------------------------------ -- INFO: fix paths in compile_commands.json --- vim.api.nvim_create_user_command('PioFixPaths', require('platformio.piolsp').fix_pio_compile_commands, {}) vim.api.nvim_create_user_command('PioFixPaths', function() - pio.fix_pio_compile_commands() - -- pio.run_sequence({ - -- { - -- cmd = 'pio run -t compiledb', - -- cb = pio.handleDb, - -- }, - -- }) + pio.compile_commandsFix() end, {}) ------------------------------------------------------ From 8e0934bc79b69b23f20eb17838b2a82100dc17fc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 12:56:11 +0300 Subject: [PATCH 0758/1406] update --- lua/platformio/utils/pio.lua | 73 ++++++++++++++++++++++++++++++------ 1 file changed, 61 insertions(+), 12 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 1447f11a..3e471b8a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -9,50 +9,99 @@ local lsp_restart = require('platformio.lsp.tools').lsp_restart -- stylua: ignore function M.compile_commandsFix() local filename = vim.uv.cwd() .. '/compile_commands.json' - local content = vim.fn.readfile(filename) - if #content == 0 then return end + if vim.fn.filereadable(filename) == 0 then return end - local ok, data = pcall(vim.json.decode, table.concat(content, "\n")) + -- Atomic read using built-in Vim function + local content = table.concat(vim.fn.readfile(filename), "\n") + local ok, data = pcall(vim.json.decode, content) if not ok or type(data) ~= 'table' then return end -- 1. Build Path Map (Scan toolchain) local path_map = {} - - local pio_binaries = _G.metadata.query_driver or "/bin/*" - -- local pio_binaries = (_G.metadata.toolchain or "") .. '/bin/*' - for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do + local toolchain_bin = (_G.metadata and _G.metadata.toolchain or "") .. '/bin/*' + for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = full_path end - -- 2. Update Entries + -- 2. Update Entries efficiently with string matching local modified = false for _, entry in ipairs(data) do local cmd = entry.command or "" - local first_token = cmd:match("^%S+") -- Get first word before space + local first_token = cmd:match("^%S+") -- Grab only the compiler driver + -- Fix if it's a relative path (doesn't start with / or Drive letter) if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then local short_name = first_token:gsub('%.exe$', '') if path_map[short_name] then - -- Swap first token with full path safely + -- Replace only the first token to preserve arguments entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) modified = true end end end - -- 3. Save with Formatting + -- 3. Save with Python formatting if modified then local json_str = vim.json.encode(data) - -- Use python to format, then write file local formatted = vim.fn.system('python -m json.tool', json_str) + if vim.v.shell_error == 0 then + -- Atomic write back to disk vim.fn.writefile(vim.split(formatted, "\n"), filename) vim.notify('compiledb: paths fixed', vim.log.levels.INFO) + else + vim.notify('PIO Fix: Python formatting failed', vim.log.levels.ERROR) end end end +-- function M.compile_commandsFix() +-- local filename = vim.uv.cwd() .. '/compile_commands.json' +-- local content = vim.fn.readfile(filename) +-- if #content == 0 then return end +-- +-- local ok, data = pcall(vim.json.decode, table.concat(content, "\n")) +-- if not ok or type(data) ~= 'table' then return end +-- +-- -- 1. Build Path Map (Scan toolchain) +-- local path_map = {} +-- +-- local pio_binaries = _G.metadata.query_driver or "/bin/*" +-- -- local pio_binaries = (_G.metadata.toolchain or "") .. '/bin/*' +-- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do +-- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') +-- path_map[name] = full_path +-- end +-- +-- -- 2. Update Entries +-- local modified = false +-- for _, entry in ipairs(data) do +-- local cmd = entry.command or "" +-- local first_token = cmd:match("^%S+") -- Get first word before space +-- +-- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then +-- local short_name = first_token:gsub('%.exe$', '') +-- if path_map[short_name] then +-- -- Swap first token with full path safely +-- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) +-- modified = true +-- end +-- end +-- end +-- +-- -- 3. Save with Formatting +-- if modified then +-- local json_str = vim.json.encode(data) +-- -- Use python to format, then write file +-- local formatted = vim.fn.system('python -m json.tool', json_str) +-- if vim.v.shell_error == 0 then +-- vim.fn.writefile(vim.split(formatted, "\n"), filename) +-- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) +-- end +-- end +-- end + -- function M.compile_commandsFix() -- local filename = vim.uv.cwd() .. '/compile_commands.json' -- local file = io.open(filename, 'r') From aecf7bb486257f9493fb94449e9a4735502db102 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 15:02:50 +0300 Subject: [PATCH 0759/1406] update --- lua/platformio/utils/pio2.lua | 154 ++++++++++++++++++++++++++++++++++ lua/platformio/utils/term.lua | 13 +-- 2 files changed, 162 insertions(+), 5 deletions(-) create mode 100644 lua/platformio/utils/pio2.lua diff --git a/lua/platformio/utils/pio2.lua b/lua/platformio/utils/pio2.lua new file mode 100644 index 00000000..876ae4f5 --- /dev/null +++ b/lua/platformio/utils/pio2.lua @@ -0,0 +1,154 @@ +local M = {} +local Terminal = require('toggleterm.terminal').Terminal + +M.queue = {} +M.is_processing = false + +-- 1. Persistent Terminal Instance +-- Using a high ID (99) to avoid clashing with your usual terminals +local pio_terminal = Terminal:new({ + id = 99, + direction = 'float', + close_on_exit = false, + hidden = true, -- Don't show in the standard toggle cycle +}) + +-- 2. The Optimized Path Fixer +function M.compile_commandsFix() + local filename = vim.uv.cwd() .. '/compile_commands.json' + if vim.fn.filereadable(filename) == 0 then + M.process_queue() + return + end + + -- Atomic read using built-in Vim function + local content = table.concat(vim.fn.readfile(filename), '\n') + local ok, data = pcall(vim.json.decode, content) + if not ok or type(data) ~= 'table' then + M.process_queue() + return + end + + -- 1. Build Path Map (Scan toolchain) + local path_map = {} + local toolchain_bin = (_G.metadata and _G.metadata.toolchain or '') .. '/bin/*' + for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do + local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') + path_map[name] = full_path + end + + -- 2. Update Entries efficiently with string matching + local modified = false + for _, entry in ipairs(data) do + local cmd = entry.command or '' + local first_token = cmd:match('^%S+') -- Grab only the compiler driver + + -- Fix if it's a relative path (doesn't start with / or Drive letter) + if first_token and not (first_token:sub(1, 1) == '/' or first_token:match('^%a:')) then + local short_name = first_token:gsub('%.exe$', '') + if path_map[short_name] then + -- Replace only the first token to preserve arguments + entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) + modified = true + end + end + end + + -- 3. Save with Python formatting + if modified then + local json_str = vim.json.encode(data) + local formatted = vim.fn.system('python -m json.tool', json_str) + + if vim.v.shell_error == 0 then + -- Atomic write back to disk + vim.fn.writefile(vim.split(formatted, '\n'), filename) + vim.notify('compiledb: paths fixed', vim.log.levels.INFO) + else + vim.notify('PIO Fix: Python formatting failed', vim.log.levels.ERROR) + end + end + + -- Chain to next task + M.process_queue() +end + +-- 3. Shell Runner via ToggleTerm +function M.run_shell_job(cmd, on_exit_callback, is_manual) + pio_terminal.cmd = cmd + + if is_manual then + -- Manual mode: No queue logic, just run and stop + pio_terminal.on_exit = nil + else + -- Queue mode: Define sequential behavior + pio_terminal.on_exit = function(_, _, exit_code) + if exit_code == 0 then + if on_exit_callback then + on_exit_callback() + end + -- Always schedule queue moves to avoid terminal-state race conditions + vim.schedule(function() + M.process_queue() + end) + else + vim.notify('PIO Queue Stopped: Error in ' .. cmd, vim.log.levels.ERROR) + M.queue = {} + M.is_processing = false + end + end + end + + pio_terminal:spawn() +end + +-- 4. The Queue Controller +function M.process_queue() + local task = table.remove(M.queue, 1) + + if not task then + M.is_processing = false + return + end + + M.is_processing = true + + if task.cmd then + M.run_shell_job(task.cmd, task.cb, false) + elseif type(task.cb) == 'function' then + -- For Lua-only tasks, they must eventually call M.process_queue() + vim.schedule(task.cb) + end +end + +-- 5. Public API +-- Use this for the sequential build/init flow +function M.setup_project(board_id, framework) + if M.is_processing then + vim.notify('PIO: Processing already in progress', vim.log.levels.WARN) + return + end + + M.queue = { + { + cmd = string.format('pio project init --board %s -O "framework=%s"', board_id, framework), + cb = function() + vim.notify('Init Complete') + end, + }, + { + cmd = 'pio run -t compiledb', + }, + { + cb = M.compile_commandsFix, + }, + } + + M.process_queue() +end + +-- Use this for one-off commands that don't trigger the queue +function M.run_manual(cmd) + M.run_shell_job(cmd, nil, true) +end + +return M diff --git a/lua/platformio/utils/term.lua b/lua/platformio/utils/term.lua index 5eb1a9ad..ce278105 100644 --- a/lua/platformio/utils/term.lua +++ b/lua/platformio/utils/term.lua @@ -23,10 +23,6 @@ function M.check_prefix(str, prefix) return str:sub(1, #prefix) == prefix end -local function pathmul(n) - return '..' .. string.rep('/..', n) -end - ------------------------------------------------------ -- INFO: get current OS enter @@ -144,6 +140,8 @@ function M.ToggleTerminal(command, direction) end title = 'Pio Monitor: [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' pioOpts.display_name = 'piomon:' .. orig_window + pioOpts.id = 98 + pioOpts.on_stdout = nil else -- INFO: if previous cli terminal already opened ==> reopen if prev.cli then prev.cli.display_name = 'piocli:' .. orig_window @@ -163,6 +161,11 @@ function M.ToggleTerminal(command, direction) end title = 'Pio CLI> [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' pioOpts.display_name = 'piocli:' .. orig_window + pioOpts.id = 99 + + -- INFO: on_stdout + -- on_stdout = stdout_callback, + pioOpts.on_stdout = pio.stdoutFilter end pioOpts.direction = direction ------------------------------------------------------ @@ -245,7 +248,7 @@ function M.ToggleTerminal(command, direction) -- INFO: on_stdout -- on_stdout = stdout_callback, - on_stdout = pio.stdoutFilter, + -- on_stdout = pio.stdoutFilter, -- INFO: on_create() { on_create = function(t) From f531ab37ab226eda0bad8879c970d87948a7fa77 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 15:08:44 +0300 Subject: [PATCH 0760/1406] update --- lua/platformio/utils/term.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/term.lua b/lua/platformio/utils/term.lua index ce278105..f7639394 100644 --- a/lua/platformio/utils/term.lua +++ b/lua/platformio/utils/term.lua @@ -265,7 +265,7 @@ function M.ToggleTerminal(command, direction) local quitbang = vim.fn.getcmdline() == 'q!' if quitbang or quit then local name_splt = M.strsplit(t.display_name, ':') - if quitbang then + if t and quitbang then if name_splt[1] == 'piomon' then -- monitor terminal local exit = vim.api.nvim_replace_termcodes('exit', true, true, true) send(t, exit) From 7c39c0d754342e1d5839f059994034d167cc6a24 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 15:15:07 +0300 Subject: [PATCH 0761/1406] update --- lua/platformio/utils/term.lua | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/term.lua b/lua/platformio/utils/term.lua index f7639394..5e4ba463 100644 --- a/lua/platformio/utils/term.lua +++ b/lua/platformio/utils/term.lua @@ -81,6 +81,9 @@ end ------------------------------------------------------ -- INFO: Send command local function send(term, cmd) + if not term.job_id then + return + end vim.fn.chansend(term.job_id, cmd .. M.enter()) if vim.api.nvim_buf_is_loaded(term.bufnr) and vim.api.nvim_buf_is_valid(term.bufnr) then if term.window and vim.api.nvim_win_is_valid(term.window) then --vim.ui.term_has_open_win(term) then @@ -265,7 +268,7 @@ function M.ToggleTerminal(command, direction) local quitbang = vim.fn.getcmdline() == 'q!' if quitbang or quit then local name_splt = M.strsplit(t.display_name, ':') - if t and quitbang then + if quitbang then if name_splt[1] == 'piomon' then -- monitor terminal local exit = vim.api.nvim_replace_termcodes('exit', true, true, true) send(t, exit) From c7f27ad35068312b0387fdd8ae03e8a7b0280fda Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 16:54:58 +0300 Subject: [PATCH 0762/1406] update --- lua/platformio/pioinit.lua | 23 +-- lua/platformio/utils/pio2.lua | 134 +++++++++----- lua/platformio/utils/term.lua | 3 - lua/platformio/utils/term2.lua | 326 +++++++++++++++++++++++++++++++++ 4 files changed, 423 insertions(+), 63 deletions(-) create mode 100644 lua/platformio/utils/term2.lua diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index c1d3d911..722e9342 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -58,17 +58,18 @@ local function pick_framework(board_details) local pio = require('platformio.utils.pio') pio.selected_framework = selection[1] - - pio.run_sequence({ - { - cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', - cb = pio.handlePioinit, - }, - { - cmd = 'pio run -t compiledb', - cb = pio.handleDb, - }, - }) + local setup_project = require('platformio.utils.pio2').setup_project + setup_project(board_details['id'], pio.selected_framework) + -- pio.run_sequence({ + -- { + -- cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', + -- cb = pio.handlePioinit, + -- }, + -- { + -- cmd = 'pio run -t compiledb', + -- cb = pio.handleDb, + -- }, + -- }) end) return true end, diff --git a/lua/platformio/utils/pio2.lua b/lua/platformio/utils/pio2.lua index 876ae4f5..520ef430 100644 --- a/lua/platformio/utils/pio2.lua +++ b/lua/platformio/utils/pio2.lua @@ -1,97 +1,126 @@ local M = {} local Terminal = require('toggleterm.terminal').Terminal +-- State Management M.queue = {} M.is_processing = false - --- 1. Persistent Terminal Instance --- Using a high ID (99) to avoid clashing with your usual terminals -local pio_terminal = Terminal:new({ - id = 99, - direction = 'float', - close_on_exit = false, - hidden = true, -- Don't show in the standard toggle cycle -}) +M.current_callback = nil + +-- 1. Persistent Terminal Configuration +-- Defined once to avoid "cannot assign after loading" errors. +local ToggleTerminal = require('platformio.utils.term2').ToggleTerminal +_G.metadata.isBusy = true +local pio_terminal = ToggleTerminal('', 'float') +-- local pio_terminal = Terminal:new({ +-- id = 99, +-- direction = 'float', +-- close_on_exit = false, -- Keep window open so user can see results +-- -- Proxy callback: uses the variable defined in M.run_shell_job +-- on_exit = function(t, job, exit_code) +-- if type(current_callback) == 'function' then +-- current_callback(t, job, exit_code) +-- end +-- end, +-- -- Dynamic focus/scroll handler +-- on_open = function(term) +-- if term.window and vim.api.nvim_win_is_valid(term.window) then +-- vim.api.nvim_set_current_win(term.window) +-- vim.cmd('normal! G') -- Scroll to bottom +-- end +-- end, +-- }) -- 2. The Optimized Path Fixer function M.compile_commandsFix() local filename = vim.uv.cwd() .. '/compile_commands.json' + + -- Nil/Error Check: Ensure file exists if vim.fn.filereadable(filename) == 0 then M.process_queue() return end - -- Atomic read using built-in Vim function - local content = table.concat(vim.fn.readfile(filename), '\n') + -- Atomic Read + local lines = vim.fn.readfile(filename) + if not lines or #lines == 0 then + M.process_queue() + return + end + + local content = table.concat(lines, '\n') local ok, data = pcall(vim.json.decode, content) + + -- Nil/Error Check: Valid JSON if not ok or type(data) ~= 'table' then + vim.notify('PIO Fix: Invalid JSON', vim.log.levels.ERROR) M.process_queue() return end - -- 1. Build Path Map (Scan toolchain) + -- Build Path Map from Toolchain Metadata local path_map = {} - local toolchain_bin = (_G.metadata and _G.metadata.toolchain or '') .. '/bin/*' - for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do - local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') - path_map[name] = full_path + local toolchain = _G.metadata and _G.metadata.toolchain or '' + if toolchain ~= '' then + local bin_path = toolchain .. '/bin/*' + for _, full_path in ipairs(vim.fn.glob(bin_path, false, true)) do + local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') + path_map[name] = full_path + end end - -- 2. Update Entries efficiently with string matching + -- Update Entries local modified = false for _, entry in ipairs(data) do local cmd = entry.command or '' - local first_token = cmd:match('^%S+') -- Grab only the compiler driver - - -- Fix if it's a relative path (doesn't start with / or Drive letter) + local first_token = cmd:match('^%S+') + -- If driver is relative, replace with absolute path from map if first_token and not (first_token:sub(1, 1) == '/' or first_token:match('^%a:')) then local short_name = first_token:gsub('%.exe$', '') if path_map[short_name] then - -- Replace only the first token to preserve arguments entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) modified = true end end end - -- 3. Save with Python formatting + -- Save if changes made if modified then local json_str = vim.json.encode(data) local formatted = vim.fn.system('python -m json.tool', json_str) - if vim.v.shell_error == 0 then - -- Atomic write back to disk vim.fn.writefile(vim.split(formatted, '\n'), filename) - vim.notify('compiledb: paths fixed', vim.log.levels.INFO) - else - vim.notify('PIO Fix: Python formatting failed', vim.log.levels.ERROR) + vim.notify('PIO: Fixed compile_commands.json', vim.log.levels.INFO) end end - -- Chain to next task + -- Proceed to next task (or final shell handoff) M.process_queue() end --- 3. Shell Runner via ToggleTerm +-- 3. Shell Runner (Queue and Manual) function M.run_shell_job(cmd, on_exit_callback, is_manual) + if not cmd or cmd == '' then + return + end + pio_terminal.cmd = cmd if is_manual then - -- Manual mode: No queue logic, just run and stop - pio_terminal.on_exit = nil + -- Manual Mode: Clear callback to prevent queue interference + M.current_callback = nil else - -- Queue mode: Define sequential behavior - pio_terminal.on_exit = function(_, _, exit_code) + -- Queue Mode: Set logic for the next step + M.current_callback = function(_, _, exit_code) if exit_code == 0 then - if on_exit_callback then + if type(on_exit_callback) == 'function' then on_exit_callback() end - -- Always schedule queue moves to avoid terminal-state race conditions + -- Use schedule to avoid race conditions with terminal closing/opening vim.schedule(function() M.process_queue() end) else - vim.notify('PIO Queue Stopped: Error in ' .. cmd, vim.log.levels.ERROR) + vim.notify('PIO Queue Failed: ' .. cmd, vim.log.levels.ERROR) M.queue = {} M.is_processing = false end @@ -105,6 +134,7 @@ end function M.process_queue() local task = table.remove(M.queue, 1) + -- Nil Check: End of queue if not task then M.is_processing = false return @@ -112,43 +142,49 @@ function M.process_queue() M.is_processing = true + -- Decide execution path if task.cmd then M.run_shell_job(task.cmd, task.cb, false) elseif type(task.cb) == 'function' then - -- For Lua-only tasks, they must eventually call M.process_queue() + -- For Lua tasks (like Fixer), run directly vim.schedule(task.cb) + else + -- Fallback: Skip invalid tasks + M.process_queue() end end --- 5. Public API --- Use this for the sequential build/init flow +-- 5. Main Entry Point function M.setup_project(board_id, framework) if M.is_processing then - vim.notify('PIO: Processing already in progress', vim.log.levels.WARN) + vim.notify('PIO: Queue already running', vim.log.levels.WARN) return end + -- Determine OS Shell for the final handoff + local shell = vim.o.shell or (vim.fn.has('win32') == 1 and 'cmd' or 'bash') + M.queue = { { cmd = string.format('pio project init --board %s -O "framework=%s"', board_id, framework), - cb = function() - vim.notify('Init Complete') - end, }, { cmd = 'pio run -t compiledb', }, { - cb = M.compile_commandsFix, + cb = M.compile_commandsFix, -- Internal: calls M.process_queue() + }, + { + -- FINAL TASK: Spawn an interactive shell + -- This keeps the terminal alive so the user can type or use :send() + cmd = shell, + cb = function() + vim.notify('PIO: Automation complete. Shell ready.', vim.log.levels.INFO) + end, }, } M.process_queue() end --- Use this for one-off commands that don't trigger the queue -function M.run_manual(cmd) - M.run_shell_job(cmd, nil, true) -end - return M diff --git a/lua/platformio/utils/term.lua b/lua/platformio/utils/term.lua index 5e4ba463..ce278105 100644 --- a/lua/platformio/utils/term.lua +++ b/lua/platformio/utils/term.lua @@ -81,9 +81,6 @@ end ------------------------------------------------------ -- INFO: Send command local function send(term, cmd) - if not term.job_id then - return - end vim.fn.chansend(term.job_id, cmd .. M.enter()) if vim.api.nvim_buf_is_loaded(term.bufnr) and vim.api.nvim_buf_is_valid(term.bufnr) then if term.window and vim.api.nvim_win_is_valid(term.window) then --vim.ui.term_has_open_win(term) then diff --git a/lua/platformio/utils/term2.lua b/lua/platformio/utils/term2.lua new file mode 100644 index 00000000..0d981aa3 --- /dev/null +++ b/lua/platformio/utils/term2.lua @@ -0,0 +1,326 @@ +local M = {} + +local is_windows = jit.os == 'Windows' +M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' +-- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' +-- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' + +local config = require('platformio').config +local pio = require('platformio.utils.pio') + +local current_callback = require('platformio.utils.pio2').current_callback +------------------------------------------------------ +function M.strsplit(inputstr, del) + local t = {} + if type(inputstr) == 'string' and inputstr and inputstr ~= '' then + for str in string.gmatch(inputstr, '([^' .. del .. ']+)') do + table.insert(t, str) + end + end + return t +end + +function M.check_prefix(str, prefix) + return str:sub(1, #prefix) == prefix +end + +------------------------------------------------------ + +-- INFO: get current OS enter +function M.enter() + local shell = vim.o.shell + if is_windows then + return vim.fn.executable('pwsh') and '\r' or '\r\n' + elseif shell:find('nu') then + return '\r' + else + return '\n' + end +end + +-- INFO: get previous window +local function getPreviousWindow(orig_window) + local prev = { + orig_window = orig_window, + term = nil, --active terminal + cli = nil, --cli terminal + mon = nil, --mon terminal + float = false, --is active terminal direction float + } + local terms = require('toggleterm.terminal').get_all(true) + if #terms ~= 0 then + for i = 1, #terms do + if terms[i].display_name and terms[i].display_name ~= '' and terms[i].display_name:find('pio', 1) then + local name_splt = M.strsplit(terms[i].display_name, ':') + if name_splt[1] == 'piocli' then + prev.cli = terms[i] + if terms[i].window == orig_window then + ---@diagnostic disable-next-line: cast-local-type + prev.orig_window = tonumber(name_splt[2]) -- set orig_window to the previous terminal onrig_window + prev.term = terms[i] + end + if terms[i].direction == 'float' then + prev.float = true + end + elseif name_splt[1] == 'piomon' then + prev.mon = terms[i] + if terms[i].window == orig_window then + ---@diagnostic disable-next-line: cast-local-type + prev.orig_window = tonumber(name_splt[2]) -- set orig_window to the previous terminal onrig_window + prev.term = terms[i] + end + if terms[i].direction == 'float' then + prev.float = true + end + end + end + end + end + return prev +end + +------------------------------------------------------ +-- INFO: Send command +local function send(term, cmd) + vim.fn.chansend(term.job_id, cmd .. M.enter()) + if vim.api.nvim_buf_is_loaded(term.bufnr) and vim.api.nvim_buf_is_valid(term.bufnr) then + if term.window and vim.api.nvim_win_is_valid(term.window) then --vim.ui.term_has_open_win(term) then + vim.api.nvim_set_current_win(term.window) -- terminal focus + vim.api.nvim_buf_call(term.bufnr, function() + local mode = vim.api.nvim_get_mode().mode + if mode == 'n' or mode == 'nt' then + vim.cmd('normal! G') -- normal command to Goto bottom of buffer (scroll) + end + end) + end + end +end + +------------------------------------------------------ +-- INFO: PioTermClose +local function PioTermClose(t) + local orig_window = tonumber(M.strsplit(t.display_name, ':')[2]) + -- close terminal window + vim.api.nvim_win_close(t.window, true) + + -- go back to previous window + if orig_window and vim.api.nvim_win_is_valid(orig_window) then + vim.api.nvim_set_current_win(orig_window) + else + vim.api.nvim_set_current_win(0) + end +end + +------------------------------------------------------ +-- INFO: ToggleTerminal +function M.ToggleTerminal(command, direction) + local status_ok, _ = pcall(require, 'toggleterm') + if not status_ok then + vim.api.nvim_echo({ { 'toggleterm not found!', 'ErrorMsg' } }, true, {}) + return + end + + local title = '' + local pioOpts = {} + + -- INFO: set orig_window to current window, or if available get current toggleterm previous window + local prev = getPreviousWindow(vim.api.nvim_get_current_win()) + local orig_window = prev.orig_window + + if string.find(command, ' monitor') then + if prev.mon then -- INFO: if previous monitor terminal already opened ==> reopen + prev.mon.display_name = 'piomon:' .. orig_window + local win_type = vim.fn.win_gettype(prev.mon.window) + local win_open = win_type == '' or win_type == 'popup' + if prev.mon.window and (win_open and vim.api.nvim_win_get_buf(prev.mon.window) == prev.mon.bufnr) then + vim.api.nvim_set_current_win(prev.mon.window) + else + prev.mon:open() + end + return + end + title = 'Pio Monitor: [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' + pioOpts.display_name = 'piomon:' .. orig_window + pioOpts.id = 98 + pioOpts.on_stdout = nil + else -- INFO: if previous cli terminal already opened ==> reopen + if prev.cli then + prev.cli.display_name = 'piocli:' .. orig_window + local win_type = vim.fn.win_gettype(prev.cli.window) + local win_open = win_type == '' or win_type == 'popup' + if prev.cli.window and (win_open and vim.api.nvim_win_get_buf(prev.cli.window) == prev.cli.bufnr) then + vim.api.nvim_set_current_win(prev.cli.window) + else + prev.cli:open() + end + vim.defer_fn(function() + if command and command ~= '' then + send(prev.cli, command) + end + end, 50) -- 50ms delay, adjust as needed + return + end + title = 'Pio CLI> [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' + pioOpts.display_name = 'piocli:' .. orig_window + pioOpts.id = 99 + + -- INFO: on_stdout + -- on_stdout = stdout_callback, + pioOpts.on_stdout = pio.stdoutFilter + end + pioOpts.direction = direction + ------------------------------------------------------ + + -- INFO: termConfig table start + local termConfig = { + hidden = true, -- Start hidden, we'll open it explicitly + hide_numbers = true, + float_opts = { + winblend = 0, + width = function() + return math.ceil(vim.o.columns * 0.85) + end, + height = function() + return math.ceil(vim.o.lines * 0.85) + end, + -- shell = vim.o.shell, + shell = vim.o.shell, + highlights = { + border = 'FloatBorder', + background = 'NormalFloat', + }, + }, + close_on_exit = false, --closeOnexit, + + -- INFO: on_open() + on_open = function(t) + -- Get properties of the 'Normal' highlight group (background of main editor) + -- local hl = vim.api.nvim_get_hl(0, { name = 'PmenuSel' }) + -- local hl = { bg = '#e4cf0e', fg = '#0012d9' } + local hl = { bg = '#80a3d4', fg = '#000000' } + + if hl then + vim.api.nvim_set_hl(0, 'MyWinBar', { bg = hl.bg, fg = hl.fg }) + + local winBartitle = '%#MyWinBar#' .. title .. '%*' + vim.api.nvim_set_option_value('winbar', winBartitle, { scope = 'local', win = t.window }) + + -- Following necessary to solve that some time winbar not showing + vim.schedule(function() + vim.api.nvim_set_option_value('winbar', winBartitle, { scope = 'local', win = t.window }) + end) + end + vim.keymap.set('t', '', [[k]], { buffer = t.bufnr }) + vim.keymap.set('n', '', [[a]], { buffer = t.bufnr }) + + vim.keymap.set('n', 'q', function() + PioTermClose(t) + end, { desc = 'PioTermClose', buffer = t.bufnr }) + + if config.debug then + local name_splt = M.strsplit(t.display_name, ':') + vim.api.nvim_echo({ + { 'ToggleTerm ', 'MoreMsg' }, + { '(Term name: ' .. name_splt[1] .. ')', 'MoreMsg' }, + { '(Prev win ID: ' .. name_splt[2] .. ')', 'MoreMsg' }, + { '(Term Win ID: ' .. t.window .. ')', 'MoreMsg' }, + { '(Term Buffer#: ' .. t.bufnr .. ')', 'MoreMsg' }, + { '(Term id: ' .. t.id .. ')', 'MoreMsg' }, + { '(Job ID: ' .. t.job_id .. ')', 'MoreMsg' }, + }, true, {}) + end + end, + + -- INFO: on_close() + on_close = function(t) + orig_window = tonumber(M.strsplit(t.display_name, ':')[2]) + ---@diagnostic disable-next-line: param-type-mismatch + if orig_window and vim.api.nvim_win_is_valid(orig_window) then + vim.api.nvim_set_current_win(orig_window) + else + vim.api.nvim_set_current_win(0) + end + end, + + -- -- INFO: on_exit() + -- on_exit = function(_) + -- exit_callback() + -- end, + on_exit = function(t, job, exit_code) + if type(current_callback) == 'function' then + current_callback(t, job, exit_code) + end + end, + + -- INFO: on_stdout + -- on_stdout = stdout_callback, + -- on_stdout = pio.stdoutFilter, + + -- INFO: on_create() { + on_create = function(t) + local platformio = vim.api.nvim_create_augroup(M.strsplit(t.display_name, ':')[1], { clear = true }) + + -- INFO: CmdlineLeave + vim.api.nvim_create_autocmd('CmdlineLeave', { + group = platformio, + -- pattern = ':', + buffer = t.bufnr, + callback = function() + if vim.v.event and not vim.v.event.abort and vim.v.event.cmdtype == ':' then + local quit = vim.fn.getcmdline() == 'q' + local quitbang = vim.fn.getcmdline() == 'q!' + if quitbang or quit then + local name_splt = M.strsplit(t.display_name, ':') + if quitbang then + if name_splt[1] == 'piomon' then -- monitor terminal + local exit = vim.api.nvim_replace_termcodes('exit', true, true, true) + send(t, exit) + else -- cli terminal + send(t, 'exit') + end + end + + orig_window = tonumber(name_splt[2]) + vim.schedule(function() + -- go back to previous window + if orig_window and vim.api.nvim_win_is_valid(orig_window) then + vim.api.nvim_set_current_win(orig_window) + else + vim.api.nvim_set_current_win(0) + end + end) + end + end + end, + }) + + -- INFO: BufUnload + vim.api.nvim_create_autocmd('BufUnload', { + group = platformio, + desc = 'toggleterm buffer unloaded', + buffer = t.bufnr, + callback = function(args) + vim.keymap.del('t', '', { buffer = args.buf }) + vim.keymap.del('n', '', { buffer = args.buf }) + + -- clear autommmand when quit + vim.api.nvim_clear_autocmds({ group = M.strsplit(t.display_name, ':')[1] }) + end, + }) + end, + } + -- INFO: termConfig table end + + termConfig = vim.tbl_deep_extend('force', termConfig, pioOpts or {}) + + -- INFO: create new terminal + local terminal = require('toggleterm.terminal').Terminal:new(termConfig) + if prev.term and prev.float then + prev.term:close() + end + terminal:toggle() + return terminal +end + +return M +---------------------------------------------------------------------------------------- From 47a5a0f4b10fff5544829a75ffdc127b02241a5b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 17:02:20 +0300 Subject: [PATCH 0763/1406] update --- lua/platformio/utils/pio2.lua | 6 +++--- lua/platformio/utils/term2.lua | 7 ++++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/lua/platformio/utils/pio2.lua b/lua/platformio/utils/pio2.lua index 520ef430..bbe0e4eb 100644 --- a/lua/platformio/utils/pio2.lua +++ b/lua/platformio/utils/pio2.lua @@ -4,7 +4,7 @@ local Terminal = require('toggleterm.terminal').Terminal -- State Management M.queue = {} M.is_processing = false -M.current_callback = nil +local current_callback = require('platformio.utils.term2').current_callback -- 1. Persistent Terminal Configuration -- Defined once to avoid "cannot assign after loading" errors. @@ -107,10 +107,10 @@ function M.run_shell_job(cmd, on_exit_callback, is_manual) if is_manual then -- Manual Mode: Clear callback to prevent queue interference - M.current_callback = nil + current_callback = nil else -- Queue Mode: Set logic for the next step - M.current_callback = function(_, _, exit_code) + current_callback = function(_, _, exit_code) if exit_code == 0 then if type(on_exit_callback) == 'function' then on_exit_callback() diff --git a/lua/platformio/utils/term2.lua b/lua/platformio/utils/term2.lua index 0d981aa3..03668b9b 100644 --- a/lua/platformio/utils/term2.lua +++ b/lua/platformio/utils/term2.lua @@ -5,10 +5,11 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' +M.current_callback = nil + local config = require('platformio').config local pio = require('platformio.utils.pio') -local current_callback = require('platformio.utils.pio2').current_callback ------------------------------------------------------ function M.strsplit(inputstr, del) local t = {} @@ -247,8 +248,8 @@ function M.ToggleTerminal(command, direction) -- exit_callback() -- end, on_exit = function(t, job, exit_code) - if type(current_callback) == 'function' then - current_callback(t, job, exit_code) + if type(M.current_callback) == 'function' then + M.current_callback(t, job, exit_code) end end, From 384ef5146777b38c5a8f1284310f8aa40d20681c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 19:32:18 +0300 Subject: [PATCH 0764/1406] update --- lua/platformio/utils/pio.lua | 102 ++++-- lua/platformio/utils/term.lua | 11 +- pio.lua | 346 ++++++++++++++++++++ lua/platformio/utils/pio2.lua => pio2.lua | 0 term.lua | 324 ++++++++++++++++++ lua/platformio/utils/term2.lua => term2.lua | 0 6 files changed, 757 insertions(+), 26 deletions(-) create mode 100644 pio.lua rename lua/platformio/utils/pio2.lua => pio2.lua (100%) create mode 100644 term.lua rename lua/platformio/utils/term2.lua => term2.lua (100%) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 3e471b8a..d8e277c7 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -5,6 +5,10 @@ M.selected_framework = '' local misc = require('platformio.utils.misc') local lsp_restart = require('platformio.lsp.tools').lsp_restart +local ToggleTerminal = require('platformio.utils.term').ToggleTerminal +-- _G.metadata.isBusy = true +local pio_terminal = ToggleTerminal('', 'float') +M.is_processing = false ------------------------------------------------------ -- stylua: ignore function M.compile_commandsFix() @@ -203,15 +207,16 @@ function M.stdoutFilter(_, _, data) for status in pio_buffer:gmatch('_DONE_:(%a+)') do if status then if status == 'PASS' then + M.process_queue() -- 4. Store the last element as the new partial buffer for the next call pio_buffer = data[#data] - local task = table.remove(M.queue, 1) - if task then vim.schedule(task) end - elseif status == 'LAST' then - _G.metadata.isBusy = false - M.queue = {} -- Clear queue on any other status - pio_buffer = '' - vim.schedule(function() vim.notify('PIO Sequence: Finished', 4) end) + -- local task = table.remove(M.queue, 1) + -- if task then vim.schedule(task) end + -- elseif status == 'LAST' then + -- _G.metadata.isBusy = false + -- M.queue = {} -- Clear queue on any other status + -- pio_buffer = '' + -- vim.schedule(function() vim.notify('PIO Sequence: Finished', 4) end) elseif status == 'FAIL' then M.queue = {} -- Clear queue on any other status (failure) pio_buffer = '' @@ -234,24 +239,79 @@ M.run_sequence = function(tasks) local full_cmd = '' local pass = 'echo _DONE_":"PASS' - local last = 'echo _DONE_":"LAST' - local failure = 'echo _DONE_":"FAIL' + -- local last = 'echo _DONE_":"LAST' + local fail = 'echo _DONE_":"FAIL' - for _, task in ipairs(tasks) do - table.insert(M.queue, task.cb) - local part = string.format('%s && %s', task.cmd, pass) - if full_cmd == '' then - full_cmd = part - else - full_cmd = full_cmd .. ' && ' .. part - end -- Chain multiple commands + for _, row in ipairs(tasks) do + -- Build the wrapped command string + local wrapped_cmd = string.format('%s && %s || %s', row.cmd, pass, fail) + table.insert(M.queue, { + cmd = wrapped_cmd, + cb = row.cb, + }) end - full_cmd = full_cmd .. ' && ' .. last .. ' || ' .. failure - local ToggleTerminal = require('platformio.utils.term').ToggleTerminal - _G.metadata.isBusy = true - ToggleTerminal(full_cmd, 'float') + + -- for _, task in ipairs(tasks) do + -- table.insert(M.queue, task.cb) + -- local part = string.format('%s && %s', task.cmd, pass) + -- if full_cmd == '' then + -- full_cmd = part + -- else + -- full_cmd = full_cmd .. ' && ' .. part + -- end -- Chain multiple commands + -- end + -- full_cmd = full_cmd .. ' && ' .. last .. ' || ' .. failure + -- local ToggleTerminal = require('platformio.utils.term').ToggleTerminal + -- _G.metadata.isBusy = true + -- ToggleTerminal(full_cmd, 'float') end +-- 2. Shell Runner: Sends text to the live shell +function M.run_shell_job(cmd, on_exit_callback) + -- Ensure terminal is open and process is alive + if not pio_terminal then + return + end + if not pio_terminal:is_open() then + pio_terminal:open() + end + + -- Wrap the command: + -- 1. Run the actual command + -- 2. Run the callback logic (optional) + -- 3. Print the sentinel so the Lua listener knows we're done + -- local full_cmd = string.format('%s && echo %s', cmd, sentinel) + + -- Store callback for the listener if needed + M.current_cb = on_exit_callback + + -- Send the text + Enter key + pio_terminal:send(cmd) +end +-- 3. Queue Controller +function M.process_queue() + local task = table.remove(M.queue, 1) + + if not task then + M.is_processing = false + if M.current_cb then + M.current_cb() + end -- Final callback + return + end + + M.is_processing = true + + if task.cmd then + M.run_shell_job(task.cmd, task.cb) + elseif type(task.cb) == 'function' then + vim.schedule(function() + task.cb() + -- Lua tasks need to manually move the queue + M.process_queue() + end) + end +end ------------------------------------------------------ -- Handle after 'pio run -t compiledb' execution function M.handleDb() diff --git a/lua/platformio/utils/term.lua b/lua/platformio/utils/term.lua index ce278105..3d652f3c 100644 --- a/lua/platformio/utils/term.lua +++ b/lua/platformio/utils/term.lua @@ -313,11 +313,12 @@ function M.ToggleTerminal(command, direction) prev.term:close() end terminal:toggle() - vim.defer_fn(function() - if command and command ~= '' then - send(terminal, command) - end - end, 50) -- 50ms delay, adjust as needed sgget + -- vim.defer_fn(function() + -- if command and command ~= '' then + -- send(terminal, command) + -- end + -- end, 50) -- 50ms delay, adjust as needed sgget + return terminal end return M diff --git a/pio.lua b/pio.lua new file mode 100644 index 00000000..b38a4068 --- /dev/null +++ b/pio.lua @@ -0,0 +1,346 @@ +local M = {} + +M.selected_framework = '' + +local misc = require('platformio.utils.misc') +local lsp_restart = require('platformio.lsp.tools').lsp_restart + +------------------------------------------------------ +-- stylua: ignore +function M.compile_commandsFix() + local filename = vim.uv.cwd() .. '/compile_commands.json' + if vim.fn.filereadable(filename) == 0 then return end + + -- Atomic read using built-in Vim function + local content = table.concat(vim.fn.readfile(filename), "\n") + local ok, data = pcall(vim.json.decode, content) + if not ok or type(data) ~= 'table' then return end + + -- 1. Build Path Map (Scan toolchain) + local path_map = {} + local toolchain_bin = (_G.metadata and _G.metadata.toolchain or "") .. '/bin/*' + for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do + local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') + path_map[name] = full_path + end + + -- 2. Update Entries efficiently with string matching + local modified = false + for _, entry in ipairs(data) do + local cmd = entry.command or "" + local first_token = cmd:match("^%S+") -- Grab only the compiler driver + + -- Fix if it's a relative path (doesn't start with / or Drive letter) + if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then + local short_name = first_token:gsub('%.exe$', '') + if path_map[short_name] then + -- Replace only the first token to preserve arguments + entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) + modified = true + end + end + end + + -- 3. Save with Python formatting + if modified then + local json_str = vim.json.encode(data) + local formatted = vim.fn.system('python -m json.tool', json_str) + + if vim.v.shell_error == 0 then + -- Atomic write back to disk + vim.fn.writefile(vim.split(formatted, "\n"), filename) + vim.notify('compiledb: paths fixed', vim.log.levels.INFO) + else + vim.notify('PIO Fix: Python formatting failed', vim.log.levels.ERROR) + end + end +end + +-- function M.compile_commandsFix() +-- local filename = vim.uv.cwd() .. '/compile_commands.json' +-- local content = vim.fn.readfile(filename) +-- if #content == 0 then return end +-- +-- local ok, data = pcall(vim.json.decode, table.concat(content, "\n")) +-- if not ok or type(data) ~= 'table' then return end +-- +-- -- 1. Build Path Map (Scan toolchain) +-- local path_map = {} +-- +-- local pio_binaries = _G.metadata.query_driver or "/bin/*" +-- -- local pio_binaries = (_G.metadata.toolchain or "") .. '/bin/*' +-- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do +-- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') +-- path_map[name] = full_path +-- end +-- +-- -- 2. Update Entries +-- local modified = false +-- for _, entry in ipairs(data) do +-- local cmd = entry.command or "" +-- local first_token = cmd:match("^%S+") -- Get first word before space +-- +-- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then +-- local short_name = first_token:gsub('%.exe$', '') +-- if path_map[short_name] then +-- -- Swap first token with full path safely +-- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) +-- modified = true +-- end +-- end +-- end +-- +-- -- 3. Save with Formatting +-- if modified then +-- local json_str = vim.json.encode(data) +-- -- Use python to format, then write file +-- local formatted = vim.fn.system('python -m json.tool', json_str) +-- if vim.v.shell_error == 0 then +-- vim.fn.writefile(vim.split(formatted, "\n"), filename) +-- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) +-- end +-- end +-- end + +-- function M.compile_commandsFix() +-- local filename = vim.uv.cwd() .. '/compile_commands.json' +-- local file = io.open(filename, 'r') +-- if not file then return end +-- +-- -- read compile_commands.json file to content +-- local content = file:read('*a') +-- file:close() +-- if not content or content == '' then return end +-- +-- -- JSON decoding content to data +-- local ok, data = pcall(vim.json.decode, content) +-- if not ok or type(data) ~= 'table' then +-- vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) +-- return +-- end +-- +-- -- print('PioFix0') +-- -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path +-- local path_map = {} +-- local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') +-- if pio_home then +-- -- Recursively find all binaries in PIO packages +-- local pio_packages = _G.metadata.toolchain .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' +-- local found_binaries = vim.fn.glob(pio_packages, false, true) +-- +-- for _, full_path in ipairs(found_binaries) do +-- -- Extract filename (e.g., riscv32-esp-elf-gcc) +-- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') +-- path_map[name] = full_path +-- -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) +-- end +-- end +-- +-- -- PHASE 2: Update JSON using the Map +-- local modified = 0 +-- for _, entry in ipairs(data) do +-- if type(entry.command) == 'string' then +-- local cmd_parts = vim.split(entry.command, ' ') +-- local first_token = cmd_parts[1] +-- if first_token then +-- -- Check if it's already a short name (not an absolute path) +-- local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') +-- if not is_abs then +-- local short_name = first_token:gsub('%.exe$', '') +-- -- print('PioFix2: short_name=' .. short_name) +-- -- Direct Query: Does this name exist in our discovered list? +-- if path_map[short_name] then +-- cmd_parts[1] = path_map[short_name] +-- -- print('PioFix3: full_name=' .. cmd_parts[1]) +-- entry.command = table.concat(cmd_parts, ' ') +-- modified = modified + 1 +-- end +-- end +-- end +-- end +-- end +-- +-- -- PHASE 3: Save and Refresh +-- -- Safe JSON encoding +-- if modified > 0 then +-- local out_file = io.open(filename, 'w') +-- if out_file then +-- local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) +-- if encode_ok and json_str then +-- -- 1. Format the string using python's json.tool +-- -- The second argument to vim.fn.system() is the "stdin" passed to the command +-- local formatted_json = vim.fn.system('python -m json.tool', json_str) +-- +-- -- out_file:write(json_str) +-- out_file:write(formatted_json) +-- out_file:close() +-- vim.notify('compiledb: fixed', vim.log.levels.INFO) +-- -- lsp_restart('clangd') +-- end +-- end +-- end +-- end + +------------------------------------------------------ +-- INFO: ToggleTerminal commands sequencer + +M.is_processing = false +M.queue = {} +local pio_buffer = '' -- Persistent stream buffer + +------------------------------------------------------ +-- INFO: ToggleTerminal commands stdout filter +-- stylua: ignore +function M.stdoutFilter(_, _, data) + if #M.queue == 0 then return end + + -- 1. attach partial buffer from previous data last line to 1st line + pio_buffer = pio_buffer .. data[1] + -- 2. If the chunk has more than one element, we've encountered newlines + if #data > 1 then + -- 3. Process any "middle" lines which are guaranteed to be complete + for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end + + for status in pio_buffer:gmatch('_DONE_:(%a+)') do + if status then + if status == 'PASS' then + pio_buffer = data[#data] + vim.schedule(function() M.process_queue() end) + elseif status == 'FAIL' then + end + -- if status == 'PASS' then + -- -- 4. Store the last element as the new partial buffer for the next call + -- pio_buffer = data[#data] + -- local task = table.remove(M.queue, 1) + -- if task then vim.schedule(task) end + -- elseif status == 'LAST' then + -- _G.metadata.isBusy = false + -- M.queue = {} -- Clear queue on any other status + -- pio_buffer = '' + -- vim.schedule(function() vim.notify('PIO Sequence: Finished', 4) end) + -- elseif status == 'FAIL' then + -- M.queue = {} -- Clear queue on any other status (failure) + -- pio_buffer = '' + -- vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) + -- end + break + end + end + end + if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end +end + +------------------------------------------------------ +-- INFO: ToggleTerminal commands Sequencer +--- stylua: ignore +M.run_sequence = function(tasks) + -- Reset local state for new run + M.queue = {} + pio_buffer = '' + -- local full_cmd = '' + -- + local pass = 'echo _DONE_":"PASS' + local last = 'echo _DONE_":"LAST' + local fail = 'echo _DONE_":"FAIL' + -- + -- for _, task in ipairs(tasks) do + -- table.insert(M.queue, task.cb) + -- local part = string.format('%s && %s', task.cmd, pass) + -- if full_cmd == '' then + -- full_cmd = part + -- else + -- full_cmd = full_cmd .. ' && ' .. part + -- end -- Chain multiple commands + -- end + -- full_cmd = full_cmd .. ' && ' .. last .. ' || ' .. fail + -- local ToggleTerminal = require('platformio.utils.term').ToggleTerminal + -- _G.metadata.isBusy = true + -- ToggleTerminal(full_cmd, 'float') + + for _, task in ipairs(tasks) do + -- Build the wrapped command string + local wrapped_cmd = string.format('%s && %s || %s', task.cmd, pass, fail) + + -- Insert a SINGLE table containing everything needed for this step + table.insert(M.queue, { + cmd = wrapped_cmd, + cb = task.cb, + }) + end + M.process_queue() +end + +------------------------------------------------------------------ +-- 3. Queue Controller +function M.process_queue() + local task = table.remove(M.queue, 1) + + if not task then + M.is_processing = false + if M.current_cb then + M.current_cb() + end -- Final callback + return + end + + M.is_processing = true + + if task.cmd then + M.run_shell_job(task.cmd, task.cb) + elseif type(task.cb) == 'function' then + vim.schedule(function() + task.cb() + -- Lua tasks need to manually move the queue + M.process_queue() + end) + end +end + +-- 4. Entry Point +function M.setup_project(board, framework) + M.queue = { + { cmd = 'pio project init --board ' .. board }, + { cmd = 'pio run -t compiledb' }, + { cb = M.compile_commandsFix }, + } + M.process_queue() +end +------------------------------------------------------ +-- Handle after 'pio run -t compiledb' execution +function M.handleDb() + vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) + misc.gitignore_lsp_configs('compile_commands.json') + local pio_manager = require('platformio.pio_setup').pio_manager + pio_manager.refresh(function() + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + boilerplate_gen([[.clangd]], _G.metadata.core_dir) + M.compile_commandsFix() + lsp_restart('clangd') + end) +end + +------------------------------------------------------ +-- Handle after poioinit execution +--- stylua: ignore +function M.handlePioinit() + -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + -- vim.schedule(function() + -- local pio_manager = require('platformio.pio_setup').pio_manager + -- pio_manager.refresh(function() + -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + -- boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + vim.notify('Pioinit: Success', vim.log.levels.INFO) + -- end) + -- end) +end +-- Handle after poioinit execution +-- stylua: ignore +function M.handlePiolib() + vim.notify('Piolib: Success', vim.log.levels.INFO) +end +-- INFO: end commands sequencer +------------------------------------------------------ + +return M diff --git a/lua/platformio/utils/pio2.lua b/pio2.lua similarity index 100% rename from lua/platformio/utils/pio2.lua rename to pio2.lua diff --git a/term.lua b/term.lua new file mode 100644 index 00000000..ce278105 --- /dev/null +++ b/term.lua @@ -0,0 +1,324 @@ +local M = {} + +local is_windows = jit.os == 'Windows' +M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' +-- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' +-- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' + +local config = require('platformio').config +local pio = require('platformio.utils.pio') + +------------------------------------------------------ +function M.strsplit(inputstr, del) + local t = {} + if type(inputstr) == 'string' and inputstr and inputstr ~= '' then + for str in string.gmatch(inputstr, '([^' .. del .. ']+)') do + table.insert(t, str) + end + end + return t +end + +function M.check_prefix(str, prefix) + return str:sub(1, #prefix) == prefix +end + +------------------------------------------------------ + +-- INFO: get current OS enter +function M.enter() + local shell = vim.o.shell + if is_windows then + return vim.fn.executable('pwsh') and '\r' or '\r\n' + elseif shell:find('nu') then + return '\r' + else + return '\n' + end +end + +-- INFO: get previous window +local function getPreviousWindow(orig_window) + local prev = { + orig_window = orig_window, + term = nil, --active terminal + cli = nil, --cli terminal + mon = nil, --mon terminal + float = false, --is active terminal direction float + } + local terms = require('toggleterm.terminal').get_all(true) + if #terms ~= 0 then + for i = 1, #terms do + if terms[i].display_name and terms[i].display_name ~= '' and terms[i].display_name:find('pio', 1) then + local name_splt = M.strsplit(terms[i].display_name, ':') + if name_splt[1] == 'piocli' then + prev.cli = terms[i] + if terms[i].window == orig_window then + ---@diagnostic disable-next-line: cast-local-type + prev.orig_window = tonumber(name_splt[2]) -- set orig_window to the previous terminal onrig_window + prev.term = terms[i] + end + if terms[i].direction == 'float' then + prev.float = true + end + elseif name_splt[1] == 'piomon' then + prev.mon = terms[i] + if terms[i].window == orig_window then + ---@diagnostic disable-next-line: cast-local-type + prev.orig_window = tonumber(name_splt[2]) -- set orig_window to the previous terminal onrig_window + prev.term = terms[i] + end + if terms[i].direction == 'float' then + prev.float = true + end + end + end + end + end + return prev +end + +------------------------------------------------------ +-- INFO: Send command +local function send(term, cmd) + vim.fn.chansend(term.job_id, cmd .. M.enter()) + if vim.api.nvim_buf_is_loaded(term.bufnr) and vim.api.nvim_buf_is_valid(term.bufnr) then + if term.window and vim.api.nvim_win_is_valid(term.window) then --vim.ui.term_has_open_win(term) then + vim.api.nvim_set_current_win(term.window) -- terminal focus + vim.api.nvim_buf_call(term.bufnr, function() + local mode = vim.api.nvim_get_mode().mode + if mode == 'n' or mode == 'nt' then + vim.cmd('normal! G') -- normal command to Goto bottom of buffer (scroll) + end + end) + end + end +end + +------------------------------------------------------ +-- INFO: PioTermClose +local function PioTermClose(t) + local orig_window = tonumber(M.strsplit(t.display_name, ':')[2]) + -- close terminal window + vim.api.nvim_win_close(t.window, true) + + -- go back to previous window + if orig_window and vim.api.nvim_win_is_valid(orig_window) then + vim.api.nvim_set_current_win(orig_window) + else + vim.api.nvim_set_current_win(0) + end +end + +------------------------------------------------------ +-- INFO: ToggleTerminal +function M.ToggleTerminal(command, direction) + local status_ok, _ = pcall(require, 'toggleterm') + if not status_ok then + vim.api.nvim_echo({ { 'toggleterm not found!', 'ErrorMsg' } }, true, {}) + return + end + + local title = '' + local pioOpts = {} + + -- INFO: set orig_window to current window, or if available get current toggleterm previous window + local prev = getPreviousWindow(vim.api.nvim_get_current_win()) + local orig_window = prev.orig_window + + if string.find(command, ' monitor') then + if prev.mon then -- INFO: if previous monitor terminal already opened ==> reopen + prev.mon.display_name = 'piomon:' .. orig_window + local win_type = vim.fn.win_gettype(prev.mon.window) + local win_open = win_type == '' or win_type == 'popup' + if prev.mon.window and (win_open and vim.api.nvim_win_get_buf(prev.mon.window) == prev.mon.bufnr) then + vim.api.nvim_set_current_win(prev.mon.window) + else + prev.mon:open() + end + return + end + title = 'Pio Monitor: [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' + pioOpts.display_name = 'piomon:' .. orig_window + pioOpts.id = 98 + pioOpts.on_stdout = nil + else -- INFO: if previous cli terminal already opened ==> reopen + if prev.cli then + prev.cli.display_name = 'piocli:' .. orig_window + local win_type = vim.fn.win_gettype(prev.cli.window) + local win_open = win_type == '' or win_type == 'popup' + if prev.cli.window and (win_open and vim.api.nvim_win_get_buf(prev.cli.window) == prev.cli.bufnr) then + vim.api.nvim_set_current_win(prev.cli.window) + else + prev.cli:open() + end + vim.defer_fn(function() + if command and command ~= '' then + send(prev.cli, command) + end + end, 50) -- 50ms delay, adjust as needed + return + end + title = 'Pio CLI> [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' + pioOpts.display_name = 'piocli:' .. orig_window + pioOpts.id = 99 + + -- INFO: on_stdout + -- on_stdout = stdout_callback, + pioOpts.on_stdout = pio.stdoutFilter + end + pioOpts.direction = direction + ------------------------------------------------------ + + -- INFO: termConfig table start + local termConfig = { + hidden = true, -- Start hidden, we'll open it explicitly + hide_numbers = true, + float_opts = { + winblend = 0, + width = function() + return math.ceil(vim.o.columns * 0.85) + end, + height = function() + return math.ceil(vim.o.lines * 0.85) + end, + -- shell = vim.o.shell, + shell = vim.o.shell, + highlights = { + border = 'FloatBorder', + background = 'NormalFloat', + }, + }, + close_on_exit = false, --closeOnexit, + + -- INFO: on_open() + on_open = function(t) + -- Get properties of the 'Normal' highlight group (background of main editor) + -- local hl = vim.api.nvim_get_hl(0, { name = 'PmenuSel' }) + -- local hl = { bg = '#e4cf0e', fg = '#0012d9' } + local hl = { bg = '#80a3d4', fg = '#000000' } + + if hl then + vim.api.nvim_set_hl(0, 'MyWinBar', { bg = hl.bg, fg = hl.fg }) + + local winBartitle = '%#MyWinBar#' .. title .. '%*' + vim.api.nvim_set_option_value('winbar', winBartitle, { scope = 'local', win = t.window }) + + -- Following necessary to solve that some time winbar not showing + vim.schedule(function() + vim.api.nvim_set_option_value('winbar', winBartitle, { scope = 'local', win = t.window }) + end) + end + vim.keymap.set('t', '', [[k]], { buffer = t.bufnr }) + vim.keymap.set('n', '', [[a]], { buffer = t.bufnr }) + + vim.keymap.set('n', 'q', function() + PioTermClose(t) + end, { desc = 'PioTermClose', buffer = t.bufnr }) + + if config.debug then + local name_splt = M.strsplit(t.display_name, ':') + vim.api.nvim_echo({ + { 'ToggleTerm ', 'MoreMsg' }, + { '(Term name: ' .. name_splt[1] .. ')', 'MoreMsg' }, + { '(Prev win ID: ' .. name_splt[2] .. ')', 'MoreMsg' }, + { '(Term Win ID: ' .. t.window .. ')', 'MoreMsg' }, + { '(Term Buffer#: ' .. t.bufnr .. ')', 'MoreMsg' }, + { '(Term id: ' .. t.id .. ')', 'MoreMsg' }, + { '(Job ID: ' .. t.job_id .. ')', 'MoreMsg' }, + }, true, {}) + end + end, + + -- INFO: on_close() + on_close = function(t) + orig_window = tonumber(M.strsplit(t.display_name, ':')[2]) + ---@diagnostic disable-next-line: param-type-mismatch + if orig_window and vim.api.nvim_win_is_valid(orig_window) then + vim.api.nvim_set_current_win(orig_window) + else + vim.api.nvim_set_current_win(0) + end + end, + + -- -- INFO: on_exit() + -- on_exit = function(_) + -- exit_callback() + -- end, + + -- INFO: on_stdout + -- on_stdout = stdout_callback, + -- on_stdout = pio.stdoutFilter, + + -- INFO: on_create() { + on_create = function(t) + local platformio = vim.api.nvim_create_augroup(M.strsplit(t.display_name, ':')[1], { clear = true }) + + -- INFO: CmdlineLeave + vim.api.nvim_create_autocmd('CmdlineLeave', { + group = platformio, + -- pattern = ':', + buffer = t.bufnr, + callback = function() + if vim.v.event and not vim.v.event.abort and vim.v.event.cmdtype == ':' then + local quit = vim.fn.getcmdline() == 'q' + local quitbang = vim.fn.getcmdline() == 'q!' + if quitbang or quit then + local name_splt = M.strsplit(t.display_name, ':') + if quitbang then + if name_splt[1] == 'piomon' then -- monitor terminal + local exit = vim.api.nvim_replace_termcodes('exit', true, true, true) + send(t, exit) + else -- cli terminal + send(t, 'exit') + end + end + + orig_window = tonumber(name_splt[2]) + vim.schedule(function() + -- go back to previous window + if orig_window and vim.api.nvim_win_is_valid(orig_window) then + vim.api.nvim_set_current_win(orig_window) + else + vim.api.nvim_set_current_win(0) + end + end) + end + end + end, + }) + + -- INFO: BufUnload + vim.api.nvim_create_autocmd('BufUnload', { + group = platformio, + desc = 'toggleterm buffer unloaded', + buffer = t.bufnr, + callback = function(args) + vim.keymap.del('t', '', { buffer = args.buf }) + vim.keymap.del('n', '', { buffer = args.buf }) + + -- clear autommmand when quit + vim.api.nvim_clear_autocmds({ group = M.strsplit(t.display_name, ':')[1] }) + end, + }) + end, + } + -- INFO: termConfig table end + + termConfig = vim.tbl_deep_extend('force', termConfig, pioOpts or {}) + + -- INFO: create new terminal + local terminal = require('toggleterm.terminal').Terminal:new(termConfig) + if prev.term and prev.float then + prev.term:close() + end + terminal:toggle() + vim.defer_fn(function() + if command and command ~= '' then + send(terminal, command) + end + end, 50) -- 50ms delay, adjust as needed sgget +end + +return M +---------------------------------------------------------------------------------------- diff --git a/lua/platformio/utils/term2.lua b/term2.lua similarity index 100% rename from lua/platformio/utils/term2.lua rename to term2.lua From ead6da91fa881c77cc4553298ae8234c36031db4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 20:22:10 +0300 Subject: [PATCH 0765/1406] update --- lua/platformio/utils/pio.lua | 9 +++++---- lua/platformio/utils/term.lua | 8 ++++---- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index d8e277c7..bce3bce5 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -5,9 +5,6 @@ M.selected_framework = '' local misc = require('platformio.utils.misc') local lsp_restart = require('platformio.lsp.tools').lsp_restart -local ToggleTerminal = require('platformio.utils.term').ToggleTerminal --- _G.metadata.isBusy = true -local pio_terminal = ToggleTerminal('', 'float') M.is_processing = false ------------------------------------------------------ -- stylua: ignore @@ -207,9 +204,9 @@ function M.stdoutFilter(_, _, data) for status in pio_buffer:gmatch('_DONE_:(%a+)') do if status then if status == 'PASS' then - M.process_queue() -- 4. Store the last element as the new partial buffer for the next call pio_buffer = data[#data] + M.process_queue() -- local task = table.remove(M.queue, 1) -- if task then vim.schedule(task) end -- elseif status == 'LAST' then @@ -229,6 +226,10 @@ function M.stdoutFilter(_, _, data) if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end end +local ToggleTerminal = require('platformio.utils.term') +-- _G.metadata.isBusy = true +ToggleTerminal.stdoutFilter = M.stdoutFilter +local pio_terminal = ToggleTerminal.ToggleTerminal('', 'float') ------------------------------------------------------ -- INFO: ToggleTerminal commands Sequencer --- stylua: ignore diff --git a/lua/platformio/utils/term.lua b/lua/platformio/utils/term.lua index 3d652f3c..dd1cd62c 100644 --- a/lua/platformio/utils/term.lua +++ b/lua/platformio/utils/term.lua @@ -6,8 +6,8 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' local config = require('platformio').config -local pio = require('platformio.utils.pio') - +-- local pio = require('platformio.utils.pio') +M.stdoutFilter = nil ------------------------------------------------------ function M.strsplit(inputstr, del) local t = {} @@ -141,7 +141,7 @@ function M.ToggleTerminal(command, direction) title = 'Pio Monitor: [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' pioOpts.display_name = 'piomon:' .. orig_window pioOpts.id = 98 - pioOpts.on_stdout = nil + pioOpts.on_stdout = M.stdoutFilter else -- INFO: if previous cli terminal already opened ==> reopen if prev.cli then prev.cli.display_name = 'piocli:' .. orig_window @@ -165,7 +165,7 @@ function M.ToggleTerminal(command, direction) -- INFO: on_stdout -- on_stdout = stdout_callback, - pioOpts.on_stdout = pio.stdoutFilter + pioOpts.on_stdout = M.stdoutFilter end pioOpts.direction = direction ------------------------------------------------------ From 011e6bf599b1adc20f0aa26f6a364a16e7d96ddf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 20:24:11 +0300 Subject: [PATCH 0766/1406] update --- lua/platformio/utils/pio.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index bce3bce5..8ef439a4 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -4,6 +4,8 @@ M.selected_framework = '' local misc = require('platformio.utils.misc') local lsp_restart = require('platformio.lsp.tools').lsp_restart +local ToggleTerminal = require('platformio.utils.term') +ToggleTerminal.stdoutFilter = nil M.is_processing = false ------------------------------------------------------ @@ -226,7 +228,6 @@ function M.stdoutFilter(_, _, data) if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end end -local ToggleTerminal = require('platformio.utils.term') -- _G.metadata.isBusy = true ToggleTerminal.stdoutFilter = M.stdoutFilter local pio_terminal = ToggleTerminal.ToggleTerminal('', 'float') From a1bdbc3517a4fd1539096908d83dbbd994aeed9d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 20:27:50 +0300 Subject: [PATCH 0767/1406] update --- lua/platformio/utils/term.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/lua/platformio/utils/term.lua b/lua/platformio/utils/term.lua index dd1cd62c..ecd0ba57 100644 --- a/lua/platformio/utils/term.lua +++ b/lua/platformio/utils/term.lua @@ -6,7 +6,6 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' local config = require('platformio').config --- local pio = require('platformio.utils.pio') M.stdoutFilter = nil ------------------------------------------------------ function M.strsplit(inputstr, del) From 3ba23031472254d3c309ce01c09d67a86843ea1f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 19 Apr 2026 20:46:39 +0300 Subject: [PATCH 0768/1406] update --- lua/platformio/utils/pio.lua | 4 ++-- lua/platformio/utils/term.lua | 12 +++++++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 8ef439a4..0a45e210 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -5,7 +5,7 @@ M.selected_framework = '' local misc = require('platformio.utils.misc') local lsp_restart = require('platformio.lsp.tools').lsp_restart local ToggleTerminal = require('platformio.utils.term') -ToggleTerminal.stdoutFilter = nil +ToggleTerminal.on_stdout_handler = nil M.is_processing = false ------------------------------------------------------ @@ -229,7 +229,7 @@ function M.stdoutFilter(_, _, data) end -- _G.metadata.isBusy = true -ToggleTerminal.stdoutFilter = M.stdoutFilter +ToggleTerminal.on_stdout_handler = M.stdoutFilter local pio_terminal = ToggleTerminal.ToggleTerminal('', 'float') ------------------------------------------------------ -- INFO: ToggleTerminal commands Sequencer diff --git a/lua/platformio/utils/term.lua b/lua/platformio/utils/term.lua index ecd0ba57..a1d88de8 100644 --- a/lua/platformio/utils/term.lua +++ b/lua/platformio/utils/term.lua @@ -6,7 +6,8 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' local config = require('platformio').config -M.stdoutFilter = nil +M.on_stdout_handler = nil + ------------------------------------------------------ function M.strsplit(inputstr, del) local t = {} @@ -140,7 +141,7 @@ function M.ToggleTerminal(command, direction) title = 'Pio Monitor: [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' pioOpts.display_name = 'piomon:' .. orig_window pioOpts.id = 98 - pioOpts.on_stdout = M.stdoutFilter + pioOpts.on_stdout = nil else -- INFO: if previous cli terminal already opened ==> reopen if prev.cli then prev.cli.display_name = 'piocli:' .. orig_window @@ -164,7 +165,12 @@ function M.ToggleTerminal(command, direction) -- INFO: on_stdout -- on_stdout = stdout_callback, - pioOpts.on_stdout = M.stdoutFilter + pioOpts.on_stdout = function(t, job, data) + -- Only run if pio.lua has successfully "plugged in" the handler + if M.on_stdout_handler then + M.on_stdout_handler(t, job, data) + end + end end pioOpts.direction = direction ------------------------------------------------------ From 531912c9e98a6ddfdcc834eb75dd1e0e865da19d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 05:49:39 +0300 Subject: [PATCH 0769/1406] update --- lua/platformio/utils/pio.lua | 12 ++++++------ lua/platformio/utils/term.lua | 3 +-- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 0a45e210..9c3f82b8 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -4,8 +4,8 @@ M.selected_framework = '' local misc = require('platformio.utils.misc') local lsp_restart = require('platformio.lsp.tools').lsp_restart -local ToggleTerminal = require('platformio.utils.term') -ToggleTerminal.on_stdout_handler = nil +local term = require('platformio.utils.term') +term.on_stdout_handler = nil M.is_processing = false ------------------------------------------------------ @@ -229,8 +229,8 @@ function M.stdoutFilter(_, _, data) end -- _G.metadata.isBusy = true -ToggleTerminal.on_stdout_handler = M.stdoutFilter -local pio_terminal = ToggleTerminal.ToggleTerminal('', 'float') +term.on_stdout_handler = M.stdoutFilter +local pio_terminal = term.ToggleTerminal('', 'float') ------------------------------------------------------ -- INFO: ToggleTerminal commands Sequencer --- stylua: ignore @@ -263,9 +263,9 @@ M.run_sequence = function(tasks) -- end -- Chain multiple commands -- end -- full_cmd = full_cmd .. ' && ' .. last .. ' || ' .. failure - -- local ToggleTerminal = require('platformio.utils.term').ToggleTerminal + -- local term = require('platformio.utils.term').ToggleTerminal -- _G.metadata.isBusy = true - -- ToggleTerminal(full_cmd, 'float') + -- term(full_cmd, 'float') end -- 2. Shell Runner: Sends text to the live shell diff --git a/lua/platformio/utils/term.lua b/lua/platformio/utils/term.lua index a1d88de8..76d607c1 100644 --- a/lua/platformio/utils/term.lua +++ b/lua/platformio/utils/term.lua @@ -141,7 +141,7 @@ function M.ToggleTerminal(command, direction) title = 'Pio Monitor: [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' pioOpts.display_name = 'piomon:' .. orig_window pioOpts.id = 98 - pioOpts.on_stdout = nil + pioOpts.on_stdout = nil -- INFO: on_stdout else -- INFO: if previous cli terminal already opened ==> reopen if prev.cli then prev.cli.display_name = 'piocli:' .. orig_window @@ -164,7 +164,6 @@ function M.ToggleTerminal(command, direction) pioOpts.id = 99 -- INFO: on_stdout - -- on_stdout = stdout_callback, pioOpts.on_stdout = function(t, job, data) -- Only run if pio.lua has successfully "plugged in" the handler if M.on_stdout_handler then From 97fc0b9c5ee5b40d13899bc13c92c1029618dc2e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 06:08:00 +0300 Subject: [PATCH 0770/1406] update --- lua/platformio/utils/pio.lua | 3 ++- lua/platformio/utils/term.lua | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 9c3f82b8..45cbf30b 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -4,8 +4,9 @@ M.selected_framework = '' local misc = require('platformio.utils.misc') local lsp_restart = require('platformio.lsp.tools').lsp_restart + local term = require('platformio.utils.term') -term.on_stdout_handler = nil +-- term.on_stdout_handler = nil M.is_processing = false ------------------------------------------------------ diff --git a/lua/platformio/utils/term.lua b/lua/platformio/utils/term.lua index 76d607c1..4dd7e8e4 100644 --- a/lua/platformio/utils/term.lua +++ b/lua/platformio/utils/term.lua @@ -6,6 +6,7 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' local config = require('platformio').config + M.on_stdout_handler = nil ------------------------------------------------------ From 0c51f2f13387e5bb582a1e292141982dae7f0fb4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 06:26:27 +0300 Subject: [PATCH 0771/1406] update --- lua/platformio/utils/pio.lua | 152 +++++++------- lua/platformio/utils/pio2.lua | 356 +++++++++++++++++++++++++++++++++ lua/platformio/utils/term.lua | 24 +-- lua/platformio/utils/term2.lua | 330 ++++++++++++++++++++++++++++++ 4 files changed, 768 insertions(+), 94 deletions(-) create mode 100644 lua/platformio/utils/pio2.lua create mode 100644 lua/platformio/utils/term2.lua diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 45cbf30b..7a4dd01d 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -5,10 +5,6 @@ M.selected_framework = '' local misc = require('platformio.utils.misc') local lsp_restart = require('platformio.lsp.tools').lsp_restart -local term = require('platformio.utils.term') --- term.on_stdout_handler = nil - -M.is_processing = false ------------------------------------------------------ -- stylua: ignore function M.compile_commandsFix() @@ -188,6 +184,7 @@ end ------------------------------------------------------ -- INFO: ToggleTerminal commands sequencer +M.is_processing = false M.queue = {} local pio_buffer = '' -- Persistent stream buffer @@ -206,17 +203,21 @@ function M.stdoutFilter(_, _, data) for status in pio_buffer:gmatch('_DONE_:(%a+)') do if status then + -- if status == 'PASS' then + -- pio_buffer = data[#data] + -- vim.schedule(function() M.process_queue() end) + -- elseif status == 'FAIL' then + -- end if status == 'PASS' then -- 4. Store the last element as the new partial buffer for the next call pio_buffer = data[#data] - M.process_queue() - -- local task = table.remove(M.queue, 1) - -- if task then vim.schedule(task) end - -- elseif status == 'LAST' then - -- _G.metadata.isBusy = false - -- M.queue = {} -- Clear queue on any other status - -- pio_buffer = '' - -- vim.schedule(function() vim.notify('PIO Sequence: Finished', 4) end) + local task = table.remove(M.queue, 1) + if task then vim.schedule(task) end + elseif status == 'LAST' then + _G.metadata.isBusy = false + M.queue = {} -- Clear queue on any other status + pio_buffer = '' + vim.schedule(function() vim.notify('PIO Sequence: Finished', 4) end) elseif status == 'FAIL' then M.queue = {} -- Clear queue on any other status (failure) pio_buffer = '' @@ -229,9 +230,6 @@ function M.stdoutFilter(_, _, data) if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end end --- _G.metadata.isBusy = true -term.on_stdout_handler = M.stdoutFilter -local pio_terminal = term.ToggleTerminal('', 'float') ------------------------------------------------------ -- INFO: ToggleTerminal commands Sequencer --- stylua: ignore @@ -240,80 +238,76 @@ M.run_sequence = function(tasks) M.queue = {} pio_buffer = '' local full_cmd = '' - + -- local pass = 'echo _DONE_":"PASS' - -- local last = 'echo _DONE_":"LAST' + local last = 'echo _DONE_":"LAST' local fail = 'echo _DONE_":"FAIL' - - for _, row in ipairs(tasks) do - -- Build the wrapped command string - local wrapped_cmd = string.format('%s && %s || %s', row.cmd, pass, fail) - table.insert(M.queue, { - cmd = wrapped_cmd, - cb = row.cb, - }) + -- + for _, task in ipairs(tasks) do + table.insert(M.queue, task.cb) + local part = string.format('%s && %s', task.cmd, pass) + if full_cmd == '' then + full_cmd = part + else + full_cmd = full_cmd .. ' && ' .. part + end -- Chain multiple commands end + full_cmd = full_cmd .. ' && ' .. last .. ' || ' .. fail + local ToggleTerminal = require('platformio.utils.term').ToggleTerminal + _G.metadata.isBusy = true + ToggleTerminal(full_cmd, 'float') - -- for _, task in ipairs(tasks) do - -- table.insert(M.queue, task.cb) - -- local part = string.format('%s && %s', task.cmd, pass) - -- if full_cmd == '' then - -- full_cmd = part + -- for _, task in ipairs(M.tasks) do + -- if task.cmd then + -- -- It's a shell task: wrap it with the pass/fail sentinels + -- local wrapped_cmd = string.format('%s && %s || %s', task.cmd, pass, fail) + -- + -- table.insert(M.queue, { + -- cmd = wrapped_cmd, + -- cb = task.cb, + -- }) -- else - -- full_cmd = full_cmd .. ' && ' .. part - -- end -- Chain multiple commands + -- -- It's a Lua-only task: pass it through exactly as it is + -- table.insert(M.queue, task) + -- end -- end - -- full_cmd = full_cmd .. ' && ' .. last .. ' || ' .. failure - -- local term = require('platformio.utils.term').ToggleTerminal - -- _G.metadata.isBusy = true - -- term(full_cmd, 'float') + -- M.process_queue() end --- 2. Shell Runner: Sends text to the live shell -function M.run_shell_job(cmd, on_exit_callback) - -- Ensure terminal is open and process is alive - if not pio_terminal then - return - end - if not pio_terminal:is_open() then - pio_terminal:open() - end - - -- Wrap the command: - -- 1. Run the actual command - -- 2. Run the callback logic (optional) - -- 3. Print the sentinel so the Lua listener knows we're done - -- local full_cmd = string.format('%s && echo %s', cmd, sentinel) - - -- Store callback for the listener if needed - M.current_cb = on_exit_callback - - -- Send the text + Enter key - pio_terminal:send(cmd) -end +------------------------------------------------------------------ -- 3. Queue Controller -function M.process_queue() - local task = table.remove(M.queue, 1) - - if not task then - M.is_processing = false - if M.current_cb then - M.current_cb() - end -- Final callback - return - end - - M.is_processing = true +-- function M.process_queue() +-- local task = table.remove(M.queue, 1) +-- +-- if not task then +-- M.is_processing = false +-- if M.current_cb then +-- M.current_cb() +-- end -- Final callback +-- return +-- end +-- +-- M.is_processing = true +-- +-- if task.cmd then +-- M.run_shell_job(task.cmd, task.cb) +-- elseif type(task.cb) == 'function' then +-- vim.schedule(function() +-- task.cb() +-- -- Lua tasks need to manually move the queue +-- M.process_queue() +-- end) +-- end +-- end - if task.cmd then - M.run_shell_job(task.cmd, task.cb) - elseif type(task.cb) == 'function' then - vim.schedule(function() - task.cb() - -- Lua tasks need to manually move the queue - M.process_queue() - end) - end +-- 4. Entry Point +function M.setup_project(board, framework) + M.queue = { + { cmd = 'pio project init --board ' .. board }, + { cmd = 'pio run -t compiledb' }, + { cb = M.compile_commandsFix }, + } + M.process_queue() end ------------------------------------------------------ -- Handle after 'pio run -t compiledb' execution diff --git a/lua/platformio/utils/pio2.lua b/lua/platformio/utils/pio2.lua new file mode 100644 index 00000000..45cbf30b --- /dev/null +++ b/lua/platformio/utils/pio2.lua @@ -0,0 +1,356 @@ +local M = {} + +M.selected_framework = '' + +local misc = require('platformio.utils.misc') +local lsp_restart = require('platformio.lsp.tools').lsp_restart + +local term = require('platformio.utils.term') +-- term.on_stdout_handler = nil + +M.is_processing = false +------------------------------------------------------ +-- stylua: ignore +function M.compile_commandsFix() + local filename = vim.uv.cwd() .. '/compile_commands.json' + if vim.fn.filereadable(filename) == 0 then return end + + -- Atomic read using built-in Vim function + local content = table.concat(vim.fn.readfile(filename), "\n") + local ok, data = pcall(vim.json.decode, content) + if not ok or type(data) ~= 'table' then return end + + -- 1. Build Path Map (Scan toolchain) + local path_map = {} + local toolchain_bin = (_G.metadata and _G.metadata.toolchain or "") .. '/bin/*' + for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do + local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') + path_map[name] = full_path + end + + -- 2. Update Entries efficiently with string matching + local modified = false + for _, entry in ipairs(data) do + local cmd = entry.command or "" + local first_token = cmd:match("^%S+") -- Grab only the compiler driver + + -- Fix if it's a relative path (doesn't start with / or Drive letter) + if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then + local short_name = first_token:gsub('%.exe$', '') + if path_map[short_name] then + -- Replace only the first token to preserve arguments + entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) + modified = true + end + end + end + + -- 3. Save with Python formatting + if modified then + local json_str = vim.json.encode(data) + local formatted = vim.fn.system('python -m json.tool', json_str) + + if vim.v.shell_error == 0 then + -- Atomic write back to disk + vim.fn.writefile(vim.split(formatted, "\n"), filename) + vim.notify('compiledb: paths fixed', vim.log.levels.INFO) + else + vim.notify('PIO Fix: Python formatting failed', vim.log.levels.ERROR) + end + end +end + +-- function M.compile_commandsFix() +-- local filename = vim.uv.cwd() .. '/compile_commands.json' +-- local content = vim.fn.readfile(filename) +-- if #content == 0 then return end +-- +-- local ok, data = pcall(vim.json.decode, table.concat(content, "\n")) +-- if not ok or type(data) ~= 'table' then return end +-- +-- -- 1. Build Path Map (Scan toolchain) +-- local path_map = {} +-- +-- local pio_binaries = _G.metadata.query_driver or "/bin/*" +-- -- local pio_binaries = (_G.metadata.toolchain or "") .. '/bin/*' +-- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do +-- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') +-- path_map[name] = full_path +-- end +-- +-- -- 2. Update Entries +-- local modified = false +-- for _, entry in ipairs(data) do +-- local cmd = entry.command or "" +-- local first_token = cmd:match("^%S+") -- Get first word before space +-- +-- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then +-- local short_name = first_token:gsub('%.exe$', '') +-- if path_map[short_name] then +-- -- Swap first token with full path safely +-- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) +-- modified = true +-- end +-- end +-- end +-- +-- -- 3. Save with Formatting +-- if modified then +-- local json_str = vim.json.encode(data) +-- -- Use python to format, then write file +-- local formatted = vim.fn.system('python -m json.tool', json_str) +-- if vim.v.shell_error == 0 then +-- vim.fn.writefile(vim.split(formatted, "\n"), filename) +-- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) +-- end +-- end +-- end + +-- function M.compile_commandsFix() +-- local filename = vim.uv.cwd() .. '/compile_commands.json' +-- local file = io.open(filename, 'r') +-- if not file then return end +-- +-- -- read compile_commands.json file to content +-- local content = file:read('*a') +-- file:close() +-- if not content or content == '' then return end +-- +-- -- JSON decoding content to data +-- local ok, data = pcall(vim.json.decode, content) +-- if not ok or type(data) ~= 'table' then +-- vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) +-- return +-- end +-- +-- -- print('PioFix0') +-- -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path +-- local path_map = {} +-- local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') +-- if pio_home then +-- -- Recursively find all binaries in PIO packages +-- local pio_packages = _G.metadata.toolchain .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' +-- local found_binaries = vim.fn.glob(pio_packages, false, true) +-- +-- for _, full_path in ipairs(found_binaries) do +-- -- Extract filename (e.g., riscv32-esp-elf-gcc) +-- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') +-- path_map[name] = full_path +-- -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) +-- end +-- end +-- +-- -- PHASE 2: Update JSON using the Map +-- local modified = 0 +-- for _, entry in ipairs(data) do +-- if type(entry.command) == 'string' then +-- local cmd_parts = vim.split(entry.command, ' ') +-- local first_token = cmd_parts[1] +-- if first_token then +-- -- Check if it's already a short name (not an absolute path) +-- local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') +-- if not is_abs then +-- local short_name = first_token:gsub('%.exe$', '') +-- -- print('PioFix2: short_name=' .. short_name) +-- -- Direct Query: Does this name exist in our discovered list? +-- if path_map[short_name] then +-- cmd_parts[1] = path_map[short_name] +-- -- print('PioFix3: full_name=' .. cmd_parts[1]) +-- entry.command = table.concat(cmd_parts, ' ') +-- modified = modified + 1 +-- end +-- end +-- end +-- end +-- end +-- +-- -- PHASE 3: Save and Refresh +-- -- Safe JSON encoding +-- if modified > 0 then +-- local out_file = io.open(filename, 'w') +-- if out_file then +-- local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) +-- if encode_ok and json_str then +-- -- 1. Format the string using python's json.tool +-- -- The second argument to vim.fn.system() is the "stdin" passed to the command +-- local formatted_json = vim.fn.system('python -m json.tool', json_str) +-- +-- -- out_file:write(json_str) +-- out_file:write(formatted_json) +-- out_file:close() +-- vim.notify('compiledb: fixed', vim.log.levels.INFO) +-- -- lsp_restart('clangd') +-- end +-- end +-- end +-- end + +------------------------------------------------------ +-- INFO: ToggleTerminal commands sequencer + +M.queue = {} +local pio_buffer = '' -- Persistent stream buffer + +------------------------------------------------------ +-- INFO: ToggleTerminal commands stdout filter +-- stylua: ignore +function M.stdoutFilter(_, _, data) + if #M.queue == 0 then return end + + -- 1. attach partial buffer from previous data last line to 1st line + pio_buffer = pio_buffer .. data[1] + -- 2. If the chunk has more than one element, we've encountered newlines + if #data > 1 then + -- 3. Process any "middle" lines which are guaranteed to be complete + for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end + + for status in pio_buffer:gmatch('_DONE_:(%a+)') do + if status then + if status == 'PASS' then + -- 4. Store the last element as the new partial buffer for the next call + pio_buffer = data[#data] + M.process_queue() + -- local task = table.remove(M.queue, 1) + -- if task then vim.schedule(task) end + -- elseif status == 'LAST' then + -- _G.metadata.isBusy = false + -- M.queue = {} -- Clear queue on any other status + -- pio_buffer = '' + -- vim.schedule(function() vim.notify('PIO Sequence: Finished', 4) end) + elseif status == 'FAIL' then + M.queue = {} -- Clear queue on any other status (failure) + pio_buffer = '' + vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) + end + break + end + end + end + if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end +end + +-- _G.metadata.isBusy = true +term.on_stdout_handler = M.stdoutFilter +local pio_terminal = term.ToggleTerminal('', 'float') +------------------------------------------------------ +-- INFO: ToggleTerminal commands Sequencer +--- stylua: ignore +M.run_sequence = function(tasks) + -- Reset local state for new run + M.queue = {} + pio_buffer = '' + local full_cmd = '' + + local pass = 'echo _DONE_":"PASS' + -- local last = 'echo _DONE_":"LAST' + local fail = 'echo _DONE_":"FAIL' + + for _, row in ipairs(tasks) do + -- Build the wrapped command string + local wrapped_cmd = string.format('%s && %s || %s', row.cmd, pass, fail) + table.insert(M.queue, { + cmd = wrapped_cmd, + cb = row.cb, + }) + end + + -- for _, task in ipairs(tasks) do + -- table.insert(M.queue, task.cb) + -- local part = string.format('%s && %s', task.cmd, pass) + -- if full_cmd == '' then + -- full_cmd = part + -- else + -- full_cmd = full_cmd .. ' && ' .. part + -- end -- Chain multiple commands + -- end + -- full_cmd = full_cmd .. ' && ' .. last .. ' || ' .. failure + -- local term = require('platformio.utils.term').ToggleTerminal + -- _G.metadata.isBusy = true + -- term(full_cmd, 'float') +end + +-- 2. Shell Runner: Sends text to the live shell +function M.run_shell_job(cmd, on_exit_callback) + -- Ensure terminal is open and process is alive + if not pio_terminal then + return + end + if not pio_terminal:is_open() then + pio_terminal:open() + end + + -- Wrap the command: + -- 1. Run the actual command + -- 2. Run the callback logic (optional) + -- 3. Print the sentinel so the Lua listener knows we're done + -- local full_cmd = string.format('%s && echo %s', cmd, sentinel) + + -- Store callback for the listener if needed + M.current_cb = on_exit_callback + + -- Send the text + Enter key + pio_terminal:send(cmd) +end +-- 3. Queue Controller +function M.process_queue() + local task = table.remove(M.queue, 1) + + if not task then + M.is_processing = false + if M.current_cb then + M.current_cb() + end -- Final callback + return + end + + M.is_processing = true + + if task.cmd then + M.run_shell_job(task.cmd, task.cb) + elseif type(task.cb) == 'function' then + vim.schedule(function() + task.cb() + -- Lua tasks need to manually move the queue + M.process_queue() + end) + end +end +------------------------------------------------------ +-- Handle after 'pio run -t compiledb' execution +function M.handleDb() + vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) + misc.gitignore_lsp_configs('compile_commands.json') + local pio_manager = require('platformio.pio_setup').pio_manager + pio_manager.refresh(function() + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + boilerplate_gen([[.clangd]], _G.metadata.core_dir) + M.compile_commandsFix() + lsp_restart('clangd') + end) +end + +------------------------------------------------------ +-- Handle after poioinit execution +--- stylua: ignore +function M.handlePioinit() + -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + -- vim.schedule(function() + -- local pio_manager = require('platformio.pio_setup').pio_manager + -- pio_manager.refresh(function() + -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + -- boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + vim.notify('Pioinit: Success', vim.log.levels.INFO) + -- end) + -- end) +end +-- Handle after poioinit execution +-- stylua: ignore +function M.handlePiolib() + vim.notify('Piolib: Success', vim.log.levels.INFO) +end +-- INFO: end commands sequencer +------------------------------------------------------ + +return M diff --git a/lua/platformio/utils/term.lua b/lua/platformio/utils/term.lua index 4dd7e8e4..ce278105 100644 --- a/lua/platformio/utils/term.lua +++ b/lua/platformio/utils/term.lua @@ -6,8 +6,7 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' local config = require('platformio').config - -M.on_stdout_handler = nil +local pio = require('platformio.utils.pio') ------------------------------------------------------ function M.strsplit(inputstr, del) @@ -142,7 +141,7 @@ function M.ToggleTerminal(command, direction) title = 'Pio Monitor: [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' pioOpts.display_name = 'piomon:' .. orig_window pioOpts.id = 98 - pioOpts.on_stdout = nil -- INFO: on_stdout + pioOpts.on_stdout = nil else -- INFO: if previous cli terminal already opened ==> reopen if prev.cli then prev.cli.display_name = 'piocli:' .. orig_window @@ -165,12 +164,8 @@ function M.ToggleTerminal(command, direction) pioOpts.id = 99 -- INFO: on_stdout - pioOpts.on_stdout = function(t, job, data) - -- Only run if pio.lua has successfully "plugged in" the handler - if M.on_stdout_handler then - M.on_stdout_handler(t, job, data) - end - end + -- on_stdout = stdout_callback, + pioOpts.on_stdout = pio.stdoutFilter end pioOpts.direction = direction ------------------------------------------------------ @@ -318,12 +313,11 @@ function M.ToggleTerminal(command, direction) prev.term:close() end terminal:toggle() - -- vim.defer_fn(function() - -- if command and command ~= '' then - -- send(terminal, command) - -- end - -- end, 50) -- 50ms delay, adjust as needed sgget - return terminal + vim.defer_fn(function() + if command and command ~= '' then + send(terminal, command) + end + end, 50) -- 50ms delay, adjust as needed sgget end return M diff --git a/lua/platformio/utils/term2.lua b/lua/platformio/utils/term2.lua new file mode 100644 index 00000000..4dd7e8e4 --- /dev/null +++ b/lua/platformio/utils/term2.lua @@ -0,0 +1,330 @@ +local M = {} + +local is_windows = jit.os == 'Windows' +M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' +-- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' +-- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' + +local config = require('platformio').config + +M.on_stdout_handler = nil + +------------------------------------------------------ +function M.strsplit(inputstr, del) + local t = {} + if type(inputstr) == 'string' and inputstr and inputstr ~= '' then + for str in string.gmatch(inputstr, '([^' .. del .. ']+)') do + table.insert(t, str) + end + end + return t +end + +function M.check_prefix(str, prefix) + return str:sub(1, #prefix) == prefix +end + +------------------------------------------------------ + +-- INFO: get current OS enter +function M.enter() + local shell = vim.o.shell + if is_windows then + return vim.fn.executable('pwsh') and '\r' or '\r\n' + elseif shell:find('nu') then + return '\r' + else + return '\n' + end +end + +-- INFO: get previous window +local function getPreviousWindow(orig_window) + local prev = { + orig_window = orig_window, + term = nil, --active terminal + cli = nil, --cli terminal + mon = nil, --mon terminal + float = false, --is active terminal direction float + } + local terms = require('toggleterm.terminal').get_all(true) + if #terms ~= 0 then + for i = 1, #terms do + if terms[i].display_name and terms[i].display_name ~= '' and terms[i].display_name:find('pio', 1) then + local name_splt = M.strsplit(terms[i].display_name, ':') + if name_splt[1] == 'piocli' then + prev.cli = terms[i] + if terms[i].window == orig_window then + ---@diagnostic disable-next-line: cast-local-type + prev.orig_window = tonumber(name_splt[2]) -- set orig_window to the previous terminal onrig_window + prev.term = terms[i] + end + if terms[i].direction == 'float' then + prev.float = true + end + elseif name_splt[1] == 'piomon' then + prev.mon = terms[i] + if terms[i].window == orig_window then + ---@diagnostic disable-next-line: cast-local-type + prev.orig_window = tonumber(name_splt[2]) -- set orig_window to the previous terminal onrig_window + prev.term = terms[i] + end + if terms[i].direction == 'float' then + prev.float = true + end + end + end + end + end + return prev +end + +------------------------------------------------------ +-- INFO: Send command +local function send(term, cmd) + vim.fn.chansend(term.job_id, cmd .. M.enter()) + if vim.api.nvim_buf_is_loaded(term.bufnr) and vim.api.nvim_buf_is_valid(term.bufnr) then + if term.window and vim.api.nvim_win_is_valid(term.window) then --vim.ui.term_has_open_win(term) then + vim.api.nvim_set_current_win(term.window) -- terminal focus + vim.api.nvim_buf_call(term.bufnr, function() + local mode = vim.api.nvim_get_mode().mode + if mode == 'n' or mode == 'nt' then + vim.cmd('normal! G') -- normal command to Goto bottom of buffer (scroll) + end + end) + end + end +end + +------------------------------------------------------ +-- INFO: PioTermClose +local function PioTermClose(t) + local orig_window = tonumber(M.strsplit(t.display_name, ':')[2]) + -- close terminal window + vim.api.nvim_win_close(t.window, true) + + -- go back to previous window + if orig_window and vim.api.nvim_win_is_valid(orig_window) then + vim.api.nvim_set_current_win(orig_window) + else + vim.api.nvim_set_current_win(0) + end +end + +------------------------------------------------------ +-- INFO: ToggleTerminal +function M.ToggleTerminal(command, direction) + local status_ok, _ = pcall(require, 'toggleterm') + if not status_ok then + vim.api.nvim_echo({ { 'toggleterm not found!', 'ErrorMsg' } }, true, {}) + return + end + + local title = '' + local pioOpts = {} + + -- INFO: set orig_window to current window, or if available get current toggleterm previous window + local prev = getPreviousWindow(vim.api.nvim_get_current_win()) + local orig_window = prev.orig_window + + if string.find(command, ' monitor') then + if prev.mon then -- INFO: if previous monitor terminal already opened ==> reopen + prev.mon.display_name = 'piomon:' .. orig_window + local win_type = vim.fn.win_gettype(prev.mon.window) + local win_open = win_type == '' or win_type == 'popup' + if prev.mon.window and (win_open and vim.api.nvim_win_get_buf(prev.mon.window) == prev.mon.bufnr) then + vim.api.nvim_set_current_win(prev.mon.window) + else + prev.mon:open() + end + return + end + title = 'Pio Monitor: [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' + pioOpts.display_name = 'piomon:' .. orig_window + pioOpts.id = 98 + pioOpts.on_stdout = nil -- INFO: on_stdout + else -- INFO: if previous cli terminal already opened ==> reopen + if prev.cli then + prev.cli.display_name = 'piocli:' .. orig_window + local win_type = vim.fn.win_gettype(prev.cli.window) + local win_open = win_type == '' or win_type == 'popup' + if prev.cli.window and (win_open and vim.api.nvim_win_get_buf(prev.cli.window) == prev.cli.bufnr) then + vim.api.nvim_set_current_win(prev.cli.window) + else + prev.cli:open() + end + vim.defer_fn(function() + if command and command ~= '' then + send(prev.cli, command) + end + end, 50) -- 50ms delay, adjust as needed + return + end + title = 'Pio CLI> [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' + pioOpts.display_name = 'piocli:' .. orig_window + pioOpts.id = 99 + + -- INFO: on_stdout + pioOpts.on_stdout = function(t, job, data) + -- Only run if pio.lua has successfully "plugged in" the handler + if M.on_stdout_handler then + M.on_stdout_handler(t, job, data) + end + end + end + pioOpts.direction = direction + ------------------------------------------------------ + + -- INFO: termConfig table start + local termConfig = { + hidden = true, -- Start hidden, we'll open it explicitly + hide_numbers = true, + float_opts = { + winblend = 0, + width = function() + return math.ceil(vim.o.columns * 0.85) + end, + height = function() + return math.ceil(vim.o.lines * 0.85) + end, + -- shell = vim.o.shell, + shell = vim.o.shell, + highlights = { + border = 'FloatBorder', + background = 'NormalFloat', + }, + }, + close_on_exit = false, --closeOnexit, + + -- INFO: on_open() + on_open = function(t) + -- Get properties of the 'Normal' highlight group (background of main editor) + -- local hl = vim.api.nvim_get_hl(0, { name = 'PmenuSel' }) + -- local hl = { bg = '#e4cf0e', fg = '#0012d9' } + local hl = { bg = '#80a3d4', fg = '#000000' } + + if hl then + vim.api.nvim_set_hl(0, 'MyWinBar', { bg = hl.bg, fg = hl.fg }) + + local winBartitle = '%#MyWinBar#' .. title .. '%*' + vim.api.nvim_set_option_value('winbar', winBartitle, { scope = 'local', win = t.window }) + + -- Following necessary to solve that some time winbar not showing + vim.schedule(function() + vim.api.nvim_set_option_value('winbar', winBartitle, { scope = 'local', win = t.window }) + end) + end + vim.keymap.set('t', '', [[k]], { buffer = t.bufnr }) + vim.keymap.set('n', '', [[a]], { buffer = t.bufnr }) + + vim.keymap.set('n', 'q', function() + PioTermClose(t) + end, { desc = 'PioTermClose', buffer = t.bufnr }) + + if config.debug then + local name_splt = M.strsplit(t.display_name, ':') + vim.api.nvim_echo({ + { 'ToggleTerm ', 'MoreMsg' }, + { '(Term name: ' .. name_splt[1] .. ')', 'MoreMsg' }, + { '(Prev win ID: ' .. name_splt[2] .. ')', 'MoreMsg' }, + { '(Term Win ID: ' .. t.window .. ')', 'MoreMsg' }, + { '(Term Buffer#: ' .. t.bufnr .. ')', 'MoreMsg' }, + { '(Term id: ' .. t.id .. ')', 'MoreMsg' }, + { '(Job ID: ' .. t.job_id .. ')', 'MoreMsg' }, + }, true, {}) + end + end, + + -- INFO: on_close() + on_close = function(t) + orig_window = tonumber(M.strsplit(t.display_name, ':')[2]) + ---@diagnostic disable-next-line: param-type-mismatch + if orig_window and vim.api.nvim_win_is_valid(orig_window) then + vim.api.nvim_set_current_win(orig_window) + else + vim.api.nvim_set_current_win(0) + end + end, + + -- -- INFO: on_exit() + -- on_exit = function(_) + -- exit_callback() + -- end, + + -- INFO: on_stdout + -- on_stdout = stdout_callback, + -- on_stdout = pio.stdoutFilter, + + -- INFO: on_create() { + on_create = function(t) + local platformio = vim.api.nvim_create_augroup(M.strsplit(t.display_name, ':')[1], { clear = true }) + + -- INFO: CmdlineLeave + vim.api.nvim_create_autocmd('CmdlineLeave', { + group = platformio, + -- pattern = ':', + buffer = t.bufnr, + callback = function() + if vim.v.event and not vim.v.event.abort and vim.v.event.cmdtype == ':' then + local quit = vim.fn.getcmdline() == 'q' + local quitbang = vim.fn.getcmdline() == 'q!' + if quitbang or quit then + local name_splt = M.strsplit(t.display_name, ':') + if quitbang then + if name_splt[1] == 'piomon' then -- monitor terminal + local exit = vim.api.nvim_replace_termcodes('exit', true, true, true) + send(t, exit) + else -- cli terminal + send(t, 'exit') + end + end + + orig_window = tonumber(name_splt[2]) + vim.schedule(function() + -- go back to previous window + if orig_window and vim.api.nvim_win_is_valid(orig_window) then + vim.api.nvim_set_current_win(orig_window) + else + vim.api.nvim_set_current_win(0) + end + end) + end + end + end, + }) + + -- INFO: BufUnload + vim.api.nvim_create_autocmd('BufUnload', { + group = platformio, + desc = 'toggleterm buffer unloaded', + buffer = t.bufnr, + callback = function(args) + vim.keymap.del('t', '', { buffer = args.buf }) + vim.keymap.del('n', '', { buffer = args.buf }) + + -- clear autommmand when quit + vim.api.nvim_clear_autocmds({ group = M.strsplit(t.display_name, ':')[1] }) + end, + }) + end, + } + -- INFO: termConfig table end + + termConfig = vim.tbl_deep_extend('force', termConfig, pioOpts or {}) + + -- INFO: create new terminal + local terminal = require('toggleterm.terminal').Terminal:new(termConfig) + if prev.term and prev.float then + prev.term:close() + end + terminal:toggle() + -- vim.defer_fn(function() + -- if command and command ~= '' then + -- send(terminal, command) + -- end + -- end, 50) -- 50ms delay, adjust as needed sgget + return terminal +end + +return M +---------------------------------------------------------------------------------------- From 93aa4c15e88e7ac72221b4f645adfc1ca8ab8e74 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 06:33:58 +0300 Subject: [PATCH 0772/1406] update --- lua/platformio/pioinit.lua | 22 ++--- pio2.lua | 190 ------------------------------------- 2 files changed, 10 insertions(+), 202 deletions(-) delete mode 100644 pio2.lua diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 722e9342..4e95eab2 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -58,18 +58,16 @@ local function pick_framework(board_details) local pio = require('platformio.utils.pio') pio.selected_framework = selection[1] - local setup_project = require('platformio.utils.pio2').setup_project - setup_project(board_details['id'], pio.selected_framework) - -- pio.run_sequence({ - -- { - -- cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', - -- cb = pio.handlePioinit, - -- }, - -- { - -- cmd = 'pio run -t compiledb', - -- cb = pio.handleDb, - -- }, - -- }) + pio.run_sequence({ + { + cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', + cb = pio.handlePioinit, + }, + { + cmd = 'pio run -t compiledb', + cb = pio.handleDb, + }, + }) end) return true end, diff --git a/pio2.lua b/pio2.lua deleted file mode 100644 index bbe0e4eb..00000000 --- a/pio2.lua +++ /dev/null @@ -1,190 +0,0 @@ -local M = {} -local Terminal = require('toggleterm.terminal').Terminal - --- State Management -M.queue = {} -M.is_processing = false -local current_callback = require('platformio.utils.term2').current_callback - --- 1. Persistent Terminal Configuration --- Defined once to avoid "cannot assign after loading" errors. -local ToggleTerminal = require('platformio.utils.term2').ToggleTerminal -_G.metadata.isBusy = true -local pio_terminal = ToggleTerminal('', 'float') --- local pio_terminal = Terminal:new({ --- id = 99, --- direction = 'float', --- close_on_exit = false, -- Keep window open so user can see results --- -- Proxy callback: uses the variable defined in M.run_shell_job --- on_exit = function(t, job, exit_code) --- if type(current_callback) == 'function' then --- current_callback(t, job, exit_code) --- end --- end, --- -- Dynamic focus/scroll handler --- on_open = function(term) --- if term.window and vim.api.nvim_win_is_valid(term.window) then --- vim.api.nvim_set_current_win(term.window) --- vim.cmd('normal! G') -- Scroll to bottom --- end --- end, --- }) - --- 2. The Optimized Path Fixer -function M.compile_commandsFix() - local filename = vim.uv.cwd() .. '/compile_commands.json' - - -- Nil/Error Check: Ensure file exists - if vim.fn.filereadable(filename) == 0 then - M.process_queue() - return - end - - -- Atomic Read - local lines = vim.fn.readfile(filename) - if not lines or #lines == 0 then - M.process_queue() - return - end - - local content = table.concat(lines, '\n') - local ok, data = pcall(vim.json.decode, content) - - -- Nil/Error Check: Valid JSON - if not ok or type(data) ~= 'table' then - vim.notify('PIO Fix: Invalid JSON', vim.log.levels.ERROR) - M.process_queue() - return - end - - -- Build Path Map from Toolchain Metadata - local path_map = {} - local toolchain = _G.metadata and _G.metadata.toolchain or '' - if toolchain ~= '' then - local bin_path = toolchain .. '/bin/*' - for _, full_path in ipairs(vim.fn.glob(bin_path, false, true)) do - local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') - path_map[name] = full_path - end - end - - -- Update Entries - local modified = false - for _, entry in ipairs(data) do - local cmd = entry.command or '' - local first_token = cmd:match('^%S+') - -- If driver is relative, replace with absolute path from map - if first_token and not (first_token:sub(1, 1) == '/' or first_token:match('^%a:')) then - local short_name = first_token:gsub('%.exe$', '') - if path_map[short_name] then - entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) - modified = true - end - end - end - - -- Save if changes made - if modified then - local json_str = vim.json.encode(data) - local formatted = vim.fn.system('python -m json.tool', json_str) - if vim.v.shell_error == 0 then - vim.fn.writefile(vim.split(formatted, '\n'), filename) - vim.notify('PIO: Fixed compile_commands.json', vim.log.levels.INFO) - end - end - - -- Proceed to next task (or final shell handoff) - M.process_queue() -end - --- 3. Shell Runner (Queue and Manual) -function M.run_shell_job(cmd, on_exit_callback, is_manual) - if not cmd or cmd == '' then - return - end - - pio_terminal.cmd = cmd - - if is_manual then - -- Manual Mode: Clear callback to prevent queue interference - current_callback = nil - else - -- Queue Mode: Set logic for the next step - current_callback = function(_, _, exit_code) - if exit_code == 0 then - if type(on_exit_callback) == 'function' then - on_exit_callback() - end - -- Use schedule to avoid race conditions with terminal closing/opening - vim.schedule(function() - M.process_queue() - end) - else - vim.notify('PIO Queue Failed: ' .. cmd, vim.log.levels.ERROR) - M.queue = {} - M.is_processing = false - end - end - end - - pio_terminal:spawn() -end - --- 4. The Queue Controller -function M.process_queue() - local task = table.remove(M.queue, 1) - - -- Nil Check: End of queue - if not task then - M.is_processing = false - return - end - - M.is_processing = true - - -- Decide execution path - if task.cmd then - M.run_shell_job(task.cmd, task.cb, false) - elseif type(task.cb) == 'function' then - -- For Lua tasks (like Fixer), run directly - vim.schedule(task.cb) - else - -- Fallback: Skip invalid tasks - M.process_queue() - end -end - --- 5. Main Entry Point -function M.setup_project(board_id, framework) - if M.is_processing then - vim.notify('PIO: Queue already running', vim.log.levels.WARN) - return - end - - -- Determine OS Shell for the final handoff - local shell = vim.o.shell or (vim.fn.has('win32') == 1 and 'cmd' or 'bash') - - M.queue = { - { - cmd = string.format('pio project init --board %s -O "framework=%s"', board_id, framework), - }, - { - cmd = 'pio run -t compiledb', - }, - { - cb = M.compile_commandsFix, -- Internal: calls M.process_queue() - }, - { - -- FINAL TASK: Spawn an interactive shell - -- This keeps the terminal alive so the user can type or use :send() - cmd = shell, - cb = function() - vim.notify('PIO: Automation complete. Shell ready.', vim.log.levels.INFO) - end, - }, - } - - M.process_queue() -end - -return M From df72bff6522ff07894dda561f8295cfeba1a27ea Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 07:40:26 +0300 Subject: [PATCH 0773/1406] update --- lua/platformio/pioinit.lua | 8 ++++++-- lua/platformio/utils/pio.lua | 33 +++++++++++++++++++++++++-------- 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 4e95eab2..15ad170a 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -61,12 +61,16 @@ local function pick_framework(board_details) pio.run_sequence({ { cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', - cb = pio.handlePioinit, + cb = pio.handlePioinitPass, }, { cmd = 'pio run -t compiledb', - cb = pio.handleDb, + cb = pio.handlePioinitDb, }, + -- { + -- cmd = 'echo _DONE_":"LAST', + -- cb = pio.handlePioinitLast, + -- }, }) end) return true diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 7a4dd01d..7ca70d91 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -201,7 +201,7 @@ function M.stdoutFilter(_, _, data) -- 3. Process any "middle" lines which are guaranteed to be complete for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end - for status in pio_buffer:gmatch('_DONE_:(%a+)') do + for status in pio_buffer:gmatch('_COMMANDS_:(%a+)') do if status then -- if status == 'PASS' then -- pio_buffer = data[#data] @@ -214,7 +214,7 @@ function M.stdoutFilter(_, _, data) local task = table.remove(M.queue, 1) if task then vim.schedule(task) end elseif status == 'LAST' then - _G.metadata.isBusy = false + -- _G.metadata.isBusy = false M.queue = {} -- Clear queue on any other status pio_buffer = '' vim.schedule(function() vim.notify('PIO Sequence: Finished', 4) end) @@ -239,9 +239,9 @@ M.run_sequence = function(tasks) pio_buffer = '' local full_cmd = '' -- - local pass = 'echo _DONE_":"PASS' - local last = 'echo _DONE_":"LAST' - local fail = 'echo _DONE_":"FAIL' + local pass = 'echo _COMMANDS_":"PASS' + local last = 'echo _COMMANDS_":"LAST' + local fail = 'echo _COMMANDS_":"FAIL' -- for _, task in ipairs(tasks) do table.insert(M.queue, task.cb) @@ -253,6 +253,7 @@ M.run_sequence = function(tasks) end -- Chain multiple commands end full_cmd = full_cmd .. ' && ' .. last .. ' || ' .. fail + -- full_cmd = full_cmd .. ' || ' .. fail local ToggleTerminal = require('platformio.utils.term').ToggleTerminal _G.metadata.isBusy = true ToggleTerminal(full_cmd, 'float') @@ -311,7 +312,8 @@ function M.setup_project(board, framework) end ------------------------------------------------------ -- Handle after 'pio run -t compiledb' execution -function M.handleDb() +function M.handlePioinitDb() + M.compile_commandsFix() vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) misc.gitignore_lsp_configs('compile_commands.json') local pio_manager = require('platformio.pio_setup').pio_manager @@ -319,15 +321,30 @@ function M.handleDb() local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') boilerplate_gen([[.clangd]], _G.metadata.core_dir) - M.compile_commandsFix() lsp_restart('clangd') end) + _G.metadata.isBusy = false end +------------------------------------------------------ +-- Handle after 'pio run -t compiledb' execution +function M.handlePioinitLast() + M.compile_commandsFix() + vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) + misc.gitignore_lsp_configs('compile_commands.json') + local pio_manager = require('platformio.pio_setup').pio_manager + pio_manager.refresh(function() + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + boilerplate_gen([[.clangd]], _G.metadata.core_dir) + M.compile_commandsFix() + lsp_restart('clangd') + end) +end ------------------------------------------------------ -- Handle after poioinit execution --- stylua: ignore -function M.handlePioinit() +function M.handlePioinitPass() -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) -- vim.schedule(function() From 01bfb3f416701c1e65107da7894cc91d0964d505 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 07:57:48 +0300 Subject: [PATCH 0774/1406] update --- lua/platformio/pioinit.lua | 2 +- lua/platformio/utils/pio.lua | 52 +++++++++++++++++------------------- 2 files changed, 26 insertions(+), 28 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 15ad170a..ede72584 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -65,7 +65,7 @@ local function pick_framework(board_details) }, { cmd = 'pio run -t compiledb', - cb = pio.handlePioinitDb, + cb = pio.handleDb, }, -- { -- cmd = 'echo _DONE_":"LAST', diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 7ca70d91..f7dbec14 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -54,6 +54,14 @@ function M.compile_commandsFix() vim.notify('PIO Fix: Python formatting failed', vim.log.levels.ERROR) end end + local pio_manager = require('platformio.pio_setup').pio_manager + pio_manager.refresh(function() + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + boilerplate_gen([[.clangd]], _G.metadata.core_dir) + M.compile_commandsFix() + lsp_restart('clangd') + end) end -- function M.compile_commandsFix() @@ -213,7 +221,7 @@ function M.stdoutFilter(_, _, data) pio_buffer = data[#data] local task = table.remove(M.queue, 1) if task then vim.schedule(task) end - elseif status == 'LAST' then + elseif status == 'DONE' then -- _G.metadata.isBusy = false M.queue = {} -- Clear queue on any other status pio_buffer = '' @@ -240,7 +248,7 @@ M.run_sequence = function(tasks) local full_cmd = '' -- local pass = 'echo _COMMANDS_":"PASS' - local last = 'echo _COMMANDS_":"LAST' + local done = 'echo _COMMANDS_":"DONE' local fail = 'echo _COMMANDS_":"FAIL' -- for _, task in ipairs(tasks) do @@ -252,7 +260,7 @@ M.run_sequence = function(tasks) full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands end - full_cmd = full_cmd .. ' && ' .. last .. ' || ' .. fail + full_cmd = full_cmd .. ' && ' .. done .. ' || ' .. fail -- full_cmd = full_cmd .. ' || ' .. fail local ToggleTerminal = require('platformio.utils.term').ToggleTerminal _G.metadata.isBusy = true @@ -262,7 +270,6 @@ M.run_sequence = function(tasks) -- if task.cmd then -- -- It's a shell task: wrap it with the pass/fail sentinels -- local wrapped_cmd = string.format('%s && %s || %s', task.cmd, pass, fail) - -- -- table.insert(M.queue, { -- cmd = wrapped_cmd, -- cb = task.cb, @@ -312,7 +319,7 @@ function M.setup_project(board, framework) end ------------------------------------------------------ -- Handle after 'pio run -t compiledb' execution -function M.handlePioinitDb() +function M.handleDb() M.compile_commandsFix() vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) misc.gitignore_lsp_configs('compile_commands.json') @@ -326,34 +333,25 @@ function M.handlePioinitDb() _G.metadata.isBusy = false end ------------------------------------------------------- --- Handle after 'pio run -t compiledb' execution -function M.handlePioinitLast() - M.compile_commandsFix() - vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) - misc.gitignore_lsp_configs('compile_commands.json') - local pio_manager = require('platformio.pio_setup').pio_manager - pio_manager.refresh(function() - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - boilerplate_gen([[.clangd]], _G.metadata.core_dir) - M.compile_commandsFix() - lsp_restart('clangd') - end) -end ------------------------------------------------------ -- Handle after poioinit execution --- stylua: ignore function M.handlePioinitPass() - -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - -- vim.schedule(function() + vim.notify('Pioinit: Done', vim.log.levels.INFO) +end +------------------------------------------------------ +-- Handle after 'pio run -t compiledb' execution +function M.handlePioinitDone() + vim.notify('compiledb: Done', vim.log.levels.INFO) + M.compile_commandsFix() + misc.gitignore_lsp_configs('compile_commands.json') -- local pio_manager = require('platformio.pio_setup').pio_manager -- pio_manager.refresh(function() - -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - -- boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - vim.notify('Pioinit: Success', vim.log.levels.INFO) - -- end) + -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + -- boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) + -- M.compile_commandsFix() + -- lsp_restart('clangd') -- end) end -- Handle after poioinit execution From 530773654f57b1490ae9dabf5f99a934fb612335 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 08:02:41 +0300 Subject: [PATCH 0775/1406] update --- lua/platformio/utils/pio.lua | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f7dbec14..19fadcec 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -323,14 +323,14 @@ function M.handleDb() M.compile_commandsFix() vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) misc.gitignore_lsp_configs('compile_commands.json') - local pio_manager = require('platformio.pio_setup').pio_manager - pio_manager.refresh(function() - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - boilerplate_gen([[.clangd]], _G.metadata.core_dir) - lsp_restart('clangd') - end) - _G.metadata.isBusy = false + -- local pio_manager = require('platformio.pio_setup').pio_manager + -- pio_manager.refresh(function() + -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + -- boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) + -- lsp_restart('clangd') + -- end) + -- _G.metadata.isBusy = false end ------------------------------------------------------ From 6e055d409ddabf1079639aa22c419eb3f5e45833 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 08:09:25 +0300 Subject: [PATCH 0776/1406] update --- lua/platformio/utils/pio.lua | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 19fadcec..93164ea1 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -59,7 +59,6 @@ function M.compile_commandsFix() local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') boilerplate_gen([[.clangd]], _G.metadata.core_dir) - M.compile_commandsFix() lsp_restart('clangd') end) end @@ -320,9 +319,9 @@ end ------------------------------------------------------ -- Handle after 'pio run -t compiledb' execution function M.handleDb() - M.compile_commandsFix() - vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) + vim.notify('compiledb: Done', vim.log.levels.INFO) misc.gitignore_lsp_configs('compile_commands.json') + M.compile_commandsFix() -- local pio_manager = require('platformio.pio_setup').pio_manager -- pio_manager.refresh(function() -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen @@ -337,14 +336,12 @@ end -- Handle after poioinit execution --- stylua: ignore function M.handlePioinitPass() - vim.notify('Pioinit: Done', vim.log.levels.INFO) + vim.notify('Pioinit: PASS', vim.log.levels.INFO) end ------------------------------------------------------ -- Handle after 'pio run -t compiledb' execution function M.handlePioinitDone() - vim.notify('compiledb: Done', vim.log.levels.INFO) - M.compile_commandsFix() - misc.gitignore_lsp_configs('compile_commands.json') + vim.notify('Pioinit: Done', vim.log.levels.INFO) -- local pio_manager = require('platformio.pio_setup').pio_manager -- pio_manager.refresh(function() -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen From 81647689606b74736a8e8e147f704e0cbbf12d36 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 08:37:53 +0300 Subject: [PATCH 0777/1406] update --- lua/platformio/pio_setup.lua | 11 ++++--- lua/platformio/pioinit.lua | 9 +++--- lua/platformio/piolib.lua | 6 +++- lua/platformio/utils/pio.lua | 61 ++++++++++++++++-------------------- 4 files changed, 43 insertions(+), 44 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 65a33146..0e9f9229 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -350,23 +350,24 @@ end -- 2. Smart Save/Load: Uses JSON and Hashing -- 3. Robust Execution: Mutes watcher and handles LSP restart function M.run_compiledb() - -- if _G.metadata.isBusy then - -- return - -- end + if _G.metadata.isBusy then + return + end _G.metadata.isBusy = true vim.notify('Building Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) vim.schedule(function() - _G.metadata.isBusy = false + -- _G.metadata.isBusy = false if obj.code == 0 then + M.compile_commandsFix() vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) -- Use pcall in case M.refresh is defined elsewhere -- pio_manager.refresh(function() -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) -- pio_generate_db() - lsp_restart('clangd') + -- lsp_restart('clangd') -- end) -- else diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index ede72584..3ba7b56e 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -61,16 +61,17 @@ local function pick_framework(board_details) pio.run_sequence({ { cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', + -- cb = function () vim.notify('Pioinit: Pass', vim.log.levels.INFO) end cb = pio.handlePioinitPass, }, { cmd = 'pio run -t compiledb', cb = pio.handleDb, }, - -- { - -- cmd = 'echo _DONE_":"LAST', - -- cb = pio.handlePioinitLast, - -- }, + { + cmd = 'echo _CMMNDS_":"LAST', + cb = function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end + }, }) end) return true diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 1d5e980d..b1c80fc6 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -64,12 +64,16 @@ local function pick_library(json_data) pio.run_sequence({ { cmd = 'pio pkg install --library "' .. pkg_name .. '"', - cb = pio.handlePiolib, + cb = function () vim.notify('Piolib: Done', vim.log.levels.INFO) end }, -- { -- cmd = 'pio run -t compiledb', -- cb = pio.handleDb, -- }, + { + cmd = 'echo _CMMNDS_":"LAST', + cb = function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end + }, }) end) return true diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 93164ea1..0e80f7e0 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -54,13 +54,8 @@ function M.compile_commandsFix() vim.notify('PIO Fix: Python formatting failed', vim.log.levels.ERROR) end end - local pio_manager = require('platformio.pio_setup').pio_manager - pio_manager.refresh(function() - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - boilerplate_gen([[.clangd]], _G.metadata.core_dir) - lsp_restart('clangd') - end) + lsp_restart('clangd') + _G.metadata.isBusy = false end -- function M.compile_commandsFix() @@ -208,7 +203,7 @@ function M.stdoutFilter(_, _, data) -- 3. Process any "middle" lines which are guaranteed to be complete for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end - for status in pio_buffer:gmatch('_COMMANDS_:(%a+)') do + for status in pio_buffer:gmatch('_CMMNDS_:(%a+)') do if status then -- if status == 'PASS' then -- pio_buffer = data[#data] @@ -246,9 +241,9 @@ M.run_sequence = function(tasks) pio_buffer = '' local full_cmd = '' -- - local pass = 'echo _COMMANDS_":"PASS' - local done = 'echo _COMMANDS_":"DONE' - local fail = 'echo _COMMANDS_":"FAIL' + local pass = 'echo _CMMNDS_":"PASS' + -- local done = 'echo _CMMNDS_":"DONE' + local fail = 'echo _CMMNDS_":"FAIL' -- for _, task in ipairs(tasks) do table.insert(M.queue, task.cb) @@ -259,8 +254,8 @@ M.run_sequence = function(tasks) full_cmd = full_cmd .. ' && ' .. part end -- Chain multiple commands end - full_cmd = full_cmd .. ' && ' .. done .. ' || ' .. fail - -- full_cmd = full_cmd .. ' || ' .. fail + -- full_cmd = full_cmd .. ' && ' .. done .. ' || ' .. fail + full_cmd = full_cmd .. ' || ' .. fail local ToggleTerminal = require('platformio.utils.term').ToggleTerminal _G.metadata.isBusy = true ToggleTerminal(full_cmd, 'float') @@ -319,38 +314,36 @@ end ------------------------------------------------------ -- Handle after 'pio run -t compiledb' execution function M.handleDb() - vim.notify('compiledb: Done', vim.log.levels.INFO) + vim.notify('compiledb: Pass', vim.log.levels.INFO) misc.gitignore_lsp_configs('compile_commands.json') M.compile_commandsFix() - -- local pio_manager = require('platformio.pio_setup').pio_manager - -- pio_manager.refresh(function() - -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - -- boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) - -- lsp_restart('clangd') - -- end) - -- _G.metadata.isBusy = false end ------------------------------------------------------ -- Handle after poioinit execution --- stylua: ignore function M.handlePioinitPass() - vim.notify('Pioinit: PASS', vim.log.levels.INFO) + local pio_manager = require('platformio.pio_setup').pio_manager + pio_manager.refresh(function() + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + boilerplate_gen([[.clangd]], _G.metadata.core_dir) + end) + vim.notify('Pioinit: Pass', vim.log.levels.INFO) end ------------------------------------------------------ -- Handle after 'pio run -t compiledb' execution -function M.handlePioinitDone() - vim.notify('Pioinit: Done', vim.log.levels.INFO) - -- local pio_manager = require('platformio.pio_setup').pio_manager - -- pio_manager.refresh(function() - -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - -- boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) - -- M.compile_commandsFix() - -- lsp_restart('clangd') - -- end) -end +-- function M.handlePioinitDone() +-- vim.notify('Pioinit: Done', vim.log.levels.INFO) +-- -- local pio_manager = require('platformio.pio_setup').pio_manager +-- -- pio_manager.refresh(function() +-- -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +-- -- boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') +-- -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) +-- -- M.compile_commandsFix() +-- -- lsp_restart('clangd') +-- -- end) +-- end -- Handle after poioinit execution -- stylua: ignore function M.handlePiolib() From eff861ddaf58fff7b7a34b0551d87d21ad3ed6ea Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 08:44:59 +0300 Subject: [PATCH 0778/1406] update --- lua/platformio/pioinit.lua | 2 +- lua/platformio/utils/pio.lua | 9 --------- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 3ba7b56e..f469bd24 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -69,7 +69,7 @@ local function pick_framework(board_details) cb = pio.handleDb, }, { - cmd = 'echo _CMMNDS_":"LAST', + cmd = 'echo _CMMNDS_":"DONE', cb = function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end }, }) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 0e80f7e0..55a97aeb 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -302,15 +302,6 @@ end -- end -- end --- 4. Entry Point -function M.setup_project(board, framework) - M.queue = { - { cmd = 'pio project init --board ' .. board }, - { cmd = 'pio run -t compiledb' }, - { cb = M.compile_commandsFix }, - } - M.process_queue() -end ------------------------------------------------------ -- Handle after 'pio run -t compiledb' execution function M.handleDb() From 965da25cc1a8054fa5f775976526874712ff9259 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 09:09:25 +0300 Subject: [PATCH 0779/1406] update --- lua/platformio/utils/pio.lua | 86 +++++++----------------------------- 1 file changed, 15 insertions(+), 71 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 55a97aeb..09026319 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -234,74 +234,34 @@ end ------------------------------------------------------ -- INFO: ToggleTerminal commands Sequencer ---- stylua: ignore +-- stylua: ignore M.run_sequence = function(tasks) -- Reset local state for new run M.queue = {} pio_buffer = '' local full_cmd = '' - -- - local pass = 'echo _CMMNDS_":"PASS' -- local done = 'echo _CMMNDS_":"DONE' - local fail = 'echo _CMMNDS_":"FAIL' + local pass = ' && echo _CMMNDS_":"PASS' + local fail = ' || echo _CMMNDS_":"FAIL' -- - for _, task in ipairs(tasks) do + local total_tasks = #tasks + for i, task in ipairs(tasks) do table.insert(M.queue, task.cb) - local part = string.format('%s && %s', task.cmd, pass) - if full_cmd == '' then - full_cmd = part - else - full_cmd = full_cmd .. ' && ' .. part - end -- Chain multiple commands + + local part = '' + if i == total_tasks then part = task.cmd or '' + else part = string.format('%s && %s', task.cmd, pass) end + + if full_cmd == '' then full_cmd = part + else full_cmd = full_cmd .. ' && ' .. part end end -- full_cmd = full_cmd .. ' && ' .. done .. ' || ' .. fail full_cmd = full_cmd .. ' || ' .. fail local ToggleTerminal = require('platformio.utils.term').ToggleTerminal _G.metadata.isBusy = true ToggleTerminal(full_cmd, 'float') - - -- for _, task in ipairs(M.tasks) do - -- if task.cmd then - -- -- It's a shell task: wrap it with the pass/fail sentinels - -- local wrapped_cmd = string.format('%s && %s || %s', task.cmd, pass, fail) - -- table.insert(M.queue, { - -- cmd = wrapped_cmd, - -- cb = task.cb, - -- }) - -- else - -- -- It's a Lua-only task: pass it through exactly as it is - -- table.insert(M.queue, task) - -- end - -- end - -- M.process_queue() end ------------------------------------------------------------------- --- 3. Queue Controller --- function M.process_queue() --- local task = table.remove(M.queue, 1) --- --- if not task then --- M.is_processing = false --- if M.current_cb then --- M.current_cb() --- end -- Final callback --- return --- end --- --- M.is_processing = true --- --- if task.cmd then --- M.run_shell_job(task.cmd, task.cb) --- elseif type(task.cb) == 'function' then --- vim.schedule(function() --- task.cb() --- -- Lua tasks need to manually move the queue --- M.process_queue() --- end) --- end --- end - ------------------------------------------------------ -- Handle after 'pio run -t compiledb' execution function M.handleDb() @@ -311,36 +271,20 @@ function M.handleDb() end ------------------------------------------------------ --- Handle after poioinit execution ---- stylua: ignore +-- Handle after pioinit execution function M.handlePioinitPass() + vim.notify('Pioinit: Pass', vim.log.levels.INFO) local pio_manager = require('platformio.pio_setup').pio_manager pio_manager.refresh(function() local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') boilerplate_gen([[.clangd]], _G.metadata.core_dir) end) - vim.notify('Pioinit: Pass', vim.log.levels.INFO) end ------------------------------------------------------ --- Handle after 'pio run -t compiledb' execution --- function M.handlePioinitDone() --- vim.notify('Pioinit: Done', vim.log.levels.INFO) --- -- local pio_manager = require('platformio.pio_setup').pio_manager --- -- pio_manager.refresh(function() --- -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen --- -- boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') --- -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --- -- M.compile_commandsFix() --- -- lsp_restart('clangd') --- -- end) --- end --- Handle after poioinit execution --- stylua: ignore +-- Handle after piolib execution function M.handlePiolib() vim.notify('Piolib: Success', vim.log.levels.INFO) end --- INFO: end commands sequencer ------------------------------------------------------- return M From 347eb8f889ec4f4e6d1a32c7fb9bef2311d04bcb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 09:29:44 +0300 Subject: [PATCH 0780/1406] update --- lua/platformio/pioinit.lua | 8 ++++---- lua/platformio/piolib.lua | 8 ++++---- lua/platformio/utils/pio.lua | 31 ++++++++++++++++--------------- 3 files changed, 24 insertions(+), 23 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index f469bd24..5a0b4fa3 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -68,10 +68,10 @@ local function pick_framework(board_details) cmd = 'pio run -t compiledb', cb = pio.handleDb, }, - { - cmd = 'echo _CMMNDS_":"DONE', - cb = function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end - }, + -- { + -- cmd = 'echo _CMMNDS_":"DONE', + -- cb = function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end + -- }, }) end) return true diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index b1c80fc6..2d10de83 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -70,10 +70,10 @@ local function pick_library(json_data) -- cmd = 'pio run -t compiledb', -- cb = pio.handleDb, -- }, - { - cmd = 'echo _CMMNDS_":"LAST', - cb = function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end - }, + -- { + -- cmd = 'echo _CMMNDS_":"LAST', + -- cb = function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end + -- }, }) end) return true diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 09026319..2542b384 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -216,14 +216,15 @@ function M.stdoutFilter(_, _, data) local task = table.remove(M.queue, 1) if task then vim.schedule(task) end elseif status == 'DONE' then - -- _G.metadata.isBusy = false M.queue = {} -- Clear queue on any other status pio_buffer = '' - vim.schedule(function() vim.notify('PIO Sequence: Finished', 4) end) + local task = table.remove(M.queue, 1) + if task then vim.schedule(task) end elseif status == 'FAIL' then M.queue = {} -- Clear queue on any other status (failure) pio_buffer = '' - vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) + local task = table.remove(M.queue, 1) + if task then vim.schedule(task) end end break end @@ -240,28 +241,28 @@ M.run_sequence = function(tasks) M.queue = {} pio_buffer = '' local full_cmd = '' - -- local done = 'echo _CMMNDS_":"DONE' + local done = ' && echo _CMMNDS_":"DONE' local pass = ' && echo _CMMNDS_":"PASS' local fail = ' || echo _CMMNDS_":"FAIL' -- - local total_tasks = #tasks - for i, task in ipairs(tasks) do + for _, task in ipairs(tasks) do table.insert(M.queue, task.cb) - - local part = '' - if i == total_tasks then part = task.cmd or '' - else part = string.format('%s && %s', task.cmd, pass) end - - if full_cmd == '' then full_cmd = part - else full_cmd = full_cmd .. ' && ' .. part end + local part = string.format('%s %s', task.cmd, pass) + full_cmd = full_cmd .. part end - -- full_cmd = full_cmd .. ' && ' .. done .. ' || ' .. fail - full_cmd = full_cmd .. ' || ' .. fail + full_cmd = full_cmd .. done .. fail + table.insert(M.queue, function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end) + table.insert(M.queue, function () vim.notify('Pioinit: Failed', vim.log.levels.INFO) end) + -- full_cmd = full_cmd .. ' || ' .. fail local ToggleTerminal = require('platformio.utils.term').ToggleTerminal _G.metadata.isBusy = true ToggleTerminal(full_cmd, 'float') end +-- { +-- cmd = 'echo _CMMNDS_":"DONE', +-- cb = function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end +-- }, ------------------------------------------------------ -- Handle after 'pio run -t compiledb' execution function M.handleDb() From eaa068a8cbdccebf2a4a391407b04e2a9bfe9cbf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 09:42:19 +0300 Subject: [PATCH 0781/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 2542b384..e67d7e8a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -242,7 +242,7 @@ M.run_sequence = function(tasks) pio_buffer = '' local full_cmd = '' local done = ' && echo _CMMNDS_":"DONE' - local pass = ' && echo _CMMNDS_":"PASS' + local pass = ' && echo _CMMNDS_":"PASS ' local fail = ' || echo _CMMNDS_":"FAIL' -- for _, task in ipairs(tasks) do From d02b21d973d610615b51b59b0234bdf799a8c4bb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 09:45:16 +0300 Subject: [PATCH 0782/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index e67d7e8a..7bee846a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -242,7 +242,7 @@ M.run_sequence = function(tasks) pio_buffer = '' local full_cmd = '' local done = ' && echo _CMMNDS_":"DONE' - local pass = ' && echo _CMMNDS_":"PASS ' + local pass = ' && echo _CMMNDS_":"PASS && ' local fail = ' || echo _CMMNDS_":"FAIL' -- for _, task in ipairs(tasks) do From 3ce8052715ace73f704ba86646ad00f2729fea51 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 09:52:26 +0300 Subject: [PATCH 0783/1406] update --- lua/platformio/utils/pio.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 7bee846a..468899bb 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -242,13 +242,14 @@ M.run_sequence = function(tasks) pio_buffer = '' local full_cmd = '' local done = ' && echo _CMMNDS_":"DONE' - local pass = ' && echo _CMMNDS_":"PASS && ' + local pass = ' && echo _CMMNDS_":"PASS' local fail = ' || echo _CMMNDS_":"FAIL' -- for _, task in ipairs(tasks) do table.insert(M.queue, task.cb) local part = string.format('%s %s', task.cmd, pass) - full_cmd = full_cmd .. part + if full_cmd == '' then full_cmd = part + else full_cmd = full_cmd .. ' && ' .. part end end full_cmd = full_cmd .. done .. fail table.insert(M.queue, function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end) From b0e5a18018c03c48c291b74084e40fb4295f646e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 10:04:06 +0300 Subject: [PATCH 0784/1406] update --- lua/platformio/pio_setup.lua | 19 +++++++++++++------ lua/platformio/utils/pio.lua | 4 ++-- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 0e9f9229..64b1a991 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -104,12 +104,12 @@ M.pio_manager = (function() _G.metadata.fallbackFlags = fallbackFlags -- print(vim.inspect(_G.metadata)) - if callback then - vim.schedule(function() - vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) - callback() - end) - end + -- if callback then + -- vim.schedule(function() + -- vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) + -- callback() + -- end) + -- end end else vim.schedule(function() @@ -122,6 +122,13 @@ M.pio_manager = (function() vim.defer_fn(function() get_metadata(attempts - 1) end, 500) + else + if callback then + vim.schedule(function() + vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) + callback() + end) + end end end) end) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 468899bb..1f8f97ed 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -216,13 +216,13 @@ function M.stdoutFilter(_, _, data) local task = table.remove(M.queue, 1) if task then vim.schedule(task) end elseif status == 'DONE' then - M.queue = {} -- Clear queue on any other status pio_buffer = '' + M.queue = {} -- Clear queue on any other status local task = table.remove(M.queue, 1) if task then vim.schedule(task) end elseif status == 'FAIL' then - M.queue = {} -- Clear queue on any other status (failure) pio_buffer = '' + M.queue = {} -- Clear queue on any other status (failure) local task = table.remove(M.queue, 1) if task then vim.schedule(task) end end From d65920458ce20f1077502822616d07dc2a6e976c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 11:02:03 +0300 Subject: [PATCH 0785/1406] update --- lua/platformio/metadata.lua | 259 +++++++++++++---------------------- lua/platformio/utils/pio.lua | 3 +- metadata.lua | 232 ++++++++++++++++++++----------- metadataolld.lua | 133 ++++++++++++++++++ 4 files changed, 378 insertions(+), 249 deletions(-) create mode 100644 metadataolld.lua diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index b579c0d9..509f43dd 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,23 +1,4 @@ --- 1. Initialize Global Table immediately (Prevents nil errors) -_G.metadata = _G.metadata - or { - is_busy = false, - envs = {}, - active_env = '', - default_envs = {}, - core_dir = '', - packages_dir = '', - platforms_dir = '', - query_driver = '', - cc_compiler = '', - triplet = '', - toolchain = '', - sysroot = '', - fallbackFlags = {}, - } - --- Move the %#PioStatus# and %* outside of the curly braces -vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' +local M = {} _G.get_pio_status = function() if _G.metadata and _G.metadata.active_env ~= '' then @@ -25,180 +6,124 @@ _G.get_pio_status = function() end return '' end +-- Move the %#PioStatus# and %* outside of the curly braces +vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua._G.get_pio_status()}%* %y %p%% %l:%c' -local M = {} +-- 1. Internal State & Defaults local last_saved_hash = '' -local config_path = vim.fn.getcwd() .. '/.project_config.json' - -local function getHash(data) - return vim.fn.sha256(data) -end - --- local last_hash = '' --- local dir_path = vim.uv.cwd() --- local config_file = vim.fs.joinpath(dir_path, '.project_config.json') --- --- function M.sync_config(force_load) --- if force_load then --- if vim.fn.filereadable(config_file) == 1 then --- local data = table.concat(vim.fn.readfile(config_file), '') --- _G.metadata = vim.json.decode(data) --- last_hash = getHash(data) --- end --- else --- local current_data = vim.json.encode(_G.metadata) --- local current_hash = getHash(current_data) --- if current_hash ~= last_hash then --- vim.fn.writefile({ current_data }, config_file) --- last_hash = current_hash --- end --- end --- end - --- 2. Self-Healing Load & Auto-Create -function M.load_project_config() - local success = false - - if vim.fn.filereadable(config_path) == 1 then - local file = io.open(config_path, 'r') - if file then - local content = file:read('*a') - file:close() - local ok, decoded = pcall(vim.json.decode, content) - if ok and type(decoded) == 'table' then - _G.metadata = decoded - last_saved_hash = getHash(content) - success = true - end - end - end - - -- If file is missing or corrupted, initialize and force-save - if not success then - -- Use the global table we initialized at the top - local encoded = vim.json.encode(_G.metadata) - local file = io.open(config_path, 'w') - if file then - file:write(encoded) - file:close() - last_saved_hash = getHash(encoded) - if vim.fn.filereadable('platformio.ini') == 1 then - vim.notify('New project config created', vim.log.levels.INFO, { title = 'PlatformIO' }) +local config_path = vim.fs.joinpath(vim.uv.cwd(), '.project_config.json') + +local _raw_metadata = { + envs = {}, + active_env = '', + default_envs = {}, + core_dir = '', + packages_dir = '', + platforms_dir = '', + query_driver = '', + cc_compiler = '', + triplet = '', + toolchain = '', + sysroot = '', + fallbackFlags = {}, + dbTrigger = false, +} + +-- 2. The Reactive Proxy Wrapper +-- Any write to _G.metadata.key = val triggers this logic +_G.metadata = setmetatable({}, { + __index = _raw_metadata, + __newindex = function(_, key, value) + if _raw_metadata[key] == value then + return + end -- Performance check + _raw_metadata[key] = value + + -- Trigger background actions + vim.schedule(function() + M.save_project_config(true) + if key == 'cc_compiler' then + vim.notify('Env: ' .. value, vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) + pcall(function() + local LspRestart = require('platformio.utils.lsp').lsp_restart + if _raw_metadata.dbTrigger then + local dbFix = require('platformio.utils.pio').compile_commandsFix + dbFix() + _raw_metadata.dbTrigger = false + else + LspRestart('clangd') + end + end) end - end - end -end + -- if key == 'active_env' then + -- vim.notify('Env: ' .. value, vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) + -- pcall(function() + -- vim.cmd('LspRestart clangd') + -- end) + -- end + end) + end, +}) --- 3. Performance-Proof Save (Hash Check) +-- 3. Save Logic (Uses sha256 for stability) function M.save_project_config(quiet) - if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then + if vim.fn.filereadable('platformio.ini') == 0 then return end - local current_data = vim.json.encode(_G.metadata) - local current_hash = getHash(current_data) + local current_data = vim.json.encode(_raw_metadata) + local current_hash = vim.fn.sha256(current_data) - -- Only write if data actually changed since last load/save if current_hash ~= last_saved_hash then local file = io.open(config_path, 'w') if file then file:write(current_data) file:close() last_saved_hash = current_hash - if not quiet then - vim.notify('Settings synced to disk', vim.log.levels.INFO, { - title = 'PlatformIO', - render = 'compact', - }) + vim.notify('Config synced', vim.log.levels.INFO, { title = 'PlatformIO' }) end end end end --- 4. Fixed Status Function (Fixes line 472 error) -function M.show_status() - -- Ensure we access the table, NOT call it - local meta = _G.metadata - local env = meta.active_env ~= '' and meta.active_env or 'None' +-- 4. Load Logic (Populates proxy safely) +function M.load_project_config() + if vim.fn.filereadable(config_path) == 1 then + local file = io.open(config_path, 'r') + if file then + local content = file:read('*a') + file:close() + local ok, decoded = pcall(vim.json.decode, content) + if ok and type(decoded) == 'table' then + -- We update _raw_metadata directly to avoid triggering + -- 50+ notifications/restarts during the initial load loop + for k, v in pairs(decoded) do + _raw_metadata[k] = v + end + last_saved_hash = vim.fn.sha256(content) + return + end + end + end + -- If no file, initialize hash with defaults + last_saved_hash = vim.fn.sha256(vim.json.encode(_raw_metadata)) +end - vim.notify(string.format('Environment: %s\nTarget: %s', env, meta.triplet or 'Unknown'), vim.log.levels.INFO, { title = 'PlatformIO Status' }) +-- 5. Helper for ToggleTerm / Commands +function M.run_command(cmd_str) + -- Mute watcher logic would go here if needed + require('toggleterm').exec(cmd_str) end -local pio_group = vim.api.nvim_create_augroup('PioPersist', { clear = true }) -vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { - group = pio_group, +-- 6. Initialization +M.load_project_config() + +-- Auto-save on exit even if no manual changes were made +vim.api.nvim_create_autocmd('VimLeavePre', { callback = function() - -- Pass 'true' to save silently in the background M.save_project_config(true) end, - desc = 'Automatically save PlatformIO project metadata', }) --- 5. Environment Switcher UI -function M.switch_env() - -- 1. Safety check for metadata - if not _G.metadata.envs or next(_G.metadata.envs) == nil then - vim.notify('No environments found. Please refresh PlatformIO data.', vim.log.levels.WARN) - return - end - - -- 2. Prepare the list of environments - local options = vim.tbl_keys(_G.metadata.envs) - table.sort(options) - - -- 3. Open the selection UI - vim.ui.select(options, { - prompt = 'Select PlatformIO Environment:', - format_item = function(item) - local icon = (item == _G.metadata.active_env) and ' ' or '○ ' - return icon .. item - end, - }, function(choice) - if choice then - -- Update active environment - _G.metadata.active_env = choice - - -- 4. Persist change to disk (silently) - M.save_project_config(true) - - -- 5. Notify the user with the new board info - local board = _G.metadata.envs[choice].board or 'unknown' - vim.notify(string.format('Switched to %s\nBoard: %s', choice, board), vim.log.levels.INFO, { title = 'PlatformIO' }) - - -- 6. RESTART LSP (Crucial for refreshing includes/defines) - -- We wrap in pcall in case clangd isn't actually running yet - - local pio_manager = require('platformio.pio_setup').pio_manager - pio_manager.refresh(function() - M.compile_commands() - local lsp_restart = require('platformio.tools').lsp_restart - lsp_restart('clangd') - end) - - pcall(function() - -- Force LSP to pick up new fallbackFlags/defines - local lsp_restart = require('platformio.lsp.tools').lsp_restart - lsp_restart() - end) - end - end) -end - --- 6. Keybindings --- Switch Environment -vim.keymap.set('n', '\\e', function() - M.switch_env() -end, { desc = 'Switch [E]nvironment' }) - --- write -vim.keymap.set('n', '\\w', function() - M.save_project_config(false) -end, { desc = 'config [W]rite' }) - --- Manual Status Check -vim.keymap.set('n', '\\s', function() - M.show_status() -end, { desc = 'config [S]tatus' }) - return M diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 1f8f97ed..d8bffcf5 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -269,7 +269,8 @@ end function M.handleDb() vim.notify('compiledb: Pass', vim.log.levels.INFO) misc.gitignore_lsp_configs('compile_commands.json') - M.compile_commandsFix() + -- M.compile_commandsFix() + _G.metadata.dbTrigger = true end ------------------------------------------------------ diff --git a/metadata.lua b/metadata.lua index f89054d9..5a769cf5 100644 --- a/metadata.lua +++ b/metadata.lua @@ -1,133 +1,203 @@ --- -- Performance-proof: Uses guaranteed Vimscript sha256 via Lua bridge --- local function get_safe_hash(data) --- -- sha256 is built into Neovim's core and never nil --- return vim.fn.sha256(data) --- end --- --- local M = {} --- local last_saved_hash = nil --- local config_path = vim.fn.getcwd() .. '/.pioConfig.json' --- --- -- -- Global metadata initialization --- -- _G.metadata = _G.metadata --- -- or { --- -- envs = {}, --- -- active_env = '', --- -- default_envs = {}, --- -- core_dir = '', --- -- packages_dir = '', --- -- platforms_dir = '', --- -- query_driver = '', --- -- cc_compiler = '', --- -- triplet = '', --- -- toolchain = '', --- -- sysroot = '', --- -- fallbackFlags = {}, --- -- } --- --- -- 1. Optimized Save Function +-- -- 1. Initialize Global Table immediately (Prevents nil errors) +-- _G.metadata = _G.metadata +-- or { +-- is_busy = false, +-- envs = {}, +-- active_env = '', +-- default_envs = {}, +-- core_dir = '', +-- packages_dir = '', +-- platforms_dir = '', +-- query_driver = '', +-- cc_compiler = '', +-- triplet = '', +-- toolchain = '', +-- sysroot = '', +-- fallbackFlags = {}, +-- } -- --- function M.save_project_config(quiet) --- if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then --- return +-- _G.get_pio_status = function() +-- if _G.metadata and _G.metadata.active_env ~= '' then +-- return ' [ ' .. _G.metadata.active_env .. '] ' -- end +-- return '' +-- end +-- -- Move the %#PioStatus# and %* outside of the curly braces +-- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua._G.get_pio_status()}%* %y %p%% %l:%c' -- --- local current_data = vim.json.encode(_G.metadata) --- local current_hash = get_safe_hash(current_data) --- --- -- Only write if data actually changed --- if current_hash ~= last_saved_hash then --- local file = io.open(config_path, 'w') --- if file then --- file:write(current_data) --- file:close() --- last_saved_hash = current_hash +-- local M = {} +-- local last_saved_hash = '' +-- local config_path = vim.fn.getcwd() .. '/.project_config.json' -- --- if not quiet then --- vim.notify('Project settings synced to disk', vim.log.levels.INFO, { --- title = 'PlatformIO', --- render = 'compact', --- }) --- end --- end --- end +-- local function getHash(data) +-- return vim.fn.sha256(data) -- end -- --- -- 2. Robust Load Function (Startup) --- local default_metadata = { --- envs = {}, --- active_env = '', --- default_envs = {}, --- core_dir = '', --- packages_dir = '', --- platforms_dir = '', --- query_driver = '', --- cc_compiler = '', --- triplet = '', --- toolchain = '', --- sysroot = '', --- fallbackFlags = {}, --- } +-- -- local last_hash = '' +-- -- local dir_path = vim.uv.cwd() +-- -- local config_file = vim.fs.joinpath(dir_path, '.project_config.json') +-- -- +-- -- function M.sync_config(force_load) +-- -- if force_load then +-- -- if vim.fn.filereadable(config_file) == 1 then +-- -- local data = table.concat(vim.fn.readfile(config_file), '') +-- -- _G.metadata = vim.json.decode(data) +-- -- last_hash = getHash(data) +-- -- end +-- -- else +-- -- local current_data = vim.json.encode(_G.metadata) +-- -- local current_hash = getHash(current_data) +-- -- if current_hash ~= last_hash then +-- -- vim.fn.writefile({ current_data }, config_file) +-- -- last_hash = current_hash +-- -- end +-- -- end +-- -- end -- +-- -- 2. Self-Healing Load & Auto-Create -- function M.load_project_config() --- local path = vim.fn.getcwd() .. '/.project_config.json' -- local success = false -- --- if vim.fn.filereadable(path) == 1 then --- local file = io.open(path, 'r') +-- if vim.fn.filereadable(config_path) == 1 then +-- local file = io.open(config_path, 'r') -- if file then -- local content = file:read('*a') -- file:close() -- local ok, decoded = pcall(vim.json.decode, content) -- if ok and type(decoded) == 'table' then -- _G.metadata = decoded --- last_saved_hash = get_safe_hash(content) +-- last_saved_hash = getHash(content) -- success = true -- end -- end -- end -- --- -- If no file or failed to read, write defaults immediately +-- -- If file is missing or corrupted, initialize and force-save -- if not success then --- _G.metadata = vim.deepcopy(default_metadata) +-- -- Use the global table we initialized at the top -- local encoded = vim.json.encode(_G.metadata) --- local file = io.open(path, 'w') +-- local file = io.open(config_path, 'w') -- if file then -- file:write(encoded) -- file:close() --- last_saved_hash = get_safe_hash(encoded) +-- last_saved_hash = getHash(encoded) -- if vim.fn.filereadable('platformio.ini') == 1 then --- vim.notify('Initialized new project settings', vim.log.levels.INFO, { title = 'PlatformIO' }) +-- vim.notify('New project config created', vim.log.levels.INFO, { title = 'PlatformIO' }) -- end -- end -- end -- end -- --- -- 3. Environment Switcher UI +-- -- 3. Performance-Proof Save (Hash Check) +-- function M.save_project_config(quiet) +-- if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then +-- return +-- end +-- +-- local current_data = vim.json.encode(_G.metadata) +-- local current_hash = getHash(current_data) +-- +-- -- Only write if data actually changed since last load/save +-- if current_hash ~= last_saved_hash then +-- local file = io.open(config_path, 'w') +-- if file then +-- file:write(current_data) +-- file:close() +-- last_saved_hash = current_hash +-- +-- if not quiet then +-- vim.notify('Settings synced to disk', vim.log.levels.INFO, { +-- title = 'PlatformIO', +-- render = 'compact', +-- }) +-- end +-- end +-- end +-- end +-- +-- -- 4. Fixed Status Function (Fixes line 472 error) +-- function M.show_status() +-- -- Ensure we access the table, NOT call it +-- local meta = _G.metadata +-- local env = meta.active_env ~= '' and meta.active_env or 'None' +-- +-- vim.notify(string.format('Environment: %s\nTarget: %s', env, meta.triplet or 'Unknown'), vim.log.levels.INFO, { title = 'PlatformIO Status' }) +-- end +-- +-- local pio_group = vim.api.nvim_create_augroup('PioPersist', { clear = true }) +-- vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { +-- group = pio_group, +-- callback = function() +-- -- Pass 'true' to save silently in the background +-- M.save_project_config(true) +-- end, +-- desc = 'Automatically save PlatformIO project metadata', +-- }) +-- +-- -- 5. Environment Switcher UI -- function M.switch_env() +-- -- 1. Safety check for metadata -- if not _G.metadata.envs or next(_G.metadata.envs) == nil then --- vim.notify('No environments found. Run PlatformIO Refresh first.', vim.log.levels.WARN) +-- vim.notify('No environments found. Please refresh PlatformIO data.', vim.log.levels.WARN) -- return -- end -- +-- -- 2. Prepare the list of environments -- local options = vim.tbl_keys(_G.metadata.envs) -- table.sort(options) -- +-- -- 3. Open the selection UI -- vim.ui.select(options, { -- prompt = 'Select PlatformIO Environment:', -- format_item = function(item) --- local indicator = (item == _G.metadata.active_env) and '● ' or '○ ' --- return indicator .. item +-- local icon = (item == _G.metadata.active_env) and ' ' or '○ ' +-- return icon .. item -- end, -- }, function(choice) -- if choice then +-- -- Update active environment -- _G.metadata.active_env = choice --- -- Save immediately on user selection --- M.save_project_config(false) --- -- Force LSP to pick up new fallbackFlags/defines --- vim.cmd('LspRestart clangd') +-- +-- -- 4. Persist change to disk (silently) +-- M.save_project_config(true) +-- +-- -- 5. Notify the user with the new board info +-- local board = _G.metadata.envs[choice].board or 'unknown' +-- vim.notify(string.format('Switched to %s\nBoard: %s', choice, board), vim.log.levels.INFO, { title = 'PlatformIO' }) +-- +-- -- 6. RESTART LSP (Crucial for refreshing includes/defines) +-- -- We wrap in pcall in case clangd isn't actually running yet +-- +-- local pio_manager = require('platformio.pio_setup').pio_manager +-- pio_manager.refresh(function() +-- M.compile_commands() +-- local lsp_restart = require('platformio.tools').lsp_restart +-- lsp_restart('clangd') +-- end) +-- +-- pcall(function() +-- -- Force LSP to pick up new fallbackFlags/defines +-- local lsp_restart = require('platformio.lsp.tools').lsp_restart +-- lsp_restart() +-- end) -- end -- end) -- end -- +-- -- 6. Keybindings +-- -- Switch Environment +-- vim.keymap.set('n', '\\e', function() +-- M.switch_env() +-- end, { desc = 'Switch [E]nvironment' }) +-- +-- -- write +-- vim.keymap.set('n', '\\w', function() +-- M.save_project_config(false) +-- end, { desc = 'config [W]rite' }) +-- +-- -- Manual Status Check +-- vim.keymap.set('n', '\\s', function() +-- M.show_status() +-- end, { desc = 'config [S]tatus' }) +-- -- return M diff --git a/metadataolld.lua b/metadataolld.lua new file mode 100644 index 00000000..f89054d9 --- /dev/null +++ b/metadataolld.lua @@ -0,0 +1,133 @@ +-- -- Performance-proof: Uses guaranteed Vimscript sha256 via Lua bridge +-- local function get_safe_hash(data) +-- -- sha256 is built into Neovim's core and never nil +-- return vim.fn.sha256(data) +-- end +-- +-- local M = {} +-- local last_saved_hash = nil +-- local config_path = vim.fn.getcwd() .. '/.pioConfig.json' +-- +-- -- -- Global metadata initialization +-- -- _G.metadata = _G.metadata +-- -- or { +-- -- envs = {}, +-- -- active_env = '', +-- -- default_envs = {}, +-- -- core_dir = '', +-- -- packages_dir = '', +-- -- platforms_dir = '', +-- -- query_driver = '', +-- -- cc_compiler = '', +-- -- triplet = '', +-- -- toolchain = '', +-- -- sysroot = '', +-- -- fallbackFlags = {}, +-- -- } +-- +-- -- 1. Optimized Save Function +-- +-- function M.save_project_config(quiet) +-- if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then +-- return +-- end +-- +-- local current_data = vim.json.encode(_G.metadata) +-- local current_hash = get_safe_hash(current_data) +-- +-- -- Only write if data actually changed +-- if current_hash ~= last_saved_hash then +-- local file = io.open(config_path, 'w') +-- if file then +-- file:write(current_data) +-- file:close() +-- last_saved_hash = current_hash +-- +-- if not quiet then +-- vim.notify('Project settings synced to disk', vim.log.levels.INFO, { +-- title = 'PlatformIO', +-- render = 'compact', +-- }) +-- end +-- end +-- end +-- end +-- +-- -- 2. Robust Load Function (Startup) +-- local default_metadata = { +-- envs = {}, +-- active_env = '', +-- default_envs = {}, +-- core_dir = '', +-- packages_dir = '', +-- platforms_dir = '', +-- query_driver = '', +-- cc_compiler = '', +-- triplet = '', +-- toolchain = '', +-- sysroot = '', +-- fallbackFlags = {}, +-- } +-- +-- function M.load_project_config() +-- local path = vim.fn.getcwd() .. '/.project_config.json' +-- local success = false +-- +-- if vim.fn.filereadable(path) == 1 then +-- local file = io.open(path, 'r') +-- if file then +-- local content = file:read('*a') +-- file:close() +-- local ok, decoded = pcall(vim.json.decode, content) +-- if ok and type(decoded) == 'table' then +-- _G.metadata = decoded +-- last_saved_hash = get_safe_hash(content) +-- success = true +-- end +-- end +-- end +-- +-- -- If no file or failed to read, write defaults immediately +-- if not success then +-- _G.metadata = vim.deepcopy(default_metadata) +-- local encoded = vim.json.encode(_G.metadata) +-- local file = io.open(path, 'w') +-- if file then +-- file:write(encoded) +-- file:close() +-- last_saved_hash = get_safe_hash(encoded) +-- if vim.fn.filereadable('platformio.ini') == 1 then +-- vim.notify('Initialized new project settings', vim.log.levels.INFO, { title = 'PlatformIO' }) +-- end +-- end +-- end +-- end +-- +-- -- 3. Environment Switcher UI +-- function M.switch_env() +-- if not _G.metadata.envs or next(_G.metadata.envs) == nil then +-- vim.notify('No environments found. Run PlatformIO Refresh first.', vim.log.levels.WARN) +-- return +-- end +-- +-- local options = vim.tbl_keys(_G.metadata.envs) +-- table.sort(options) +-- +-- vim.ui.select(options, { +-- prompt = 'Select PlatformIO Environment:', +-- format_item = function(item) +-- local indicator = (item == _G.metadata.active_env) and '● ' or '○ ' +-- return indicator .. item +-- end, +-- }, function(choice) +-- if choice then +-- _G.metadata.active_env = choice +-- -- Save immediately on user selection +-- M.save_project_config(false) +-- -- Force LSP to pick up new fallbackFlags/defines +-- vim.cmd('LspRestart clangd') +-- end +-- end) +-- end +-- +-- return M From 8629637605d54525e8eb15a3501e3f9290ba5874 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 11:09:55 +0300 Subject: [PATCH 0786/1406] update --- lua/platformio/metadata.lua | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 509f43dd..3f2861d9 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -45,13 +45,15 @@ _G.metadata = setmetatable({}, { if key == 'cc_compiler' then vim.notify('Env: ' .. value, vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) pcall(function() - local LspRestart = require('platformio.utils.lsp').lsp_restart if _raw_metadata.dbTrigger then local dbFix = require('platformio.utils.pio').compile_commandsFix dbFix() _raw_metadata.dbTrigger = false + vim.notify('Env: dbTrigger', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) else + local LspRestart = require('platformio.utils.lsp').lsp_restart LspRestart('clangd') + vim.notify('Env: LspRestart', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) end end) end From 86fa1d25c9500577018e3ea322935ca08c6af1ea Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 11:15:58 +0300 Subject: [PATCH 0787/1406] update --- lua/platformio/utils/pio.lua | 250 +++++++++++++++++------------------ 1 file changed, 125 insertions(+), 125 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index d8bffcf5..f96b7d24 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -7,182 +7,182 @@ local lsp_restart = require('platformio.lsp.tools').lsp_restart ------------------------------------------------------ -- stylua: ignore -function M.compile_commandsFix() - local filename = vim.uv.cwd() .. '/compile_commands.json' - if vim.fn.filereadable(filename) == 0 then return end - - -- Atomic read using built-in Vim function - local content = table.concat(vim.fn.readfile(filename), "\n") - local ok, data = pcall(vim.json.decode, content) - if not ok or type(data) ~= 'table' then return end - - -- 1. Build Path Map (Scan toolchain) - local path_map = {} - local toolchain_bin = (_G.metadata and _G.metadata.toolchain or "") .. '/bin/*' - for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do - local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') - path_map[name] = full_path - end - - -- 2. Update Entries efficiently with string matching - local modified = false - for _, entry in ipairs(data) do - local cmd = entry.command or "" - local first_token = cmd:match("^%S+") -- Grab only the compiler driver - - -- Fix if it's a relative path (doesn't start with / or Drive letter) - if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then - local short_name = first_token:gsub('%.exe$', '') - if path_map[short_name] then - -- Replace only the first token to preserve arguments - entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) - modified = true - end - end - end - - -- 3. Save with Python formatting - if modified then - local json_str = vim.json.encode(data) - local formatted = vim.fn.system('python -m json.tool', json_str) - - if vim.v.shell_error == 0 then - -- Atomic write back to disk - vim.fn.writefile(vim.split(formatted, "\n"), filename) - vim.notify('compiledb: paths fixed', vim.log.levels.INFO) - else - vim.notify('PIO Fix: Python formatting failed', vim.log.levels.ERROR) - end - end - lsp_restart('clangd') - _G.metadata.isBusy = false -end - -- function M.compile_commandsFix() -- local filename = vim.uv.cwd() .. '/compile_commands.json' --- local content = vim.fn.readfile(filename) --- if #content == 0 then return end +-- if vim.fn.filereadable(filename) == 0 then return end -- --- local ok, data = pcall(vim.json.decode, table.concat(content, "\n")) +-- -- Atomic read using built-in Vim function +-- local content = table.concat(vim.fn.readfile(filename), "\n") +-- local ok, data = pcall(vim.json.decode, content) -- if not ok or type(data) ~= 'table' then return end -- -- -- 1. Build Path Map (Scan toolchain) -- local path_map = {} --- --- local pio_binaries = _G.metadata.query_driver or "/bin/*" --- -- local pio_binaries = (_G.metadata.toolchain or "") .. '/bin/*' --- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do +-- local toolchain_bin = (_G.metadata and _G.metadata.toolchain or "") .. '/bin/*' +-- for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do -- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') -- path_map[name] = full_path -- end -- --- -- 2. Update Entries +-- -- 2. Update Entries efficiently with string matching -- local modified = false -- for _, entry in ipairs(data) do -- local cmd = entry.command or "" --- local first_token = cmd:match("^%S+") -- Get first word before space +-- local first_token = cmd:match("^%S+") -- Grab only the compiler driver -- +-- -- Fix if it's a relative path (doesn't start with / or Drive letter) -- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then -- local short_name = first_token:gsub('%.exe$', '') -- if path_map[short_name] then --- -- Swap first token with full path safely +-- -- Replace only the first token to preserve arguments -- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) -- modified = true -- end -- end -- end -- --- -- 3. Save with Formatting +-- -- 3. Save with Python formatting -- if modified then -- local json_str = vim.json.encode(data) --- -- Use python to format, then write file -- local formatted = vim.fn.system('python -m json.tool', json_str) +-- -- if vim.v.shell_error == 0 then +-- -- Atomic write back to disk -- vim.fn.writefile(vim.split(formatted, "\n"), filename) -- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) +-- else +-- vim.notify('PIO Fix: Python formatting failed', vim.log.levels.ERROR) -- end -- end +-- lsp_restart('clangd') +-- _G.metadata.isBusy = false -- end -- function M.compile_commandsFix() -- local filename = vim.uv.cwd() .. '/compile_commands.json' --- local file = io.open(filename, 'r') --- if not file then return end --- --- -- read compile_commands.json file to content --- local content = file:read('*a') --- file:close() --- if not content or content == '' then return end +-- local content = vim.fn.readfile(filename) +-- if #content == 0 then return end -- --- -- JSON decoding content to data --- local ok, data = pcall(vim.json.decode, content) --- if not ok or type(data) ~= 'table' then --- vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) --- return --- end +-- local ok, data = pcall(vim.json.decode, table.concat(content, "\n")) +-- if not ok or type(data) ~= 'table' then return end -- --- -- print('PioFix0') --- -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path +-- -- 1. Build Path Map (Scan toolchain) -- local path_map = {} --- local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') --- if pio_home then --- -- Recursively find all binaries in PIO packages --- local pio_packages = _G.metadata.toolchain .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' --- local found_binaries = vim.fn.glob(pio_packages, false, true) -- --- for _, full_path in ipairs(found_binaries) do --- -- Extract filename (e.g., riscv32-esp-elf-gcc) --- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') --- path_map[name] = full_path --- -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) --- end +-- local pio_binaries = _G.metadata.query_driver or "/bin/*" +-- -- local pio_binaries = (_G.metadata.toolchain or "") .. '/bin/*' +-- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do +-- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') +-- path_map[name] = full_path -- end -- --- -- PHASE 2: Update JSON using the Map --- local modified = 0 +-- -- 2. Update Entries +-- local modified = false -- for _, entry in ipairs(data) do --- if type(entry.command) == 'string' then --- local cmd_parts = vim.split(entry.command, ' ') --- local first_token = cmd_parts[1] --- if first_token then --- -- Check if it's already a short name (not an absolute path) --- local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') --- if not is_abs then --- local short_name = first_token:gsub('%.exe$', '') --- -- print('PioFix2: short_name=' .. short_name) --- -- Direct Query: Does this name exist in our discovered list? --- if path_map[short_name] then --- cmd_parts[1] = path_map[short_name] --- -- print('PioFix3: full_name=' .. cmd_parts[1]) --- entry.command = table.concat(cmd_parts, ' ') --- modified = modified + 1 --- end --- end +-- local cmd = entry.command or "" +-- local first_token = cmd:match("^%S+") -- Get first word before space +-- +-- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then +-- local short_name = first_token:gsub('%.exe$', '') +-- if path_map[short_name] then +-- -- Swap first token with full path safely +-- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) +-- modified = true -- end -- end -- end -- --- -- PHASE 3: Save and Refresh --- -- Safe JSON encoding --- if modified > 0 then --- local out_file = io.open(filename, 'w') --- if out_file then --- local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) --- if encode_ok and json_str then --- -- 1. Format the string using python's json.tool --- -- The second argument to vim.fn.system() is the "stdin" passed to the command --- local formatted_json = vim.fn.system('python -m json.tool', json_str) --- --- -- out_file:write(json_str) --- out_file:write(formatted_json) --- out_file:close() --- vim.notify('compiledb: fixed', vim.log.levels.INFO) --- -- lsp_restart('clangd') --- end +-- -- 3. Save with Formatting +-- if modified then +-- local json_str = vim.json.encode(data) +-- -- Use python to format, then write file +-- local formatted = vim.fn.system('python -m json.tool', json_str) +-- if vim.v.shell_error == 0 then +-- vim.fn.writefile(vim.split(formatted, "\n"), filename) +-- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) -- end -- end -- end +function M.compile_commandsFix() + local filename = vim.uv.cwd() .. '/compile_commands.json' + local file = io.open(filename, 'r') + if not file then return end + + -- read compile_commands.json file to content + local content = file:read('*a') + file:close() + if not content or content == '' then return end + + -- JSON decoding content to data + local ok, data = pcall(vim.json.decode, content) + if not ok or type(data) ~= 'table' then + vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) + return + end + + -- print('PioFix0') + -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path + local path_map = {} + local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') + if pio_home then + -- Recursively find all binaries in PIO packages + local pio_packages = _G.metadata.toolchain .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' + local found_binaries = vim.fn.glob(pio_packages, false, true) + + for _, full_path in ipairs(found_binaries) do + -- Extract filename (e.g., riscv32-esp-elf-gcc) + local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') + path_map[name] = full_path + -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) + end + end + + -- PHASE 2: Update JSON using the Map + local modified = 0 + for _, entry in ipairs(data) do + if type(entry.command) == 'string' then + local cmd_parts = vim.split(entry.command, ' ') + local first_token = cmd_parts[1] + if first_token then + -- Check if it's already a short name (not an absolute path) + local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') + if not is_abs then + local short_name = first_token:gsub('%.exe$', '') + -- print('PioFix2: short_name=' .. short_name) + -- Direct Query: Does this name exist in our discovered list? + if path_map[short_name] then + cmd_parts[1] = path_map[short_name] + -- print('PioFix3: full_name=' .. cmd_parts[1]) + entry.command = table.concat(cmd_parts, ' ') + modified = modified + 1 + end + end + end + end + end + + -- PHASE 3: Save and Refresh + -- Safe JSON encoding + if modified > 0 then + local out_file = io.open(filename, 'w') + if out_file then + local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) + if encode_ok and json_str then + -- 1. Format the string using python's json.tool + -- The second argument to vim.fn.system() is the "stdin" passed to the command + local formatted_json = vim.fn.system('python -m json.tool', json_str) + + -- out_file:write(json_str) + out_file:write(formatted_json) + out_file:close() + vim.notify('compiledb: fixed', vim.log.levels.INFO) + -- lsp_restart('clangd') + end + end + end +end + ------------------------------------------------------ -- INFO: ToggleTerminal commands sequencer From 35070f332701933f9f9a5e74265aaa03aaa159dd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 11:22:04 +0300 Subject: [PATCH 0788/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f96b7d24..853bce2f 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -121,7 +121,7 @@ function M.compile_commandsFix() return end - -- print('PioFix0') + print('PioFix0') -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path local path_map = {} local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') From 626046b07591c64a9dbd7a756b91c385748d1e44 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 11:31:33 +0300 Subject: [PATCH 0789/1406] update --- lua/platformio/lsp/tools.lua | 112 +++++++++++++++++------------------ lua/platformio/pio_setup.lua | 56 ++++++++++++++++++ 2 files changed, 112 insertions(+), 56 deletions(-) diff --git a/lua/platformio/lsp/tools.lua b/lua/platformio/lsp/tools.lua index 4fe55a22..f7165192 100644 --- a/lua/platformio/lsp/tools.lua +++ b/lua/platformio/lsp/tools.lua @@ -1,60 +1,60 @@ local M = {} --- INFO: --- ============================================================================= --- UNIVERSAL TOOLCHAIN DETECTION --- ============================================================================= ---- stylua: ignore -function M.get_sysroot_triplet(cc_compiler) - local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') - - -- Early exit if path is nil or not a directory - if not bin_path or vim.fn.isdirectory(bin_path) == 0 then - return nil - end - - -- Normalize backslashes to forward slashes for cross-platform consistency - bin_path = bin_path:gsub('\\', '/') - local files = vim.fn.readdir(bin_path) - local triplet = nil - - -- Loop through files to find the compiler and extract the triplet - for _, name in ipairs(files) do - -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ - local match = name:match('^(.*)%-g[c%+][c%+]') - if match then - triplet = match - break - end - end - - -- Return nil if no compiler was found in the bin directory - if not triplet then - return nil - end - - -- toolchain_root is the parent of the 'bin' folder - local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') - -- sysroot folder is expected to have the same name as the triplet - local sysroot = toolchain_root .. '/' .. triplet - local query_driver = bin_path .. '/' .. triplet .. '-*' - - -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) - -- Only return data if the sysroot folder actually exists on disk - if vim.fn.isdirectory(sysroot) == 1 then - _G.metadata.triplet = triplet - _G.metadata.sysroot = sysroot - _G.metadata.toolchain = toolchain_root - _G.metadata.query_driver = query_driver - return { - triplet = triplet, - sysroot = sysroot, - toolchain_root = toolchain_root, - query_driver = query_driver, - } - end - return nil -end +-- -- INFO: +-- -- ============================================================================= +-- -- UNIVERSAL TOOLCHAIN DETECTION +-- -- ============================================================================= +-- --- stylua: ignore +-- function M.get_sysroot_triplet(cc_compiler) +-- local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') +-- +-- -- Early exit if path is nil or not a directory +-- if not bin_path or vim.fn.isdirectory(bin_path) == 0 then +-- return nil +-- end +-- +-- -- Normalize backslashes to forward slashes for cross-platform consistency +-- bin_path = bin_path:gsub('\\', '/') +-- local files = vim.fn.readdir(bin_path) +-- local triplet = nil +-- +-- -- Loop through files to find the compiler and extract the triplet +-- for _, name in ipairs(files) do +-- -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ +-- local match = name:match('^(.*)%-g[c%+][c%+]') +-- if match then +-- triplet = match +-- break +-- end +-- end +-- +-- -- Return nil if no compiler was found in the bin directory +-- if not triplet then +-- return nil +-- end +-- +-- -- toolchain_root is the parent of the 'bin' folder +-- local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') +-- -- sysroot folder is expected to have the same name as the triplet +-- local sysroot = toolchain_root .. '/' .. triplet +-- local query_driver = bin_path .. '/' .. triplet .. '-*' +-- +-- -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) +-- -- Only return data if the sysroot folder actually exists on disk +-- if vim.fn.isdirectory(sysroot) == 1 then +-- _G.metadata.triplet = triplet +-- _G.metadata.sysroot = sysroot +-- _G.metadata.toolchain = toolchain_root +-- _G.metadata.query_driver = query_driver +-- return { +-- triplet = triplet, +-- sysroot = sysroot, +-- toolchain_root = toolchain_root, +-- query_driver = query_driver, +-- } +-- end +-- return nil +-- end --- stylua: ignore function M.lsp_restart(name) @@ -62,7 +62,7 @@ function M.lsp_restart(name) vim.notify('LSP restart.', vim.log.levels.WARN) -- local status, data = pcall(M.get_sysroot_triplet, _G.metadata.cc_compiler) - pcall(M.get_sysroot_triplet, _G.metadata.cc_compiler) + -- pcall(M.get_sysroot_triplet, _G.metadata.cc_compiler) -- if status and data and data.triplet and data.triplet ~= '' then -- _G.metadata.triplet = data.triplet -- _G.metadata.sysroot = data.sysroot diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 64b1a991..f5e7b7e2 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -5,6 +5,61 @@ local lsp_restart = require('platformio.lsp.tools').lsp_restart local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -- local debounce_timer = vim.uv.new_timer() +-- INFO: +-- ============================================================================= +-- UNIVERSAL TOOLCHAIN DETECTION +-- ============================================================================= +--- stylua: ignore +function M.get_sysroot_triplet(cc_compiler) + local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') + + -- Early exit if path is nil or not a directory + if not bin_path or vim.fn.isdirectory(bin_path) == 0 then + return nil + end + + -- Normalize backslashes to forward slashes for cross-platform consistency + bin_path = bin_path:gsub('\\', '/') + local files = vim.fn.readdir(bin_path) + local triplet = nil + + -- Loop through files to find the compiler and extract the triplet + for _, name in ipairs(files) do + -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ + local match = name:match('^(.*)%-g[c%+][c%+]') + if match then + triplet = match + break + end + end + + -- Return nil if no compiler was found in the bin directory + if not triplet then + return nil + end + + -- toolchain_root is the parent of the 'bin' folder + local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') + -- sysroot folder is expected to have the same name as the triplet + local sysroot = toolchain_root .. '/' .. triplet + local query_driver = bin_path .. '/' .. triplet .. '-*' + + -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) + -- Only return data if the sysroot folder actually exists on disk + if vim.fn.isdirectory(sysroot) == 1 then + _G.metadata.triplet = triplet + _G.metadata.sysroot = sysroot + _G.metadata.toolchain = toolchain_root + _G.metadata.query_driver = query_driver + return { + triplet = triplet, + sysroot = sysroot, + toolchain_root = toolchain_root, + query_driver = query_driver, + } + end + return nil +end -- INFO: 1. The Core PIO Manager & Generic Extractor @@ -103,6 +158,7 @@ M.pio_manager = (function() _G.metadata.cc_compiler = misc.normalize_path(data.cc_path) or '' _G.metadata.fallbackFlags = fallbackFlags + pcall(M.get_sysroot_triplet, _G.metadata.cc_compiler) -- print(vim.inspect(_G.metadata)) -- if callback then -- vim.schedule(function() From 31587cc11f461c545bcad22e3d46ef6ae2ec64d9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 11:49:51 +0300 Subject: [PATCH 0790/1406] update --- lua/platformio/metadata.lua | 7 +- lua/platformio/pio_setup.lua | 2 +- lua/platformio/utils/pio.lua | 250 +++++++++++++++++------------------ 3 files changed, 130 insertions(+), 129 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 3f2861d9..1d18822b 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -14,6 +14,7 @@ local last_saved_hash = '' local config_path = vim.fs.joinpath(vim.uv.cwd(), '.project_config.json') local _raw_metadata = { + is_busy = false, envs = {}, active_env = '', default_envs = {}, @@ -23,7 +24,7 @@ local _raw_metadata = { query_driver = '', cc_compiler = '', triplet = '', - toolchain = '', + toolchain_root = '', sysroot = '', fallbackFlags = {}, dbTrigger = false, @@ -42,14 +43,14 @@ _G.metadata = setmetatable({}, { -- Trigger background actions vim.schedule(function() M.save_project_config(true) - if key == 'cc_compiler' then + if key == 'toolchain_root' then vim.notify('Env: ' .. value, vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) pcall(function() if _raw_metadata.dbTrigger then + vim.notify('Env: dbTrigger', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) local dbFix = require('platformio.utils.pio').compile_commandsFix dbFix() _raw_metadata.dbTrigger = false - vim.notify('Env: dbTrigger', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) else local LspRestart = require('platformio.utils.lsp').lsp_restart LspRestart('clangd') diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index f5e7b7e2..b5367de1 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,7 +1,7 @@ M = {} local misc = require('platformio.utils.misc') -local lsp_restart = require('platformio.lsp.tools').lsp_restart +-- local lsp_restart = require('platformio.lsp.tools').lsp_restart local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen -- local debounce_timer = vim.uv.new_timer() diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 853bce2f..47527bf9 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -7,182 +7,182 @@ local lsp_restart = require('platformio.lsp.tools').lsp_restart ------------------------------------------------------ -- stylua: ignore +function M.compile_commandsFix() + local filename = vim.uv.cwd() .. '/compile_commands.json' + if vim.fn.filereadable(filename) == 0 then return end + + -- Atomic read using built-in Vim function + local content = table.concat(vim.fn.readfile(filename), "\n") + local ok, data = pcall(vim.json.decode, content) + if not ok or type(data) ~= 'table' then return end + + -- 1. Build Path Map (Scan toolchain) + local path_map = {} + local toolchain_bin = (_G.metadata and _G.metadata.toolchain or "") .. '/bin/*' + for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do + local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') + path_map[name] = full_path + end + + -- 2. Update Entries efficiently with string matching + local modified = false + for _, entry in ipairs(data) do + local cmd = entry.command or "" + local first_token = cmd:match("^%S+") -- Grab only the compiler driver + + -- Fix if it's a relative path (doesn't start with / or Drive letter) + if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then + local short_name = first_token:gsub('%.exe$', '') + if path_map[short_name] then + -- Replace only the first token to preserve arguments + entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) + modified = true + end + end + end + + -- 3. Save with Python formatting + if modified then + local json_str = vim.json.encode(data) + local formatted = vim.fn.system('python -m json.tool', json_str) + + if vim.v.shell_error == 0 then + -- Atomic write back to disk + vim.fn.writefile(vim.split(formatted, "\n"), filename) + vim.notify('compiledb: paths fixed', vim.log.levels.INFO) + else + vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) + end + end + lsp_restart('clangd') + _G.metadata.isBusy = false +end + -- function M.compile_commandsFix() -- local filename = vim.uv.cwd() .. '/compile_commands.json' --- if vim.fn.filereadable(filename) == 0 then return end +-- local content = vim.fn.readfile(filename) +-- if #content == 0 then return end -- --- -- Atomic read using built-in Vim function --- local content = table.concat(vim.fn.readfile(filename), "\n") --- local ok, data = pcall(vim.json.decode, content) +-- local ok, data = pcall(vim.json.decode, table.concat(content, "\n")) -- if not ok or type(data) ~= 'table' then return end -- -- -- 1. Build Path Map (Scan toolchain) -- local path_map = {} --- local toolchain_bin = (_G.metadata and _G.metadata.toolchain or "") .. '/bin/*' --- for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do +-- +-- local pio_binaries = _G.metadata.query_driver or "/bin/*" +-- -- local pio_binaries = (_G.metadata.toolchain or "") .. '/bin/*' +-- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do -- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') -- path_map[name] = full_path -- end -- --- -- 2. Update Entries efficiently with string matching +-- -- 2. Update Entries -- local modified = false -- for _, entry in ipairs(data) do -- local cmd = entry.command or "" --- local first_token = cmd:match("^%S+") -- Grab only the compiler driver +-- local first_token = cmd:match("^%S+") -- Get first word before space -- --- -- Fix if it's a relative path (doesn't start with / or Drive letter) -- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then -- local short_name = first_token:gsub('%.exe$', '') -- if path_map[short_name] then --- -- Replace only the first token to preserve arguments +-- -- Swap first token with full path safely -- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) -- modified = true -- end -- end -- end -- --- -- 3. Save with Python formatting +-- -- 3. Save with Formatting -- if modified then -- local json_str = vim.json.encode(data) +-- -- Use python to format, then write file -- local formatted = vim.fn.system('python -m json.tool', json_str) --- -- if vim.v.shell_error == 0 then --- -- Atomic write back to disk -- vim.fn.writefile(vim.split(formatted, "\n"), filename) -- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) --- else --- vim.notify('PIO Fix: Python formatting failed', vim.log.levels.ERROR) -- end -- end --- lsp_restart('clangd') --- _G.metadata.isBusy = false -- end -- function M.compile_commandsFix() -- local filename = vim.uv.cwd() .. '/compile_commands.json' --- local content = vim.fn.readfile(filename) --- if #content == 0 then return end +-- local file = io.open(filename, 'r') +-- if not file then return end -- --- local ok, data = pcall(vim.json.decode, table.concat(content, "\n")) --- if not ok or type(data) ~= 'table' then return end +-- -- read compile_commands.json file to content +-- local content = file:read('*a') +-- file:close() +-- if not content or content == '' then return end -- --- -- 1. Build Path Map (Scan toolchain) +-- -- JSON decoding content to data +-- local ok, data = pcall(vim.json.decode, content) +-- if not ok or type(data) ~= 'table' then +-- vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) +-- return +-- end +-- +-- print('PioFix0') +-- -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path -- local path_map = {} +-- local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') +-- if pio_home then +-- -- Recursively find all binaries in PIO packages +-- local pio_packages = _G.metadata.toolchain .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' +-- local found_binaries = vim.fn.glob(pio_packages, false, true) -- --- local pio_binaries = _G.metadata.query_driver or "/bin/*" --- -- local pio_binaries = (_G.metadata.toolchain or "") .. '/bin/*' --- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do --- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') --- path_map[name] = full_path +-- for _, full_path in ipairs(found_binaries) do +-- -- Extract filename (e.g., riscv32-esp-elf-gcc) +-- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') +-- path_map[name] = full_path +-- -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) +-- end -- end -- --- -- 2. Update Entries --- local modified = false +-- -- PHASE 2: Update JSON using the Map +-- local modified = 0 -- for _, entry in ipairs(data) do --- local cmd = entry.command or "" --- local first_token = cmd:match("^%S+") -- Get first word before space --- --- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then --- local short_name = first_token:gsub('%.exe$', '') --- if path_map[short_name] then --- -- Swap first token with full path safely --- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) --- modified = true +-- if type(entry.command) == 'string' then +-- local cmd_parts = vim.split(entry.command, ' ') +-- local first_token = cmd_parts[1] +-- if first_token then +-- -- Check if it's already a short name (not an absolute path) +-- local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') +-- if not is_abs then +-- local short_name = first_token:gsub('%.exe$', '') +-- -- print('PioFix2: short_name=' .. short_name) +-- -- Direct Query: Does this name exist in our discovered list? +-- if path_map[short_name] then +-- cmd_parts[1] = path_map[short_name] +-- -- print('PioFix3: full_name=' .. cmd_parts[1]) +-- entry.command = table.concat(cmd_parts, ' ') +-- modified = modified + 1 +-- end +-- end -- end -- end -- end -- --- -- 3. Save with Formatting --- if modified then --- local json_str = vim.json.encode(data) --- -- Use python to format, then write file --- local formatted = vim.fn.system('python -m json.tool', json_str) --- if vim.v.shell_error == 0 then --- vim.fn.writefile(vim.split(formatted, "\n"), filename) --- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) +-- -- PHASE 3: Save and Refresh +-- -- Safe JSON encoding +-- if modified > 0 then +-- local out_file = io.open(filename, 'w') +-- if out_file then +-- local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) +-- if encode_ok and json_str then +-- -- 1. Format the string using python's json.tool +-- -- The second argument to vim.fn.system() is the "stdin" passed to the command +-- local formatted_json = vim.fn.system('python -m json.tool', json_str) +-- +-- -- out_file:write(json_str) +-- out_file:write(formatted_json) +-- out_file:close() +-- vim.notify('compiledb: fixed', vim.log.levels.INFO) +-- -- lsp_restart('clangd') +-- end -- end -- end -- end -function M.compile_commandsFix() - local filename = vim.uv.cwd() .. '/compile_commands.json' - local file = io.open(filename, 'r') - if not file then return end - - -- read compile_commands.json file to content - local content = file:read('*a') - file:close() - if not content or content == '' then return end - - -- JSON decoding content to data - local ok, data = pcall(vim.json.decode, content) - if not ok or type(data) ~= 'table' then - vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) - return - end - - print('PioFix0') - -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path - local path_map = {} - local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') - if pio_home then - -- Recursively find all binaries in PIO packages - local pio_packages = _G.metadata.toolchain .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' - local found_binaries = vim.fn.glob(pio_packages, false, true) - - for _, full_path in ipairs(found_binaries) do - -- Extract filename (e.g., riscv32-esp-elf-gcc) - local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') - path_map[name] = full_path - -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) - end - end - - -- PHASE 2: Update JSON using the Map - local modified = 0 - for _, entry in ipairs(data) do - if type(entry.command) == 'string' then - local cmd_parts = vim.split(entry.command, ' ') - local first_token = cmd_parts[1] - if first_token then - -- Check if it's already a short name (not an absolute path) - local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') - if not is_abs then - local short_name = first_token:gsub('%.exe$', '') - -- print('PioFix2: short_name=' .. short_name) - -- Direct Query: Does this name exist in our discovered list? - if path_map[short_name] then - cmd_parts[1] = path_map[short_name] - -- print('PioFix3: full_name=' .. cmd_parts[1]) - entry.command = table.concat(cmd_parts, ' ') - modified = modified + 1 - end - end - end - end - end - - -- PHASE 3: Save and Refresh - -- Safe JSON encoding - if modified > 0 then - local out_file = io.open(filename, 'w') - if out_file then - local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) - if encode_ok and json_str then - -- 1. Format the string using python's json.tool - -- The second argument to vim.fn.system() is the "stdin" passed to the command - local formatted_json = vim.fn.system('python -m json.tool', json_str) - - -- out_file:write(json_str) - out_file:write(formatted_json) - out_file:close() - vim.notify('compiledb: fixed', vim.log.levels.INFO) - -- lsp_restart('clangd') - end - end - end -end - ------------------------------------------------------ -- INFO: ToggleTerminal commands sequencer From 6532aa4252ecc292ccd484f91059855d7308ba02 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 11:54:47 +0300 Subject: [PATCH 0791/1406] update --- lua/platformio/utils/pio.lua | 251 ++++++++++++++++++----------------- 1 file changed, 126 insertions(+), 125 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 47527bf9..841d8ad4 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -7,182 +7,183 @@ local lsp_restart = require('platformio.lsp.tools').lsp_restart ------------------------------------------------------ -- stylua: ignore -function M.compile_commandsFix() - local filename = vim.uv.cwd() .. '/compile_commands.json' - if vim.fn.filereadable(filename) == 0 then return end - - -- Atomic read using built-in Vim function - local content = table.concat(vim.fn.readfile(filename), "\n") - local ok, data = pcall(vim.json.decode, content) - if not ok or type(data) ~= 'table' then return end - - -- 1. Build Path Map (Scan toolchain) - local path_map = {} - local toolchain_bin = (_G.metadata and _G.metadata.toolchain or "") .. '/bin/*' - for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do - local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') - path_map[name] = full_path - end - - -- 2. Update Entries efficiently with string matching - local modified = false - for _, entry in ipairs(data) do - local cmd = entry.command or "" - local first_token = cmd:match("^%S+") -- Grab only the compiler driver - - -- Fix if it's a relative path (doesn't start with / or Drive letter) - if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then - local short_name = first_token:gsub('%.exe$', '') - if path_map[short_name] then - -- Replace only the first token to preserve arguments - entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) - modified = true - end - end - end - - -- 3. Save with Python formatting - if modified then - local json_str = vim.json.encode(data) - local formatted = vim.fn.system('python -m json.tool', json_str) - - if vim.v.shell_error == 0 then - -- Atomic write back to disk - vim.fn.writefile(vim.split(formatted, "\n"), filename) - vim.notify('compiledb: paths fixed', vim.log.levels.INFO) - else - vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) - end - end - lsp_restart('clangd') - _G.metadata.isBusy = false -end - -- function M.compile_commandsFix() -- local filename = vim.uv.cwd() .. '/compile_commands.json' --- local content = vim.fn.readfile(filename) --- if #content == 0 then return end +-- if vim.fn.filereadable(filename) == 0 then return end -- --- local ok, data = pcall(vim.json.decode, table.concat(content, "\n")) +-- -- Atomic read using built-in Vim function +-- local content = table.concat(vim.fn.readfile(filename), "\n") +-- local ok, data = pcall(vim.json.decode, content) -- if not ok or type(data) ~= 'table' then return end -- -- -- 1. Build Path Map (Scan toolchain) -- local path_map = {} --- --- local pio_binaries = _G.metadata.query_driver or "/bin/*" --- -- local pio_binaries = (_G.metadata.toolchain or "") .. '/bin/*' --- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do +-- local toolchain_bin = (_G.metadata and _G.metadata.toolchain or "") .. '/bin/*' +-- for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do -- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') -- path_map[name] = full_path -- end -- --- -- 2. Update Entries +-- -- 2. Update Entries efficiently with string matching -- local modified = false -- for _, entry in ipairs(data) do -- local cmd = entry.command or "" --- local first_token = cmd:match("^%S+") -- Get first word before space +-- local first_token = cmd:match("^%S+") -- Grab only the compiler driver -- +-- -- Fix if it's a relative path (doesn't start with / or Drive letter) -- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then -- local short_name = first_token:gsub('%.exe$', '') -- if path_map[short_name] then --- -- Swap first token with full path safely +-- -- Replace only the first token to preserve arguments -- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) -- modified = true -- end -- end -- end -- --- -- 3. Save with Formatting +-- -- 3. Save with Python formatting -- if modified then -- local json_str = vim.json.encode(data) --- -- Use python to format, then write file -- local formatted = vim.fn.system('python -m json.tool', json_str) +-- -- if vim.v.shell_error == 0 then +-- -- Atomic write back to disk -- vim.fn.writefile(vim.split(formatted, "\n"), filename) -- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) +-- else +-- vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) -- end -- end +-- lsp_restart('clangd') +-- _G.metadata.isBusy = false -- end -- function M.compile_commandsFix() -- local filename = vim.uv.cwd() .. '/compile_commands.json' --- local file = io.open(filename, 'r') --- if not file then return end --- --- -- read compile_commands.json file to content --- local content = file:read('*a') --- file:close() --- if not content or content == '' then return end +-- local content = vim.fn.readfile(filename) +-- if #content == 0 then return end -- --- -- JSON decoding content to data --- local ok, data = pcall(vim.json.decode, content) --- if not ok or type(data) ~= 'table' then --- vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) --- return --- end +-- local ok, data = pcall(vim.json.decode, table.concat(content, "\n")) +-- if not ok or type(data) ~= 'table' then return end -- --- print('PioFix0') --- -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path +-- -- 1. Build Path Map (Scan toolchain) -- local path_map = {} --- local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') --- if pio_home then --- -- Recursively find all binaries in PIO packages --- local pio_packages = _G.metadata.toolchain .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' --- local found_binaries = vim.fn.glob(pio_packages, false, true) -- --- for _, full_path in ipairs(found_binaries) do --- -- Extract filename (e.g., riscv32-esp-elf-gcc) --- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') --- path_map[name] = full_path --- -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) --- end +-- local pio_binaries = _G.metadata.query_driver or "/bin/*" +-- -- local pio_binaries = (_G.metadata.toolchain or "") .. '/bin/*' +-- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do +-- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') +-- path_map[name] = full_path -- end -- --- -- PHASE 2: Update JSON using the Map --- local modified = 0 +-- -- 2. Update Entries +-- local modified = false -- for _, entry in ipairs(data) do --- if type(entry.command) == 'string' then --- local cmd_parts = vim.split(entry.command, ' ') --- local first_token = cmd_parts[1] --- if first_token then --- -- Check if it's already a short name (not an absolute path) --- local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') --- if not is_abs then --- local short_name = first_token:gsub('%.exe$', '') --- -- print('PioFix2: short_name=' .. short_name) --- -- Direct Query: Does this name exist in our discovered list? --- if path_map[short_name] then --- cmd_parts[1] = path_map[short_name] --- -- print('PioFix3: full_name=' .. cmd_parts[1]) --- entry.command = table.concat(cmd_parts, ' ') --- modified = modified + 1 --- end --- end +-- local cmd = entry.command or "" +-- local first_token = cmd:match("^%S+") -- Get first word before space +-- +-- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then +-- local short_name = first_token:gsub('%.exe$', '') +-- if path_map[short_name] then +-- -- Swap first token with full path safely +-- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) +-- modified = true -- end -- end -- end -- --- -- PHASE 3: Save and Refresh --- -- Safe JSON encoding --- if modified > 0 then --- local out_file = io.open(filename, 'w') --- if out_file then --- local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) --- if encode_ok and json_str then --- -- 1. Format the string using python's json.tool --- -- The second argument to vim.fn.system() is the "stdin" passed to the command --- local formatted_json = vim.fn.system('python -m json.tool', json_str) --- --- -- out_file:write(json_str) --- out_file:write(formatted_json) --- out_file:close() --- vim.notify('compiledb: fixed', vim.log.levels.INFO) --- -- lsp_restart('clangd') --- end +-- -- 3. Save with Formatting +-- if modified then +-- local json_str = vim.json.encode(data) +-- -- Use python to format, then write file +-- local formatted = vim.fn.system('python -m json.tool', json_str) +-- if vim.v.shell_error == 0 then +-- vim.fn.writefile(vim.split(formatted, "\n"), filename) +-- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) -- end -- end -- end +function M.compile_commandsFix() + local filename = vim.uv.cwd() .. '/compile_commands.json' + local file = io.open(filename, 'r') + if not file then return end + + -- read compile_commands.json file to content + local content = file:read('*a') + file:close() + if not content or content == '' then return end + + -- JSON decoding content to data + local ok, data = pcall(vim.json.decode, content) + if not ok or type(data) ~= 'table' then + vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) + return + end + + print('PioFix0') + -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path + local path_map = {} + local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') + if pio_home then + -- Recursively find all binaries in PIO packages + local pio_packages = _G.metadata.toolchain .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' + local found_binaries = vim.fn.glob(pio_packages, false, true) + + for _, full_path in ipairs(found_binaries) do + -- Extract filename (e.g., riscv32-esp-elf-gcc) + local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') + path_map[name] = full_path + -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) + end + end + + -- PHASE 2: Update JSON using the Map + local modified = 0 + for _, entry in ipairs(data) do + if type(entry.command) == 'string' then + local cmd_parts = vim.split(entry.command, ' ') + local first_token = cmd_parts[1] + if first_token then + -- Check if it's already a short name (not an absolute path) + local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') + if not is_abs then + local short_name = first_token:gsub('%.exe$', '') + -- print('PioFix2: short_name=' .. short_name) + -- Direct Query: Does this name exist in our discovered list? + if path_map[short_name] then + cmd_parts[1] = path_map[short_name] + -- print('PioFix3: full_name=' .. cmd_parts[1]) + entry.command = table.concat(cmd_parts, ' ') + modified = modified + 1 + end + end + end + end + end + + -- PHASE 3: Save and Refresh + -- Safe JSON encoding + if modified > 0 then + local out_file = io.open(filename, 'w') + if out_file then + local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) + if encode_ok and json_str then + -- 1. Format the string using python's json.tool + -- The second argument to vim.fn.system() is the "stdin" passed to the command + local formatted_json = vim.fn.system('python -m json.tool', json_str) + + -- out_file:write(json_str) + out_file:write(formatted_json) + out_file:close() + vim.notify('compiledb: fixed', vim.log.levels.INFO) + lsp_restart('clangd') + _G.metadata.isBusy = false + end + end + end +end + ------------------------------------------------------ -- INFO: ToggleTerminal commands sequencer From 4790fdf2bc95693628279d7b2d4735bf22786344 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 12:23:17 +0300 Subject: [PATCH 0792/1406] update --- lua/platformio/archived/pio_setup.lua | 2 +- lua/platformio/lsp/clangd.lua | 11 ----------- lua/platformio/lsp/tools.lua | 4 ++-- lua/platformio/pio_setup.lua | 2 +- metadata.lua | 2 +- metadataolld.lua | 4 ++-- pio_setupold.lua | 2 +- 7 files changed, 8 insertions(+), 19 deletions(-) diff --git a/lua/platformio/archived/pio_setup.lua b/lua/platformio/archived/pio_setup.lua index 05203705..61243a9e 100644 --- a/lua/platformio/archived/pio_setup.lua +++ b/lua/platformio/archived/pio_setup.lua @@ -430,7 +430,7 @@ -- _G.metadata.triplet = data.triplet -- _G.metadata.sysroot = data.sysroot -- _G.metadata.query_driver = data.query_driver --- _G.metadata.toolchain = data.toolchain_root +-- _G.metadata.toolchain_root = data.toolchain_root -- end -- -- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua index 0372c60c..abefff28 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -115,17 +115,6 @@ function _G.get_clangd_config() -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) q_driver = _G.metadata.query_driver -- use with "--query-driver=%s" - -- q_driver = '--query-driver=' .. _G.metadata.query_driver -- use with %q - -- q_driver = string.format([['--query-driver=%s']], _G.metadata.query_driver) -- use with %s - -- q_driver = '' -- use with %s ,not to use --query-driver - - -- 2.1 Add it to the PATH for this Neovim session - -- local pio_toolchain = _G.metadata.toolchain .. '/bin' - -- local current_path = vim.env.PATH - -- if not current_path:find(pio_toolchain, 1, true) then - -- local sep = (vim.fn.has("win32") == 1 and ";" or ":") - -- vim.env.PATH = pio_toolchain .. sep .. current_path - -- end end end diff --git a/lua/platformio/lsp/tools.lua b/lua/platformio/lsp/tools.lua index f7165192..391b6767 100644 --- a/lua/platformio/lsp/tools.lua +++ b/lua/platformio/lsp/tools.lua @@ -44,7 +44,7 @@ local M = {} -- if vim.fn.isdirectory(sysroot) == 1 then -- _G.metadata.triplet = triplet -- _G.metadata.sysroot = sysroot --- _G.metadata.toolchain = toolchain_root +-- _G.metadata.toolchain_root = toolchain_root -- _G.metadata.query_driver = query_driver -- return { -- triplet = triplet, @@ -67,7 +67,7 @@ function M.lsp_restart(name) -- _G.metadata.triplet = data.triplet -- _G.metadata.sysroot = data.sysroot -- _G.metadata.query_driver = data.query_driver - -- _G.metadata.toolchain = data.toolchain_root + -- _G.metadata.toolchain_root = data.toolchain_root -- end local clangConfig = _G.get_clangd_config() diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b5367de1..c96e63ee 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -49,7 +49,7 @@ function M.get_sysroot_triplet(cc_compiler) if vim.fn.isdirectory(sysroot) == 1 then _G.metadata.triplet = triplet _G.metadata.sysroot = sysroot - _G.metadata.toolchain = toolchain_root + _G.metadata.toolchain_root = toolchain_root _G.metadata.query_driver = query_driver return { triplet = triplet, diff --git a/metadata.lua b/metadata.lua index 5a769cf5..d32d4c45 100644 --- a/metadata.lua +++ b/metadata.lua @@ -11,7 +11,7 @@ -- query_driver = '', -- cc_compiler = '', -- triplet = '', --- toolchain = '', +-- toolchain_root = '', -- sysroot = '', -- fallbackFlags = {}, -- } diff --git a/metadataolld.lua b/metadataolld.lua index f89054d9..500ec1b6 100644 --- a/metadataolld.lua +++ b/metadataolld.lua @@ -20,7 +20,7 @@ -- -- query_driver = '', -- -- cc_compiler = '', -- -- triplet = '', --- -- toolchain = '', +-- -- toolchain_root = '', -- -- sysroot = '', -- -- fallbackFlags = {}, -- -- } @@ -64,7 +64,7 @@ -- query_driver = '', -- cc_compiler = '', -- triplet = '', --- toolchain = '', +-- toolchain_root = '', -- sysroot = '', -- fallbackFlags = {}, -- } diff --git a/pio_setupold.lua b/pio_setupold.lua index 9293e0a9..dbbdf35e 100644 --- a/pio_setupold.lua +++ b/pio_setupold.lua @@ -432,7 +432,7 @@ -- _G.metadata.triplet = data.triplet -- _G.metadata.sysroot = data.sysroot -- _G.metadata.query_driver = data.query_driver --- _G.metadata.toolchain = data.toolchain_root +-- _G.metadata.toolchain_root = data.toolchain_root -- end -- -- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) From daead3fdc056a002fad4597dd0b1329553633d64 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 12:25:00 +0300 Subject: [PATCH 0793/1406] update --- lua/platformio/utils/pio.lua | 252 +++++++++++++++++------------------ 1 file changed, 126 insertions(+), 126 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 841d8ad4..657cc12c 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -7,183 +7,183 @@ local lsp_restart = require('platformio.lsp.tools').lsp_restart ------------------------------------------------------ -- stylua: ignore +function M.compile_commandsFix() + local filename = vim.uv.cwd() .. '/compile_commands.json' + if vim.fn.filereadable(filename) == 0 then return end + + -- Atomic read using built-in Vim function + local content = table.concat(vim.fn.readfile(filename), "\n") + local ok, data = pcall(vim.json.decode, content) + if not ok or type(data) ~= 'table' then return end + + -- 1. Build Path Map (Scan toolchain) + local path_map = {} + local toolchain_bin = (_G.metadata and _G.metadata.toolchain or "") .. '/bin/*' + for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do + local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') + path_map[name] = full_path + end + + -- 2. Update Entries efficiently with string matching + local modified = false + for _, entry in ipairs(data) do + local cmd = entry.command or "" + local first_token = cmd:match("^%S+") -- Grab only the compiler driver + + -- Fix if it's a relative path (doesn't start with / or Drive letter) + if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then + local short_name = first_token:gsub('%.exe$', '') + if path_map[short_name] then + -- Replace only the first token to preserve arguments + entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) + modified = true + end + end + end + + -- 3. Save with Python formatting + if modified then + local json_str = vim.json.encode(data) + local formatted = vim.fn.system('python -m json.tool', json_str) + + if vim.v.shell_error == 0 then + -- Atomic write back to disk + vim.fn.writefile(vim.split(formatted, "\n"), filename) + vim.notify('compiledb: paths fixed', vim.log.levels.INFO) + else + vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) + end + end + lsp_restart('clangd') + _G.metadata.isBusy = false +end + -- function M.compile_commandsFix() -- local filename = vim.uv.cwd() .. '/compile_commands.json' --- if vim.fn.filereadable(filename) == 0 then return end +-- local content = vim.fn.readfile(filename) +-- if #content == 0 then return end -- --- -- Atomic read using built-in Vim function --- local content = table.concat(vim.fn.readfile(filename), "\n") --- local ok, data = pcall(vim.json.decode, content) +-- local ok, data = pcall(vim.json.decode, table.concat(content, "\n")) -- if not ok or type(data) ~= 'table' then return end -- -- -- 1. Build Path Map (Scan toolchain) -- local path_map = {} --- local toolchain_bin = (_G.metadata and _G.metadata.toolchain or "") .. '/bin/*' --- for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do +-- +-- local pio_binaries = _G.metadata.query_driver or "/bin/*" +-- -- local pio_binaries = (_G.metadata.toolchain or "") .. '/bin/*' +-- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do -- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') -- path_map[name] = full_path -- end -- --- -- 2. Update Entries efficiently with string matching +-- -- 2. Update Entries -- local modified = false -- for _, entry in ipairs(data) do -- local cmd = entry.command or "" --- local first_token = cmd:match("^%S+") -- Grab only the compiler driver +-- local first_token = cmd:match("^%S+") -- Get first word before space -- --- -- Fix if it's a relative path (doesn't start with / or Drive letter) -- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then -- local short_name = first_token:gsub('%.exe$', '') -- if path_map[short_name] then --- -- Replace only the first token to preserve arguments +-- -- Swap first token with full path safely -- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) -- modified = true -- end -- end -- end -- --- -- 3. Save with Python formatting +-- -- 3. Save with Formatting -- if modified then -- local json_str = vim.json.encode(data) +-- -- Use python to format, then write file -- local formatted = vim.fn.system('python -m json.tool', json_str) --- -- if vim.v.shell_error == 0 then --- -- Atomic write back to disk -- vim.fn.writefile(vim.split(formatted, "\n"), filename) -- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) --- else --- vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) -- end -- end --- lsp_restart('clangd') --- _G.metadata.isBusy = false -- end -- function M.compile_commandsFix() -- local filename = vim.uv.cwd() .. '/compile_commands.json' --- local content = vim.fn.readfile(filename) --- if #content == 0 then return end +-- local file = io.open(filename, 'r') +-- if not file then return end -- --- local ok, data = pcall(vim.json.decode, table.concat(content, "\n")) --- if not ok or type(data) ~= 'table' then return end +-- -- read compile_commands.json file to content +-- local content = file:read('*a') +-- file:close() +-- if not content or content == '' then return end -- --- -- 1. Build Path Map (Scan toolchain) +-- -- JSON decoding content to data +-- local ok, data = pcall(vim.json.decode, content) +-- if not ok or type(data) ~= 'table' then +-- vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) +-- return +-- end +-- +-- print('PioFix0') +-- -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path -- local path_map = {} +-- local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') +-- if pio_home then +-- -- Recursively find all binaries in PIO packages +-- local pio_packages = _G.metadata.toolchain .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' +-- local found_binaries = vim.fn.glob(pio_packages, false, true) -- --- local pio_binaries = _G.metadata.query_driver or "/bin/*" --- -- local pio_binaries = (_G.metadata.toolchain or "") .. '/bin/*' --- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do --- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') --- path_map[name] = full_path +-- for _, full_path in ipairs(found_binaries) do +-- -- Extract filename (e.g., riscv32-esp-elf-gcc) +-- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') +-- path_map[name] = full_path +-- -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) +-- end -- end -- --- -- 2. Update Entries --- local modified = false +-- -- PHASE 2: Update JSON using the Map +-- local modified = 0 -- for _, entry in ipairs(data) do --- local cmd = entry.command or "" --- local first_token = cmd:match("^%S+") -- Get first word before space --- --- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then --- local short_name = first_token:gsub('%.exe$', '') --- if path_map[short_name] then --- -- Swap first token with full path safely --- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) --- modified = true +-- if type(entry.command) == 'string' then +-- local cmd_parts = vim.split(entry.command, ' ') +-- local first_token = cmd_parts[1] +-- if first_token then +-- -- Check if it's already a short name (not an absolute path) +-- local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') +-- if not is_abs then +-- local short_name = first_token:gsub('%.exe$', '') +-- -- print('PioFix2: short_name=' .. short_name) +-- -- Direct Query: Does this name exist in our discovered list? +-- if path_map[short_name] then +-- cmd_parts[1] = path_map[short_name] +-- -- print('PioFix3: full_name=' .. cmd_parts[1]) +-- entry.command = table.concat(cmd_parts, ' ') +-- modified = modified + 1 +-- end +-- end -- end -- end -- end -- --- -- 3. Save with Formatting --- if modified then --- local json_str = vim.json.encode(data) --- -- Use python to format, then write file --- local formatted = vim.fn.system('python -m json.tool', json_str) --- if vim.v.shell_error == 0 then --- vim.fn.writefile(vim.split(formatted, "\n"), filename) --- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) +-- -- PHASE 3: Save and Refresh +-- -- Safe JSON encoding +-- if modified > 0 then +-- local out_file = io.open(filename, 'w') +-- if out_file then +-- local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) +-- if encode_ok and json_str then +-- -- 1. Format the string using python's json.tool +-- -- The second argument to vim.fn.system() is the "stdin" passed to the command +-- local formatted_json = vim.fn.system('python -m json.tool', json_str) +-- +-- -- out_file:write(json_str) +-- out_file:write(formatted_json) +-- out_file:close() +-- vim.notify('compiledb: fixed', vim.log.levels.INFO) +-- lsp_restart('clangd') +-- _G.metadata.isBusy = false +-- end -- end -- end -- end -function M.compile_commandsFix() - local filename = vim.uv.cwd() .. '/compile_commands.json' - local file = io.open(filename, 'r') - if not file then return end - - -- read compile_commands.json file to content - local content = file:read('*a') - file:close() - if not content or content == '' then return end - - -- JSON decoding content to data - local ok, data = pcall(vim.json.decode, content) - if not ok or type(data) ~= 'table' then - vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) - return - end - - print('PioFix0') - -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path - local path_map = {} - local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') - if pio_home then - -- Recursively find all binaries in PIO packages - local pio_packages = _G.metadata.toolchain .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' - local found_binaries = vim.fn.glob(pio_packages, false, true) - - for _, full_path in ipairs(found_binaries) do - -- Extract filename (e.g., riscv32-esp-elf-gcc) - local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') - path_map[name] = full_path - -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) - end - end - - -- PHASE 2: Update JSON using the Map - local modified = 0 - for _, entry in ipairs(data) do - if type(entry.command) == 'string' then - local cmd_parts = vim.split(entry.command, ' ') - local first_token = cmd_parts[1] - if first_token then - -- Check if it's already a short name (not an absolute path) - local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') - if not is_abs then - local short_name = first_token:gsub('%.exe$', '') - -- print('PioFix2: short_name=' .. short_name) - -- Direct Query: Does this name exist in our discovered list? - if path_map[short_name] then - cmd_parts[1] = path_map[short_name] - -- print('PioFix3: full_name=' .. cmd_parts[1]) - entry.command = table.concat(cmd_parts, ' ') - modified = modified + 1 - end - end - end - end - end - - -- PHASE 3: Save and Refresh - -- Safe JSON encoding - if modified > 0 then - local out_file = io.open(filename, 'w') - if out_file then - local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) - if encode_ok and json_str then - -- 1. Format the string using python's json.tool - -- The second argument to vim.fn.system() is the "stdin" passed to the command - local formatted_json = vim.fn.system('python -m json.tool', json_str) - - -- out_file:write(json_str) - out_file:write(formatted_json) - out_file:close() - vim.notify('compiledb: fixed', vim.log.levels.INFO) - lsp_restart('clangd') - _G.metadata.isBusy = false - end - end - end -end - ------------------------------------------------------ -- INFO: ToggleTerminal commands sequencer From 22e05eac6a4ff995ca14b237aa847b1a9681b938 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 12:33:35 +0300 Subject: [PATCH 0794/1406] update --- lua/platformio/utils/pio.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 657cc12c..7378fe82 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -18,7 +18,7 @@ function M.compile_commandsFix() -- 1. Build Path Map (Scan toolchain) local path_map = {} - local toolchain_bin = (_G.metadata and _G.metadata.toolchain or "") .. '/bin/*' + local toolchain_bin = (_G.metadata and _G.metadata.toolchain_root or "") .. '/bin/*' for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') path_map[name] = full_path @@ -70,7 +70,7 @@ end -- local path_map = {} -- -- local pio_binaries = _G.metadata.query_driver or "/bin/*" --- -- local pio_binaries = (_G.metadata.toolchain or "") .. '/bin/*' +-- -- local pio_binaries = (_G.metadata.toolchain_root or "") .. '/bin/*' -- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do -- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') -- path_map[name] = full_path @@ -127,7 +127,7 @@ end -- local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') -- if pio_home then -- -- Recursively find all binaries in PIO packages --- local pio_packages = _G.metadata.toolchain .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' +-- local pio_packages = _G.metadata.toolchain_root .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' -- local found_binaries = vim.fn.glob(pio_packages, false, true) -- -- for _, full_path in ipairs(found_binaries) do From 19c4acbc6e240f0cd8a31aa836243d6391234be1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 12:42:57 +0300 Subject: [PATCH 0795/1406] update --- lua/platformio/pio_setup.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index c96e63ee..1161cac1 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -423,7 +423,8 @@ function M.run_compiledb() vim.schedule(function() -- _G.metadata.isBusy = false if obj.code == 0 then - M.compile_commandsFix() + local dbFix = require('platformio.utils.pio').compile_commandsFix + dbFix() vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) -- Use pcall in case M.refresh is defined elsewhere -- pio_manager.refresh(function() From 5131c95d36fc462fb9fe8ed370e51fed9ecb8743 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 12:54:30 +0300 Subject: [PATCH 0796/1406] update --- lua/platformio/metadata.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 1d18822b..bc2f38a5 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -14,7 +14,7 @@ local last_saved_hash = '' local config_path = vim.fs.joinpath(vim.uv.cwd(), '.project_config.json') local _raw_metadata = { - is_busy = false, + isBusy = false, envs = {}, active_env = '', default_envs = {}, From 20b1b7cd04384318f9fe9ed706d94117d893a78b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 13:40:22 +0300 Subject: [PATCH 0797/1406] update --- lua/platformio/lsp/clangd.lua | 15 ++++++++++++++- metadata.lua | 2 +- mini_nvimPlatformio.lua | 9 --------- 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua index abefff28..d1cbc01f 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -69,7 +69,7 @@ end) local mok, mason_lspconfig = pcall(require, 'mason-lspconfig') if mok then mason_lspconfig.setup({ - ensure_installed = { 'clangd', 'lua_ls', 'pyrefly', 'yamlls' }, + ensure_installed = { 'clangd', 'lua_ls', 'pyrefly', 'yamlls', 'jsonls' }, automatic_enable = true, -- this will automatically enable LSP servers after lsp.config }) end @@ -134,6 +134,19 @@ end vim.lsp.config('clangd', _G.get_clangd_config()) vim.lsp.enable('clangd') +---------------------------------------------------------------------------------------- +-- INFO: configure jsonls lsp server +----------------------------------------------------------------------------------------- +local jsonls = { + -- lazy-load schemastore when needed + cmd = { 'vscode-json-language-server', '--stdio' }, + filetypes = { 'json', 'jsonc' }, + init_options = { provideFormatter = true }, + root_makers = { '.git' }, +} +-- Apply and Enable +vim.lsp.config('jsonls', jsonls) + ---------------------------------------------------------------------------------------- -- INFO: configure clangd lsp server ----------------------------------------------------------------------------------------- diff --git a/metadata.lua b/metadata.lua index d32d4c45..f274936f 100644 --- a/metadata.lua +++ b/metadata.lua @@ -1,7 +1,7 @@ -- -- 1. Initialize Global Table immediately (Prevents nil errors) -- _G.metadata = _G.metadata -- or { --- is_busy = false, +-- isBusy = false, -- envs = {}, -- active_env = '', -- default_envs = {}, diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 927d362e..de68eb1c 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -128,15 +128,6 @@ keymap('n', 'bd', function() -- Delete the buffer we started with (using pcall to ignore "No buffers deleted" errors) pcall(vim.api.nvim_buf_delete, bufnr, { force = false }) - - -- if #bufs <= 1 then - -- -- If it's the last buffer, create a new empty one first - -- -- This prevents focus from jumping to NvimTree - -- vim.cmd('enew | bd #') - -- else - -- -- Otherwise, go to the previous buffer and delete the old one - -- vim.cmd('bp | bd #') - -- end end, { desc = '[D]elete Buffer' }) keymap('n', 'bP', 'BufferLineGroupClose ungrouped', { desc = 'Delete Non-Pinned Buffers' }) From 77b99aa463a018e8eb9a6618f9eca3afa0681cd4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 14:14:22 +0300 Subject: [PATCH 0798/1406] update --- lua/platformio/metadata.lua | 30 ++++++++++++++++++++++++------ mini_nvimPlatformio.lua | 8 ++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index bc2f38a5..791bcb19 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,14 +1,32 @@ local M = {} -_G.get_pio_status = function() - if _G.metadata and _G.metadata.active_env ~= '' then - return ' [ ' .. _G.metadata.active_env .. '] ' +-- _G.get_pio_status = function() +-- if _G.metadata and _G.metadata.active_env ~= '' then +-- return ' [ ' .. _G.metadata.active_env .. '] ' +-- end +-- return '' +-- end +-- -- Move the %#PioStatus# and %* outside of the curly braces +-- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' + +-- Add this to your init.lua or statusline config +vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' + +-- Optional: Add a nice color for the environment name +vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) + +function M.refresh_statusline() + local env = (_G.metadata and _G.metadata.active_env ~= '') and _G.metadata.active_env or nil + + if env then + -- We set the variable for the CURRENT buffer + vim.b.pio_env = string.format(' [ %s ] ', env) + else + vim.b.pio_env = '' end - return '' end --- Move the %#PioStatus# and %* outside of the curly braces -vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua._G.get_pio_status()}%* %y %p%% %l:%c' +------------------------------------------------------------------------------------------------------- -- 1. Internal State & Defaults local last_saved_hash = '' local config_path = vim.fs.joinpath(vim.uv.cwd(), '.project_config.json') diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index de68eb1c..458f8137 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -324,6 +324,14 @@ vim.api.nvim_create_autocmd('User', { end, }) +-- INFO: refreshes the statusline whenever you enter a C/C++ file +vim.api.nvim_create_autocmd({ 'BufEnter', 'FileType' }, { + pattern = { 'c', 'cpp', 'objc', 'objcpp' }, + callback = function() + -- Assuming your module is required as 'pio' + require('platformio.metadata()').refresh_statusline() + end, +}) ---------------------------------------------------------------------------------------- -- INFO: set up python nvim venv (virtual environment 'nenv'), activaten. local platformio_core_dir, pynvim_env, pynvim_python, pynvim_lib, pynvim_bin, pynvim_activate From 96cf4c4e576f2c9aa00188af6944aead53008f23 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 14:23:07 +0300 Subject: [PATCH 0799/1406] update --- mini_nvimPlatformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 458f8137..7d7eaa7a 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -329,7 +329,7 @@ vim.api.nvim_create_autocmd({ 'BufEnter', 'FileType' }, { pattern = { 'c', 'cpp', 'objc', 'objcpp' }, callback = function() -- Assuming your module is required as 'pio' - require('platformio.metadata()').refresh_statusline() + require('platformio.metadata').refresh_statusline() end, }) ---------------------------------------------------------------------------------------- From 8adecf8e86e7295464fde9ef2285dfba5d5be338 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 14:45:51 +0300 Subject: [PATCH 0800/1406] update --- lua/platformio/metadata.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 791bcb19..5dd113ed 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -10,7 +10,7 @@ local M = {} -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' -- Add this to your init.lua or statusline config -vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' +-- vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' -- Optional: Add a nice color for the environment name vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) From 8357433c3e70b6af7f859fec12c975d9793f0050 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 14:54:00 +0300 Subject: [PATCH 0801/1406] update --- lua/platformio/metadata.lua | 38 +++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 5dd113ed..b3881ba9 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -9,22 +9,36 @@ local M = {} -- -- Move the %#PioStatus# and %* outside of the curly braces -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' --- Add this to your init.lua or statusline config +-- -- Add this to your init.lua or statusline config -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' +-- +-- -- Optional: Add a nice color for the environment name +-- vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) +-- +-- function M.refresh_statusline() +-- local env = (_G.metadata and _G.metadata.active_env ~= '') and _G.metadata.active_env or nil +-- +-- if env then +-- -- We set the variable for the CURRENT buffer +-- vim.b.pio_env = string.format(' [ %s ] ', env) +-- else +-- vim.b.pio_env = '' +-- end +-- end --- Optional: Add a nice color for the environment name -vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) +-- 1. Define the logic in a global table to make it accessible to v:lua +_G.MyStatusLine = function() + local mode = vim.api.nvim_get_mode().mode + local file = vim.fn.expand('%:t') -- Just the filename + local modified = vim.bo.modified and ' [+]' or '' + return string.format(' %s | %s%s %%= %%l:%%c ', mode, file, modified) +end -function M.refresh_statusline() - local env = (_G.metadata and _G.metadata.active_env ~= '') and _G.metadata.active_env or nil +-- 2. Set the global statusline behavior +vim.o.laststatus = 3 - if env then - -- We set the variable for the CURRENT buffer - vim.b.pio_env = string.format(' [ %s ] ', env) - else - vim.b.pio_env = '' - end -end +-- 3. Use v:lua to call your function +vim.o.statusline = '%!v:lua.MyStatusLine()' ------------------------------------------------------------------------------------------------------- -- 1. Internal State & Defaults From 3f3b5a82ed5d5bb20d0002ca434aa9bc58b8c076 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 14:58:08 +0300 Subject: [PATCH 0802/1406] update --- mini_nvimPlatformio.lua | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 7d7eaa7a..bb45454b 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -324,14 +324,14 @@ vim.api.nvim_create_autocmd('User', { end, }) --- INFO: refreshes the statusline whenever you enter a C/C++ file -vim.api.nvim_create_autocmd({ 'BufEnter', 'FileType' }, { - pattern = { 'c', 'cpp', 'objc', 'objcpp' }, - callback = function() - -- Assuming your module is required as 'pio' - require('platformio.metadata').refresh_statusline() - end, -}) +-- -- INFO: refreshes the statusline whenever you enter a C/C++ file +-- vim.api.nvim_create_autocmd({ 'BufEnter', 'FileType' }, { +-- pattern = { 'c', 'cpp', 'objc', 'objcpp' }, +-- callback = function() +-- -- Assuming your module is required as 'pio' +-- require('platformio.metadata').refresh_statusline() +-- end, +-- }) ---------------------------------------------------------------------------------------- -- INFO: set up python nvim venv (virtual environment 'nenv'), activaten. local platformio_core_dir, pynvim_env, pynvim_python, pynvim_lib, pynvim_bin, pynvim_activate From c80f3e19d2fdfb84852ca7ec57e5c88b7ee9437b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 15:04:56 +0300 Subject: [PATCH 0803/1406] update --- lua/platformio/metadata.lua | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index b3881ba9..b46cc2a6 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -12,8 +12,8 @@ local M = {} -- -- Add this to your init.lua or statusline config -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' -- --- -- Optional: Add a nice color for the environment name --- vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) +-- Optional: Add a nice color for the environment name +vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) -- -- function M.refresh_statusline() -- local env = (_G.metadata and _G.metadata.active_env ~= '') and _G.metadata.active_env or nil @@ -38,7 +38,8 @@ end vim.o.laststatus = 3 -- 3. Use v:lua to call your function -vim.o.statusline = '%!v:lua.MyStatusLine()' +-- vim.o.statusline = '%!v:lua.MyStatusLine()' +vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.MyStatusLine()}%* %y %p%% %l:%c' ------------------------------------------------------------------------------------------------------- -- 1. Internal State & Defaults From 704a156a96e30ab23a21bbe8f0eed5475d82cd74 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 15:12:27 +0300 Subject: [PATCH 0804/1406] update --- lua/platformio/metadata.lua | 46 ++++++++++++++++++++++++++++--------- mini_nvimPlatformio.lua | 16 ++++++------- 2 files changed, 43 insertions(+), 19 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index b46cc2a6..25614f58 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -13,7 +13,7 @@ local M = {} -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' -- -- Optional: Add a nice color for the environment name -vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) +-- vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) -- -- function M.refresh_statusline() -- local env = (_G.metadata and _G.metadata.active_env ~= '') and _G.metadata.active_env or nil @@ -27,19 +27,43 @@ vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) -- end -- 1. Define the logic in a global table to make it accessible to v:lua -_G.MyStatusLine = function() - local mode = vim.api.nvim_get_mode().mode - local file = vim.fn.expand('%:t') -- Just the filename - local modified = vim.bo.modified and ' [+]' or '' - return string.format(' %s | %s%s %%= %%l:%%c ', mode, file, modified) +-- _G.MyStatusLine = function() +-- local mode = vim.api.nvim_get_mode().mode +-- local file = vim.fn.expand('%:t') -- Just the filename +-- local modified = vim.bo.modified and ' [+]' or '' +-- return string.format(' %s | %s%s %%= %%l:%%c ', mode, file, modified) +-- end +-- +-- -- 2. Set the global statusline behavior +-- vim.o.laststatus = 3 +-- +-- -- 3. Use v:lua to call your function +-- -- vim.o.statusline = '%!v:lua.MyStatusLine()' +-- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.MyStatusLine()}%* %y %p%% %l:%c' + +function M.refresh_statusline() + -- Check if metadata exists and has an active environment + local env = (_G.metadata and _G.metadata.active_env ~= '') and _G.metadata.active_env or nil + + if env then + -- Set the buffer-local variable + vim.b.pio_env = string.format(' [ %s ] ', env) + else + vim.b.pio_env = '' -- Clear it if not in a PIO project + end + + -- Force an immediate visual refresh of the status bar + vim.cmd('redrawstatus') end --- 2. Set the global statusline behavior -vim.o.laststatus = 3 +-- Standard Statusline layout +-- %#PioStatus# applies your custom color +-- %{get(b:,"pio_env","")} safely reads the buffer variable +-- %* resets the color back to default +vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' --- 3. Use v:lua to call your function --- vim.o.statusline = '%!v:lua.MyStatusLine()' -vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.MyStatusLine()}%* %y %p%% %l:%c' +-- Define a nice color for the environment name (e.g., Blue) +vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) ------------------------------------------------------------------------------------------------------- -- 1. Internal State & Defaults diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index bb45454b..3ddddaa3 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -324,14 +324,14 @@ vim.api.nvim_create_autocmd('User', { end, }) --- -- INFO: refreshes the statusline whenever you enter a C/C++ file --- vim.api.nvim_create_autocmd({ 'BufEnter', 'FileType' }, { --- pattern = { 'c', 'cpp', 'objc', 'objcpp' }, --- callback = function() --- -- Assuming your module is required as 'pio' --- require('platformio.metadata').refresh_statusline() --- end, --- }) +-- INFO: refreshes the statusline whenever you enter a C/C++ file +vim.api.nvim_create_autocmd({ 'BufEnter', 'FileType' }, { + pattern = { 'c', 'cpp', 'objc', 'objcpp', 'h', 'hpp' }, + callback = function() + -- Assuming your module is required as 'pio' + require('platformio.metadata').refresh_statusline() + end, +}) ---------------------------------------------------------------------------------------- -- INFO: set up python nvim venv (virtual environment 'nenv'), activaten. local platformio_core_dir, pynvim_env, pynvim_python, pynvim_lib, pynvim_bin, pynvim_activate From 8a9685351f0e966b16037d2f4724a868f0384357 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 15:46:29 +0300 Subject: [PATCH 0805/1406] update --- lua/platformio/metadata.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 25614f58..1fa6204b 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -41,6 +41,9 @@ local M = {} -- -- vim.o.statusline = '%!v:lua.MyStatusLine()' -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.MyStatusLine()}%* %y %p%% %l:%c' +-- Define a nice color for the environment name (e.g., Blue) +vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) + function M.refresh_statusline() -- Check if metadata exists and has an active environment local env = (_G.metadata and _G.metadata.active_env ~= '') and _G.metadata.active_env or nil @@ -62,9 +65,6 @@ end -- %* resets the color back to default vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' --- Define a nice color for the environment name (e.g., Blue) -vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) - ------------------------------------------------------------------------------------------------------- -- 1. Internal State & Defaults local last_saved_hash = '' From 741f9b7aadd3298cdd781ea26859f4a5be5bf3ee Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 16:07:01 +0300 Subject: [PATCH 0806/1406] update --- lua/platformio/metadata.lua | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 1fa6204b..799af04d 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -114,6 +114,12 @@ _G.metadata = setmetatable({}, { vim.notify('Env: LspRestart', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) end end) + elseif key == 'active_env' then + -- Force global statusline so it doesn't get pushed around by Trouble or splits + vim.o.laststatus = 3 + + -- Ensure your custom layout is the final word + vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' end -- if key == 'active_env' then -- vim.notify('Env: ' .. value, vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) From 946defda9146d375447d5ad3475bb3e7421def5c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 16:13:52 +0300 Subject: [PATCH 0807/1406] update --- lua/platformio/metadata.lua | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 799af04d..a33760f6 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -59,11 +59,18 @@ function M.refresh_statusline() vim.cmd('redrawstatus') end +-- We define this globally so v:lua can see it +_G.get_pio_status = function() + -- Lua can always see its own vim.b variables correctly + return vim.b.pio_env or '' +end +-- Use %! to execute a Lua function that returns your string +vim.o.statusline = '%f %m %r %= %#PioStatus#%!v:lua.get_pio_status()%* %y %p%% %l:%c' -- Standard Statusline layout -- %#PioStatus# applies your custom color -- %{get(b:,"pio_env","")} safely reads the buffer variable -- %* resets the color back to default -vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' +-- vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' ------------------------------------------------------------------------------------------------------- -- 1. Internal State & Defaults From d1a642211a8e3353248de707d1e1e5c22b83b6c3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 16:20:27 +0300 Subject: [PATCH 0808/1406] update --- lua/platformio/metadata.lua | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index a33760f6..738bc6d3 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -65,7 +65,12 @@ _G.get_pio_status = function() return vim.b.pio_env or '' end -- Use %! to execute a Lua function that returns your string -vim.o.statusline = '%f %m %r %= %#PioStatus#%!v:lua.get_pio_status()%* %y %p%% %l:%c' +-- vim.o.statusline = '%f %m %r %= %#PioStatus#%!v:lua.get_pio_status()%* %y %p%% %l:%c' + +-- We use %{ } for evaluation and v:lua to call your module-based function. +-- This bypasses the strict character limits of the %! prefix. +vim.o.statusline = '%f %m %r %= %#PioStatus#%{%v:lua.require("platformio.metadata").get_pio_status()%}%* %y %p%% %l:%c' + -- Standard Statusline layout -- %#PioStatus# applies your custom color -- %{get(b:,"pio_env","")} safely reads the buffer variable From f8c0ae7e7fb0202a8dbb4628895aa2e8e36f1543 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 16:22:56 +0300 Subject: [PATCH 0809/1406] update --- lua/platformio/metadata.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 738bc6d3..847a8435 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -69,7 +69,7 @@ end -- We use %{ } for evaluation and v:lua to call your module-based function. -- This bypasses the strict character limits of the %! prefix. -vim.o.statusline = '%f %m %r %= %#PioStatus#%{%v:lua.require("platformio.metadata").get_pio_status()%}%* %y %p%% %l:%c' +vim.o.statusline = '%f %m %r %= %#PioStatus#%{%v:lua.require("platformio.metadata").refresh_statusline()%}%* %y %p%% %l:%c' -- Standard Statusline layout -- %#PioStatus# applies your custom color From ece50e40bd227f9ddd6e530821d843c151467897 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 16:29:23 +0300 Subject: [PATCH 0810/1406] update --- lua/platformio/metadata.lua | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 847a8435..a6eb7417 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -69,7 +69,11 @@ end -- We use %{ } for evaluation and v:lua to call your module-based function. -- This bypasses the strict character limits of the %! prefix. -vim.o.statusline = '%f %m %r %= %#PioStatus#%{%v:lua.require("platformio.metadata").refresh_statusline()%}%* %y %p%% %l:%c' +-- vim.o.statusline = '%f %m %r %= %#PioStatus#%{%v:lua.require(\"platformio.metadata\").refresh_statusline()%}%* %y %p%% %l:%c' + +-- We use luaeval to call your function. +-- The single quotes around the function call are essential. +vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("require(\'platformio.metadata\').refresh_statusline()")} %y %p%% %l:%c' -- Standard Statusline layout -- %#PioStatus# applies your custom color From 8f01b51cabe9e0ae194d755be11207efd49e94bc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 16:35:41 +0300 Subject: [PATCH 0811/1406] update --- lua/platformio/metadata.lua | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index a6eb7417..be1fc73e 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -46,17 +46,21 @@ vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) function M.refresh_statusline() -- Check if metadata exists and has an active environment - local env = (_G.metadata and _G.metadata.active_env ~= '') and _G.metadata.active_env or nil - - if env then - -- Set the buffer-local variable - vim.b.pio_env = string.format(' [ %s ] ', env) - else - vim.b.pio_env = '' -- Clear it if not in a PIO project + -- local env = (_G.metadata and _G.metadata.active_env ~= '') and _G.metadata.active_env or nil + -- + -- if env then + -- -- Set the buffer-local variable + -- vim.b.pio_env = string.format(' [ %s ] ', env) + -- else + -- vim.b.pio_env = '' -- Clear it if not in a PIO project + -- end + + -- Always return a string, even if empty + if _G.metadata and _G.metadata.active_env and _G.metadata.active_env ~= '' then + return string.format(' [ %s ] ', _G.metadata.active_env) end - + return '' -- Force an immediate visual refresh of the status bar - vim.cmd('redrawstatus') end -- We define this globally so v:lua can see it From 05d6a9d329773a9e010771a9b2ba6b605edc7063 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 16:43:02 +0300 Subject: [PATCH 0812/1406] update --- lua/platformio/metadata.lua | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index be1fc73e..200292bb 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -46,21 +46,17 @@ vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) function M.refresh_statusline() -- Check if metadata exists and has an active environment - -- local env = (_G.metadata and _G.metadata.active_env ~= '') and _G.metadata.active_env or nil - -- - -- if env then - -- -- Set the buffer-local variable - -- vim.b.pio_env = string.format(' [ %s ] ', env) - -- else - -- vim.b.pio_env = '' -- Clear it if not in a PIO project - -- end - - -- Always return a string, even if empty - if _G.metadata and _G.metadata.active_env and _G.metadata.active_env ~= '' then - return string.format(' [ %s ] ', _G.metadata.active_env) + local env = (_G.metadata and _G.metadata.active_env ~= '') and _G.metadata.active_env or nil + + if env then + -- Set the buffer-local variable + vim.b.pio_env = string.format(' [ %s ] ', env) + else + vim.b.pio_env = '' -- Clear it if not in a PIO project end - return '' + -- Force an immediate visual refresh of the status bar + vim.cmd('redrawstatus') end -- We define this globally so v:lua can see it @@ -73,11 +69,11 @@ end -- We use %{ } for evaluation and v:lua to call your module-based function. -- This bypasses the strict character limits of the %! prefix. --- vim.o.statusline = '%f %m %r %= %#PioStatus#%{%v:lua.require(\"platformio.metadata\").refresh_statusline()%}%* %y %p%% %l:%c' +vim.o.statusline = "%f %m %r %= %#PioStatus#%{%v:lua.require('platformio.metadata').refresh_statusline()%}%* %y %p%% %l:%c" -- We use luaeval to call your function. -- The single quotes around the function call are essential. -vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("require(\'platformio.metadata\').refresh_statusline()")} %y %p%% %l:%c' +-- vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("require(\'platformio.metadata\').get_pio_status()")} %y %p%% %l:%c' -- Standard Statusline layout -- %#PioStatus# applies your custom color From c7c9e4876bb54e4ff8f1c2552fbc288d553109bf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 16:57:06 +0300 Subject: [PATCH 0813/1406] update --- lua/platformio/metadata.lua | 84 ++++--------------------------------- 1 file changed, 8 insertions(+), 76 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 200292bb..2823c7ff 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,86 +1,18 @@ local M = {} --- _G.get_pio_status = function() --- if _G.metadata and _G.metadata.active_env ~= '' then --- return ' [ ' .. _G.metadata.active_env .. '] ' --- end --- return '' --- end --- -- Move the %#PioStatus# and %* outside of the curly braces --- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' +_G.get_pio_status = function() + if _G.metadata and _G.metadata.active_env ~= '' then + return ' [ ' .. _G.metadata.active_env .. '] ' + end + return '' +end +-- Move the %#PioStatus# and %* outside of the curly braces +vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' --- -- Add this to your init.lua or statusline config --- vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' -- -- Optional: Add a nice color for the environment name --- vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) --- --- function M.refresh_statusline() --- local env = (_G.metadata and _G.metadata.active_env ~= '') and _G.metadata.active_env or nil --- --- if env then --- -- We set the variable for the CURRENT buffer --- vim.b.pio_env = string.format(' [ %s ] ', env) --- else --- vim.b.pio_env = '' --- end --- end - --- 1. Define the logic in a global table to make it accessible to v:lua --- _G.MyStatusLine = function() --- local mode = vim.api.nvim_get_mode().mode --- local file = vim.fn.expand('%:t') -- Just the filename --- local modified = vim.bo.modified and ' [+]' or '' --- return string.format(' %s | %s%s %%= %%l:%%c ', mode, file, modified) --- end --- --- -- 2. Set the global statusline behavior --- vim.o.laststatus = 3 --- --- -- 3. Use v:lua to call your function --- -- vim.o.statusline = '%!v:lua.MyStatusLine()' --- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.MyStatusLine()}%* %y %p%% %l:%c' - --- Define a nice color for the environment name (e.g., Blue) vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) -function M.refresh_statusline() - -- Check if metadata exists and has an active environment - local env = (_G.metadata and _G.metadata.active_env ~= '') and _G.metadata.active_env or nil - - if env then - -- Set the buffer-local variable - vim.b.pio_env = string.format(' [ %s ] ', env) - else - vim.b.pio_env = '' -- Clear it if not in a PIO project - end - - -- Force an immediate visual refresh of the status bar - vim.cmd('redrawstatus') -end - --- We define this globally so v:lua can see it -_G.get_pio_status = function() - -- Lua can always see its own vim.b variables correctly - return vim.b.pio_env or '' -end --- Use %! to execute a Lua function that returns your string --- vim.o.statusline = '%f %m %r %= %#PioStatus#%!v:lua.get_pio_status()%* %y %p%% %l:%c' - --- We use %{ } for evaluation and v:lua to call your module-based function. --- This bypasses the strict character limits of the %! prefix. -vim.o.statusline = "%f %m %r %= %#PioStatus#%{%v:lua.require('platformio.metadata').refresh_statusline()%}%* %y %p%% %l:%c" - --- We use luaeval to call your function. --- The single quotes around the function call are essential. --- vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("require(\'platformio.metadata\').get_pio_status()")} %y %p%% %l:%c' - --- Standard Statusline layout --- %#PioStatus# applies your custom color --- %{get(b:,"pio_env","")} safely reads the buffer variable --- %* resets the color back to default --- vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' - ------------------------------------------------------------------------------------------------------- -- 1. Internal State & Defaults local last_saved_hash = '' From 0f2a70d41d60404bbadec94c077e425a2b4bcef8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 17:27:11 +0300 Subject: [PATCH 0814/1406] update --- lua/platformio/metadata.lua | 19 +++++++++++++------ lua/platformio/utils/pio.lua | 7 +++++-- lua/platformio/utils/term.lua | 12 ++++++++++-- plugin/platformio.lua | 7 ++++++- 4 files changed, 34 insertions(+), 11 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 2823c7ff..564f5d59 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,14 +1,21 @@ local M = {} -_G.get_pio_status = function() - if _G.metadata and _G.metadata.active_env ~= '' then - return ' [ ' .. _G.metadata.active_env .. '] ' +-- _G.get_pio_status = function() +-- if _G.metadata and _G.metadata.active_env ~= '' then +-- return ' [ ' .. _G.metadata.active_env .. '] ' +-- end +-- return '' +-- end +-- -- Move the %#PioStatus# and %* outside of the curly braces +-- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' + +-- The Statusline Getter (used by the UI) +function M.get_pio_status() + if _G.metadata and _G.metadata.active_env and _G.metadata.active_env ~= '' then + return string.format(' [ %s ] ', _G.metadata.active_env) end return '' end --- Move the %#PioStatus# and %* outside of the curly braces -vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' - -- -- Optional: Add a nice color for the environment name vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 7378fe82..ad20be01 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -2,6 +2,7 @@ local M = {} M.selected_framework = '' +M.term = nil local misc = require('platformio.utils.misc') local lsp_restart = require('platformio.lsp.tools').lsp_restart @@ -256,9 +257,11 @@ M.run_sequence = function(tasks) table.insert(M.queue, function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end) table.insert(M.queue, function () vim.notify('Pioinit: Failed', vim.log.levels.INFO) end) -- full_cmd = full_cmd .. ' || ' .. fail - local ToggleTerminal = require('platformio.utils.term').ToggleTerminal _G.metadata.isBusy = true - ToggleTerminal(full_cmd, 'float') + -- local ToggleTerminal = require('platformio.utils.term').ToggleTerminal + -- ToggleTerminal(full_cmd, 'float') + M.term.ToggleTerminal(full_cmd, 'float') + end -- { diff --git a/lua/platformio/utils/term.lua b/lua/platformio/utils/term.lua index ce278105..582350cc 100644 --- a/lua/platformio/utils/term.lua +++ b/lua/platformio/utils/term.lua @@ -6,7 +6,10 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' local config = require('platformio').config -local pio = require('platformio.utils.pio') + +-- local pio = require('platformio.utils.pio') +-- A socket for the logic module to plug into +M.stdout_callback = nil ------------------------------------------------------ function M.strsplit(inputstr, del) @@ -165,7 +168,12 @@ function M.ToggleTerminal(command, direction) -- INFO: on_stdout -- on_stdout = stdout_callback, - pioOpts.on_stdout = pio.stdoutFilter + -- pioOpts.on_stdout = pio.stdoutFilter + pioOpts.on_stdout = function(t, job, exit_code) + if type(M.stdout_callback) == 'function' then + M.stdout_callback(t, job, exit_code) + end + end end pioOpts.direction = direction ------------------------------------------------------ diff --git a/plugin/platformio.lua b/plugin/platformio.lua index c38d4372..9b8e7ad3 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -6,9 +6,14 @@ -- +: At least one argument. -- -1: Zero or one argument (like ?, explicitly). +local piolsserial = require('platformio.piolsserial') local misc = require('platformio.utils.misc') + +local term = require('platformio.utils.term') local pio = require('platformio.utils.pio') -local piolsserial = require('platformio.piolsserial') +--Dependency Injection: Plug the logic into the terminal +term.stdout_callback = pio.stdoutFilter +pio.term = term.ToggleTerminal -- Pioinit vim.api.nvim_create_user_command('Pioinit', function() From 045002a7a8d1727559c4e75f07abd32925fdf47d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 17:35:48 +0300 Subject: [PATCH 0815/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index ad20be01..fa129532 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -260,7 +260,7 @@ M.run_sequence = function(tasks) _G.metadata.isBusy = true -- local ToggleTerminal = require('platformio.utils.term').ToggleTerminal -- ToggleTerminal(full_cmd, 'float') - M.term.ToggleTerminal(full_cmd, 'float') + if M.term then M.term.ToggleTerminal(full_cmd, 'float') end end From 9bda76ff2e59733d7d88289563527aa16d0bb8d4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 17:40:46 +0300 Subject: [PATCH 0816/1406] update --- lua/platformio/utils/pio.lua | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index fa129532..663034dd 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -260,7 +260,9 @@ M.run_sequence = function(tasks) _G.metadata.isBusy = true -- local ToggleTerminal = require('platformio.utils.term').ToggleTerminal -- ToggleTerminal(full_cmd, 'float') - if M.term then M.term.ToggleTerminal(full_cmd, 'float') end + -- if M.term then + M.term(full_cmd, 'float') + -- end end From 2071d74d50e955d218c606ceba34fa5d03056c1d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 18:04:54 +0300 Subject: [PATCH 0817/1406] update --- lua/platformio/utils/pio.lua | 32 +++++++++++++++++++++++--------- lua/platformio/utils/term.lua | 16 +++++++++------- plugin/platformio.lua | 6 ++++-- 3 files changed, 36 insertions(+), 18 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 663034dd..d8348814 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -2,7 +2,10 @@ local M = {} M.selected_framework = '' +-- to fix require loop, this value is set in plugin/platformio M.term = nil +M.stdout_callback = nil + local misc = require('platformio.utils.misc') local lsp_restart = require('platformio.lsp.tools').lsp_restart @@ -195,7 +198,7 @@ local pio_buffer = '' -- Persistent stream buffer ------------------------------------------------------ -- INFO: ToggleTerminal commands stdout filter -- stylua: ignore -function M.stdoutFilter(_, _, data) +function M.stdoutcallback(_, _, data) if #M.queue == 0 then return end -- 1. attach partial buffer from previous data last line to 1st line @@ -237,7 +240,7 @@ end ------------------------------------------------------ -- INFO: ToggleTerminal commands Sequencer --- stylua: ignore +--- stylua: ignore M.run_sequence = function(tasks) -- Reset local state for new run M.queue = {} @@ -250,20 +253,31 @@ M.run_sequence = function(tasks) for _, task in ipairs(tasks) do table.insert(M.queue, task.cb) local part = string.format('%s %s', task.cmd, pass) - if full_cmd == '' then full_cmd = part - else full_cmd = full_cmd .. ' && ' .. part end + if full_cmd == '' then + full_cmd = part + else + full_cmd = full_cmd .. ' && ' .. part + end end full_cmd = full_cmd .. done .. fail - table.insert(M.queue, function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end) - table.insert(M.queue, function () vim.notify('Pioinit: Failed', vim.log.levels.INFO) end) + + table.insert(M.queue, function() + vim.notify('Pioinit: Done', vim.log.levels.INFO) + M.stdout_callback = nil + end) + + table.insert(M.queue, function() + vim.notify('Pioinit: Failed', vim.log.levels.INFO) + end) + -- full_cmd = full_cmd .. ' || ' .. fail _G.metadata.isBusy = true -- local ToggleTerminal = require('platformio.utils.term').ToggleTerminal -- ToggleTerminal(full_cmd, 'float') - -- if M.term then - M.term(full_cmd, 'float') + -- if M.term then + M.stdout_callback = M.stdoutcallback() + M.term(full_cmd, 'float') -- end - end -- { diff --git a/lua/platformio/utils/term.lua b/lua/platformio/utils/term.lua index 582350cc..14251b99 100644 --- a/lua/platformio/utils/term.lua +++ b/lua/platformio/utils/term.lua @@ -7,8 +7,9 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' local config = require('platformio').config --- local pio = require('platformio.utils.pio') --- A socket for the logic module to plug into +-- to fix require loop, toggleterm is using stdout_callback function in 'platformio.utils.pio' +-- M.stdout_callback will be assigned in 'plgin/platformio' to 'platformio.utils.pio.stdout_callback' +-- below on_stdout will be assigned to M.stdout_callback M.stdout_callback = nil ------------------------------------------------------ @@ -169,11 +170,12 @@ function M.ToggleTerminal(command, direction) -- INFO: on_stdout -- on_stdout = stdout_callback, -- pioOpts.on_stdout = pio.stdoutFilter - pioOpts.on_stdout = function(t, job, exit_code) - if type(M.stdout_callback) == 'function' then - M.stdout_callback(t, job, exit_code) - end - end + pioOpts.on_stdout = M.stdout_callback + -- function(t, job, exit_code) + -- if type(M.stdout_callback) == 'function' then + -- M.stdout_callback(t, job, exit_code) + -- end + -- end end pioOpts.direction = direction ------------------------------------------------------ diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 9b8e7ad3..fa672719 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -9,10 +9,12 @@ local piolsserial = require('platformio.piolsserial') local misc = require('platformio.utils.misc') +-- INFO: Dependency Injection: Plug the logic into the terminal +-- these 4 lines used to fix require loop between +-- 'platformio.utils.term' and 'platformio.utils.pio' local term = require('platformio.utils.term') local pio = require('platformio.utils.pio') ---Dependency Injection: Plug the logic into the terminal -term.stdout_callback = pio.stdoutFilter +term.stdout_callback = pio.stdoutcallback pio.term = term.ToggleTerminal -- Pioinit From bacfe51f734acfbdd604576a1080ed398cb03685 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 18:08:55 +0300 Subject: [PATCH 0818/1406] update --- plugin/platformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/platformio.lua b/plugin/platformio.lua index fa672719..6fa61a20 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -14,7 +14,7 @@ local misc = require('platformio.utils.misc') -- 'platformio.utils.term' and 'platformio.utils.pio' local term = require('platformio.utils.term') local pio = require('platformio.utils.pio') -term.stdout_callback = pio.stdoutcallback +term.stdout_callback = pio.stdout_callback pio.term = term.ToggleTerminal -- Pioinit From 8c3ace2e471e4f3047d5610b1a528074342a830f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 18:12:48 +0300 Subject: [PATCH 0819/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index d8348814..afd7c648 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -275,7 +275,7 @@ M.run_sequence = function(tasks) -- local ToggleTerminal = require('platformio.utils.term').ToggleTerminal -- ToggleTerminal(full_cmd, 'float') -- if M.term then - M.stdout_callback = M.stdoutcallback() + M.stdout_callback = M.stdoutcallback M.term(full_cmd, 'float') -- end end From 323ba3cc03838b4881653ed01f336a5d97955c68 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 18:44:07 +0300 Subject: [PATCH 0820/1406] update --- lua/platformio/utils/pio.lua | 4 ++++ plugin/platformio.lua | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index afd7c648..47a8a2e6 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -4,7 +4,11 @@ M.selected_framework = '' -- to fix require loop, this value is set in plugin/platformio M.term = nil + M.stdout_callback = nil +M.stdout = function() + return M.stdout_callback +end local misc = require('platformio.utils.misc') local lsp_restart = require('platformio.lsp.tools').lsp_restart diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 6fa61a20..bb1ee391 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -14,7 +14,7 @@ local misc = require('platformio.utils.misc') -- 'platformio.utils.term' and 'platformio.utils.pio' local term = require('platformio.utils.term') local pio = require('platformio.utils.pio') -term.stdout_callback = pio.stdout_callback +term.stdout_callback = pio.stdout pio.term = term.ToggleTerminal -- Pioinit From 15c875a618b8242fd0b6a79c6a62432a37c76aa2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 19:25:05 +0300 Subject: [PATCH 0821/1406] update --- plugin/platformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/platformio.lua b/plugin/platformio.lua index bb1ee391..d10182aa 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -14,7 +14,7 @@ local misc = require('platformio.utils.misc') -- 'platformio.utils.term' and 'platformio.utils.pio' local term = require('platformio.utils.term') local pio = require('platformio.utils.pio') -term.stdout_callback = pio.stdout +term.stdout_callback = pio.stdout() pio.term = term.ToggleTerminal -- Pioinit From 55b82307af7dd61dbd0d2313ab8176d6710201a7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 20:17:53 +0300 Subject: [PATCH 0822/1406] update --- lua/platformio/utils/pio.lua | 16 ++++------------ lua/platformio/utils/term.lua | 20 ++++++-------------- plugin/platformio.lua | 7 ------- 3 files changed, 10 insertions(+), 33 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 47a8a2e6..ba12df21 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -3,13 +3,8 @@ local M = {} M.selected_framework = '' -- to fix require loop, this value is set in plugin/platformio -M.term = nil - -M.stdout_callback = nil -M.stdout = function() - return M.stdout_callback -end +local term = require('platformio.utils.term') local misc = require('platformio.utils.misc') local lsp_restart = require('platformio.lsp.tools').lsp_restart @@ -267,7 +262,7 @@ M.run_sequence = function(tasks) table.insert(M.queue, function() vim.notify('Pioinit: Done', vim.log.levels.INFO) - M.stdout_callback = nil + term.stdout_callback = nil end) table.insert(M.queue, function() @@ -277,11 +272,8 @@ M.run_sequence = function(tasks) -- full_cmd = full_cmd .. ' || ' .. fail _G.metadata.isBusy = true -- local ToggleTerminal = require('platformio.utils.term').ToggleTerminal - -- ToggleTerminal(full_cmd, 'float') - -- if M.term then - M.stdout_callback = M.stdoutcallback - M.term(full_cmd, 'float') - -- end + term.stdout_callback = M.stdoutcallback + term.ToggleTerminal(full_cmd, 'float') end -- { diff --git a/lua/platformio/utils/term.lua b/lua/platformio/utils/term.lua index 14251b99..4eed338b 100644 --- a/lua/platformio/utils/term.lua +++ b/lua/platformio/utils/term.lua @@ -8,8 +8,7 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' local config = require('platformio').config -- to fix require loop, toggleterm is using stdout_callback function in 'platformio.utils.pio' --- M.stdout_callback will be assigned in 'plgin/platformio' to 'platformio.utils.pio.stdout_callback' --- below on_stdout will be assigned to M.stdout_callback +-- M.stdout_callback will be assigned by 'platformio.utils.pio' M.stdout_callback = nil ------------------------------------------------------ @@ -168,14 +167,11 @@ function M.ToggleTerminal(command, direction) pioOpts.id = 99 -- INFO: on_stdout - -- on_stdout = stdout_callback, - -- pioOpts.on_stdout = pio.stdoutFilter - pioOpts.on_stdout = M.stdout_callback - -- function(t, job, exit_code) - -- if type(M.stdout_callback) == 'function' then - -- M.stdout_callback(t, job, exit_code) - -- end - -- end + pioOpts.on_stdout = function(t, job, exit_code) + if type(M.stdout_callback) == 'function' then + M.stdout_callback(t, job, exit_code) + end + end end pioOpts.direction = direction ------------------------------------------------------ @@ -256,10 +252,6 @@ function M.ToggleTerminal(command, direction) -- exit_callback() -- end, - -- INFO: on_stdout - -- on_stdout = stdout_callback, - -- on_stdout = pio.stdoutFilter, - -- INFO: on_create() { on_create = function(t) local platformio = vim.api.nvim_create_augroup(M.strsplit(t.display_name, ':')[1], { clear = true }) diff --git a/plugin/platformio.lua b/plugin/platformio.lua index d10182aa..eac4286a 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -8,14 +8,7 @@ local piolsserial = require('platformio.piolsserial') local misc = require('platformio.utils.misc') - --- INFO: Dependency Injection: Plug the logic into the terminal --- these 4 lines used to fix require loop between --- 'platformio.utils.term' and 'platformio.utils.pio' -local term = require('platformio.utils.term') local pio = require('platformio.utils.pio') -term.stdout_callback = pio.stdout() -pio.term = term.ToggleTerminal -- Pioinit vim.api.nvim_create_user_command('Pioinit', function() From cccfcc8e19d46c54e90c4cbe4d400f2272158cdd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 20:49:03 +0300 Subject: [PATCH 0823/1406] update --- lua/platformio/metadata.lua | 17 +++++++-------- lua/platformio/utils/pio.lua | 40 +++++++++++++++++++++++++++--------- mini_nvimPlatformio.lua | 14 ++++++++++++- 3 files changed, 52 insertions(+), 19 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 564f5d59..f1487641 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -11,15 +11,16 @@ local M = {} -- The Statusline Getter (used by the UI) function M.get_pio_status() - if _G.metadata and _G.metadata.active_env and _G.metadata.active_env ~= '' then - return string.format(' [ %s ] ', _G.metadata.active_env) - end - return '' + -- Using pcall ensures that if 'require' or 'metadata' fails, + -- the statusline just shows nothing instead of throwing an error. + local ok, status = pcall(function() + if _G.metadata and _G.metadata.active_env and _G.metadata.active_env ~= '' then + return string.format(' [ %s ] ', _G.metadata.active_env) + end + return '' + end) + return ok and status or '' end --- --- Optional: Add a nice color for the environment name -vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) - ------------------------------------------------------------------------------------------------------- -- 1. Internal State & Defaults local last_saved_hash = '' diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index ba12df21..137a7380 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -44,19 +44,39 @@ function M.compile_commandsFix() end end - -- 3. Save with Python formatting - if modified then - local json_str = vim.json.encode(data) - local formatted = vim.fn.system('python -m json.tool', json_str) + -- PHASE 3: Save and Refresh + if modified > 0 then + -- 1. Native Lua encoding (indented 2 spaces) + local _, json_str = pcall(vim.json.encode, data, { indent = " " }) - if vim.v.shell_error == 0 then - -- Atomic write back to disk - vim.fn.writefile(vim.split(formatted, "\n"), filename) - vim.notify('compiledb: paths fixed', vim.log.levels.INFO) - else - vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) + if ok and json_str then + -- 2. Convert string to a table of lines (required by writefile) + local lines = vim.split(json_str, '\n') + + -- 3. Atomic write to disk + -- 's' flag forces a system sync to ensure data is physically written + local status = vim.fn.writefile(lines, filename, 's') + + if status == 0 then + vim.notify('compiledb: fixed and saved safely', vim.log.levels.INFO) + else + vim.notify('compiledb: failed to write file', vim.log.levels.ERROR) + end end end + -- 3. Save with Python formatting + -- if modified then + -- local json_str = vim.json.encode(data) + -- local formatted = vim.fn.system('python -m json.tool', json_str) + -- + -- if vim.v.shell_error == 0 then + -- -- Atomic write back to disk + -- vim.fn.writefile(vim.split(formatted, "\n"), filename) + -- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) + -- else + -- vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) + -- end + -- end lsp_restart('clangd') _G.metadata.isBusy = false end diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 3ddddaa3..d6037604 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -324,12 +324,24 @@ vim.api.nvim_create_autocmd('User', { end, }) +-- We use luaeval to call the getter we defined in pio.lua (or metadata.lua) +vim.o.laststatus = 3 +vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("require(\'platformio.metadata\').get_pio_status()")} %y %p%% %l:%c' +vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) + -- INFO: refreshes the statusline whenever you enter a C/C++ file vim.api.nvim_create_autocmd({ 'BufEnter', 'FileType' }, { pattern = { 'c', 'cpp', 'objc', 'objcpp', 'h', 'hpp' }, callback = function() -- Assuming your module is required as 'pio' - require('platformio.metadata').refresh_statusline() + if _G.metadata then + -- 1. Run your refresh logic + require('platformio.metadata').refresh_statusline() + + -- 2. Force an immediate visual repaint of the status bar + -- This is the 'secret sauce' for %{ } expressions + vim.cmd('redrawstatus') + end end, }) ---------------------------------------------------------------------------------------- From 1efa9969632e0ca07564089e3aeca48adf55e29a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 20:59:04 +0300 Subject: [PATCH 0824/1406] update --- lua/platformio/utils/pio.lua | 58 ++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 137a7380..fc560193 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -45,38 +45,38 @@ function M.compile_commandsFix() end -- PHASE 3: Save and Refresh - if modified > 0 then - -- 1. Native Lua encoding (indented 2 spaces) - local _, json_str = pcall(vim.json.encode, data, { indent = " " }) - - if ok and json_str then - -- 2. Convert string to a table of lines (required by writefile) - local lines = vim.split(json_str, '\n') - - -- 3. Atomic write to disk - -- 's' flag forces a system sync to ensure data is physically written - local status = vim.fn.writefile(lines, filename, 's') - - if status == 0 then - vim.notify('compiledb: fixed and saved safely', vim.log.levels.INFO) - else - vim.notify('compiledb: failed to write file', vim.log.levels.ERROR) - end - end - end - -- 3. Save with Python formatting - -- if modified then - -- local json_str = vim.json.encode(data) - -- local formatted = vim.fn.system('python -m json.tool', json_str) + -- if modified > 0 then + -- -- 1. Native Lua encoding (indented 2 spaces) + -- local _, json_str = pcall(vim.json.encode, data, { indent = " " }) -- - -- if vim.v.shell_error == 0 then - -- -- Atomic write back to disk - -- vim.fn.writefile(vim.split(formatted, "\n"), filename) - -- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) - -- else - -- vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) + -- if ok and json_str then + -- -- 2. Convert string to a table of lines (required by writefile) + -- local lines = vim.split(json_str, '\n') + -- + -- -- 3. Atomic write to disk + -- -- 's' flag forces a system sync to ensure data is physically written + -- local status = vim.fn.writefile(lines, filename, 's') + -- + -- if status == 0 then + -- vim.notify('compiledb: fixed and saved safely', vim.log.levels.INFO) + -- else + -- vim.notify('compiledb: failed to write file', vim.log.levels.ERROR) + -- end -- end -- end + -- 3. Save with Python formatting + if modified then + local json_str = vim.json.encode(data) + local formatted = vim.fn.system('python -m json.tool', json_str) + + if vim.v.shell_error == 0 then + -- Atomic write back to disk + vim.fn.writefile(vim.split(formatted, "\n"), filename) + vim.notify('compiledb: paths fixed', vim.log.levels.INFO) + else + vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) + end + end lsp_restart('clangd') _G.metadata.isBusy = false end From 76541b053ac397a9cbe14a2baede1356a2e03d96 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 21:05:38 +0300 Subject: [PATCH 0825/1406] update --- lua/platformio/utils/pio.lua | 56 ++++++++++++++++++------------------ 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index fc560193..d494cc0a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -45,38 +45,38 @@ function M.compile_commandsFix() end -- PHASE 3: Save and Refresh - -- if modified > 0 then - -- -- 1. Native Lua encoding (indented 2 spaces) - -- local _, json_str = pcall(vim.json.encode, data, { indent = " " }) - -- - -- if ok and json_str then - -- -- 2. Convert string to a table of lines (required by writefile) - -- local lines = vim.split(json_str, '\n') - -- - -- -- 3. Atomic write to disk - -- -- 's' flag forces a system sync to ensure data is physically written - -- local status = vim.fn.writefile(lines, filename, 's') - -- - -- if status == 0 then - -- vim.notify('compiledb: fixed and saved safely', vim.log.levels.INFO) - -- else - -- vim.notify('compiledb: failed to write file', vim.log.levels.ERROR) - -- end - -- end - -- end - -- 3. Save with Python formatting if modified then - local json_str = vim.json.encode(data) - local formatted = vim.fn.system('python -m json.tool', json_str) + -- 1. Native Lua encoding (indented 2 spaces) + local _, json_str = pcall(vim.json.encode, data, { indent = " " }) - if vim.v.shell_error == 0 then - -- Atomic write back to disk - vim.fn.writefile(vim.split(formatted, "\n"), filename) - vim.notify('compiledb: paths fixed', vim.log.levels.INFO) - else - vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) + if ok and json_str then + -- 2. Convert string to a table of lines (required by writefile) + local lines = vim.split(json_str, '\n') + + -- 3. Atomic write to disk + -- 's' flag forces a system sync to ensure data is physically written + local status = vim.fn.writefile(lines, filename, 's') + + if status == 0 then + vim.notify('compiledb: fixed and saved safely', vim.log.levels.INFO) + else + vim.notify('compiledb: failed to write file', vim.log.levels.ERROR) + end end end + -- 3. Save with Python formatting + -- if modified then + -- local json_str = vim.json.encode(data) + -- local formatted = vim.fn.system('python -m json.tool', json_str) + -- + -- if vim.v.shell_error == 0 then + -- -- Atomic write back to disk + -- vim.fn.writefile(vim.split(formatted, "\n"), filename) + -- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) + -- else + -- vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) + -- end + -- end lsp_restart('clangd') _G.metadata.isBusy = false end From 908c5c2d06b1abe468b94d6e145d8a9e3a86fc65 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 21:17:47 +0300 Subject: [PATCH 0826/1406] update --- lua/platformio/metadata.lua | 36 ++++++++++++++++++------------------ mini_nvimPlatformio.lua | 3 ++- 2 files changed, 20 insertions(+), 19 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index f1487641..be890971 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,26 +1,26 @@ local M = {} --- _G.get_pio_status = function() --- if _G.metadata and _G.metadata.active_env ~= '' then --- return ' [ ' .. _G.metadata.active_env .. '] ' --- end --- return '' --- end --- -- Move the %#PioStatus# and %* outside of the curly braces +_G.get_pio_status = function() + if _G.metadata and _G.metadata.active_env ~= '' then + return ' [ ' .. _G.metadata.active_env .. '] ' + end + return '' +end +-- Move the %#PioStatus# and %* outside of the curly braces -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' -- The Statusline Getter (used by the UI) -function M.get_pio_status() - -- Using pcall ensures that if 'require' or 'metadata' fails, - -- the statusline just shows nothing instead of throwing an error. - local ok, status = pcall(function() - if _G.metadata and _G.metadata.active_env and _G.metadata.active_env ~= '' then - return string.format(' [ %s ] ', _G.metadata.active_env) - end - return '' - end) - return ok and status or '' -end +-- function M.get_pio_status() +-- -- Using pcall ensures that if 'require' or 'metadata' fails, +-- -- the statusline just shows nothing instead of throwing an error. +-- local ok, status = pcall(function() +-- if _G.metadata and _G.metadata.active_env and _G.metadata.active_env ~= '' then +-- return string.format(' [ %s ] ', _G.metadata.active_env) +-- end +-- return '' +-- end) +-- return ok and status or '' +-- end ------------------------------------------------------------------------------------------------------- -- 1. Internal State & Defaults local last_saved_hash = '' diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index d6037604..63d9e027 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -326,7 +326,8 @@ vim.api.nvim_create_autocmd('User', { -- We use luaeval to call the getter we defined in pio.lua (or metadata.lua) vim.o.laststatus = 3 -vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("require(\'platformio.metadata\').get_pio_status()")} %y %p%% %l:%c' +vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' +-- vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("require(\'platformio.metadata\').get_pio_status()")} %y %p%% %l:%c' vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) -- INFO: refreshes the statusline whenever you enter a C/C++ file From a8b64fe5e861a7d495202ef4d0b24195b6d9e43c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 21:19:13 +0300 Subject: [PATCH 0827/1406] update --- mini_nvimPlatformio.lua | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 63d9e027..5da1b89f 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -331,20 +331,20 @@ vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) -- INFO: refreshes the statusline whenever you enter a C/C++ file -vim.api.nvim_create_autocmd({ 'BufEnter', 'FileType' }, { - pattern = { 'c', 'cpp', 'objc', 'objcpp', 'h', 'hpp' }, - callback = function() - -- Assuming your module is required as 'pio' - if _G.metadata then - -- 1. Run your refresh logic - require('platformio.metadata').refresh_statusline() - - -- 2. Force an immediate visual repaint of the status bar - -- This is the 'secret sauce' for %{ } expressions - vim.cmd('redrawstatus') - end - end, -}) +-- vim.api.nvim_create_autocmd({ 'BufEnter', 'FileType' }, { +-- pattern = { 'c', 'cpp', 'objc', 'objcpp', 'h', 'hpp' }, +-- callback = function() +-- -- Assuming your module is required as 'pio' +-- if _G.metadata then +-- -- 1. Run your refresh logic +-- require('platformio.metadata').refresh_statusline() +-- +-- -- 2. Force an immediate visual repaint of the status bar +-- -- This is the 'secret sauce' for %{ } expressions +-- vim.cmd('redrawstatus') +-- end +-- end, +-- }) ---------------------------------------------------------------------------------------- -- INFO: set up python nvim venv (virtual environment 'nenv'), activaten. local platformio_core_dir, pynvim_env, pynvim_python, pynvim_lib, pynvim_bin, pynvim_activate From b3be8924b5f48f4dce155ad7142087958f360dd6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 21:26:57 +0300 Subject: [PATCH 0828/1406] update --- mini_nvimPlatformio.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 5da1b89f..129803d4 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -54,7 +54,8 @@ else vim.opt.shellxquote = '' end -- Define a custom highlight group -vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#A6E22E', bold = true }) +-- vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#A6E22E', bold = true }) +vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) ---------------------------------------------------------------------------------------- -- INFO: Set diagnostic config @@ -326,9 +327,8 @@ vim.api.nvim_create_autocmd('User', { -- We use luaeval to call the getter we defined in pio.lua (or metadata.lua) vim.o.laststatus = 3 -vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' --- vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("require(\'platformio.metadata\').get_pio_status()")} %y %p%% %l:%c' -vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) +-- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' +vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("require(\'platformio.metadata\').get_pio_status()")} %y %p%% %l:%c' -- INFO: refreshes the statusline whenever you enter a C/C++ file -- vim.api.nvim_create_autocmd({ 'BufEnter', 'FileType' }, { From 37f53789120a89b0094a328fb61a8470035c9406 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 21:29:22 +0300 Subject: [PATCH 0829/1406] update --- mini_nvimPlatformio.lua | 5 ----- plugin/platformio.lua | 5 +++++ 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 129803d4..d3939a27 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -325,11 +325,6 @@ vim.api.nvim_create_autocmd('User', { end, }) --- We use luaeval to call the getter we defined in pio.lua (or metadata.lua) -vim.o.laststatus = 3 --- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' -vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("require(\'platformio.metadata\').get_pio_status()")} %y %p%% %l:%c' - -- INFO: refreshes the statusline whenever you enter a C/C++ file -- vim.api.nvim_create_autocmd({ 'BufEnter', 'FileType' }, { -- pattern = { 'c', 'cpp', 'objc', 'objcpp', 'h', 'hpp' }, diff --git a/plugin/platformio.lua b/plugin/platformio.lua index eac4286a..8a5f8111 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -10,6 +10,11 @@ local piolsserial = require('platformio.piolsserial') local misc = require('platformio.utils.misc') local pio = require('platformio.utils.pio') +-- We use luaeval to call the getter we defined in pio.lua (or metadata.lua) +vim.o.laststatus = 3 +-- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' +vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("require(\'platformio.metadata\').get_pio_status()")} %y %p%% %l:%c' + -- Pioinit vim.api.nvim_create_user_command('Pioinit', function() require('platformio.pioinit').pioinit() From 5659d9345e8ccbb8cff46ff65dea34fc17f72d22 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 21:31:04 +0300 Subject: [PATCH 0830/1406] update --- plugin/platformio.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 8a5f8111..ea9a70b6 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -11,9 +11,9 @@ local misc = require('platformio.utils.misc') local pio = require('platformio.utils.pio') -- We use luaeval to call the getter we defined in pio.lua (or metadata.lua) -vim.o.laststatus = 3 --- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' -vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("require(\'platformio.metadata\').get_pio_status()")} %y %p%% %l:%c' +-- vim.o.laststatus = 3 +-- -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' +-- vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("require(\'platformio.metadata\').get_pio_status()")} %y %p%% %l:%c' -- Pioinit vim.api.nvim_create_user_command('Pioinit', function() From 3b8117bbe3b5e73d5856064c2b00a5e6485e154a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 21:32:41 +0300 Subject: [PATCH 0831/1406] update --- lua/platformio/metadata.lua | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index be890971..a46a05a8 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,11 +1,11 @@ local M = {} -_G.get_pio_status = function() - if _G.metadata and _G.metadata.active_env ~= '' then - return ' [ ' .. _G.metadata.active_env .. '] ' - end - return '' -end +-- _G.get_pio_status = function() +-- if _G.metadata and _G.metadata.active_env ~= '' then +-- return ' [ ' .. _G.metadata.active_env .. '] ' +-- end +-- return '' +-- end -- Move the %#PioStatus# and %* outside of the curly braces -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' From 39bb43834a5ce4b328570bd686e0d24872aae9ae Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 21:53:26 +0300 Subject: [PATCH 0832/1406] update --- lua/platformio/metadata.lua | 14 +++++----- lua/platformio/utils/pio.lua | 51 +++++++++++++++++++++++++++--------- 2 files changed, 45 insertions(+), 20 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index a46a05a8..a41f8cc5 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,13 +1,13 @@ local M = {} --- _G.get_pio_status = function() --- if _G.metadata and _G.metadata.active_env ~= '' then --- return ' [ ' .. _G.metadata.active_env .. '] ' --- end --- return '' --- end +_G.get_pio_status = function() + if _G.metadata and _G.metadata.active_env ~= '' then + return ' [ ' .. _G.metadata.active_env .. '] ' + end + return '' +end -- Move the %#PioStatus# and %* outside of the curly braces --- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' +vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' -- The Statusline Getter (used by the UI) -- function M.get_pio_status() diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index d494cc0a..92e772e4 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -46,22 +46,47 @@ function M.compile_commandsFix() -- PHASE 3: Save and Refresh if modified then - -- 1. Native Lua encoding (indented 2 spaces) - local _, json_str = pcall(vim.json.encode, data, { indent = " " }) + -- -- 1. Native Lua encoding (indented 2 spaces) + -- local _, json_str = pcall(vim.json.encode, data, { indent = " " }) + -- + -- if ok and json_str then + -- -- 2. Convert string to a table of lines (required by writefile) + -- local lines = vim.split(json_str, '\n') + -- + -- -- 3. Atomic write to disk + -- -- 's' flag forces a system sync to ensure data is physically written + -- local status = vim.fn.writefile(lines, filename, 's') + -- + -- if status == 0 then + -- vim.notify('compiledb: fixed and saved safely', vim.log.levels.INFO) + -- else + -- vim.notify('compiledb: failed to write file', vim.log.levels.ERROR) + -- end + -- end - if ok and json_str then - -- 2. Convert string to a table of lines (required by writefile) - local lines = vim.split(json_str, '\n') + local jok, json_str = pcall(vim.json.encode, data, { indent = " " }) + if not jok or not json_str then + vim.notify("PIO: JSON Encoding failed", 4) + return M.process_queue() -- Don't get stuck + end - -- 3. Atomic write to disk - -- 's' flag forces a system sync to ensure data is physically written - local status = vim.fn.writefile(lines, filename, 's') + local lines = vim.split(json_str, '\n') - if status == 0 then - vim.notify('compiledb: fixed and saved safely', vim.log.levels.INFO) - else - vim.notify('compiledb: failed to write file', vim.log.levels.ERROR) - end + -- 1. Check if the directory is actually writable (Safety Check) + local dir = vim.fn.fnamemodify(filename, ":h") + if vim.fn.isdirectory(dir) == 0 then + vim.notify("PIO: Directory does not exist: " .. dir, 4) + return M.process_queue() + end + + -- 2. Use pcall to prevent the function from "exiting" on error + local write_ok, status = pcall(vim.fn.writefile, lines, filename, 's') + + if write_ok and status == 0 then + vim.notify('compiledb: fixed and saved', 2) + else + local err_msg = not write_ok and status or "Write error (check permissions)" + vim.notify('PIO Save Failed: ' .. err_msg, 4) end end -- 3. Save with Python formatting From acd8aec4dd41549f5f4fc9ed851fe19a35eac42f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 21:58:15 +0300 Subject: [PATCH 0833/1406] update --- lua/platformio/metadata.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index a41f8cc5..583c4a87 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -7,7 +7,7 @@ _G.get_pio_status = function() return '' end -- Move the %#PioStatus# and %* outside of the curly braces -vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' +-- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' -- The Statusline Getter (used by the UI) -- function M.get_pio_status() @@ -75,7 +75,8 @@ _G.metadata = setmetatable({}, { vim.o.laststatus = 3 -- Ensure your custom layout is the final word - vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' + vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' + -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' end -- if key == 'active_env' then -- vim.notify('Env: ' .. value, vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) From 56693e1c4dd442cc021dde0c75f69f156bb05075 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 22:19:40 +0300 Subject: [PATCH 0834/1406] update --- lua/platformio/boilerplate.lua | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 4f60b602..111b3cd5 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -47,7 +47,9 @@ extra_scripts = ; pre:enable_toolchain.py ; enabled global env 'PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN' lib_ldf_mode = chain ;Library dependencies Finder ldf -build_flags = + +build_flags = + -I${platformio.packages_dir}/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0 -D COMPILATIONDB_INCLUDE_TOOLCHAIN ]], content = function(self) From b87ecc03e58137648ed55de3d953b24389668bdc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 22:50:18 +0300 Subject: [PATCH 0835/1406] update --- lua/platformio/metadata.lua | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 583c4a87..523caedb 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,11 +1,19 @@ local M = {} _G.get_pio_status = function() - if _G.metadata and _G.metadata.active_env ~= '' then - return ' [ ' .. _G.metadata.active_env .. '] ' + -- Add a manual check for the metatable if it exists + local val = _G.metadata and _G.metadata.active_env + if val and val ~= '' then + return ' [ ' .. val .. '] ' end return '' end +-- _G.get_pio_status = function() +-- if _G.metadata and _G.metadata.active_env ~= '' then +-- return ' [ ' .. _G.metadata.active_env .. '] ' +-- end +-- return '' +-- end -- Move the %#PioStatus# and %* outside of the curly braces -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' @@ -74,8 +82,10 @@ _G.metadata = setmetatable({}, { -- Force global statusline so it doesn't get pushed around by Trouble or splits vim.o.laststatus = 3 + -- Using luaeval with escaped quotes is the "bulletproof" Linux method + vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("_G.get_pio_status()")}%* %y %p%% %l:%c' -- Ensure your custom layout is the final word - vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' + -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' end -- if key == 'active_env' then From 1a4484d763a98081d5eaa102113440073c31176d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 23:00:08 +0300 Subject: [PATCH 0836/1406] update --- lua/platformio/metadata.lua | 6 ------ mini_nvimPlatformio.lua | 3 ++- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 523caedb..913db12b 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -88,12 +88,6 @@ _G.metadata = setmetatable({}, { -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' end - -- if key == 'active_env' then - -- vim.notify('Env: ' .. value, vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) - -- pcall(function() - -- vim.cmd('LspRestart clangd') - -- end) - -- end end) end, }) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index d3939a27..e9370c3d 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -55,7 +55,8 @@ else end -- Define a custom highlight group -- vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#A6E22E', bold = true }) -vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) +-- vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) +vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#e0af68', bold = true }) ---------------------------------------------------------------------------------------- -- INFO: Set diagnostic config From 70ed36c191e51bcac4ff6bc9e4bde49b8620d144 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 23:29:07 +0300 Subject: [PATCH 0837/1406] update --- compile_commandsFix.lua | 129 ++++++++++++++++ lua/platformio/metadata.lua | 37 ++++- lua/platformio/utils/pio.lua | 291 +++++++++++------------------------ plugin/platformio.lua | 13 ++ 4 files changed, 265 insertions(+), 205 deletions(-) create mode 100644 compile_commandsFix.lua diff --git a/compile_commandsFix.lua b/compile_commandsFix.lua new file mode 100644 index 00000000..0e81e1d2 --- /dev/null +++ b/compile_commandsFix.lua @@ -0,0 +1,129 @@ +-- function M.compile_commandsFix() +-- local filename = vim.uv.cwd() .. '/compile_commands.json' +-- local content = vim.fn.readfile(filename) +-- if #content == 0 then return end +-- +-- local ok, data = pcall(vim.json.decode, table.concat(content, "\n")) +-- if not ok or type(data) ~= 'table' then return end +-- +-- -- 1. Build Path Map (Scan toolchain) +-- local path_map = {} +-- +-- local pio_binaries = _G.metadata.query_driver or "/bin/*" +-- -- local pio_binaries = (_G.metadata.toolchain_root or "") .. '/bin/*' +-- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do +-- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') +-- path_map[name] = full_path +-- end +-- +-- -- 2. Update Entries +-- local modified = false +-- for _, entry in ipairs(data) do +-- local cmd = entry.command or "" +-- local first_token = cmd:match("^%S+") -- Get first word before space +-- +-- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then +-- local short_name = first_token:gsub('%.exe$', '') +-- if path_map[short_name] then +-- -- Swap first token with full path safely +-- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) +-- modified = true +-- end +-- end +-- end +-- +-- -- 3. Save with Formatting +-- if modified then +-- local json_str = vim.json.encode(data) +-- -- Use python to format, then write file +-- local formatted = vim.fn.system('python -m json.tool', json_str) +-- if vim.v.shell_error == 0 then +-- vim.fn.writefile(vim.split(formatted, "\n"), filename) +-- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) +-- end +-- end +-- end + +function M.compile_commandsFix() + local filename = vim.uv.cwd() .. '/compile_commands.json' + local file = io.open(filename, 'r') + if not file then + return + end + + -- read compile_commands.json file to content + local content = file:read('*a') + file:close() + if not content or content == '' then + return + end + + -- JSON decoding content to data + local ok, data = pcall(vim.json.decode, content) + if not ok or type(data) ~= 'table' then + vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) + return + end + + print('PioFix0') + -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path + local path_map = {} + local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') + if pio_home then + -- Recursively find all binaries in PIO packages + local pio_packages = _G.metadata.toolchain_root .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' + local found_binaries = vim.fn.glob(pio_packages, false, true) + + for _, full_path in ipairs(found_binaries) do + -- Extract filename (e.g., riscv32-esp-elf-gcc) + local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') + path_map[name] = full_path + -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) + end + end + + -- PHASE 2: Update JSON using the Map + local modified = 0 + for _, entry in ipairs(data) do + if type(entry.command) == 'string' then + local cmd_parts = vim.split(entry.command, ' ') + local first_token = cmd_parts[1] + if first_token then + -- Check if it's already a short name (not an absolute path) + local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') + if not is_abs then + local short_name = first_token:gsub('%.exe$', '') + -- print('PioFix2: short_name=' .. short_name) + -- Direct Query: Does this name exist in our discovered list? + if path_map[short_name] then + cmd_parts[1] = path_map[short_name] + -- print('PioFix3: full_name=' .. cmd_parts[1]) + entry.command = table.concat(cmd_parts, ' ') + modified = modified + 1 + end + end + end + end + end + + -- PHASE 3: Save and Refresh + -- Safe JSON encoding + if modified > 0 then + local out_file = io.open(filename, 'w') + if out_file then + local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) + if encode_ok and json_str then + -- 1. Format the string using python's json.tool + -- The second argument to vim.fn.system() is the "stdin" passed to the command + local formatted_json = vim.fn.system('python -m json.tool', json_str) + + -- out_file:write(json_str) + out_file:write(formatted_json) + out_file:close() + vim.notify('compiledb: fixed', vim.log.levels.INFO) + lsp_restart('clangd') + _G.metadata.isBusy = false + end + end + end +end diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 913db12b..86a15609 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,14 +1,36 @@ local M = {} -_G.get_pio_status = function() - -- Add a manual check for the metatable if it exists - local val = _G.metadata and _G.metadata.active_env - if val and val ~= '' then - return ' [ ' .. val .. '] ' +local frames = { '⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏' } +local frame_idx = 1 + +function M.get_pio_status() + local meta = _G.metadata + if not meta then + return '' + end + + -- Accessing meta.active_env triggers __index automatically in Lua + local active = meta.active_env or '' + if active == '' then + return '' + end + + if M.is_busy then + local icon = frames[frame_idx] + frame_idx = (frame_idx % #frames) + 1 + return string.format(' [ %s %s ] ', icon, active) end - return '' + return string.format(' [ %s ] ', active) end -- _G.get_pio_status = function() +-- -- Add a manual check for the metatable if it exists +-- local val = _G.metadata and _G.metadata.active_env +-- if val and val ~= '' then +-- return ' [ ' .. val .. '] ' +-- end +-- return '' +-- end +-- _G.get_pio_status = function() -- if _G.metadata and _G.metadata.active_env ~= '' then -- return ' [ ' .. _G.metadata.active_env .. '] ' -- end @@ -83,7 +105,8 @@ _G.metadata = setmetatable({}, { vim.o.laststatus = 3 -- Using luaeval with escaped quotes is the "bulletproof" Linux method - vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("_G.get_pio_status()")}%* %y %p%% %l:%c' + -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("_G.get_pio_status()")}%* %y %p%% %l:%c' + -- Ensure your custom layout is the final word -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 92e772e4..0ed730a3 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -1,6 +1,10 @@ local M = {} +local sep = package.config:sub(1, 1) -- Dynamic OS separator (\ or /) M.selected_framework = '' +M.is_processing = false +M.queue = {} +local pio_buffer = '' -- Persistent stream buffer -- to fix require loop, this value is set in plugin/platformio @@ -10,235 +14,126 @@ local lsp_restart = require('platformio.lsp.tools').lsp_restart ------------------------------------------------------ -- stylua: ignore +-- 1. Optimized Cross-Platform Path Fixer function M.compile_commandsFix() - local filename = vim.uv.cwd() .. '/compile_commands.json' - if vim.fn.filereadable(filename) == 0 then return end + local filename = vim.fs.joinpath(vim.uv.cwd(), 'compile_commands.json') + if vim.fn.filereadable(filename) == 0 then M.process_queue() return end - -- Atomic read using built-in Vim function - local content = table.concat(vim.fn.readfile(filename), "\n") - local ok, data = pcall(vim.json.decode, content) - if not ok or type(data) ~= 'table' then return end + local ok, data = pcall(vim.json.decode, table.concat(vim.fn.readfile(filename), "\n")) + if not ok or type(data) ~= 'table' then M.process_queue() return end - -- 1. Build Path Map (Scan toolchain) local path_map = {} - local toolchain_bin = (_G.metadata and _G.metadata.toolchain_root or "") .. '/bin/*' - for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do - local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') - path_map[name] = full_path + local toolchain = _G.metadata and _G.metadata.toolchain_root or "" + if toolchain ~= "" then + local bin_glob = vim.fs.joinpath(toolchain, "bin", "*") + for _, full_path in ipairs(vim.fn.glob(bin_glob, false, true)) do + local name = full_path:match('([^' .. sep .. ']+)$'):gsub('%.exe$', '') + path_map[name] = full_path + end end - -- 2. Update Entries efficiently with string matching local modified = false for _, entry in ipairs(data) do local cmd = entry.command or "" - local first_token = cmd:match("^%S+") -- Grab only the compiler driver - - -- Fix if it's a relative path (doesn't start with / or Drive letter) + local first_token = cmd:match("^%S+") if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then - local short_name = first_token:gsub('%.exe$', '') - if path_map[short_name] then - -- Replace only the first token to preserve arguments - entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) + local name = first_token:gsub('%.exe$', '') + if path_map[name] then + entry.command = path_map[name] .. cmd:sub(#first_token + 1) modified = true end end end - -- PHASE 3: Save and Refresh if modified then - -- -- 1. Native Lua encoding (indented 2 spaces) - -- local _, json_str = pcall(vim.json.encode, data, { indent = " " }) - -- - -- if ok and json_str then - -- -- 2. Convert string to a table of lines (required by writefile) - -- local lines = vim.split(json_str, '\n') - -- - -- -- 3. Atomic write to disk - -- -- 's' flag forces a system sync to ensure data is physically written - -- local status = vim.fn.writefile(lines, filename, 's') - -- - -- if status == 0 then - -- vim.notify('compiledb: fixed and saved safely', vim.log.levels.INFO) - -- else - -- vim.notify('compiledb: failed to write file', vim.log.levels.ERROR) - -- end - -- end - - local jok, json_str = pcall(vim.json.encode, data, { indent = " " }) - if not jok or not json_str then - vim.notify("PIO: JSON Encoding failed", 4) - return M.process_queue() -- Don't get stuck - end - - local lines = vim.split(json_str, '\n') - - -- 1. Check if the directory is actually writable (Safety Check) - local dir = vim.fn.fnamemodify(filename, ":h") - if vim.fn.isdirectory(dir) == 0 then - vim.notify("PIO: Directory does not exist: " .. dir, 4) - return M.process_queue() - end - - -- 2. Use pcall to prevent the function from "exiting" on error - local write_ok, status = pcall(vim.fn.writefile, lines, filename, 's') - - if write_ok and status == 0 then - vim.notify('compiledb: fixed and saved', 2) - else - local err_msg = not write_ok and status or "Write error (check permissions)" - vim.notify('PIO Save Failed: ' .. err_msg, 4) + local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " " }) + if ok_enc then + vim.fn.writefile(vim.split(json_str, "\n"), filename, 's') end end - -- 3. Save with Python formatting + -- function M.compile_commandsFix() + -- local filename = vim.uv.cwd() .. '/compile_commands.json' + -- if vim.fn.filereadable(filename) == 0 then return end + -- + -- -- Atomic read using built-in Vim function + -- local content = table.concat(vim.fn.readfile(filename), "\n") + -- local ok, data = pcall(vim.json.decode, content) + -- if not ok or type(data) ~= 'table' then return end + -- + -- -- 1. Build Path Map (Scan toolchain) + -- local path_map = {} + -- local toolchain_bin = (_G.metadata and _G.metadata.toolchain_root or "") .. '/bin/*' + -- for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do + -- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') + -- path_map[name] = full_path + -- end + -- + -- -- 2. Update Entries efficiently with string matching + -- local modified = false + -- for _, entry in ipairs(data) do + -- local cmd = entry.command or "" + -- local first_token = cmd:match("^%S+") -- Grab only the compiler driver + -- + -- -- Fix if it's a relative path (doesn't start with / or Drive letter) + -- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then + -- local short_name = first_token:gsub('%.exe$', '') + -- if path_map[short_name] then + -- -- Replace only the first token to preserve arguments + -- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) + -- modified = true + -- end + -- end + -- end + -- + -- -- PHASE 3: Save and Refresh -- if modified then - -- local json_str = vim.json.encode(data) - -- local formatted = vim.fn.system('python -m json.tool', json_str) + -- local jok, json_str = pcall(vim.json.encode, data, { indent = " " }) + -- if not jok or not json_str then + -- vim.notify("PIO: JSON Encoding failed", 4) + -- return M.process_queue() -- Don't get stuck + -- end -- - -- if vim.v.shell_error == 0 then - -- -- Atomic write back to disk - -- vim.fn.writefile(vim.split(formatted, "\n"), filename) - -- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) + -- local lines = vim.split(json_str, '\n') + -- + -- -- 1. Check if the directory is actually writable (Safety Check) + -- local dir = vim.fn.fnamemodify(filename, ":h") + -- if vim.fn.isdirectory(dir) == 0 then + -- vim.notify("PIO: Directory does not exist: " .. dir, 4) + -- return M.process_queue() + -- end + -- + -- -- 2. Use pcall to prevent the function from "exiting" on error + -- local write_ok, status = pcall(vim.fn.writefile, lines, filename, 's') + -- + -- if write_ok and status == 0 then + -- vim.notify('compiledb: fixed and saved', 2) -- else - -- vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) + -- local err_msg = not write_ok and status or "Write error (check permissions)" + -- vim.notify('PIO Save Failed: ' .. err_msg, 4) -- end -- end + -- -- 3. Save with Python formatting + -- -- if modified then + -- -- local json_str = vim.json.encode(data) + -- -- local formatted = vim.fn.system('python -m json.tool', json_str) + -- -- + -- -- if vim.v.shell_error == 0 then + -- -- -- Atomic write back to disk + -- -- vim.fn.writefile(vim.split(formatted, "\n"), filename) + -- -- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) + -- -- else + -- -- vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) + -- -- end + -- -- end lsp_restart('clangd') _G.metadata.isBusy = false + -- M.process_queue() end --- function M.compile_commandsFix() --- local filename = vim.uv.cwd() .. '/compile_commands.json' --- local content = vim.fn.readfile(filename) --- if #content == 0 then return end --- --- local ok, data = pcall(vim.json.decode, table.concat(content, "\n")) --- if not ok or type(data) ~= 'table' then return end --- --- -- 1. Build Path Map (Scan toolchain) --- local path_map = {} --- --- local pio_binaries = _G.metadata.query_driver or "/bin/*" --- -- local pio_binaries = (_G.metadata.toolchain_root or "") .. '/bin/*' --- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do --- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') --- path_map[name] = full_path --- end --- --- -- 2. Update Entries --- local modified = false --- for _, entry in ipairs(data) do --- local cmd = entry.command or "" --- local first_token = cmd:match("^%S+") -- Get first word before space --- --- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then --- local short_name = first_token:gsub('%.exe$', '') --- if path_map[short_name] then --- -- Swap first token with full path safely --- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) --- modified = true --- end --- end --- end --- --- -- 3. Save with Formatting --- if modified then --- local json_str = vim.json.encode(data) --- -- Use python to format, then write file --- local formatted = vim.fn.system('python -m json.tool', json_str) --- if vim.v.shell_error == 0 then --- vim.fn.writefile(vim.split(formatted, "\n"), filename) --- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) --- end --- end --- end - --- function M.compile_commandsFix() --- local filename = vim.uv.cwd() .. '/compile_commands.json' --- local file = io.open(filename, 'r') --- if not file then return end --- --- -- read compile_commands.json file to content --- local content = file:read('*a') --- file:close() --- if not content or content == '' then return end --- --- -- JSON decoding content to data --- local ok, data = pcall(vim.json.decode, content) --- if not ok or type(data) ~= 'table' then --- vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) --- return --- end --- --- print('PioFix0') --- -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path --- local path_map = {} --- local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') --- if pio_home then --- -- Recursively find all binaries in PIO packages --- local pio_packages = _G.metadata.toolchain_root .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' --- local found_binaries = vim.fn.glob(pio_packages, false, true) --- --- for _, full_path in ipairs(found_binaries) do --- -- Extract filename (e.g., riscv32-esp-elf-gcc) --- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') --- path_map[name] = full_path --- -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) --- end --- end --- --- -- PHASE 2: Update JSON using the Map --- local modified = 0 --- for _, entry in ipairs(data) do --- if type(entry.command) == 'string' then --- local cmd_parts = vim.split(entry.command, ' ') --- local first_token = cmd_parts[1] --- if first_token then --- -- Check if it's already a short name (not an absolute path) --- local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') --- if not is_abs then --- local short_name = first_token:gsub('%.exe$', '') --- -- print('PioFix2: short_name=' .. short_name) --- -- Direct Query: Does this name exist in our discovered list? --- if path_map[short_name] then --- cmd_parts[1] = path_map[short_name] --- -- print('PioFix3: full_name=' .. cmd_parts[1]) --- entry.command = table.concat(cmd_parts, ' ') --- modified = modified + 1 --- end --- end --- end --- end --- end --- --- -- PHASE 3: Save and Refresh --- -- Safe JSON encoding --- if modified > 0 then --- local out_file = io.open(filename, 'w') --- if out_file then --- local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) --- if encode_ok and json_str then --- -- 1. Format the string using python's json.tool --- -- The second argument to vim.fn.system() is the "stdin" passed to the command --- local formatted_json = vim.fn.system('python -m json.tool', json_str) --- --- -- out_file:write(json_str) --- out_file:write(formatted_json) --- out_file:close() --- vim.notify('compiledb: fixed', vim.log.levels.INFO) --- lsp_restart('clangd') --- _G.metadata.isBusy = false --- end --- end --- end --- end ------------------------------------------------------ -- INFO: ToggleTerminal commands sequencer -M.is_processing = false -M.queue = {} -local pio_buffer = '' -- Persistent stream buffer - ------------------------------------------------------ -- INFO: ToggleTerminal commands stdout filter -- stylua: ignore diff --git a/plugin/platformio.lua b/plugin/platformio.lua index ea9a70b6..c4d3fc1d 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -9,6 +9,19 @@ local piolsserial = require('platformio.piolsserial') local misc = require('platformio.utils.misc') local pio = require('platformio.utils.pio') +local meta = require('platformio.meta') + +-- Statusline: Using luaeval for best cross-platform stability +vim.o.laststatus = 3 +vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("require(\'platformio.metadata\').get_pio_status()")} %y %p%% %l:%c' +vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) + +-- Simple timer to animate the spinner if M.is_busy +vim.fn.timer_start(100, function() + if meta.is_busy then + vim.cmd('redrawstatus') + end +end, { ['repeat'] = -1 }) -- We use luaeval to call the getter we defined in pio.lua (or metadata.lua) -- vim.o.laststatus = 3 From 28d7d85767cc6f2820177498a85dc1d354d2e9de Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 23:31:52 +0300 Subject: [PATCH 0838/1406] update --- plugin/platformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/platformio.lua b/plugin/platformio.lua index c4d3fc1d..874a2d8b 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -9,7 +9,7 @@ local piolsserial = require('platformio.piolsserial') local misc = require('platformio.utils.misc') local pio = require('platformio.utils.pio') -local meta = require('platformio.meta') +local meta = require('platformio.metadata') -- Statusline: Using luaeval for best cross-platform stability vim.o.laststatus = 3 From 4110cc1e4642fcab54c0cc0e97d8fc597566210c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 20 Apr 2026 23:52:43 +0300 Subject: [PATCH 0839/1406] update --- lua/platformio/utils/pio.lua | 174 +++++++++++++++++------------------ 1 file changed, 87 insertions(+), 87 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 0ed730a3..b23245a7 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -1,6 +1,6 @@ local M = {} -local sep = package.config:sub(1, 1) -- Dynamic OS separator (\ or /) +-- local sep = package.config:sub(1, 1) -- Dynamic OS separator (\ or /) M.selected_framework = '' M.is_processing = false M.queue = {} @@ -15,116 +15,116 @@ local lsp_restart = require('platformio.lsp.tools').lsp_restart ------------------------------------------------------ -- stylua: ignore -- 1. Optimized Cross-Platform Path Fixer +-- function M.compile_commandsFix() +-- local filename = vim.fs.joinpath(vim.uv.cwd(), 'compile_commands.json') +-- if vim.fn.filereadable(filename) == 0 then M.process_queue() return end +-- +-- local ok, data = pcall(vim.json.decode, table.concat(vim.fn.readfile(filename), "\n")) +-- if not ok or type(data) ~= 'table' then M.process_queue() return end +-- +-- local path_map = {} +-- local toolchain = _G.metadata and _G.metadata.toolchain_root or "" +-- if toolchain ~= "" then +-- local bin_glob = vim.fs.joinpath(toolchain, "bin", "*") +-- for _, full_path in ipairs(vim.fn.glob(bin_glob, false, true)) do +-- local name = full_path:match('([^' .. sep .. ']+)$'):gsub('%.exe$', '') +-- path_map[name] = full_path +-- end +-- end +-- +-- local modified = false +-- for _, entry in ipairs(data) do +-- local cmd = entry.command or "" +-- local first_token = cmd:match("^%S+") +-- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then +-- local name = first_token:gsub('%.exe$', '') +-- if path_map[name] then +-- entry.command = path_map[name] .. cmd:sub(#first_token + 1) +-- modified = true +-- end +-- end +-- end +-- +-- if modified then +-- local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " " }) +-- if ok_enc then +-- vim.fn.writefile(vim.split(json_str, "\n"), filename, 's') +-- end +-- end function M.compile_commandsFix() local filename = vim.fs.joinpath(vim.uv.cwd(), 'compile_commands.json') - if vim.fn.filereadable(filename) == 0 then M.process_queue() return end + if vim.fn.filereadable(filename) == 0 then return end - local ok, data = pcall(vim.json.decode, table.concat(vim.fn.readfile(filename), "\n")) - if not ok or type(data) ~= 'table' then M.process_queue() return end + -- Atomic read using built-in Vim function + local content = table.concat(vim.fn.readfile(filename), "\n") + local ok, data = pcall(vim.json.decode, content) + if not ok or type(data) ~= 'table' then return end + -- 1. Build Path Map (Scan toolchain) local path_map = {} - local toolchain = _G.metadata and _G.metadata.toolchain_root or "" - if toolchain ~= "" then - local bin_glob = vim.fs.joinpath(toolchain, "bin", "*") - for _, full_path in ipairs(vim.fn.glob(bin_glob, false, true)) do - local name = full_path:match('([^' .. sep .. ']+)$'):gsub('%.exe$', '') - path_map[name] = full_path - end + local toolchain_bin = (_G.metadata and _G.metadata.toolchain_root or "") .. '/bin/*' + for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do + local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') + path_map[name] = full_path end + -- 2. Update Entries efficiently with string matching local modified = false for _, entry in ipairs(data) do local cmd = entry.command or "" - local first_token = cmd:match("^%S+") + local first_token = cmd:match("^%S+") -- Grab only the compiler driver + + -- Fix if it's a relative path (doesn't start with / or Drive letter) if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then - local name = first_token:gsub('%.exe$', '') - if path_map[name] then - entry.command = path_map[name] .. cmd:sub(#first_token + 1) + local short_name = first_token:gsub('%.exe$', '') + if path_map[short_name] then + -- Replace only the first token to preserve arguments + entry.command = vim.fs.joinpath(path_map[short_name], cmd:sub(#first_token + 1)) modified = true end end end + -- PHASE 3: Save and Refresh if modified then - local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " " }) - if ok_enc then - vim.fn.writefile(vim.split(json_str, "\n"), filename, 's') + local jok, json_str = pcall(vim.json.encode, data, { indent = " " }) + if not jok or not json_str then + vim.notify("PIO: JSON Encoding failed", 4) + return M.process_queue() -- Don't get stuck + end + + local lines = vim.split(json_str, '\n') + + -- 1. Check if the directory is actually writable (Safety Check) + local dir = vim.fn.fnamemodify(filename, ":h") + if vim.fn.isdirectory(dir) == 0 then + vim.notify("PIO: Directory does not exist: " .. dir, 4) + return M.process_queue() + end + + -- 2. Use pcall to prevent the function from "exiting" on error + local write_ok, status = pcall(vim.fn.writefile, lines, filename, 's') + + if write_ok and status == 0 then + vim.notify('compiledb: fixed and saved', 2) + else + local err_msg = not write_ok and status or "Write error (check permissions)" + vim.notify('PIO Save Failed: ' .. err_msg, 4) end end - -- function M.compile_commandsFix() - -- local filename = vim.uv.cwd() .. '/compile_commands.json' - -- if vim.fn.filereadable(filename) == 0 then return end - -- - -- -- Atomic read using built-in Vim function - -- local content = table.concat(vim.fn.readfile(filename), "\n") - -- local ok, data = pcall(vim.json.decode, content) - -- if not ok or type(data) ~= 'table' then return end - -- - -- -- 1. Build Path Map (Scan toolchain) - -- local path_map = {} - -- local toolchain_bin = (_G.metadata and _G.metadata.toolchain_root or "") .. '/bin/*' - -- for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do - -- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') - -- path_map[name] = full_path - -- end - -- - -- -- 2. Update Entries efficiently with string matching - -- local modified = false - -- for _, entry in ipairs(data) do - -- local cmd = entry.command or "" - -- local first_token = cmd:match("^%S+") -- Grab only the compiler driver - -- - -- -- Fix if it's a relative path (doesn't start with / or Drive letter) - -- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then - -- local short_name = first_token:gsub('%.exe$', '') - -- if path_map[short_name] then - -- -- Replace only the first token to preserve arguments - -- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) - -- modified = true - -- end - -- end - -- end - -- - -- -- PHASE 3: Save and Refresh + -- 3. Save with Python formatting -- if modified then - -- local jok, json_str = pcall(vim.json.encode, data, { indent = " " }) - -- if not jok or not json_str then - -- vim.notify("PIO: JSON Encoding failed", 4) - -- return M.process_queue() -- Don't get stuck - -- end - -- - -- local lines = vim.split(json_str, '\n') - -- - -- -- 1. Check if the directory is actually writable (Safety Check) - -- local dir = vim.fn.fnamemodify(filename, ":h") - -- if vim.fn.isdirectory(dir) == 0 then - -- vim.notify("PIO: Directory does not exist: " .. dir, 4) - -- return M.process_queue() - -- end - -- - -- -- 2. Use pcall to prevent the function from "exiting" on error - -- local write_ok, status = pcall(vim.fn.writefile, lines, filename, 's') + -- local json_str = vim.json.encode(data) + -- local formatted = vim.fn.system('python -m json.tool', json_str) -- - -- if write_ok and status == 0 then - -- vim.notify('compiledb: fixed and saved', 2) + -- if vim.v.shell_error == 0 then + -- -- Atomic write back to disk + -- vim.fn.writefile(vim.split(formatted, "\n"), filename) + -- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) -- else - -- local err_msg = not write_ok and status or "Write error (check permissions)" - -- vim.notify('PIO Save Failed: ' .. err_msg, 4) + -- vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) -- end -- end - -- -- 3. Save with Python formatting - -- -- if modified then - -- -- local json_str = vim.json.encode(data) - -- -- local formatted = vim.fn.system('python -m json.tool', json_str) - -- -- - -- -- if vim.v.shell_error == 0 then - -- -- -- Atomic write back to disk - -- -- vim.fn.writefile(vim.split(formatted, "\n"), filename) - -- -- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) - -- -- else - -- -- vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) - -- -- end - -- -- end lsp_restart('clangd') _G.metadata.isBusy = false -- M.process_queue() From 4ffe381c323cf867620ce4be47b8bdc87bb8cc0f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 00:02:52 +0300 Subject: [PATCH 0840/1406] update --- lua/platformio/utils/pio.lua | 3 ++- mini_nvimPlatformio.lua | 9 +++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index b23245a7..73dc035d 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -93,7 +93,8 @@ function M.compile_commandsFix() return M.process_queue() -- Don't get stuck end - local lines = vim.split(json_str, '\n') + -- local lines = vim.split(json_str, '\n') + local lines = vim.split(json_str, "\n", { trimempty = true }) -- 1. Check if the directory is actually writable (Safety Check) local dir = vim.fn.fnamemodify(filename, ":h") diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index e9370c3d..60e19279 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -56,8 +56,13 @@ end -- Define a custom highlight group -- vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#A6E22E', bold = true }) -- vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) -vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#e0af68', bold = true }) - +-- vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#e0af68', bold = true }) +-- fg = text color, bg = background color +vim.api.nvim_set_hl(0, 'PioStatus', { + fg = '#1a1b26', -- Dark text + bg = '#7aa2f7', -- Blue background + bold = true, +}) ---------------------------------------------------------------------------------------- -- INFO: Set diagnostic config vim.diagnostic.config({ From 2e5e72d4dffd19012242882b5b4cdb4872ec7a7b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 00:09:41 +0300 Subject: [PATCH 0841/1406] update --- lua/platformio/utils/pio.lua | 59 +++++++++++++++++++++--------------- mini_nvimPlatformio.lua | 2 +- 2 files changed, 36 insertions(+), 25 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 73dc035d..12f1c951 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -87,32 +87,43 @@ function M.compile_commandsFix() -- PHASE 3: Save and Refresh if modified then - local jok, json_str = pcall(vim.json.encode, data, { indent = " " }) - if not jok or not json_str then - vim.notify("PIO: JSON Encoding failed", 4) - return M.process_queue() -- Don't get stuck - end - - -- local lines = vim.split(json_str, '\n') - local lines = vim.split(json_str, "\n", { trimempty = true }) - - -- 1. Check if the directory is actually writable (Safety Check) - local dir = vim.fn.fnamemodify(filename, ":h") - if vim.fn.isdirectory(dir) == 0 then - vim.notify("PIO: Directory does not exist: " .. dir, 4) - return M.process_queue() - end - - -- 2. Use pcall to prevent the function from "exiting" on error - local write_ok, status = pcall(vim.fn.writefile, lines, filename, 's') - - if write_ok and status == 0 then - vim.notify('compiledb: fixed and saved', 2) - else - local err_msg = not write_ok and status or "Write error (check permissions)" - vim.notify('PIO Save Failed: ' .. err_msg, 4) + local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " " }) + if ok_enc then + local f = io.open(filename, "w") + if f then + f:write(json_str) + f:close() + end end end + -- if modified then + -- local jok, json_str = pcall(vim.json.encode, data, { indent = " " }) + -- if not jok or not json_str then + -- vim.notify("PIO: JSON Encoding failed", 4) + -- return M.process_queue() -- Don't get stuck + -- end + -- + -- -- local lines = vim.split(json_str, '\n') + -- local lines = vim.split(json_str, "\n", { trimempty = true }) + -- + -- -- 1. Check if the directory is actually writable (Safety Check) + -- local dir = vim.fn.fnamemodify(filename, ":h") + -- if vim.fn.isdirectory(dir) == 0 then + -- vim.notify("PIO: Directory does not exist: " .. dir, 4) + -- return M.process_queue() + -- end + -- + -- -- 2. Use pcall to prevent the function from "exiting" on error + -- local write_ok, status = pcall(vim.fn.writefile, lines, filename, 's') + -- + -- if write_ok and status == 0 then + -- vim.notify('compiledb: fixed and saved', 2) + -- else + -- local err_msg = not write_ok and status or "Write error (check permissions)" + -- vim.notify('PIO Save Failed: ' .. err_msg, 4) + -- end + -- end + -- -- 3. Save with Python formatting -- if modified then -- local json_str = vim.json.encode(data) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 60e19279..4e8758ed 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -59,7 +59,7 @@ end -- vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#e0af68', bold = true }) -- fg = text color, bg = background color vim.api.nvim_set_hl(0, 'PioStatus', { - fg = '#1a1b26', -- Dark text + fg = '#e0af68', -- Dark text bg = '#7aa2f7', -- Blue background bold = true, }) From 4711aeda236c5588d3de93475aeb141b3e06d782 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 00:27:48 +0300 Subject: [PATCH 0842/1406] update --- lua/platformio/utils/pio.lua | 33 ++++++++++++++++++++++++++++----- mini_nvimPlatformio.lua | 2 +- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 12f1c951..c327bd03 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -86,16 +86,39 @@ function M.compile_commandsFix() end -- PHASE 3: Save and Refresh + + if modified then + -- 1. Encode with 2-space indentation local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " " }) if ok_enc then - local f = io.open(filename, "w") - if f then - f:write(json_str) - f:close() - end + -- 2. Robust split: handles both \r\n and \n correctly + -- This ensures 'lines' is a proper table for vim.fn.writefile + local lines = vim.split(json_str, "[\r\n]+", { trimempty = true }) + + -- 3. Atomic write back to disk + -- 's' flag forces a system sync for data integrity + vim.fn.writefile(lines, filename, 's') + + -- 4. Essential: Tell Neovim to refresh the file if it is already open + -- This prevents the editor from displaying stale "one-line" cached data + vim.cmd("checktime " .. vim.fn.fnameescape(filename)) + + vim.notify('compiledb: paths fixed and formatted', 2) end end + + -- if modified then + -- local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " " }) + -- if ok_enc then + -- local f = io.open(filename, "w") + -- if f then + -- f:write(json_str) + -- f:close() + -- end + -- end + -- end + -- if modified then -- local jok, json_str = pcall(vim.json.encode, data, { indent = " " }) -- if not jok or not json_str then diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 4e8758ed..0eb25a83 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -60,7 +60,7 @@ end -- fg = text color, bg = background color vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#e0af68', -- Dark text - bg = '#7aa2f7', -- Blue background + bg = '#11111b', bold = true, }) ---------------------------------------------------------------------------------------- From d677f930fb197be6d1aa15c9d6bb3928e5b425f4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 00:36:27 +0300 Subject: [PATCH 0843/1406] update --- lua/platformio/utils/pio.lua | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index c327bd03..e65c08df 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -87,24 +87,24 @@ function M.compile_commandsFix() -- PHASE 3: Save and Refresh - if modified then - -- 1. Encode with 2-space indentation local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " " }) - if ok_enc then - -- 2. Robust split: handles both \r\n and \n correctly - -- This ensures 'lines' is a proper table for vim.fn.writefile - local lines = vim.split(json_str, "[\r\n]+", { trimempty = true }) - - -- 3. Atomic write back to disk - -- 's' flag forces a system sync for data integrity - vim.fn.writefile(lines, filename, 's') - -- 4. Essential: Tell Neovim to refresh the file if it is already open - -- This prevents the editor from displaying stale "one-line" cached data - vim.cmd("checktime " .. vim.fn.fnameescape(filename)) + if ok_enc and json_str then + -- Open in 'wb' (write binary) mode to prevent Windows from + -- mangling the newlines automatically. + local f = io.open(filename, "wb") + if f then + -- Add a trailing newline to the end of the file (standard practice) + f:write(json_str .. "\n") + f:close() - vim.notify('compiledb: paths fixed and formatted', 2) + -- Force Neovim to refresh the view of the file + vim.cmd("checktime " .. vim.fn.fnameescape(filename)) + vim.notify("PIO: JSON formatted correctly", 2) + else + vim.notify("PIO: Could not open file for writing", 4) + end end end From 22558b5f3421b41afaad6d862839ad048ccd7d01 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 00:42:30 +0300 Subject: [PATCH 0844/1406] update --- lua/platformio/utils/pio.lua | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index e65c08df..d2a3e894 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -88,22 +88,26 @@ function M.compile_commandsFix() -- PHASE 3: Save and Refresh if modified then - local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " " }) + -- 1. Encode with indentation + local ok, json_str = pcall(vim.json.encode, data, { indent = " " }) - if ok_enc and json_str then - -- Open in 'wb' (write binary) mode to prevent Windows from - -- mangling the newlines automatically. + if ok and json_str then + -- 2. Windows specific: Force CRLF line endings + -- This replaces every \n that is NOT preceded by \r with \r\n + if vim.fn.has("win32") == 1 then + json_str = json_str:gsub("([^\r])\n", "%1\r\n") + end + + -- 3. Write as a Binary string to prevent the OS from + -- re-mangling the characters during the save process. local f = io.open(filename, "wb") if f then - -- Add a trailing newline to the end of the file (standard practice) - f:write(json_str .. "\n") + f:write(json_str .. "\r\n") -- Final trailing newline f:close() - -- Force Neovim to refresh the view of the file + -- Refresh Neovim's view of the file vim.cmd("checktime " .. vim.fn.fnameescape(filename)) - vim.notify("PIO: JSON formatted correctly", 2) - else - vim.notify("PIO: Could not open file for writing", 4) + vim.notify("PIO: JSON formatted for Windows (CRLF)", 2) end end end From c6984d3ba420ca5de76d97a6a49f648696ddc9df Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 00:49:45 +0300 Subject: [PATCH 0845/1406] update --- lua/platformio/utils/pio.lua | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index d2a3e894..ba3153bf 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -88,30 +88,27 @@ function M.compile_commandsFix() -- PHASE 3: Save and Refresh if modified then - -- 1. Encode with indentation + -- 1. Encode with 2-space indentation local ok, json_str = pcall(vim.json.encode, data, { indent = " " }) if ok and json_str then - -- 2. Windows specific: Force CRLF line endings - -- This replaces every \n that is NOT preceded by \r with \r\n - if vim.fn.has("win32") == 1 then - json_str = json_str:gsub("([^\r])\n", "%1\r\n") - end - - -- 3. Write as a Binary string to prevent the OS from - -- re-mangling the characters during the save process. - local f = io.open(filename, "wb") - if f then - f:write(json_str .. "\r\n") -- Final trailing newline - f:close() + -- 2. FORCE SPLIT: This ensures every \n becomes a new table element + -- We use '\n' explicitly as the delimiter to break the long string + local lines = vim.split(json_str, "\n", { plain = true }) + -- vim.fn.writefile on Windows automatically converts the table + -- elements into CRLF lines when writing to disk. + local status = vim.fn.writefile(lines, filename, 's') - -- Refresh Neovim's view of the file + if status == 0 then + -- 4. Force buffer reload to see the changes immediately vim.cmd("checktime " .. vim.fn.fnameescape(filename)) - vim.notify("PIO: JSON formatted for Windows (CRLF)", 2) + vim.notify('PIO: JSON formatted and saved (Windows Fix)', 2) end end end + + -- if modified then -- local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " " }) -- if ok_enc then From 5823150bfa5de65326c88e0fdf9ecd6dd098e3a1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 01:18:43 +0300 Subject: [PATCH 0846/1406] update --- lua/platformio/utils/pio.lua | 34 +++++++--------------------------- 1 file changed, 7 insertions(+), 27 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index ba3153bf..cd8a87d0 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -87,39 +87,19 @@ function M.compile_commandsFix() -- PHASE 3: Save and Refresh - if modified then - -- 1. Encode with 2-space indentation - local ok, json_str = pcall(vim.json.encode, data, { indent = " " }) - if ok and json_str then - -- 2. FORCE SPLIT: This ensures every \n becomes a new table element - -- We use '\n' explicitly as the delimiter to break the long string - local lines = vim.split(json_str, "\n", { plain = true }) - -- vim.fn.writefile on Windows automatically converts the table - -- elements into CRLF lines when writing to disk. - local status = vim.fn.writefile(lines, filename, 's') - if status == 0 then - -- 4. Force buffer reload to see the changes immediately - vim.cmd("checktime " .. vim.fn.fnameescape(filename)) - vim.notify('PIO: JSON formatted and saved (Windows Fix)', 2) + if modified then + local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " " }) + if ok_enc then + local f = io.open(filename, "w") + if f then + f:write(json_str) + f:close() end end end - - - -- if modified then - -- local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " " }) - -- if ok_enc then - -- local f = io.open(filename, "w") - -- if f then - -- f:write(json_str) - -- f:close() - -- end - -- end - -- end - -- if modified then -- local jok, json_str = pcall(vim.json.encode, data, { indent = " " }) -- if not jok or not json_str then From ed35879752cda963092bd7dc19337d7c07fc30b2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 01:26:15 +0300 Subject: [PATCH 0847/1406] update --- lua/platformio/utils/pio.lua | 44 ++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index cd8a87d0..46c90599 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -89,16 +89,16 @@ function M.compile_commandsFix() - if modified then - local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " " }) - if ok_enc then - local f = io.open(filename, "w") - if f then - f:write(json_str) - f:close() - end - end - end + -- if modified then + -- local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " " }) + -- if ok_enc then + -- local f = io.open(filename, "w") + -- if f then + -- f:write(json_str) + -- f:close() + -- end + -- end + -- end -- if modified then -- local jok, json_str = pcall(vim.json.encode, data, { indent = " " }) @@ -129,18 +129,18 @@ function M.compile_commandsFix() -- end -- -- 3. Save with Python formatting - -- if modified then - -- local json_str = vim.json.encode(data) - -- local formatted = vim.fn.system('python -m json.tool', json_str) - -- - -- if vim.v.shell_error == 0 then - -- -- Atomic write back to disk - -- vim.fn.writefile(vim.split(formatted, "\n"), filename) - -- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) - -- else - -- vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) - -- end - -- end + if modified then + local json_str = vim.json.encode(data) + local formatted = vim.fn.system('python -m json.tool', json_str) + + if vim.v.shell_error == 0 then + -- Atomic write back to disk + vim.fn.writefile(vim.split(formatted, "\n"), filename) + vim.notify('compiledb: paths fixed', vim.log.levels.INFO) + else + vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) + end + end lsp_restart('clangd') _G.metadata.isBusy = false -- M.process_queue() From 140365fab2427a3ff7b5f621c3a6154f2f45f786 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 01:31:24 +0300 Subject: [PATCH 0848/1406] update --- lua/platformio/utils/pio.lua | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 46c90599..bab7dbc7 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -135,7 +135,10 @@ function M.compile_commandsFix() if vim.v.shell_error == 0 then -- Atomic write back to disk - vim.fn.writefile(vim.split(formatted, "\n"), filename) + -- vim.fn.writefile(vim.split(formatted, "\n"), filename) + -- Change this line in your working code: + vim.fn.writefile(vim.split(formatted, "\n"), filename, 's') + vim.notify('compiledb: paths fixed', vim.log.levels.INFO) else vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) From c7d7f63b9b4c81b4a38f420643434cc8c88605a0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 01:42:49 +0300 Subject: [PATCH 0849/1406] update --- lua/platformio/utils/pio.lua | 47 +++++++++++++++++++++++++++++------- 1 file changed, 38 insertions(+), 9 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index bab7dbc7..b1d93dfc 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -129,21 +129,50 @@ function M.compile_commandsFix() -- end -- -- 3. Save with Python formatting + + if modified then - local json_str = vim.json.encode(data) - local formatted = vim.fn.system('python -m json.tool', json_str) + -- 1. Encode with 2-space indentation (Pure Lua) + local ok, json_str = pcall(vim.json.encode, data, { indent = " " }) - if vim.v.shell_error == 0 then - -- Atomic write back to disk - -- vim.fn.writefile(vim.split(formatted, "\n"), filename) - -- Change this line in your working code: - vim.fn.writefile(vim.split(formatted, "\n"), filename, 's') + if ok and json_str then + -- 2. Force a LITERAL split on \n. + -- The { plain = true } is the secret—it prevents regex + -- and ensures every newline creates a new table element. + local lines = vim.split(json_str, "\n", { plain = true }) - vim.notify('compiledb: paths fixed', vim.log.levels.INFO) + -- 3. Use writefile with the 's' flag + -- On Windows, writefile automatically converts this table + -- into CRLF (\r\n) line endings on disk. + local status = vim.fn.writefile(lines, filename, 's') + + if status == 0 then + -- 4. Force Neovim to refresh its view of the file + vim.cmd("checktime " .. vim.fn.fnameescape(filename)) + vim.notify('compiledb: fixed via Native Lua', vim.log.levels.INFO) + end else - vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) + vim.notify('compiledb: Lua encoding failed', vim.log.levels.ERROR) end end + + + + -- if modified then + -- local json_str = vim.json.encode(data) + -- local formatted = vim.fn.system('python -m json.tool', json_str) + -- + -- if vim.v.shell_error == 0 then + -- -- Atomic write back to disk + -- -- vim.fn.writefile(vim.split(formatted, "\n"), filename) + -- -- Change this line in your working code: + -- vim.fn.writefile(vim.split(formatted, "\n"), filename, 's') + -- + -- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) + -- else + -- vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) + -- end + -- end lsp_restart('clangd') _G.metadata.isBusy = false -- M.process_queue() From fd53807f0028e3fb4c5a4b45e4da41103280c64b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 01:49:25 +0300 Subject: [PATCH 0850/1406] update --- lua/platformio/utils/pio.lua | 53 +++++++++++++++++++++++------------- 1 file changed, 34 insertions(+), 19 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index b1d93dfc..5b3bdf68 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -130,32 +130,47 @@ function M.compile_commandsFix() -- -- 3. Save with Python formatting - if modified then - -- 1. Encode with 2-space indentation (Pure Lua) - local ok, json_str = pcall(vim.json.encode, data, { indent = " " }) + -- 1. Encode to a single string with 2-space indentation + local ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) if ok and json_str then - -- 2. Force a LITERAL split on \n. - -- The { plain = true } is the secret—it prevents regex - -- and ensures every newline creates a new table element. - local lines = vim.split(json_str, "\n", { plain = true }) - - -- 3. Use writefile with the 's' flag - -- On Windows, writefile automatically converts this table - -- into CRLF (\r\n) line endings on disk. - local status = vim.fn.writefile(lines, filename, 's') - - if status == 0 then - -- 4. Force Neovim to refresh its view of the file - vim.cmd("checktime " .. vim.fn.fnameescape(filename)) - vim.notify('compiledb: fixed via Native Lua', vim.log.levels.INFO) + -- 2. Split into a table of lines (CRITICAL for Windows formatting) + local lines = vim.split(json_str, '\n', { plain = true }) + + -- 3. Write to disk (writefile handles OS line endings automatically) + if vim.fn.writefile(lines, filename, 's') == 0 then + vim.cmd('checktime ' .. vim.fn.fnameescape(filename)) + vim.notify('compiledb: fixed (native lua)', 2) end - else - vim.notify('compiledb: Lua encoding failed', vim.log.levels.ERROR) end end + -- if modified then + -- -- 1. Encode with 2-space indentation (Pure Lua) + -- local ok, json_str = pcall(vim.json.encode, data, { indent = " " }) + -- + -- if ok and json_str then + -- -- 2. Force a LITERAL split on \n. + -- -- The { plain = true } is the secret—it prevents regex + -- -- and ensures every newline creates a new table element. + -- local lines = vim.split(json_str, "\n", { plain = true }) + -- + -- -- 3. Use writefile with the 's' flag + -- -- On Windows, writefile automatically converts this table + -- -- into CRLF (\r\n) line endings on disk. + -- local status = vim.fn.writefile(lines, filename, 's') + -- + -- if status == 0 then + -- -- 4. Force Neovim to refresh its view of the file + -- vim.cmd("checktime " .. vim.fn.fnameescape(filename)) + -- vim.notify('compiledb: fixed via Native Lua', vim.log.levels.INFO) + -- end + -- else + -- vim.notify('compiledb: Lua encoding failed', vim.log.levels.ERROR) + -- end + -- end + -- if modified then From ac63100b9fd0520f2b0a7cf4b57a0b75430df609 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 04:13:58 +0300 Subject: [PATCH 0851/1406] update --- lua/platformio/utils/pio.lua | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 5b3bdf68..211a7fe5 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -130,22 +130,32 @@ function M.compile_commandsFix() -- -- 3. Save with Python formatting + + if modified then - -- 1. Encode to a single string with 2-space indentation - local ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) + -- 1. Encode with indentation and sorted keys (Neovim 0.10+) + -- This mimics the "python -m json.tool" output exactly. + local ok, json_str = pcall(vim.json.encode, data, { indent = " ", sort_keys = true }) if ok and json_str then - -- 2. Split into a table of lines (CRITICAL for Windows formatting) - local lines = vim.split(json_str, '\n', { plain = true }) - - -- 3. Write to disk (writefile handles OS line endings automatically) - if vim.fn.writefile(lines, filename, 's') == 0 then - vim.cmd('checktime ' .. vim.fn.fnameescape(filename)) - vim.notify('compiledb: fixed (native lua)', 2) + -- 2. Force split into a proper table for writefile + local lines = vim.split(json_str, "\n", { plain = true }) + + -- 3. Atomic write with 's' (sync) and force CRLF line endings + -- Setting the fileformat to 'dos' ensures Windows-style line endings. + vim.api.nvim_command("setlocal fileformat=dos") + local status = vim.fn.writefile(lines, filename, "s") + + if status == 0 then + -- 4. Essential: Force a buffer reload + -- This fixes the "still shows as one line" visual bug in Neovim. + vim.cmd("checktime " .. vim.fn.fnameescape(filename)) + vim.notify("PIO: JSON saved with Windows line endings", 2) end end end + -- if modified then -- -- 1. Encode with 2-space indentation (Pure Lua) -- local ok, json_str = pcall(vim.json.encode, data, { indent = " " }) From a5aafce5c94a29ea2f3d69a30d1c1b3378de1973 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 04:50:22 +0300 Subject: [PATCH 0852/1406] update --- lua/platformio/utils/pio.lua | 315 +++++++++++++++++++++-------------- 1 file changed, 193 insertions(+), 122 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 211a7fe5..0318152e 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -51,159 +51,230 @@ local lsp_restart = require('platformio.lsp.tools').lsp_restart -- vim.fn.writefile(vim.split(json_str, "\n"), filename, 's') -- end -- end + + function M.compile_commandsFix() local filename = vim.fs.joinpath(vim.uv.cwd(), 'compile_commands.json') if vim.fn.filereadable(filename) == 0 then return end - -- Atomic read using built-in Vim function + -- 1. Read and Decode (Atomic read) local content = table.concat(vim.fn.readfile(filename), "\n") local ok, data = pcall(vim.json.decode, content) if not ok or type(data) ~= 'table' then return end - -- 1. Build Path Map (Scan toolchain) + -- 2. Build Path Map (Dynamic OS Separator) + local sep = package.config:sub(1,1) local path_map = {} - local toolchain_bin = (_G.metadata and _G.metadata.toolchain_root or "") .. '/bin/*' - for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do - local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') - path_map[name] = full_path + local toolchain = (_G.metadata and _G.metadata.toolchain_root or "") + + if toolchain ~= "" then + local bin_glob = vim.fs.joinpath(toolchain, "bin", "*") + for _, full_path in ipairs(vim.fn.glob(bin_glob, false, true)) do + -- Correct regex for both / and \ + local name = full_path:match("([^" .. sep .. "/]+)$"):gsub("%.exe$", "") + path_map[name] = full_path + end end - -- 2. Update Entries efficiently with string matching + -- 3. Update Entries local modified = false for _, entry in ipairs(data) do local cmd = entry.command or "" - local first_token = cmd:match("^%S+") -- Grab only the compiler driver - - -- Fix if it's a relative path (doesn't start with / or Drive letter) - if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then - local short_name = first_token:gsub('%.exe$', '') - if path_map[short_name] then - -- Replace only the first token to preserve arguments - entry.command = vim.fs.joinpath(path_map[short_name], cmd:sub(#first_token + 1)) - modified = true + local first_token = cmd:match("^%S+") + + if first_token then + -- Check if it's already absolute (starts with / or C:) + local is_abs = first_token:sub(1,1) == '/' or first_token:match("^%a:") + if not is_abs then + local name = first_token:gsub("%.exe$", "") + if path_map[name] then + entry.command = path_map[name] .. cmd:sub(#first_token + 1) + modified = true + end end end end - -- PHASE 3: Save and Refresh - - - - -- if modified then - -- local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " " }) - -- if ok_enc then - -- local f = io.open(filename, "w") - -- if f then - -- f:write(json_str) - -- f:close() - -- end - -- end - -- end - - -- if modified then - -- local jok, json_str = pcall(vim.json.encode, data, { indent = " " }) - -- if not jok or not json_str then - -- vim.notify("PIO: JSON Encoding failed", 4) - -- return M.process_queue() -- Don't get stuck - -- end - -- - -- -- local lines = vim.split(json_str, '\n') - -- local lines = vim.split(json_str, "\n", { trimempty = true }) - -- - -- -- 1. Check if the directory is actually writable (Safety Check) - -- local dir = vim.fn.fnamemodify(filename, ":h") - -- if vim.fn.isdirectory(dir) == 0 then - -- vim.notify("PIO: Directory does not exist: " .. dir, 4) - -- return M.process_queue() - -- end - -- - -- -- 2. Use pcall to prevent the function from "exiting" on error - -- local write_ok, status = pcall(vim.fn.writefile, lines, filename, 's') - -- - -- if write_ok and status == 0 then - -- vim.notify('compiledb: fixed and saved', 2) - -- else - -- local err_msg = not write_ok and status or "Write error (check permissions)" - -- vim.notify('PIO Save Failed: ' .. err_msg, 4) - -- end - -- end - -- - -- 3. Save with Python formatting - - - + -- 4. Save with Windows-Safe Formatting if modified then - -- 1. Encode with indentation and sorted keys (Neovim 0.10+) - -- This mimics the "python -m json.tool" output exactly. - local ok, json_str = pcall(vim.json.encode, data, { indent = " ", sort_keys = true }) + -- 'indent' creates the newlines, 'sort_keys' makes it predictable + local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " ", sort_keys = true }) - if ok and json_str then - -- 2. Force split into a proper table for writefile + if ok_enc then + -- CRITICAL: Split into a Table of strings. + -- This forces vim.fn.writefile to use CRLF (\r\n) on Windows. local lines = vim.split(json_str, "\n", { plain = true }) - -- 3. Atomic write with 's' (sync) and force CRLF line endings - -- Setting the fileformat to 'dos' ensures Windows-style line endings. - vim.api.nvim_command("setlocal fileformat=dos") - local status = vim.fn.writefile(lines, filename, "s") + -- Atomic write with 's' (sync) flag + vim.fn.writefile(lines, filename, 's') - if status == 0 then - -- 4. Essential: Force a buffer reload - -- This fixes the "still shows as one line" visual bug in Neovim. - vim.cmd("checktime " .. vim.fn.fnameescape(filename)) - vim.notify("PIO: JSON saved with Windows line endings", 2) - end + -- Force reload of the buffer to see changes + vim.cmd("checktime " .. vim.fn.fnameescape(filename)) + vim.notify("PIO: paths fixed and file formatted", 2) end end - - - -- if modified then - -- -- 1. Encode with 2-space indentation (Pure Lua) - -- local ok, json_str = pcall(vim.json.encode, data, { indent = " " }) - -- - -- if ok and json_str then - -- -- 2. Force a LITERAL split on \n. - -- -- The { plain = true } is the secret—it prevents regex - -- -- and ensures every newline creates a new table element. - -- local lines = vim.split(json_str, "\n", { plain = true }) - -- - -- -- 3. Use writefile with the 's' flag - -- -- On Windows, writefile automatically converts this table - -- -- into CRLF (\r\n) line endings on disk. - -- local status = vim.fn.writefile(lines, filename, 's') - -- - -- if status == 0 then - -- -- 4. Force Neovim to refresh its view of the file - -- vim.cmd("checktime " .. vim.fn.fnameescape(filename)) - -- vim.notify('compiledb: fixed via Native Lua', vim.log.levels.INFO) - -- end - -- else - -- vim.notify('compiledb: Lua encoding failed', vim.log.levels.ERROR) - -- end - -- end - - - - -- if modified then - -- local json_str = vim.json.encode(data) - -- local formatted = vim.fn.system('python -m json.tool', json_str) - -- - -- if vim.v.shell_error == 0 then - -- -- Atomic write back to disk - -- -- vim.fn.writefile(vim.split(formatted, "\n"), filename) - -- -- Change this line in your working code: - -- vim.fn.writefile(vim.split(formatted, "\n"), filename, 's') - -- - -- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) - -- else - -- vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) - -- end - -- end lsp_restart('clangd') _G.metadata.isBusy = false -- M.process_queue() end +-- function M.compile_commandsFix() +-- local filename = vim.fs.joinpath(vim.uv.cwd(), 'compile_commands.json') +-- if vim.fn.filereadable(filename) == 0 then return end +-- +-- -- Atomic read using built-in Vim function +-- local content = table.concat(vim.fn.readfile(filename), "\n") +-- local ok, data = pcall(vim.json.decode, content) +-- if not ok or type(data) ~= 'table' then return end +-- +-- -- 1. Build Path Map (Scan toolchain) +-- local path_map = {} +-- local toolchain_bin = (_G.metadata and _G.metadata.toolchain_root or "") .. '/bin/*' +-- for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do +-- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') +-- path_map[name] = full_path +-- end +-- +-- -- 2. Update Entries efficiently with string matching +-- local modified = false +-- for _, entry in ipairs(data) do +-- local cmd = entry.command or "" +-- local first_token = cmd:match("^%S+") -- Grab only the compiler driver +-- +-- -- Fix if it's a relative path (doesn't start with / or Drive letter) +-- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then +-- local short_name = first_token:gsub('%.exe$', '') +-- if path_map[short_name] then +-- -- Replace only the first token to preserve arguments +-- entry.command = vim.fs.joinpath(path_map[short_name], cmd:sub(#first_token + 1)) +-- modified = true +-- end +-- end +-- end +-- +-- -- PHASE 3: Save and Refresh +-- +-- +-- +-- -- if modified then +-- -- local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " " }) +-- -- if ok_enc then +-- -- local f = io.open(filename, "w") +-- -- if f then +-- -- f:write(json_str) +-- -- f:close() +-- -- end +-- -- end +-- -- end +-- +-- -- if modified then +-- -- local jok, json_str = pcall(vim.json.encode, data, { indent = " " }) +-- -- if not jok or not json_str then +-- -- vim.notify("PIO: JSON Encoding failed", 4) +-- -- return M.process_queue() -- Don't get stuck +-- -- end +-- -- +-- -- -- local lines = vim.split(json_str, '\n') +-- -- local lines = vim.split(json_str, "\n", { trimempty = true }) +-- -- +-- -- -- 1. Check if the directory is actually writable (Safety Check) +-- -- local dir = vim.fn.fnamemodify(filename, ":h") +-- -- if vim.fn.isdirectory(dir) == 0 then +-- -- vim.notify("PIO: Directory does not exist: " .. dir, 4) +-- -- return M.process_queue() +-- -- end +-- -- +-- -- -- 2. Use pcall to prevent the function from "exiting" on error +-- -- local write_ok, status = pcall(vim.fn.writefile, lines, filename, 's') +-- -- +-- -- if write_ok and status == 0 then +-- -- vim.notify('compiledb: fixed and saved', 2) +-- -- else +-- -- local err_msg = not write_ok and status or "Write error (check permissions)" +-- -- vim.notify('PIO Save Failed: ' .. err_msg, 4) +-- -- end +-- -- end +-- -- +-- -- 3. Save with Python formatting +-- +-- +-- +-- if modified then +-- -- 1. Encode with indentation and sorted keys (Neovim 0.10+) +-- -- This mimics the "python -m json.tool" output exactly. +-- local ok, json_str = pcall(vim.json.encode, data, { indent = " ", sort_keys = true }) +-- +-- if ok and json_str then +-- -- 2. Force split into a proper table for writefile +-- local lines = vim.split(json_str, "\n", { plain = true }) +-- +-- -- 3. Atomic write with 's' (sync) and force CRLF line endings +-- -- Setting the fileformat to 'dos' ensures Windows-style line endings. +-- vim.api.nvim_command("setlocal fileformat=dos") +-- local status = vim.fn.writefile(lines, filename, "s") +-- +-- if status == 0 then +-- -- 4. Essential: Force a buffer reload +-- -- This fixes the "still shows as one line" visual bug in Neovim. +-- vim.cmd("checktime " .. vim.fn.fnameescape(filename)) +-- vim.notify("PIO: JSON saved with Windows line endings", 2) +-- end +-- end +-- end +-- +-- +-- -- if modified then +-- -- -- 1. Encode with 2-space indentation (Pure Lua) +-- -- local ok, json_str = pcall(vim.json.encode, data, { indent = " " }) +-- -- +-- -- if ok and json_str then +-- -- -- 2. Force a LITERAL split on \n. +-- -- -- The { plain = true } is the secret—it prevents regex +-- -- -- and ensures every newline creates a new table element. +-- -- local lines = vim.split(json_str, "\n", { plain = true }) +-- -- +-- -- -- 3. Use writefile with the 's' flag +-- -- -- On Windows, writefile automatically converts this table +-- -- -- into CRLF (\r\n) line endings on disk. +-- -- local status = vim.fn.writefile(lines, filename, 's') +-- -- +-- -- if status == 0 then +-- -- -- 4. Force Neovim to refresh its view of the file +-- -- vim.cmd("checktime " .. vim.fn.fnameescape(filename)) +-- -- vim.notify('compiledb: fixed via Native Lua', vim.log.levels.INFO) +-- -- end +-- -- else +-- -- vim.notify('compiledb: Lua encoding failed', vim.log.levels.ERROR) +-- -- end +-- -- end +-- +-- +-- +-- -- if modified then +-- -- local json_str = vim.json.encode(data) +-- -- local formatted = vim.fn.system('python -m json.tool', json_str) +-- -- +-- -- if vim.v.shell_error == 0 then +-- -- -- Atomic write back to disk +-- -- -- vim.fn.writefile(vim.split(formatted, "\n"), filename) +-- -- -- Change this line in your working code: +-- -- vim.fn.writefile(vim.split(formatted, "\n"), filename, 's') +-- -- +-- -- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) +-- -- else +-- -- vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) +-- -- end +-- -- end +-- lsp_restart('clangd') +-- _G.metadata.isBusy = false +-- -- M.process_queue() +-- end + + -- lsp_restart('clangd') + -- _G.metadata.isBusy = false + -- M.process_queue() + ------------------------------------------------------ -- INFO: ToggleTerminal commands sequencer From 5a23cb54af1b5b8ffd15f2f8fde9ebc0adfe8197 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 05:02:19 +0300 Subject: [PATCH 0853/1406] update --- lua/platformio/utils/pio.lua | 46 ++++++++++++++++++++++++++++-------- 1 file changed, 36 insertions(+), 10 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 0318152e..fc755e71 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -96,23 +96,49 @@ function M.compile_commandsFix() end -- 4. Save with Windows-Safe Formatting + -- if modified then + -- -- 'indent' creates the newlines, 'sort_keys' makes it predictable + -- local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " ", sort_keys = true }) + -- + -- if ok_enc then + -- -- CRITICAL: Split into a Table of strings. + -- -- This forces vim.fn.writefile to use CRLF (\r\n) on Windows. + -- local lines = vim.split(json_str, "\n", { plain = true }) + -- + -- -- Atomic write with 's' (sync) flag + -- vim.fn.writefile(lines, filename, 's') + -- + -- -- Force reload of the buffer to see changes + -- vim.cmd("checktime " .. vim.fn.fnameescape(filename)) + -- vim.notify("PIO: paths fixed and file formatted", 2) + -- end + -- end + + if modified then - -- 'indent' creates the newlines, 'sort_keys' makes it predictable - local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " ", sort_keys = true }) + -- 1. Encode with 2-space indentation (Pure Lua) + local ok, json_str = pcall(vim.json.encode, data, { indent = " " }) - if ok_enc then - -- CRITICAL: Split into a Table of strings. - -- This forces vim.fn.writefile to use CRLF (\r\n) on Windows. + if ok and json_str then + -- 2. CRITICAL: Split the string into a list of lines + -- This ensures writefile sees multiple lines instead of one long block local lines = vim.split(json_str, "\n", { plain = true }) - -- Atomic write with 's' (sync) flag - vim.fn.writefile(lines, filename, 's') + -- 3. Atomic write with 's' (sync) flag + -- On Windows, this will automatically write \r\n for each line + local status = vim.fn.writefile(lines, filename, "s") - -- Force reload of the buffer to see changes - vim.cmd("checktime " .. vim.fn.fnameescape(filename)) - vim.notify("PIO: paths fixed and file formatted", 2) + if status == 0 then + -- 4. Force Neovim to refresh its internal view of the file + vim.cmd("checktime " .. vim.fn.fnameescape(filename)) + vim.notify("PIO: JSON saved with multiple lines (Windows Fix)", 2) + end end end + + + + lsp_restart('clangd') _G.metadata.isBusy = false -- M.process_queue() From 999bb68aa920ef9c3dfe47462ca2870c24bcaea4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 05:18:22 +0300 Subject: [PATCH 0854/1406] update --- lua/platformio/utils/pio.lua | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index fc755e71..cee8b328 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -116,22 +116,22 @@ function M.compile_commandsFix() if modified then - -- 1. Encode with 2-space indentation (Pure Lua) + -- 1. Encode with 2-space indentation (This creates \n characters in the string) local ok, json_str = pcall(vim.json.encode, data, { indent = " " }) if ok and json_str then - -- 2. CRITICAL: Split the string into a list of lines - -- This ensures writefile sees multiple lines instead of one long block + -- 2. FORCE SPLIT: Turn the one long string into a List of lines + -- The { plain = true } ensures we split on the literal \n local lines = vim.split(json_str, "\n", { plain = true }) - -- 3. Atomic write with 's' (sync) flag - -- On Windows, this will automatically write \r\n for each line - local status = vim.fn.writefile(lines, filename, "s") + -- 3. Use writefile: + -- Linux: joins table with \n + -- Windows: joins table with \r\n (Fixing your single-line issue!) + local status = vim.fn.writefile(lines, filename, 's') if status == 0 then - -- 4. Force Neovim to refresh its internal view of the file vim.cmd("checktime " .. vim.fn.fnameescape(filename)) - vim.notify("PIO: JSON saved with multiple lines (Windows Fix)", 2) + vim.notify("PIO: Fixed paths and line endings", 2) end end end From 8b1a1d8fd00c4c4ce09424addd1540f991d37be4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 06:49:14 +0300 Subject: [PATCH 0855/1406] update --- compile_commandsFix.lua | 129 ------ lua/platformio/archived/fix_compiledb.py | 63 --- lua/platformio/archived/pio_setup.lua | 484 --------------------- lua/platformio/archived/pio_setupold.lua | 277 ------------ lua/platformio/archived/piocmd.lua | 22 - lua/platformio/archived/piodebug.lua | 16 - lua/platformio/archived/piolsp.lua | 10 - lua/platformio/archived/piomon.lua | 30 -- lua/platformio/archived/tmp.lua | 108 ----- lua/platformio/archived/ufix_compiledb.py | 72 ---- lua/platformio/archived/utils.lua | 399 ------------------ lua/platformio/utils/pio.lua | 339 +++++---------- metadata.lua | 203 --------- metadataolld.lua | 133 ------ pio.lua | 346 --------------- pio_setup.lua | 417 ------------------- pio_setupold.lua | 485 ---------------------- term.lua | 324 --------------- term2.lua | 327 --------------- tmp.lua | 90 ---- 20 files changed, 112 insertions(+), 4162 deletions(-) delete mode 100644 compile_commandsFix.lua delete mode 100644 lua/platformio/archived/fix_compiledb.py delete mode 100644 lua/platformio/archived/pio_setup.lua delete mode 100644 lua/platformio/archived/pio_setupold.lua delete mode 100644 lua/platformio/archived/piocmd.lua delete mode 100644 lua/platformio/archived/piodebug.lua delete mode 100644 lua/platformio/archived/piolsp.lua delete mode 100644 lua/platformio/archived/piomon.lua delete mode 100644 lua/platformio/archived/tmp.lua delete mode 100644 lua/platformio/archived/ufix_compiledb.py delete mode 100644 lua/platformio/archived/utils.lua delete mode 100644 metadata.lua delete mode 100644 metadataolld.lua delete mode 100644 pio.lua delete mode 100644 pio_setup.lua delete mode 100644 pio_setupold.lua delete mode 100644 term.lua delete mode 100644 term2.lua delete mode 100644 tmp.lua diff --git a/compile_commandsFix.lua b/compile_commandsFix.lua deleted file mode 100644 index 0e81e1d2..00000000 --- a/compile_commandsFix.lua +++ /dev/null @@ -1,129 +0,0 @@ --- function M.compile_commandsFix() --- local filename = vim.uv.cwd() .. '/compile_commands.json' --- local content = vim.fn.readfile(filename) --- if #content == 0 then return end --- --- local ok, data = pcall(vim.json.decode, table.concat(content, "\n")) --- if not ok or type(data) ~= 'table' then return end --- --- -- 1. Build Path Map (Scan toolchain) --- local path_map = {} --- --- local pio_binaries = _G.metadata.query_driver or "/bin/*" --- -- local pio_binaries = (_G.metadata.toolchain_root or "") .. '/bin/*' --- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do --- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') --- path_map[name] = full_path --- end --- --- -- 2. Update Entries --- local modified = false --- for _, entry in ipairs(data) do --- local cmd = entry.command or "" --- local first_token = cmd:match("^%S+") -- Get first word before space --- --- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then --- local short_name = first_token:gsub('%.exe$', '') --- if path_map[short_name] then --- -- Swap first token with full path safely --- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) --- modified = true --- end --- end --- end --- --- -- 3. Save with Formatting --- if modified then --- local json_str = vim.json.encode(data) --- -- Use python to format, then write file --- local formatted = vim.fn.system('python -m json.tool', json_str) --- if vim.v.shell_error == 0 then --- vim.fn.writefile(vim.split(formatted, "\n"), filename) --- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) --- end --- end --- end - -function M.compile_commandsFix() - local filename = vim.uv.cwd() .. '/compile_commands.json' - local file = io.open(filename, 'r') - if not file then - return - end - - -- read compile_commands.json file to content - local content = file:read('*a') - file:close() - if not content or content == '' then - return - end - - -- JSON decoding content to data - local ok, data = pcall(vim.json.decode, content) - if not ok or type(data) ~= 'table' then - vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) - return - end - - print('PioFix0') - -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path - local path_map = {} - local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') - if pio_home then - -- Recursively find all binaries in PIO packages - local pio_packages = _G.metadata.toolchain_root .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' - local found_binaries = vim.fn.glob(pio_packages, false, true) - - for _, full_path in ipairs(found_binaries) do - -- Extract filename (e.g., riscv32-esp-elf-gcc) - local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') - path_map[name] = full_path - -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) - end - end - - -- PHASE 2: Update JSON using the Map - local modified = 0 - for _, entry in ipairs(data) do - if type(entry.command) == 'string' then - local cmd_parts = vim.split(entry.command, ' ') - local first_token = cmd_parts[1] - if first_token then - -- Check if it's already a short name (not an absolute path) - local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') - if not is_abs then - local short_name = first_token:gsub('%.exe$', '') - -- print('PioFix2: short_name=' .. short_name) - -- Direct Query: Does this name exist in our discovered list? - if path_map[short_name] then - cmd_parts[1] = path_map[short_name] - -- print('PioFix3: full_name=' .. cmd_parts[1]) - entry.command = table.concat(cmd_parts, ' ') - modified = modified + 1 - end - end - end - end - end - - -- PHASE 3: Save and Refresh - -- Safe JSON encoding - if modified > 0 then - local out_file = io.open(filename, 'w') - if out_file then - local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) - if encode_ok and json_str then - -- 1. Format the string using python's json.tool - -- The second argument to vim.fn.system() is the "stdin" passed to the command - local formatted_json = vim.fn.system('python -m json.tool', json_str) - - -- out_file:write(json_str) - out_file:write(formatted_json) - out_file:close() - vim.notify('compiledb: fixed', vim.log.levels.INFO) - lsp_restart('clangd') - _G.metadata.isBusy = false - end - end - end -end diff --git a/lua/platformio/archived/fix_compiledb.py b/lua/platformio/archived/fix_compiledb.py deleted file mode 100644 index bcaf49e3..00000000 --- a/lua/platformio/archived/fix_compiledb.py +++ /dev/null @@ -1,63 +0,0 @@ -import json -import os - -# Grab the environment from PlatformIO -Import("env") - -def get_toolchain_metadata(): - """Detects active toolchain and returns (cc_path, sysroot, target_triplet).""" - platform = env.PioPlatform() - - # List of known Espressif toolchains and their internal triplets - toolchains = [ - ("toolchain-riscv32-esp", "riscv32-esp-elf"), - ("toolchain-xtensa-esp32", "xtensa-esp32-elf"), - ("toolchain-xtensa-esp32s2", "xtensa-esp32s2-elf"), - ("toolchain-xtensa-esp32s3", "xtensa-esp32s3-elf"), - ] - - for pkg_name, triplet in toolchains: - pkg_dir = platform.get_package_dir(pkg_name) - if pkg_dir: - # Construct paths - cc_name = f"{triplet}-gcc" - cc_path = os.path.join(pkg_dir, "bin", cc_name) - if os.name == "nt": - cc_path += ".exe" - - sysroot = os.path.join(pkg_dir, triplet) - - # Return cleaned forward-slash paths for clangd compatibility - return cc_path.replace("\\", "/"), sysroot.replace("\\", "/"), triplet - - return None, None, None - -def update_compilation_db(source, target, env_inner): - """Callback to fix the JSON file after generation.""" - db_path = str(target) - cc_path, sysroot, triplet = get_toolchain_metadata() - - if not cc_path or not os.path.exists(db_path): - print(f"-- [FixDB] Toolchain not detected or {db_path} missing.") - return - - with open(db_path, "r") as f: - db = json.load(f) - - for entry in db: - # Inject the correct target and sysroot - extra_flags = f" --target={triplet} --sysroot=\"{sysroot}\"" - - if "--target=" not in entry["command"]: - # Replace relative compiler name with absolute path - entry["command"] = entry["command"].replace(f"{triplet}-gcc", f"\"{cc_path}\"") - entry["command"] += extra_flags - - with open(db_path, "w") as f: - json.dump(db, f, indent=2) - - print(f"\n-- [FixDB] Auto-detected {triplet}") - print(f"-- [FixDB] Injected sysroot: {sysroot}") - -# Register the hook -env.AddPostAction("$PROJECT_DIR/compile_commands.json", update_compilation_db) diff --git a/lua/platformio/archived/pio_setup.lua b/lua/platformio/archived/pio_setup.lua deleted file mode 100644 index 61243a9e..00000000 --- a/lua/platformio/archived/pio_setup.lua +++ /dev/null @@ -1,484 +0,0 @@ --- M = {} --- --- local misc = require('platformio.utils.misc') --- local lsp = require('platformio.lsp.tools') --- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen --- --- -- lua/pio_setup.lua --- -- This module manages PlatformIO project integration, LSP toolchain detection, --- -- and automatic sysroot patching for standard library headers (, etc.) --- --- local debounce_timer = vim.uv.new_timer() --- --- -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) --- -- INFO: --- -- ============================================================================= --- -- UNIVERSAL TOOLCHAIN DETECTION --- -- ============================================================================= --- --- stylua: ignore --- local function get_sysroot_triplet(cc_compiler) --- local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') --- -- Early exit if path is nil or not a directory --- if not bin_path or vim.fn.isdirectory(bin_path) == 0 then --- return nil --- end --- --- -- Normalize backslashes to forward slashes for cross-platform consistency --- bin_path = bin_path:gsub('\\', '/') --- local files = vim.fn.readdir(bin_path) --- local triplet = nil --- --- -- Loop through files to find the compiler and extract the triplet --- for _, name in ipairs(files) do --- -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ --- local match = name:match('^(.*)%-g[c%+][c%+]') --- if match then --- triplet = match --- break --- end --- end --- --- -- Return nil if no compiler was found in the bin directory --- if not triplet then --- return nil --- end --- --- -- toolchain_root is the parent of the 'bin' folder --- local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') --- -- sysroot folder is expected to have the same name as the triplet --- local sysroot = toolchain_root .. '/' .. triplet --- --- -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) --- -- Only return data if the sysroot folder actually exists on disk --- if vim.fn.isdirectory(sysroot) == 1 then --- return { --- triplet = triplet, --- sysroot = sysroot, --- toolchain_root = toolchain_root, --- query_driver = bin_path .. '/' .. triplet .. '-*', --- } --- end --- return nil --- end --- --- --- -- INFO: --- -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag --- -- stylua: ignore --- local function pio_generate_db() --- vim.schedule(function() vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) end) --- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) --- if obj.code ~= 0 then --- vim.schedule(function() --- if obj.code == 127 then --- vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) --- else --- vim.notify('PIO Manager: Generating Compile Database failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) --- end --- end) --- return --- end --- vim.schedule(function() vim.notify('PIO: Generating Compile Database successful', vim.log.levels.INFO) end) --- end) --- end --- --- -- INFO: 1. The Core PIO Manager & Generic Extractor --- --- stylua: ignore --- local pio_manager = (function() --- local cache = nil -- Stores the decoded platformio.ini JSON structure --- -- INFO: --- local function find_in_data(data, section_name, key_name) --- -- Safety check: Ensure data is a valid table from a successful JSON decode --- if type(data) ~= 'table' then --- return nil --- end --- --- for _, section in ipairs(data) do --- -- Each section must be a table with at least 2 elements: [1]=name, [2]=content --- if type(section) == 'table' and #section >= 2 then --- local s_id = section[1] -- Section header string --- local s_body = section[2] -- Table of key-value pairs --- --- if s_id == section_name and type(s_body) == 'table' then --- for _, kv in ipairs(s_body) do --- -- Each kv is a table: [1]=key, [2]=value --- if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then --- local val = kv[2] --- -- Treat empty strings or empty tables as nil to trigger fallback logic --- if val == nil or val == '' or (type(val) == 'table' and #val == 0) then --- return nil --- end --- return val --- end --- end --- end --- end --- end --- return nil --- end --- --- -- INFO: ASYNC REFRESH: Fetches the latest config from PlatformIO CLI --- --- stylua: ignore --- local function refresh(callback) --- vim.schedule(function() --- vim.notify('PIO: Fetching Config ...', vim.log.levels.INFO) --- end) --- --- -- INFO: get project metadata --- local function get_metadata(attempts, env) --- local active_env = env or _G.metadata.active_env --- vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(int_obj) --- vim.schedule(function() --- vim.notify('PIO: Fetching metadata ...', vim.log.levels.INFO) --- end) --- --- if int_obj.code ~= 0 then --- -- Schedule notification to avoid error in the system callback thread --- vim.schedule(function() --- if int_obj.code == 127 then --- vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) --- else --- vim.notify('PIO Manager: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) --- end --- end) --- return --- end --- --- if int_obj.code == 0 and int_obj.stdout then --- local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) --- if ok and raw_data then --- local _, data = next(raw_data) --- if data then --- local fallback_flags = {} --- -- 1. Process Includes --- if data.includes then --- for category, paths in pairs(data.includes) do --- -- If it's a toolchain path, use -isystem to suppress warnings --- -- and tell clangd these are standard libraries --- if category == 'toolchain' then --- local flag = '-isystem' --- for _, path in ipairs(paths) do --- -- table.insert(fallback_flags, string.format('%q', flag)) --- -- table.insert(fallback_flags, string.format('%q', path:gsub('\\', '/'))) --- table.insert(fallback_flags, string.format('%q', flag .. path:gsub('\\', '/'))) --- end --- end --- -- local flag = (category == 'toolchain') and '-isystem' or '-I' --- -- for _, path in ipairs(paths) do --- -- table.insert(fallback_flags, flag .. path) --- -- end --- end --- end --- -- 2. Process Defines --- if data.defines then --- for _, define in ipairs(data.defines) do --- table.insert(fallback_flags, string.format('%q', '-D' .. define)) --- end --- end --- --- -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' --- _G.metadata.cc_compiler = misc.normalize_path(data.cc_path) or '' --- _G.metadata.fallback_flags = fallback_flags --- --- -- print(vim.inspect(_G.metadata)) --- if callback then --- vim.schedule(function() --- vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) --- callback() --- end) --- end --- end --- else --- vim.schedule(function() --- vim.notify('PIO: Syncing Environment failed', vim.log.levels.WARN) --- end) --- end --- end --- -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save --- if attempts > 0 then --- vim.defer_fn(function() --- get_metadata(attempts - 1) --- end, 500) --- end --- end) --- end --- --- -- INFO: -- 1. Setup Base Paths --- local home = os.getenv('HOME') or os.getenv('USERPROFILE') --- -- INFO: -- 2. Define Mapping (key in INI, Env Var, Default Subfolder) --- local map = { --- core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, --- packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, --- platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, --- } --- --- -- INFO: 3. Try to get explicit value from platformio.ini --- -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' --- -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } --- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) --- if ext_obj.code ~= 0 then --- -- Schedule notification to avoid error in the system callback thread --- vim.schedule(function() --- if ext_obj.code == 127 then --- vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) --- else --- vim.notify('PIO Manager: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) --- end --- end) --- return --- end --- _G.metadata.core_dir = '' --- _G.metadata.packages_dir = '' --- _G.metadata.platforms_dir = '' --- _G.metadata.active_env = '' --- _G.metadata.default_envs = {} --- _G.metadata.envs = {} --- --- local decoded = vim.json.decode(ext_obj.stdout) --- for _, section in ipairs(decoded) do --- if type(section) == 'table' and #section >= 2 then --- local name, data = section[1], section[2] --- -- 1. Extract Global PlatformIO Settings --- if name == 'platformio' then --- for _, kv in ipairs(data) do --- local key, val = kv[1], kv[2] --- if key ~= nil then --- -- if _G.metadata[key] ~= nil then --- _G.metadata[key] = val --- end --- end --- -- 2. Extract all hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] --- elseif name:match('^env:') then --- local env_name = name:match('^env:(.+)') --- _G.metadata.envs[env_name] = {} --- for _, kv in ipairs(data) do --- _G.metadata.envs[env_name][kv[1]] = kv[2] --- end --- end --- end --- end --- if #_G.metadata.default_envs > 0 then --- _G.metadata.active_env = _G.metadata.default_envs[1] or '' --- else --- _G.metadata.active_env = next(_G.metadata.envs) or '' --- end --- --- for _, kv in ipairs(map) do --- -- 4.0 Fallback Logic: INI -> Env Var -> Default --- local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') --- -- 5. Expand ${platformio.core_dir} --- if type(result) == 'string' then --- if result:find('${platformio.core_dir}', 1, true) then --- result = result:gsub('%${platformio.core_dir}', _G.metadata.core_dir) --- end --- end --- -- 6. Normalize Slashes for Windows --- -- _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') --- _G.metadata[kv.ini] = result:gsub('\\', '/'):gsub('//+', '/') --- end --- -- return _G.metadata[map[type].ini] --- -- end --- --- if _G.metadata.active_env ~= '' then --- vim.schedule(function() --- vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) --- end) --- get_metadata(1, _G.metadata.active_env) --- else --- vim.schedule(function() --- vim.notify('PIO: no [env:] found, add board first', vim.log.levels.ERROR) --- end) --- end --- end) --- end --- --- -- INFO: --- return { --- refresh = refresh, --- -- INFO: --- get = function(s, k) --- if not cache then --- return nil --- end --- local res = find_in_data(cache, s, k) --- --- -- FALLBACK: If default_envs is missing/empty, find the first hardware [env:xxx] block --- if k == 'default_envs' and not res then --- for _, section in ipairs(cache) do --- if type(section) == 'table' and type(section[1]) == 'string' then --- local name = section[1] --- if name:find('^env:') then --- local fallback = name:match('^env:(.+)') --- if fallback then --- vim.schedule(function() --- vim.notify('PIO: default_envs empty. Using: ' .. fallback, vim.log.levels.INFO) --- end) --- return fallback --- end --- end --- end --- end --- vim.schedule(function() --- vim.notify('PIO: Config Error. Check platformio.ini no env', vim.log.levels.WARN) --- end) --- elseif k == 'default_envs' and res and type(res) == 'table' then --- return res[1] --- else --- return res --- end --- end, --- } --- end)() --- --- -- INFO: --- function _G.get_pio_sdk_info() --- local pio_info = { includes = {}, cc_compiler = '' } --- if vim.fn.filereadable('platformio.ini') == 0 then --- return nil --- end --- --- local handle = io.popen('pio run -t envdump') --- if not handle then --- return nil --- end --- --- local packages_dir, cc_name, toolchain_pkg = '', '', '' --- --- for line in handle:lines() do --- -- 1. Get the global packages directory --- packages_dir = packages_dir ~= '' and packages_dir or line:match("'PROJECT_PACKAGES_DIR': '([^']+)'") --- --- -- 2. Get the compiler executable name (e.g., riscv32-esp-elf-gcc) --- cc_name = cc_name ~= '' and cc_name or line:match("'CC': '([^']+)'") --- --- -- 3. Find the specific toolchain package name from the PACKAGES list --- -- Matches lines like "- toolchain-riscv32-esp @ 14.2.0" --- local pkg = line:match('%- (toolchain%-[^ ]+)') --- if pkg then --- toolchain_pkg = pkg --- end --- --- -- 4. Collect include paths --- local path_list = line:match("'CPPPATH': %[(.+)%]") --- if path_list then --- for path in path_list:gmatch("'([^']+)'") do --- table.insert(pio_info.includes, '-I' .. path) --- end --- end --- end --- handle:close() --- --- -- Construct the absolute path: //bin/ --- if packages_dir and packages_dir ~= '' and toolchain_pkg and toolchain_pkg ~= '' and cc_name ~= '' then --- local full_path = packages_dir .. '/' .. toolchain_pkg .. '/bin/' .. cc_name --- if vim.fn.executable(full_path) == 1 then --- pio_info.cc_compiler = full_path --- end --- end --- --- local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' --- print('get_pio_sdk_info(): final=' .. final) --- -- Normalize paths for the OS and ensure backslashes for Windows if needed --- -- print(vim.inspect(_G.metadata)) --- return (misc.normalize_path(final)) --- -- return _G.metadata.query_driver --- -- return pio_info --- end --- --- -- INFO: --- -- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync --- -- stylua: ignore --- local function start_pio_watcher() --- local dir_path = vim.uv.cwd() --- if not dir_path then return end --- --- -- Create a directory watcher --- local handle = vim.uv.new_fs_event() --- if not handle then return end --- --- -- local last_trigger = 0 --- -- Watch the directory for platformio.ini creation or changes --- handle:start( --- dir_path, --- { --- watch_entry = false, -- watch the file/dir itself --- stat = false, -- use stat to detect changes (slower but more reliable on some FS) --- recursive = false, -- watch subdirectories (if path is a directory) --- }, --- vim.schedule_wrap(function(err, filename, events) --- if err or not events or not events.change then return end --- -- Trigger only if the changed file is platformio.ini --- if filename == 'platformio.ini' and (events.change or events.rename) then --- -- -- ignore events within time --- -- local current_time = vim.uv.now() --- -- -- IGNORE events if they happen within 100ms of the last one --- -- if current_time - last_trigger < 100 then --- -- return --- -- end --- -- last_trigger = current_time --- --- if debounce_timer then --- debounce_timer:stop() --- debounce_timer:start( --- 500, --- 0, --- vim.schedule_wrap(function() --- pio_manager.refresh(function() --- -- vim.schedule(function() --- local status, data = pcall(get_sysroot_triplet, _G.metadata.cc_compiler) --- if status and data and data.triplet and data.triplet ~= '' then --- _G.metadata.triplet = data.triplet --- _G.metadata.sysroot = data.sysroot --- _G.metadata.query_driver = data.query_driver --- _G.metadata.toolchain_root = data.toolchain_root --- end --- -- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) --- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) --- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) --- --- pio_generate_db() --- lsp.lsp_restart('clangd') --- -- end) --- end) end)) end end end)) --- end --- ------------------------------------------------------------------------------------------------------ --- -- INFO: 6. Exported setup function --- function M.init() --- local config = require('platformio').config --- if config.lspClangd.enabled == true then --- vim.notify('PIO setup initialize', vim.log.levels.INFO) --- ---------------------------------------------------------------------------------------- --- -- INFO: create clangd required files --- ----------------------------------------------------------------------------------------- --- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) --- -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) --- -- boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) --- -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) --- -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') --- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) --- boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) --- --------------------------------------------------------------------------------- --- --- require('platformio.lsp.clangd') --- if config.lspClangd.attach.enabled then --- require('platformio.lsp.attach') --- end --- --- -- Always start the watcher so it can catch a future 'pio init' --- start_pio_watcher() --- --- -- If the file already exists, do an initial sync --- if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then --- pio_manager.refresh(function() --- -- vim.schedule(function() --- -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) --- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) --- pio_generate_db() --- lsp.lsp_restart('clangd') --- -- end) --- end) --- end --- end --- end --- --- return M diff --git a/lua/platformio/archived/pio_setupold.lua b/lua/platformio/archived/pio_setupold.lua deleted file mode 100644 index d4ec21df..00000000 --- a/lua/platformio/archived/pio_setupold.lua +++ /dev/null @@ -1,277 +0,0 @@ --- local misc = require('platformio.utils.misc') --- local lsp = require('platformio.lsp.tools') --- --- local debounce_timer = vim.uv.new_timer() --- --- -- INFO: 1. The Core PIO Manager & Generic Extractor --- --This manages the data cache and navigates your specific nested-list JSON structure. --- --- -- stylua: ignore --- local pio_manager = (function() --- local cache = nil --- --- -- INFO: 1 Generic extractor for nested structure: { { "name", { {"k","v"}, ... } }, ... } --- local function find_in_data(data, section_name, key_name) --- if not data or type(data) ~= 'table' then return nil end --- --- -- INFO: 1.0 SPECIFIC SEARCH: Look for a specific section (e.g., "platformio") --- if section_name then --- for _, section in ipairs(data) do --- if type(section) == 'table' and #section >= 2 then --- local s_id, s_body = section[1], section[2] --- if s_id == section_name and type(s_body) == "table" then --- for _, kv in ipairs(s_body) do --- if type(kv) == "table" and #kv >= 2 and kv[1] == key_name then --- local val = kv[2] --- if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then --- return val --- end --- end --- end --- end --- end --- end --- end --- --- -- INFO: 1.1 FALLBACK SEARCH (If we reach here, Step 1 failed or was skipped) --- local fallback_env_found = nil --- for _, section in ipairs(data) do --- if type(section) == 'table' and #section >= 2 then --- local s_id = section[1] --- local s_body = section[2] --- -- Look for hardware envs like [env:seeed_xiao_esp32c3], skipping generic [env] --- if type(s_id) == 'string' and s_id:find('^env:') then --- fallback_env_found = s_id:match('^env:(.+)') --- --- -- If we were looking for default_envs, we just found our fallback --- if key_name == 'default_envs' then --- vim.schedule(function() --- vim.notify("PIO: 'default_envs' empty. Falling back to: " .. fallback_env_found, vim.log.levels.INFO) --- end) --- return fallback_env_found --- end --- --- -- If looking for a key (like 'platform') inside this fallback env --- if type(s_body) == 'table' then --- for _, kv in ipairs(s_body) do --- if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then --- local val = kv[2] --- if val ~= nil and val ~= '' and (type(val) ~= 'table' or #val > 0) then --- vim.schedule(function() --- vim.notify("PIO: Using '" .. key_name .. "' from fallback env: " .. fallback_env_found, vim.log.levels.INFO) --- end) --- return val --- end --- end --- end --- end --- end --- end --- end --- --- -- INFO: 1.2 FINAL ERROR If even fallback fails --- if key_name == 'platform' or key_name == 'packages_dir' then --- vim.schedule(function() --- vim.notify("PIO: Critical key '" .. key_name .. "' not found anywhere!", vim.log.levels.INFO) --- end) --- end --- return nil --- end --- ------------------------------------------------------------------------------------------ --- --- -- INFO: 2. Asynchronous Refresh --- local function refresh(callback) --- -- Using vim.system to detect if the command exists --- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) --- if obj.code ~= 0 then --- -- Schedule notification to avoid error in the system callback thread --- vim.schedule(function() --- if obj.code == 127 then --- vim.notify("PIO Manager: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) --- else --- vim.notify('PIO Manager: Failed to fetch config (Error ' .. obj.code .. ')', vim.log.levels.WARN) --- end --- end) --- return --- end --- local ok, decoded = pcall(vim.json.decode, obj.stdout) --- if ok and decoded then --- cache = decoded --- if not cache or type(cache) ~= 'table' then --- print('no cahce') --- else --- print('cahced ok') --- end --- if callback then vim.schedule(callback) end --- end --- end) --- end --- return { --- refresh = refresh, --- get = function(s, k) --- return find_in_data(cache, s, k) --- end, --- } --- end)() --- --- ------------------------------------------------------------------------------------------------------ --- -- INFO: 2. Generic Toolchain & Sysroot Logic. These functions identify where the compiler and its C++ headers live. --- -- Gets the compiler glob for clangd --query-driver --- -- stylua: ignore --- function _G.get_pio_toolchain_pattern() --- local active_env = vim.g.pio_active_env or pio_manager.get("platformio", "default_envs") --- -- or pio_manager.get(nil, "default_envs") --- --- -- Handle default_envs being a list/table --- if type(active_env) == 'table' then active_env = active_env[1] end --- --- local target_env = active_env and ('env:' .. active_env) or nil --- local platform = pio_manager.get(target_env, 'platform') --- local packages_dir = pio_manager.get('platformio', 'packages_dir') or (os.getenv('HOME') or os.getenv('USERPROFILE') .. '/.platformio/packages') --- --- if not platform then return '/**/bin/*' end --- --- -- Sync call for toolchain name --- local p_handle = io.popen('pio platform show ' .. platform .. ' --json-output') --- if not p_handle then return '/**/bin/*' end --- --- local p_json = p_handle:read('*all') --- p_handle:close() --- local arch_glob = '/**/bin/*' --- local p_ok, p_data = pcall(vim.json.decode, p_json) --- if p_ok and p_data and type(p_data.packages) == 'table' then --- for pkg_name, _ in pairs(p_data.packages) do --- if type(pkg_name) == 'string' and pkg_name:find('^toolchain%-') then --- local arch = pkg_name:gsub('toolchain%-', ''):gsub('gcc%-?', '') --- arch_glob = '/**/bin/*' .. arch .. '*' --- break --- end --- end --- end --- -- local final = (packages_dir:gsub('\\', '/') .. arch_glob):gsub('//+', '/') --- local final = packages_dir .. arch_glob --- print('toolchain 5: final=' .. final) --- return (misc.normalize_path(final)) --- -- return vim.fn.has('win32') == 1 and final:gsub('/', '\\') or final --- end --- --- -- INFO: 3. Patches compile_commands.json with --sysroot to fix --- -- Helper to generate the compilation database --- -- stylua: ignore --- local function pio_generate_db() --- -- This runs in the background so it doesn't freeze Neovim --- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) --- if obj.code ~= 0 then return end --- print('pio_generate_db 0') --- local pattern = _G.get_pio_toolchain_pattern() --- local toolchain_root = pattern:match('(.*toolchain%-[^/\\]+)') --- if not toolchain_root or vim.fn.isdirectory(toolchain_root) == 0 then --- return --- end --- --- -- Find subdirectory containing 'include' (the sysroot) --- local sysroot_path = nil --- local subdirs = vim.fn.getcompletion(toolchain_root .. '/*', 'dir') --- for _, dir in ipairs(subdirs) do --- if vim.fn.isdirectory(dir .. '/include') == 1 then --- sysroot_path = dir:gsub('\\', '/') --- break --- end --- end --- if sysroot_path then --- local db_path = vim.fn.getcwd() .. '/compile_commands.json' --- local f = io.open(db_path, 'r') --- if not f then return end --- local content = f:read('*all') --- f:close() --- --- -- patch sysroot --- local patched = content:gsub('("-i")', '"--sysroot=' .. sysroot_path .. '", %1') --- local out = io.open(db_path, 'w') --- if out then --- out:write(patched) --- out:close() --- vim.schedule(function() vim.notify('PIO: DB & Sysroot Patched') end) --- end --- end --- end) --- end --- --- ------------------------------------------------------------------------------------------------------ --- -- INFO: 4. Automation & File Watcher --- --This handles the background synchronization when you save your project. --- -- stylua: ignore --- local function start_pio_watcher() --- local path = vim.fn.getcwd() .. '/platformio.ini' --- if vim.fn.filereadable(path) == 0 then return end --- --- local w = vim.uv.new_fs_event() --- if not w then return end --- --- w:start( --- path, {}, --- vim.schedule_wrap(function(err, _, events) --- if err or not events.change then return end --- --- -- 1. Stop any existing timer (cancel previous "half-finished" events) --- if debounce_timer then --- debounce_timer:stop() --- --- -- 2. Start a 500ms window. Logic only runs if NO more events happen in this time. --- debounce_timer:start( 500, 0, --- vim.schedule_wrap(function() --- vim.notify('PIO: Config change detected. Refreshing...', vim.log.levels.INFO) --- --- pio_manager.refresh(function() --- pio_generate_db() --- -- 3. Only restart LSP if the pattern actually changed or DB was updated --- lsp.lsp_restart('clangd') --- end) --- end) --- ) --- end --- end) --- ) --- end --- --- ------------------------------------------------------------------------------------------------------ --- -- INFO: 6. Exported setup function --- return { --- init = function() --- local config = require('platformio').config --- if config.lspClangd.enabled == true then --- vim.notify('PIO setup initialize', vim.log.levels.INFO) --- ---------------------------------------------------------------------------------------- --- -- INFO: create clangd required files --- ----------------------------------------------------------------------------------------- --- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen --- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) --- --- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) --- boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) --- -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) --- -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') --- --- -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) --- --- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) --- --- boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) --- -- boilerplate_gen([[enable_toolchain.py]], vim.g.platformioRootDir) --- -- boilerplate_gen([[generate_compile_commands.py]], vim.g.platformioRootDir) --- --------------------------------------------------------------------------------- --- --- -- vim.api.nvim_echo({ { 'lspClangd true', 'Info' } }, true, {}) --- require('platformio.lsp.clangd') --- if config.lspClangd.attach.enabled then --- require('platformio.lsp.attach') --- end --- if vim.fn.filereadable(vim.fn.getcwd() .. '/platformio.ini') == 1 then --- pio_manager.refresh(function() --- pio_generate_db() --- start_pio_watcher() --- end) --- end --- end --- end, --- } diff --git a/lua/platformio/archived/piocmd.lua b/lua/platformio/archived/piocmd.lua deleted file mode 100644 index 0f5fde5d..00000000 --- a/lua/platformio/archived/piocmd.lua +++ /dev/null @@ -1,22 +0,0 @@ -local utils = require('platformio.utils') -local M = {} - -function M.piocmd(cmd_table, direction) - if not utils.pio_install_check() then - return - end - - utils.cd_pioini() - - if cmd_table[1] == '' then - utils.ToggleTerminal('', direction) - else - local cmd = 'pio ' - for _, v in pairs(cmd_table) do - cmd = cmd .. ' ' .. v - end - utils.ToggleTerminal(cmd, direction) - end -end - -return M diff --git a/lua/platformio/archived/piodebug.lua b/lua/platformio/archived/piodebug.lua deleted file mode 100644 index d3786e54..00000000 --- a/lua/platformio/archived/piodebug.lua +++ /dev/null @@ -1,16 +0,0 @@ -local utils = require('platformio.utils') -local M = {} - -function M.piodebug(args_table) - if not utils.pio_install_check() then - return - end - - utils.cd_pioini() - - local command = 'pio debug --interface=gdb -- -x .pioinit' - -- local command = string.format('pio debug --interface=gdb -- -x .pioinit %s', utils.extra) - utils.ToggleTerminal(command, 'float') -end - -return M diff --git a/lua/platformio/archived/piolsp.lua b/lua/platformio/archived/piolsp.lua deleted file mode 100644 index 7b5312ac..00000000 --- a/lua/platformio/archived/piolsp.lua +++ /dev/null @@ -1,10 +0,0 @@ -local M = {} - -local lsp_restart = require('platformio.lsp.tools').lsp_restart - --- stylua: ignore -function M.piolsp() - lsp_restart() -end - -return M diff --git a/lua/platformio/archived/piomon.lua b/lua/platformio/archived/piomon.lua deleted file mode 100644 index 0917abd3..00000000 --- a/lua/platformio/archived/piomon.lua +++ /dev/null @@ -1,30 +0,0 @@ -local utils = require('platformio.utils') -local M = {} - -function M.piomon(args_table) - if not utils.pio_install_check() then - return - end - - utils.cd_pioini() - - local command = nil - if #args_table == 0 then - command = 'pio device monitor' - elseif #args_table == 1 then - local baud_rate = args_table[1] - command = string.format('pio device monitor -b %s', baud_rate) - elseif #args_table == 2 then - local baud_rate = args_table[1] - local port = args_table[2] - command = string.format('pio device monitor -b %s -p %s', baud_rate, port) - end - - if command == nil then - vim.notify('Usage: Piomon ', vim.log.levels.ERROR) - else - utils.ToggleTerminal(command, 'horizontal') - end -end - -return M diff --git a/lua/platformio/archived/tmp.lua b/lua/platformio/archived/tmp.lua deleted file mode 100644 index c536630d..00000000 --- a/lua/platformio/archived/tmp.lua +++ /dev/null @@ -1,108 +0,0 @@ -local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen --- 1. Define the template with 3 placeholders --- ============================================================================= --- DYNAMIC CLANGD CONFIGURATION TEMPLATE --- ============================================================================= --- Note: %q is used for paths to handle escaping and spaces automatically. -local clangd_template = [[ -{ - cmd = { - "clangd", - "--all-scopes-completion", - "--background-index", - "--clang-tidy", - "--compile_args_from=filesystem", - "--enable-config", - "--completion-parse=always", - "--completion-style=detailed", - "--header-insertion=iwyu", - "--fallback-style=llvm", - "-j=12", - "--log=verbose", - "--offset-encoding=utf-8", - "--pch-storage=memory", - "--pretty", - "--ranking-model=decision_forest", - "--sync", - "--offset-encoding=utf-16", - "--query-driver=%s", - }, - filetypes = { 'c', 'cpp', 'objc', 'objcpp', 'cuda', 'proto' }, - root_markers = { - 'platformio.ini', - 'CMakeLists.txt', - '.clangd', - '.clang-tidy', - '.clang-format', - 'compile_commands.json', - 'compile_flags.txt', - 'configure.ac', - '.git', - }, - workspace_required = true, - single_file_support = true, - init_options = { - usePlaceholders = true, - completeUnimported = true, - fallbackFlags = {%s}, - clangdFileStatus = true, - compilationDatabasePath = %q, - } -} -]] - --- 2. Prepare the data --- ============================================================================= --- LSP SETUP (NEOVIM 0.11+) --- ============================================================================= - -local clangd_config = { - -- on_new_config runs every time client started - -- stylua: ignore - on_new_config = function(new_config, new_root_dir) - -- Safety check for root_dir - if not new_root_dir then return end - - -- Safe defaults (Standard clangd behavior) - local f_flags, q_driver = '', '--query-driver=**' - - if _G.metadata.cc_compiler ~= '' then - if _G.metadata.triplet and _G.metadata.triplet ~= '' then - q_driver = '--query-driver=' .. (_G.metadata.query_driver or '**') - f_flags = string.format('"--target=%s", "--sysroot=%s"', _G.metadata.triplet, _G.metadata.sysroot) - end - end - - -- Format the clangd_config string - local clangd_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) - local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) - - -- Load the string as a Lua table safely - local ok, table_config = pcall(function() return load('return ' .. formatted_str)() end) - - if ok and table_config then - -- This merges table_config INTO new_config, overwriting existing values - local merged = vim.tbl_deep_extend('force', new_config, table_config) - -- Since we can't reassign the reference, we have to copy the keys back - for k, v in pairs(merged) do new_config[k] = v end - else - -- If template loading fails, alert the user but keep default cmd - vim.notify('LSP Config Table Generation Failed', vim.log.levels.ERROR) - end - end, -} - --- Apply and Enable -vim.lsp.config('clangd', clangd_config) -vim.lsp.enable('clangd') --- local q_driver = '--query-driver=' .. data.query_driver --- local f_flags = string.format('"--target=%s", "--sysroot=%s"', data.triplet, data.sysroot) --- local db_path = vim.uv.cwd() -- Using 0.11+ uv alias --- --- -- 3. Format the string --- local formatted_str = string.format(clangd_template, q_driver, f_flags, db_path) --- --- -- 4. Load it into a real Lua table --- local status, my_table = pcall(function() --- return load('return ' .. formatted_str)() --- end) diff --git a/lua/platformio/archived/ufix_compiledb.py b/lua/platformio/archived/ufix_compiledb.py deleted file mode 100644 index c206f438..00000000 --- a/lua/platformio/archived/ufix_compiledb.py +++ /dev/null @@ -1,72 +0,0 @@ -import glob -import json -import os - -Import("env") - - -def get_dynamic_toolchain(): - """Scans all installed packages to find the active toolchain and triplet.""" - platform = env.PioPlatform() - # Get the directory where all packages for this platform are stored - packages_dir = platform.get_package_dir("") or "" - - # Scan for any toolchain packages currently in use - for pkg_name in platform.packages.keys(): - if not pkg_name.startswith("toolchain-"): - continue - - pkg_dir = platform.get_package_dir(pkg_name) - if not pkg_dir: - continue - - # Logic: The triplet is usually the name of the folder inside /bin - # before the '-gcc' suffix. e.g., 'riscv32-esp-elf-gcc' -> 'riscv32-esp-elf' - bin_dir = os.path.join(pkg_dir, "bin") - gcc_files = glob.glob(os.path.join(bin_dir, "*-gcc*")) - - if gcc_files: - # Extract triplet from the first gcc binary found - # e.g., C:/.../bin/xtensa-esp32-elf-gcc.exe -> xtensa-esp32-elf - filename = os.path.basename(gcc_files[0]) - triplet = filename.split("-gcc")[0] - - cc_path = gcc_files[0].replace("\\", "/") - sysroot = os.path.join(pkg_dir, triplet).replace("\\", "/") - - if os.path.isdir(sysroot): - return cc_path, sysroot, triplet - - return None, None, None - - -def update_compilation_db(source, target, env_inner): - db_path = str(target) - cc_path, sysroot, triplet = get_dynamic_toolchain() - - if not cc_path or not os.path.exists(db_path): - print("-- [UniversalFix] Toolchain not found via dynamic scan.") - return - - with open(db_path, "r") as f: - db = json.load(f) - - for entry in db: - extra_flags = f' --target={triplet} --sysroot="{sysroot}"' - # Replace the compiler command if it's just the binary name - if triplet in entry["command"] and "--target=" not in entry["command"]: - # This regex-like replacement ensures we don't break existing flags - entry["command"] = entry["command"].replace( - f"{triplet}-gcc", f'"{cc_path}"' - ) - entry["command"] += extra_flags - - with open(db_path, "w") as f: - json.dump(db, f, indent=2) - - print(f"\n-- [UniversalFix] Detected: {triplet}") - print(f"-- [UniversalFix] Sysroot: {sysroot}") - - -# Hook into the compilation database generation -env.AddPostAction("$PROJECT_DIR/compile_commands.json", update_compilation_db) diff --git a/lua/platformio/archived/utils.lua b/lua/platformio/archived/utils.lua deleted file mode 100644 index a17b0684..00000000 --- a/lua/platformio/archived/utils.lua +++ /dev/null @@ -1,399 +0,0 @@ -local M = {} - -local is_windows = jit.os == 'Windows' -M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' --- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' --- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' - -local config = require('platformio').config --- local pio = require('platformio.utils.pio') --.piolsp - ------------------------------------------------------- -function M.strsplit(inputstr, del) - local t = {} - if type(inputstr) == 'string' and inputstr and inputstr ~= '' then - for str in string.gmatch(inputstr, '([^' .. del .. ']+)') do - table.insert(t, str) - end - end - return t -end - -function M.check_prefix(str, prefix) - return str:sub(1, #prefix) == prefix -end - -local function pathmul(n) - return '..' .. string.rep('/..', n) -end - ------------------------------------------------------- - --- INFO: get current OS enter -function M.enter() - local shell = vim.o.shell - if is_windows then - return vim.fn.executable('pwsh') and '\r' or '\r\n' - elseif shell:find('nu') then - return '\r' - else - return '\n' - end -end - --- INFO: get previous window -local function getPreviousWindow(orig_window) - local prev = { - orig_window = orig_window, - term = nil, --active terminal - cli = nil, --cli terminal - mon = nil, --mon terminal - float = false, --is active terminal direction float - } - local terms = require('toggleterm.terminal').get_all(true) - if #terms ~= 0 then - for i = 1, #terms do - if terms[i].display_name and terms[i].display_name ~= '' and terms[i].display_name:find('pio', 1) then - local name_splt = M.strsplit(terms[i].display_name, ':') - if name_splt[1] == 'piocli' then - prev.cli = terms[i] - if terms[i].window == orig_window then - ---@diagnostic disable-next-line: cast-local-type - prev.orig_window = tonumber(name_splt[2]) -- set orig_window to the previous terminal onrig_window - prev.term = terms[i] - end - if terms[i].direction == 'float' then - prev.float = true - end - elseif name_splt[1] == 'piomon' then - prev.mon = terms[i] - if terms[i].window == orig_window then - ---@diagnostic disable-next-line: cast-local-type - prev.orig_window = tonumber(name_splt[2]) -- set orig_window to the previous terminal onrig_window - prev.term = terms[i] - end - if terms[i].direction == 'float' then - prev.float = true - end - end - end - end - end - return prev -end - ------------------------------------------------------- --- INFO: Send command -local function send(term, cmd) - vim.fn.chansend(term.job_id, cmd .. M.enter()) - if vim.api.nvim_buf_is_loaded(term.bufnr) and vim.api.nvim_buf_is_valid(term.bufnr) then - if term.window and vim.api.nvim_win_is_valid(term.window) then --vim.ui.term_has_open_win(term) then - vim.api.nvim_set_current_win(term.window) -- terminal focus - vim.api.nvim_buf_call(term.bufnr, function() - local mode = vim.api.nvim_get_mode().mode - if mode == 'n' or mode == 'nt' then - vim.cmd('normal! G') -- normal command to Goto bottom of buffer (scroll) - end - end) - end - end -end - ------------------------------------------------------- --- INFO: PioTermClose -local function PioTermClose(t) - local orig_window = tonumber(M.strsplit(t.display_name, ':')[2]) - -- close terminal window - vim.api.nvim_win_close(t.window, true) - - -- go back to previous window - if orig_window and vim.api.nvim_win_is_valid(orig_window) then - vim.api.nvim_set_current_win(orig_window) - else - vim.api.nvim_set_current_win(0) - end -end - ------------------------------------------------------- --- INFO: ToggleTerminal -function M.ToggleTerminal(command, direction) - local status_ok, _ = pcall(require, 'toggleterm') - if not status_ok then - vim.api.nvim_echo({ { 'toggleterm not found!', 'ErrorMsg' } }, true, {}) - return - end - - local title = '' - local pioOpts = {} - - -- INFO: set orig_window to current window, or if available get current toggleterm previous window - local prev = getPreviousWindow(vim.api.nvim_get_current_win()) - local orig_window = prev.orig_window - - if string.find(command, ' monitor') then - if prev.mon then -- INFO: if previous monitor terminal already opened ==> reopen - prev.mon.display_name = 'piomon:' .. orig_window - local win_type = vim.fn.win_gettype(prev.mon.window) - local win_open = win_type == '' or win_type == 'popup' - if prev.mon.window and (win_open and vim.api.nvim_win_get_buf(prev.mon.window) == prev.mon.bufnr) then - vim.api.nvim_set_current_win(prev.mon.window) - else - prev.mon:open() - end - return - end - title = 'Pio Monitor: [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' - pioOpts.display_name = 'piomon:' .. orig_window - else -- INFO: if previous cli terminal already opened ==> reopen - if prev.cli then - prev.cli.display_name = 'piocli:' .. orig_window - local win_type = vim.fn.win_gettype(prev.cli.window) - local win_open = win_type == '' or win_type == 'popup' - if prev.cli.window and (win_open and vim.api.nvim_win_get_buf(prev.cli.window) == prev.cli.bufnr) then - vim.api.nvim_set_current_win(prev.cli.window) - else - prev.cli:open() - end - vim.defer_fn(function() - if command and command ~= '' then - send(prev.cli, command) - end - end, 50) -- 50ms delay, adjust as needed - return - end - title = 'Pio CLI> [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' - pioOpts.display_name = 'piocli:' .. orig_window - end - pioOpts.direction = direction - ------------------------------------------------------ - - -- INFO: termConfig table start - local termConfig = { - hidden = true, -- Start hidden, we'll open it explicitly - hide_numbers = true, - float_opts = { - winblend = 0, - width = function() - return math.ceil(vim.o.columns * 0.85) - end, - height = function() - return math.ceil(vim.o.lines * 0.85) - end, - -- shell = vim.o.shell, - shell = vim.o.shell, - highlights = { - border = 'FloatBorder', - background = 'NormalFloat', - }, - }, - close_on_exit = false, --closeOnexit, - - -- INFO: on_open() - on_open = function(t) - -- Get properties of the 'Normal' highlight group (background of main editor) - -- local hl = vim.api.nvim_get_hl(0, { name = 'PmenuSel' }) - -- local hl = { bg = '#e4cf0e', fg = '#0012d9' } - local hl = { bg = '#80a3d4', fg = '#000000' } - - if hl then - vim.api.nvim_set_hl(0, 'MyWinBar', { bg = hl.bg, fg = hl.fg }) - - local winBartitle = '%#MyWinBar#' .. title .. '%*' - vim.api.nvim_set_option_value('winbar', winBartitle, { scope = 'local', win = t.window }) - - -- Following necessary to solve that some time winbar not showing - vim.schedule(function() - vim.api.nvim_set_option_value('winbar', winBartitle, { scope = 'local', win = t.window }) - end) - end - vim.keymap.set('t', '', [[k]], { buffer = t.bufnr }) - vim.keymap.set('n', '', [[a]], { buffer = t.bufnr }) - - vim.keymap.set('n', 'q', function() - PioTermClose(t) - end, { desc = 'PioTermClose', buffer = t.bufnr }) - - if config.debug then - local name_splt = M.strsplit(t.display_name, ':') - vim.api.nvim_echo({ - { 'ToggleTerm ', 'MoreMsg' }, - { '(Term name: ' .. name_splt[1] .. ')', 'MoreMsg' }, - { '(Prev win ID: ' .. name_splt[2] .. ')', 'MoreMsg' }, - { '(Term Win ID: ' .. t.window .. ')', 'MoreMsg' }, - { '(Term Buffer#: ' .. t.bufnr .. ')', 'MoreMsg' }, - { '(Term id: ' .. t.id .. ')', 'MoreMsg' }, - { '(Job ID: ' .. t.job_id .. ')', 'MoreMsg' }, - }, true, {}) - end - end, - - -- INFO: on_close() - on_close = function(t) - orig_window = tonumber(M.strsplit(t.display_name, ':')[2]) - ---@diagnostic disable-next-line: param-type-mismatch - if orig_window and vim.api.nvim_win_is_valid(orig_window) then - vim.api.nvim_set_current_win(orig_window) - else - vim.api.nvim_set_current_win(0) - end - end, - - -- -- INFO: on_exit() - -- on_exit = function(_) - -- exit_callback() - -- end, - - -- INFO: on_stdout - -- on_stdout = stdout_callback, - on_stdout = require('platformio.utils.pio').dispatcher, - - -- INFO: on_create() { - on_create = function(t) - local platformio = vim.api.nvim_create_augroup(M.strsplit(t.display_name, ':')[1], { clear = true }) - - -- INFO: CmdlineLeave - vim.api.nvim_create_autocmd('CmdlineLeave', { - group = platformio, - -- pattern = ':', - buffer = t.bufnr, - callback = function() - if vim.v.event and not vim.v.event.abort and vim.v.event.cmdtype == ':' then - local quit = vim.fn.getcmdline() == 'q' - local quitbang = vim.fn.getcmdline() == 'q!' - if quitbang or quit then - local name_splt = M.strsplit(t.display_name, ':') - if quitbang then - if name_splt[1] == 'piomon' then -- monitor terminal - local exit = vim.api.nvim_replace_termcodes('exit', true, true, true) - send(t, exit) - else -- cli terminal - send(t, 'exit') - end - end - - orig_window = tonumber(name_splt[2]) - vim.schedule(function() - -- go back to previous window - if orig_window and vim.api.nvim_win_is_valid(orig_window) then - vim.api.nvim_set_current_win(orig_window) - else - vim.api.nvim_set_current_win(0) - end - end) - end - end - end, - }) - - -- INFO: BufUnload - vim.api.nvim_create_autocmd('BufUnload', { - group = platformio, - desc = 'toggleterm buffer unloaded', - buffer = t.bufnr, - callback = function(args) - vim.keymap.del('t', '', { buffer = args.buf }) - vim.keymap.del('n', '', { buffer = args.buf }) - - -- clear autommmand when quit - vim.api.nvim_clear_autocmds({ group = M.strsplit(t.display_name, ':')[1] }) - end, - }) - end, - } - -- INFO: termConfig table end - - termConfig = vim.tbl_deep_extend('force', termConfig, pioOpts or {}) - - -- INFO: create new terminal - local terminal = require('toggleterm.terminal').Terminal:new(termConfig) - if prev.term and prev.float then - prev.term:close() - end - terminal:toggle() - vim.defer_fn(function() - if command and command ~= '' then - send(terminal, command) - end - end, 50) -- 50ms delay, adjust as needed sgget -end - ----------------------------------------------------------------------------------------- - -local paths = { '.', '..', pathmul(1), pathmul(2), pathmul(3), pathmul(4), pathmul(5) } - -function M.file_exists(name) - local f = io.open(name, 'r') - if f ~= nil then - io.close(f) - return true - else - return false - end -end - -function M.set_platformioRootDir() - if vim.g.platformioRootDir ~= nil then - return - end - for _, path in pairs(paths) do - if M.file_exists(path .. '/platformio.ini') then - vim.g.platformioRootDir = path - return - end - end - vim.notify('Could not find platformio.ini, run :Pioinit to create a new project', vim.log.levels.ERROR) -end - -function M.cd_pioini() - M.set_platformioRootDir() - vim.cmd('cd ' .. vim.g.platformioRootDir) -end - -function M.pio_install_check() - local handel = (jit.os == 'Windows') and assert(io.popen('where.exe pio 2>./nul')) or assert(io.popen('which pio 2>/dev/null')) - local pio_path = assert(handel:read('*a')) - handel:close() - - if #pio_path == 0 then - vim.notify('Platformio not found in the path', vim.log.levels.ERROR) - return false - end - return true -end - -function M.async_shell_cmd(cmd, callback) - local output = {} - - vim.fn.jobstart(cmd, { - stdout_buffered = true, - stderr_buffered = false, - - on_stdout = function(_, data) - if data then - for _, line in ipairs(data) do - if line ~= '' then - table.insert(output, line) - end - end - end - end, - - on_exit = function(_, code) - callback(output, code) - end, - }) -end - -function M.shell_cmd_blocking(command) - local handle = io.popen(command, 'r') - if not handle then - return nil, 'failed to run command' - end - - local result = handle:read('*a') - handle:close() - - return result -end - -return M diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index cee8b328..819e28a3 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -13,285 +13,170 @@ local misc = require('platformio.utils.misc') local lsp_restart = require('platformio.lsp.tools').lsp_restart ------------------------------------------------------ --- stylua: ignore --- 1. Optimized Cross-Platform Path Fixer --- function M.compile_commandsFix() --- local filename = vim.fs.joinpath(vim.uv.cwd(), 'compile_commands.json') --- if vim.fn.filereadable(filename) == 0 then M.process_queue() return end --- --- local ok, data = pcall(vim.json.decode, table.concat(vim.fn.readfile(filename), "\n")) --- if not ok or type(data) ~= 'table' then M.process_queue() return end --- --- local path_map = {} --- local toolchain = _G.metadata and _G.metadata.toolchain_root or "" --- if toolchain ~= "" then --- local bin_glob = vim.fs.joinpath(toolchain, "bin", "*") --- for _, full_path in ipairs(vim.fn.glob(bin_glob, false, true)) do --- local name = full_path:match('([^' .. sep .. ']+)$'):gsub('%.exe$', '') --- path_map[name] = full_path --- end --- end --- --- local modified = false --- for _, entry in ipairs(data) do --- local cmd = entry.command or "" --- local first_token = cmd:match("^%S+") --- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then --- local name = first_token:gsub('%.exe$', '') --- if path_map[name] then --- entry.command = path_map[name] .. cmd:sub(#first_token + 1) --- modified = true --- end --- end --- end --- --- if modified then --- local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " " }) --- if ok_enc then --- vim.fn.writefile(vim.split(json_str, "\n"), filename, 's') --- end --- end +-- stylua: ignore +local function pretty_print(data) + local insert = table.insert + local buffer = {} + local function format_item(item, current_level) + local indent = string.rep(' ', current_level) + local next_indent = string.rep(' ', current_level + 1) + if type(item) == 'table' then + local is_array = #item > 0 + local opener = is_array and '[' or '{' + local closer = is_array and ']' or '}' + insert(buffer, opener .. '\n') + local first = true + for k, v in pairs(item) do + if not first then insert(buffer, ',\n') end + insert(buffer, next_indent) + if not is_array then insert(buffer, '"' .. k .. '": ') end + format_item(v, current_level + 1) + first = false + end + insert(buffer, '\n' .. indent .. closer) + elseif type(item) == 'string' then + -- Basic escaping for the string content + insert(buffer, '"' .. item:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"') + else insert(buffer, tostring(item)) end + end + format_item(data, 0) + return table.concat(buffer) +end -function M.compile_commandsFix() - local filename = vim.fs.joinpath(vim.uv.cwd(), 'compile_commands.json') - if vim.fn.filereadable(filename) == 0 then return end +function M.compile_commandsFix() --M.dbPathsFix() + local filename = vim.uv.cwd() .. '/compile_commands.json' + local content = vim.fn.readfile(filename) + if #content == 0 then + return + end - -- 1. Read and Decode (Atomic read) - local content = table.concat(vim.fn.readfile(filename), "\n") - local ok, data = pcall(vim.json.decode, content) - if not ok or type(data) ~= 'table' then return end + local ok, data = pcall(vim.json.decode, table.concat(content, '\n')) + if not ok or type(data) ~= 'table' then + return + end - -- 2. Build Path Map (Dynamic OS Separator) - local sep = package.config:sub(1,1) + -- 1. Build Path Map (Scan toolchain) local path_map = {} - local toolchain = (_G.metadata and _G.metadata.toolchain_root or "") - - if toolchain ~= "" then - local bin_glob = vim.fs.joinpath(toolchain, "bin", "*") - for _, full_path in ipairs(vim.fn.glob(bin_glob, false, true)) do - -- Correct regex for both / and \ - local name = full_path:match("([^" .. sep .. "/]+)$"):gsub("%.exe$", "") - path_map[name] = full_path - end + + local pio_binaries = _G.metadata.query_driver or '/bin/*' + -- local pio_binaries = (_G.metadata.toolchain_root or "") .. '/bin/*' + for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do + local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') + path_map[name] = full_path end - -- 3. Update Entries + -- 2. Update Entries local modified = false for _, entry in ipairs(data) do - local cmd = entry.command or "" - local first_token = cmd:match("^%S+") - - if first_token then - -- Check if it's already absolute (starts with / or C:) - local is_abs = first_token:sub(1,1) == '/' or first_token:match("^%a:") - if not is_abs then - local name = first_token:gsub("%.exe$", "") - if path_map[name] then - entry.command = path_map[name] .. cmd:sub(#first_token + 1) - modified = true - end + local cmd = entry.command or '' + local first_token = cmd:match('^%S+') -- Get first word before space + + if first_token and not (first_token:sub(1, 1) == '/' or first_token:match('^%a:')) then + local short_name = first_token:gsub('%.exe$', '') + if path_map[short_name] then + -- Swap first token with full path safely + entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) + modified = true end end end - -- 4. Save with Windows-Safe Formatting - -- if modified then - -- -- 'indent' creates the newlines, 'sort_keys' makes it predictable - -- local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " ", sort_keys = true }) - -- - -- if ok_enc then - -- -- CRITICAL: Split into a Table of strings. - -- -- This forces vim.fn.writefile to use CRLF (\r\n) on Windows. - -- local lines = vim.split(json_str, "\n", { plain = true }) - -- - -- -- Atomic write with 's' (sync) flag - -- vim.fn.writefile(lines, filename, 's') - -- - -- -- Force reload of the buffer to see changes - -- vim.cmd("checktime " .. vim.fn.fnameescape(filename)) - -- vim.notify("PIO: paths fixed and file formatted", 2) - -- end - -- end - - + -- 3. Save with Formatting if modified then - -- 1. Encode with 2-space indentation (This creates \n characters in the string) - local ok, json_str = pcall(vim.json.encode, data, { indent = " " }) - - if ok and json_str then - -- 2. FORCE SPLIT: Turn the one long string into a List of lines - -- The { plain = true } ensures we split on the literal \n - local lines = vim.split(json_str, "\n", { plain = true }) - - -- 3. Use writefile: - -- Linux: joins table with \n - -- Windows: joins table with \r\n (Fixing your single-line issue!) - local status = vim.fn.writefile(lines, filename, 's') - - if status == 0 then - vim.cmd("checktime " .. vim.fn.fnameescape(filename)) - vim.notify("PIO: Fixed paths and line endings", 2) - end + local start_time = vim.loop.hrtime() + local json_str = vim.json.encode(data) + local pretty = pretty_print(json_str) + + local f = io.open(filename, 'w') + if f then + f:write(pretty) + f:close() + + local end_time = vim.loop.hrtime() + local duration = (end_time - start_time) / 1e6 + print(string.format('Saved %s in %.2fms', filename, duration)) + vim.notify('compiledb: paths fixed', vim.log.levels.INFO) + lsp_restart('clangd') + _G.metadata.isBusy = false end + -- -- Use python to format, then write file + -- local formatted = vim.fn.system('python -m json.tool', json_str) + -- if vim.v.shell_error == 0 then + -- vim.fn.writefile(vim.split(formatted, '\n'), filename) + -- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) + -- end end +end - lsp_restart('clangd') - _G.metadata.isBusy = false - -- M.process_queue() -end +-- stylua: ignore -- function M.compile_commandsFix() -- local filename = vim.fs.joinpath(vim.uv.cwd(), 'compile_commands.json') -- if vim.fn.filereadable(filename) == 0 then return end -- --- -- Atomic read using built-in Vim function +-- -- 1. Read and Decode (Atomic read) -- local content = table.concat(vim.fn.readfile(filename), "\n") -- local ok, data = pcall(vim.json.decode, content) -- if not ok or type(data) ~= 'table' then return end -- --- -- 1. Build Path Map (Scan toolchain) +-- -- 2. Build Path Map (Dynamic OS Separator) +-- local sep = package.config:sub(1,1) -- local path_map = {} --- local toolchain_bin = (_G.metadata and _G.metadata.toolchain_root or "") .. '/bin/*' --- for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do --- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') --- path_map[name] = full_path +-- local toolchain = (_G.metadata and _G.metadata.toolchain_root or "") +-- +-- if toolchain ~= "" then +-- local bin_glob = vim.fs.joinpath(toolchain, "bin", "*") +-- for _, full_path in ipairs(vim.fn.glob(bin_glob, false, true)) do +-- -- Correct regex for both / and \ +-- local name = full_path:match("([^" .. sep .. "/]+)$"):gsub("%.exe$", "") +-- path_map[name] = full_path +-- end -- end -- --- -- 2. Update Entries efficiently with string matching +-- -- 3. Update Entries -- local modified = false -- for _, entry in ipairs(data) do -- local cmd = entry.command or "" --- local first_token = cmd:match("^%S+") -- Grab only the compiler driver +-- local first_token = cmd:match("^%S+") -- --- -- Fix if it's a relative path (doesn't start with / or Drive letter) --- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then --- local short_name = first_token:gsub('%.exe$', '') --- if path_map[short_name] then --- -- Replace only the first token to preserve arguments --- entry.command = vim.fs.joinpath(path_map[short_name], cmd:sub(#first_token + 1)) --- modified = true +-- if first_token then +-- -- Check if it's already absolute (starts with / or C:) +-- local is_abs = first_token:sub(1,1) == '/' or first_token:match("^%a:") +-- if not is_abs then +-- local name = first_token:gsub("%.exe$", "") +-- if path_map[name] then +-- entry.command = path_map[name] .. cmd:sub(#first_token + 1) +-- modified = true +-- end -- end -- end -- end -- --- -- PHASE 3: Save and Refresh --- --- --- --- -- if modified then --- -- local ok_enc, json_str = pcall(vim.json.encode, data, { indent = " " }) --- -- if ok_enc then --- -- local f = io.open(filename, "w") --- -- if f then --- -- f:write(json_str) --- -- f:close() --- -- end --- -- end --- -- end --- --- -- if modified then --- -- local jok, json_str = pcall(vim.json.encode, data, { indent = " " }) --- -- if not jok or not json_str then --- -- vim.notify("PIO: JSON Encoding failed", 4) --- -- return M.process_queue() -- Don't get stuck --- -- end --- -- --- -- -- local lines = vim.split(json_str, '\n') --- -- local lines = vim.split(json_str, "\n", { trimempty = true }) --- -- --- -- -- 1. Check if the directory is actually writable (Safety Check) --- -- local dir = vim.fn.fnamemodify(filename, ":h") --- -- if vim.fn.isdirectory(dir) == 0 then --- -- vim.notify("PIO: Directory does not exist: " .. dir, 4) --- -- return M.process_queue() --- -- end --- -- --- -- -- 2. Use pcall to prevent the function from "exiting" on error --- -- local write_ok, status = pcall(vim.fn.writefile, lines, filename, 's') --- -- --- -- if write_ok and status == 0 then --- -- vim.notify('compiledb: fixed and saved', 2) --- -- else --- -- local err_msg = not write_ok and status or "Write error (check permissions)" --- -- vim.notify('PIO Save Failed: ' .. err_msg, 4) --- -- end --- -- end --- -- --- -- 3. Save with Python formatting --- --- --- -- if modified then --- -- 1. Encode with indentation and sorted keys (Neovim 0.10+) --- -- This mimics the "python -m json.tool" output exactly. --- local ok, json_str = pcall(vim.json.encode, data, { indent = " ", sort_keys = true }) +-- -- 1. Encode with 2-space indentation (This creates \n characters in the string) +-- local ok, json_str = pcall(vim.json.encode, data, { indent = " " }) -- -- if ok and json_str then --- -- 2. Force split into a proper table for writefile +-- -- 2. FORCE SPLIT: Turn the one long string into a List of lines +-- -- The { plain = true } ensures we split on the literal \n -- local lines = vim.split(json_str, "\n", { plain = true }) -- --- -- 3. Atomic write with 's' (sync) and force CRLF line endings --- -- Setting the fileformat to 'dos' ensures Windows-style line endings. --- vim.api.nvim_command("setlocal fileformat=dos") --- local status = vim.fn.writefile(lines, filename, "s") +-- -- 3. Use writefile: +-- -- Linux: joins table with \n +-- -- Windows: joins table with \r\n (Fixing your single-line issue!) +-- local status = vim.fn.writefile(lines, filename, 's') -- -- if status == 0 then --- -- 4. Essential: Force a buffer reload --- -- This fixes the "still shows as one line" visual bug in Neovim. -- vim.cmd("checktime " .. vim.fn.fnameescape(filename)) --- vim.notify("PIO: JSON saved with Windows line endings", 2) +-- vim.notify("PIO: Fixed paths and line endings", 2) -- end -- end -- end --- --- --- -- if modified then --- -- -- 1. Encode with 2-space indentation (Pure Lua) --- -- local ok, json_str = pcall(vim.json.encode, data, { indent = " " }) --- -- --- -- if ok and json_str then --- -- -- 2. Force a LITERAL split on \n. --- -- -- The { plain = true } is the secret—it prevents regex --- -- -- and ensures every newline creates a new table element. --- -- local lines = vim.split(json_str, "\n", { plain = true }) --- -- --- -- -- 3. Use writefile with the 's' flag --- -- -- On Windows, writefile automatically converts this table --- -- -- into CRLF (\r\n) line endings on disk. --- -- local status = vim.fn.writefile(lines, filename, 's') --- -- --- -- if status == 0 then --- -- -- 4. Force Neovim to refresh its view of the file --- -- vim.cmd("checktime " .. vim.fn.fnameescape(filename)) --- -- vim.notify('compiledb: fixed via Native Lua', vim.log.levels.INFO) --- -- end --- -- else --- -- vim.notify('compiledb: Lua encoding failed', vim.log.levels.ERROR) --- -- end --- -- end --- --- --- --- -- if modified then --- -- local json_str = vim.json.encode(data) --- -- local formatted = vim.fn.system('python -m json.tool', json_str) --- -- --- -- if vim.v.shell_error == 0 then --- -- -- Atomic write back to disk --- -- -- vim.fn.writefile(vim.split(formatted, "\n"), filename) --- -- -- Change this line in your working code: --- -- vim.fn.writefile(vim.split(formatted, "\n"), filename, 's') --- -- --- -- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) --- -- else --- -- vim.notify('compiledb: paths fix failed', vim.log.levels.ERROR) --- -- end --- -- end -- lsp_restart('clangd') -- _G.metadata.isBusy = false -- -- M.process_queue() diff --git a/metadata.lua b/metadata.lua deleted file mode 100644 index f274936f..00000000 --- a/metadata.lua +++ /dev/null @@ -1,203 +0,0 @@ --- -- 1. Initialize Global Table immediately (Prevents nil errors) --- _G.metadata = _G.metadata --- or { --- isBusy = false, --- envs = {}, --- active_env = '', --- default_envs = {}, --- core_dir = '', --- packages_dir = '', --- platforms_dir = '', --- query_driver = '', --- cc_compiler = '', --- triplet = '', --- toolchain_root = '', --- sysroot = '', --- fallbackFlags = {}, --- } --- --- _G.get_pio_status = function() --- if _G.metadata and _G.metadata.active_env ~= '' then --- return ' [ ' .. _G.metadata.active_env .. '] ' --- end --- return '' --- end --- -- Move the %#PioStatus# and %* outside of the curly braces --- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua._G.get_pio_status()}%* %y %p%% %l:%c' --- --- local M = {} --- local last_saved_hash = '' --- local config_path = vim.fn.getcwd() .. '/.project_config.json' --- --- local function getHash(data) --- return vim.fn.sha256(data) --- end --- --- -- local last_hash = '' --- -- local dir_path = vim.uv.cwd() --- -- local config_file = vim.fs.joinpath(dir_path, '.project_config.json') --- -- --- -- function M.sync_config(force_load) --- -- if force_load then --- -- if vim.fn.filereadable(config_file) == 1 then --- -- local data = table.concat(vim.fn.readfile(config_file), '') --- -- _G.metadata = vim.json.decode(data) --- -- last_hash = getHash(data) --- -- end --- -- else --- -- local current_data = vim.json.encode(_G.metadata) --- -- local current_hash = getHash(current_data) --- -- if current_hash ~= last_hash then --- -- vim.fn.writefile({ current_data }, config_file) --- -- last_hash = current_hash --- -- end --- -- end --- -- end --- --- -- 2. Self-Healing Load & Auto-Create --- function M.load_project_config() --- local success = false --- --- if vim.fn.filereadable(config_path) == 1 then --- local file = io.open(config_path, 'r') --- if file then --- local content = file:read('*a') --- file:close() --- local ok, decoded = pcall(vim.json.decode, content) --- if ok and type(decoded) == 'table' then --- _G.metadata = decoded --- last_saved_hash = getHash(content) --- success = true --- end --- end --- end --- --- -- If file is missing or corrupted, initialize and force-save --- if not success then --- -- Use the global table we initialized at the top --- local encoded = vim.json.encode(_G.metadata) --- local file = io.open(config_path, 'w') --- if file then --- file:write(encoded) --- file:close() --- last_saved_hash = getHash(encoded) --- if vim.fn.filereadable('platformio.ini') == 1 then --- vim.notify('New project config created', vim.log.levels.INFO, { title = 'PlatformIO' }) --- end --- end --- end --- end --- --- -- 3. Performance-Proof Save (Hash Check) --- function M.save_project_config(quiet) --- if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then --- return --- end --- --- local current_data = vim.json.encode(_G.metadata) --- local current_hash = getHash(current_data) --- --- -- Only write if data actually changed since last load/save --- if current_hash ~= last_saved_hash then --- local file = io.open(config_path, 'w') --- if file then --- file:write(current_data) --- file:close() --- last_saved_hash = current_hash --- --- if not quiet then --- vim.notify('Settings synced to disk', vim.log.levels.INFO, { --- title = 'PlatformIO', --- render = 'compact', --- }) --- end --- end --- end --- end --- --- -- 4. Fixed Status Function (Fixes line 472 error) --- function M.show_status() --- -- Ensure we access the table, NOT call it --- local meta = _G.metadata --- local env = meta.active_env ~= '' and meta.active_env or 'None' --- --- vim.notify(string.format('Environment: %s\nTarget: %s', env, meta.triplet or 'Unknown'), vim.log.levels.INFO, { title = 'PlatformIO Status' }) --- end --- --- local pio_group = vim.api.nvim_create_augroup('PioPersist', { clear = true }) --- vim.api.nvim_create_autocmd({ 'BufWritePost', 'VimLeavePre' }, { --- group = pio_group, --- callback = function() --- -- Pass 'true' to save silently in the background --- M.save_project_config(true) --- end, --- desc = 'Automatically save PlatformIO project metadata', --- }) --- --- -- 5. Environment Switcher UI --- function M.switch_env() --- -- 1. Safety check for metadata --- if not _G.metadata.envs or next(_G.metadata.envs) == nil then --- vim.notify('No environments found. Please refresh PlatformIO data.', vim.log.levels.WARN) --- return --- end --- --- -- 2. Prepare the list of environments --- local options = vim.tbl_keys(_G.metadata.envs) --- table.sort(options) --- --- -- 3. Open the selection UI --- vim.ui.select(options, { --- prompt = 'Select PlatformIO Environment:', --- format_item = function(item) --- local icon = (item == _G.metadata.active_env) and ' ' or '○ ' --- return icon .. item --- end, --- }, function(choice) --- if choice then --- -- Update active environment --- _G.metadata.active_env = choice --- --- -- 4. Persist change to disk (silently) --- M.save_project_config(true) --- --- -- 5. Notify the user with the new board info --- local board = _G.metadata.envs[choice].board or 'unknown' --- vim.notify(string.format('Switched to %s\nBoard: %s', choice, board), vim.log.levels.INFO, { title = 'PlatformIO' }) --- --- -- 6. RESTART LSP (Crucial for refreshing includes/defines) --- -- We wrap in pcall in case clangd isn't actually running yet --- --- local pio_manager = require('platformio.pio_setup').pio_manager --- pio_manager.refresh(function() --- M.compile_commands() --- local lsp_restart = require('platformio.tools').lsp_restart --- lsp_restart('clangd') --- end) --- --- pcall(function() --- -- Force LSP to pick up new fallbackFlags/defines --- local lsp_restart = require('platformio.lsp.tools').lsp_restart --- lsp_restart() --- end) --- end --- end) --- end --- --- -- 6. Keybindings --- -- Switch Environment --- vim.keymap.set('n', '\\e', function() --- M.switch_env() --- end, { desc = 'Switch [E]nvironment' }) --- --- -- write --- vim.keymap.set('n', '\\w', function() --- M.save_project_config(false) --- end, { desc = 'config [W]rite' }) --- --- -- Manual Status Check --- vim.keymap.set('n', '\\s', function() --- M.show_status() --- end, { desc = 'config [S]tatus' }) --- --- return M diff --git a/metadataolld.lua b/metadataolld.lua deleted file mode 100644 index 500ec1b6..00000000 --- a/metadataolld.lua +++ /dev/null @@ -1,133 +0,0 @@ --- -- Performance-proof: Uses guaranteed Vimscript sha256 via Lua bridge --- local function get_safe_hash(data) --- -- sha256 is built into Neovim's core and never nil --- return vim.fn.sha256(data) --- end --- --- local M = {} --- local last_saved_hash = nil --- local config_path = vim.fn.getcwd() .. '/.pioConfig.json' --- --- -- -- Global metadata initialization --- -- _G.metadata = _G.metadata --- -- or { --- -- envs = {}, --- -- active_env = '', --- -- default_envs = {}, --- -- core_dir = '', --- -- packages_dir = '', --- -- platforms_dir = '', --- -- query_driver = '', --- -- cc_compiler = '', --- -- triplet = '', --- -- toolchain_root = '', --- -- sysroot = '', --- -- fallbackFlags = {}, --- -- } --- --- -- 1. Optimized Save Function --- --- function M.save_project_config(quiet) --- if not _G.metadata or vim.fn.filereadable('platformio.ini') == 0 then --- return --- end --- --- local current_data = vim.json.encode(_G.metadata) --- local current_hash = get_safe_hash(current_data) --- --- -- Only write if data actually changed --- if current_hash ~= last_saved_hash then --- local file = io.open(config_path, 'w') --- if file then --- file:write(current_data) --- file:close() --- last_saved_hash = current_hash --- --- if not quiet then --- vim.notify('Project settings synced to disk', vim.log.levels.INFO, { --- title = 'PlatformIO', --- render = 'compact', --- }) --- end --- end --- end --- end --- --- -- 2. Robust Load Function (Startup) --- local default_metadata = { --- envs = {}, --- active_env = '', --- default_envs = {}, --- core_dir = '', --- packages_dir = '', --- platforms_dir = '', --- query_driver = '', --- cc_compiler = '', --- triplet = '', --- toolchain_root = '', --- sysroot = '', --- fallbackFlags = {}, --- } --- --- function M.load_project_config() --- local path = vim.fn.getcwd() .. '/.project_config.json' --- local success = false --- --- if vim.fn.filereadable(path) == 1 then --- local file = io.open(path, 'r') --- if file then --- local content = file:read('*a') --- file:close() --- local ok, decoded = pcall(vim.json.decode, content) --- if ok and type(decoded) == 'table' then --- _G.metadata = decoded --- last_saved_hash = get_safe_hash(content) --- success = true --- end --- end --- end --- --- -- If no file or failed to read, write defaults immediately --- if not success then --- _G.metadata = vim.deepcopy(default_metadata) --- local encoded = vim.json.encode(_G.metadata) --- local file = io.open(path, 'w') --- if file then --- file:write(encoded) --- file:close() --- last_saved_hash = get_safe_hash(encoded) --- if vim.fn.filereadable('platformio.ini') == 1 then --- vim.notify('Initialized new project settings', vim.log.levels.INFO, { title = 'PlatformIO' }) --- end --- end --- end --- end --- --- -- 3. Environment Switcher UI --- function M.switch_env() --- if not _G.metadata.envs or next(_G.metadata.envs) == nil then --- vim.notify('No environments found. Run PlatformIO Refresh first.', vim.log.levels.WARN) --- return --- end --- --- local options = vim.tbl_keys(_G.metadata.envs) --- table.sort(options) --- --- vim.ui.select(options, { --- prompt = 'Select PlatformIO Environment:', --- format_item = function(item) --- local indicator = (item == _G.metadata.active_env) and '● ' or '○ ' --- return indicator .. item --- end, --- }, function(choice) --- if choice then --- _G.metadata.active_env = choice --- -- Save immediately on user selection --- M.save_project_config(false) --- -- Force LSP to pick up new fallbackFlags/defines --- vim.cmd('LspRestart clangd') --- end --- end) --- end --- --- return M diff --git a/pio.lua b/pio.lua deleted file mode 100644 index b38a4068..00000000 --- a/pio.lua +++ /dev/null @@ -1,346 +0,0 @@ -local M = {} - -M.selected_framework = '' - -local misc = require('platformio.utils.misc') -local lsp_restart = require('platformio.lsp.tools').lsp_restart - ------------------------------------------------------- --- stylua: ignore -function M.compile_commandsFix() - local filename = vim.uv.cwd() .. '/compile_commands.json' - if vim.fn.filereadable(filename) == 0 then return end - - -- Atomic read using built-in Vim function - local content = table.concat(vim.fn.readfile(filename), "\n") - local ok, data = pcall(vim.json.decode, content) - if not ok or type(data) ~= 'table' then return end - - -- 1. Build Path Map (Scan toolchain) - local path_map = {} - local toolchain_bin = (_G.metadata and _G.metadata.toolchain or "") .. '/bin/*' - for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do - local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') - path_map[name] = full_path - end - - -- 2. Update Entries efficiently with string matching - local modified = false - for _, entry in ipairs(data) do - local cmd = entry.command or "" - local first_token = cmd:match("^%S+") -- Grab only the compiler driver - - -- Fix if it's a relative path (doesn't start with / or Drive letter) - if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then - local short_name = first_token:gsub('%.exe$', '') - if path_map[short_name] then - -- Replace only the first token to preserve arguments - entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) - modified = true - end - end - end - - -- 3. Save with Python formatting - if modified then - local json_str = vim.json.encode(data) - local formatted = vim.fn.system('python -m json.tool', json_str) - - if vim.v.shell_error == 0 then - -- Atomic write back to disk - vim.fn.writefile(vim.split(formatted, "\n"), filename) - vim.notify('compiledb: paths fixed', vim.log.levels.INFO) - else - vim.notify('PIO Fix: Python formatting failed', vim.log.levels.ERROR) - end - end -end - --- function M.compile_commandsFix() --- local filename = vim.uv.cwd() .. '/compile_commands.json' --- local content = vim.fn.readfile(filename) --- if #content == 0 then return end --- --- local ok, data = pcall(vim.json.decode, table.concat(content, "\n")) --- if not ok or type(data) ~= 'table' then return end --- --- -- 1. Build Path Map (Scan toolchain) --- local path_map = {} --- --- local pio_binaries = _G.metadata.query_driver or "/bin/*" --- -- local pio_binaries = (_G.metadata.toolchain or "") .. '/bin/*' --- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do --- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') --- path_map[name] = full_path --- end --- --- -- 2. Update Entries --- local modified = false --- for _, entry in ipairs(data) do --- local cmd = entry.command or "" --- local first_token = cmd:match("^%S+") -- Get first word before space --- --- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then --- local short_name = first_token:gsub('%.exe$', '') --- if path_map[short_name] then --- -- Swap first token with full path safely --- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) --- modified = true --- end --- end --- end --- --- -- 3. Save with Formatting --- if modified then --- local json_str = vim.json.encode(data) --- -- Use python to format, then write file --- local formatted = vim.fn.system('python -m json.tool', json_str) --- if vim.v.shell_error == 0 then --- vim.fn.writefile(vim.split(formatted, "\n"), filename) --- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) --- end --- end --- end - --- function M.compile_commandsFix() --- local filename = vim.uv.cwd() .. '/compile_commands.json' --- local file = io.open(filename, 'r') --- if not file then return end --- --- -- read compile_commands.json file to content --- local content = file:read('*a') --- file:close() --- if not content or content == '' then return end --- --- -- JSON decoding content to data --- local ok, data = pcall(vim.json.decode, content) --- if not ok or type(data) ~= 'table' then --- vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) --- return --- end --- --- -- print('PioFix0') --- -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path --- local path_map = {} --- local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') --- if pio_home then --- -- Recursively find all binaries in PIO packages --- local pio_packages = _G.metadata.toolchain .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' --- local found_binaries = vim.fn.glob(pio_packages, false, true) --- --- for _, full_path in ipairs(found_binaries) do --- -- Extract filename (e.g., riscv32-esp-elf-gcc) --- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') --- path_map[name] = full_path --- -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) --- end --- end --- --- -- PHASE 2: Update JSON using the Map --- local modified = 0 --- for _, entry in ipairs(data) do --- if type(entry.command) == 'string' then --- local cmd_parts = vim.split(entry.command, ' ') --- local first_token = cmd_parts[1] --- if first_token then --- -- Check if it's already a short name (not an absolute path) --- local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') --- if not is_abs then --- local short_name = first_token:gsub('%.exe$', '') --- -- print('PioFix2: short_name=' .. short_name) --- -- Direct Query: Does this name exist in our discovered list? --- if path_map[short_name] then --- cmd_parts[1] = path_map[short_name] --- -- print('PioFix3: full_name=' .. cmd_parts[1]) --- entry.command = table.concat(cmd_parts, ' ') --- modified = modified + 1 --- end --- end --- end --- end --- end --- --- -- PHASE 3: Save and Refresh --- -- Safe JSON encoding --- if modified > 0 then --- local out_file = io.open(filename, 'w') --- if out_file then --- local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) --- if encode_ok and json_str then --- -- 1. Format the string using python's json.tool --- -- The second argument to vim.fn.system() is the "stdin" passed to the command --- local formatted_json = vim.fn.system('python -m json.tool', json_str) --- --- -- out_file:write(json_str) --- out_file:write(formatted_json) --- out_file:close() --- vim.notify('compiledb: fixed', vim.log.levels.INFO) --- -- lsp_restart('clangd') --- end --- end --- end --- end - ------------------------------------------------------- --- INFO: ToggleTerminal commands sequencer - -M.is_processing = false -M.queue = {} -local pio_buffer = '' -- Persistent stream buffer - ------------------------------------------------------- --- INFO: ToggleTerminal commands stdout filter --- stylua: ignore -function M.stdoutFilter(_, _, data) - if #M.queue == 0 then return end - - -- 1. attach partial buffer from previous data last line to 1st line - pio_buffer = pio_buffer .. data[1] - -- 2. If the chunk has more than one element, we've encountered newlines - if #data > 1 then - -- 3. Process any "middle" lines which are guaranteed to be complete - for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end - - for status in pio_buffer:gmatch('_DONE_:(%a+)') do - if status then - if status == 'PASS' then - pio_buffer = data[#data] - vim.schedule(function() M.process_queue() end) - elseif status == 'FAIL' then - end - -- if status == 'PASS' then - -- -- 4. Store the last element as the new partial buffer for the next call - -- pio_buffer = data[#data] - -- local task = table.remove(M.queue, 1) - -- if task then vim.schedule(task) end - -- elseif status == 'LAST' then - -- _G.metadata.isBusy = false - -- M.queue = {} -- Clear queue on any other status - -- pio_buffer = '' - -- vim.schedule(function() vim.notify('PIO Sequence: Finished', 4) end) - -- elseif status == 'FAIL' then - -- M.queue = {} -- Clear queue on any other status (failure) - -- pio_buffer = '' - -- vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) - -- end - break - end - end - end - if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end -end - ------------------------------------------------------- --- INFO: ToggleTerminal commands Sequencer ---- stylua: ignore -M.run_sequence = function(tasks) - -- Reset local state for new run - M.queue = {} - pio_buffer = '' - -- local full_cmd = '' - -- - local pass = 'echo _DONE_":"PASS' - local last = 'echo _DONE_":"LAST' - local fail = 'echo _DONE_":"FAIL' - -- - -- for _, task in ipairs(tasks) do - -- table.insert(M.queue, task.cb) - -- local part = string.format('%s && %s', task.cmd, pass) - -- if full_cmd == '' then - -- full_cmd = part - -- else - -- full_cmd = full_cmd .. ' && ' .. part - -- end -- Chain multiple commands - -- end - -- full_cmd = full_cmd .. ' && ' .. last .. ' || ' .. fail - -- local ToggleTerminal = require('platformio.utils.term').ToggleTerminal - -- _G.metadata.isBusy = true - -- ToggleTerminal(full_cmd, 'float') - - for _, task in ipairs(tasks) do - -- Build the wrapped command string - local wrapped_cmd = string.format('%s && %s || %s', task.cmd, pass, fail) - - -- Insert a SINGLE table containing everything needed for this step - table.insert(M.queue, { - cmd = wrapped_cmd, - cb = task.cb, - }) - end - M.process_queue() -end - ------------------------------------------------------------------- --- 3. Queue Controller -function M.process_queue() - local task = table.remove(M.queue, 1) - - if not task then - M.is_processing = false - if M.current_cb then - M.current_cb() - end -- Final callback - return - end - - M.is_processing = true - - if task.cmd then - M.run_shell_job(task.cmd, task.cb) - elseif type(task.cb) == 'function' then - vim.schedule(function() - task.cb() - -- Lua tasks need to manually move the queue - M.process_queue() - end) - end -end - --- 4. Entry Point -function M.setup_project(board, framework) - M.queue = { - { cmd = 'pio project init --board ' .. board }, - { cmd = 'pio run -t compiledb' }, - { cb = M.compile_commandsFix }, - } - M.process_queue() -end ------------------------------------------------------- --- Handle after 'pio run -t compiledb' execution -function M.handleDb() - vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) - misc.gitignore_lsp_configs('compile_commands.json') - local pio_manager = require('platformio.pio_setup').pio_manager - pio_manager.refresh(function() - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - boilerplate_gen([[.clangd]], _G.metadata.core_dir) - M.compile_commandsFix() - lsp_restart('clangd') - end) -end - ------------------------------------------------------- --- Handle after poioinit execution ---- stylua: ignore -function M.handlePioinit() - -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - -- vim.schedule(function() - -- local pio_manager = require('platformio.pio_setup').pio_manager - -- pio_manager.refresh(function() - -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - -- boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - vim.notify('Pioinit: Success', vim.log.levels.INFO) - -- end) - -- end) -end --- Handle after poioinit execution --- stylua: ignore -function M.handlePiolib() - vim.notify('Piolib: Success', vim.log.levels.INFO) -end --- INFO: end commands sequencer ------------------------------------------------------- - -return M diff --git a/pio_setup.lua b/pio_setup.lua deleted file mode 100644 index d36bca00..00000000 --- a/pio_setup.lua +++ /dev/null @@ -1,417 +0,0 @@ --- M = {} --- --- local misc = require('platformio.utils.misc') --- local lsp = require('platformio.lsp.tools') --- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen --- --- local debounce_timer = vim.uv.new_timer() --- --- -- INFO: --- -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag --- -- stylua: ignore --- local function pio_generate_db() --- vim.schedule(function() vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) end) --- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) --- if obj.code ~= 0 then --- vim.schedule(function() --- if obj.code == 127 then --- vim.notify("PIO Manager db: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) --- else --- vim.notify('PIO Manager db: Generating Compile Database failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) --- end --- end) --- return --- end --- vim.schedule(function() vim.notify('PIO: Generating Compile Database successful', vim.log.levels.INFO) end) --- end) --- end --- --- -- INFO: 1. The Core PIO Manager & Generic Extractor --- --- stylua: ignore --- local pio_manager = (function() --- local cache = nil -- Stores the decoded platformio.ini JSON structure --- -- INFO: --- local function find_in_data(data, section_name, key_name) --- -- Safety check: Ensure data is a valid table from a successful JSON decode --- if type(data) ~= 'table' then --- return nil --- end --- --- for _, section in ipairs(data) do --- -- Each section must be a table with at least 2 elements: [1]=name, [2]=content --- if section and type(section) == 'table' and #section >= 2 then --- local s_id = section[1] -- Section header string --- local s_body = section[2] -- Table of key-value pairs --- --- if s_id == section_name and type(s_body) == 'table' then --- for _, kv in ipairs(s_body) do --- -- Each kv is a table: [1]=key, [2]=value --- if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then --- local val = kv[2] --- -- Treat empty strings or empty tables as nil to trigger fallback logic --- if val == nil or val == '' or (type(val) == 'table' and #val == 0) then --- return nil --- end --- return val --- end --- end --- end --- end --- end --- return nil --- end --- --- -- INFO: ASYNC REFRESH: Fetches the latest config from PlatformIO CLI --- --- stylua: ignore --- local function refresh(callback) --- vim.schedule(function() --- vim.notify('PIO: Fetching Config ...', vim.log.levels.INFO) --- end) --- --- -- INFO: get project metadata --- local function get_metadata(attempts, env) --- local active_env = env or _G.metadata.active_env --- vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(int_obj) --- vim.schedule(function() --- vim.notify('PIO: Fetching metadata ...', vim.log.levels.INFO) --- end) --- --- if int_obj.code ~= 0 then --- -- Schedule notification to avoid error in the system callback thread --- vim.schedule(function() --- if int_obj.code == 127 then --- vim.notify("PIO Manager metadata: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) --- else --- vim.notify('PIO Manager metadata: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) --- end --- end) --- return --- end --- --- if int_obj.code == 0 and int_obj.stdout then --- local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) --- if ok and raw_data then --- local _, data = next(raw_data) --- if data then --- local fallbackFlags = {} --- -- 1. Process Includes --- if data.includes then --- for category, paths in pairs(data.includes) do --- -- If it's a toolchain path, use -isystem to suppress warnings --- -- and tell clangd these are standard libraries --- if category == 'toolchain' then --- local flag = '-isystem' --- for _, path in ipairs(paths) do --- -- table.insert(fallbackFlags, string.format('%q', flag)) --- -- table.insert(fallbackFlags, string.format('%q', path:gsub('\\', '/'))) --- table.insert(fallbackFlags, string.format('%q', flag .. path:gsub('\\', '/'))) --- end --- end --- -- local flag = (category == 'toolchain') and '-isystem' or '-I' --- -- for _, path in ipairs(paths) do --- -- table.insert(fallbackFlags, flag .. path) --- -- end --- end --- end --- -- 2. Process Defines --- if data.defines then --- for _, define in ipairs(data.defines) do --- table.insert(fallbackFlags, string.format('%q', '-D' .. define)) --- end --- end --- --- -- get [cc_compiler]and [falbackFlags] --- -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' --- _G.metadata.cc_compiler = misc.normalize_path(data.cc_path) or '' --- _G.metadata.fallbackFlags = fallbackFlags --- --- -- print(vim.inspect(_G.metadata)) --- if callback then --- vim.schedule(function() --- vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) --- callback() --- end) --- end --- end --- else --- vim.schedule(function() --- vim.notify('PIO: Syncing Environment failed', vim.log.levels.WARN) --- end) --- end --- end --- -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save --- if attempts > 0 then --- vim.defer_fn(function() --- get_metadata(attempts - 1) --- end, 500) --- end --- end) --- end --- --- -- INFO: Setup Base Paths --- local home = os.getenv('HOME') or os.getenv('USERPROFILE') --- --- -- INFO: Try to get explicit value from platformio.ini --- -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' --- -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } --- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) --- if ext_obj.code ~= 0 then --- -- Schedule notification to avoid error in the system callback thread --- vim.schedule(function() --- if ext_obj.code == 127 then --- vim.notify("PIO Manager config: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) --- else --- vim.notify('PIO Manager config: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) --- end --- end) --- return --- end --- --- _G.metadata.core_dir = '' --- _G.metadata.packages_dir = '' --- _G.metadata.platforms_dir = '' --- _G.metadata.active_env = '' --- _G.metadata.default_envs = {} --- _G.metadata.envs = {} --- --- local decoded = vim.json.decode(ext_obj.stdout) --- for _, section in ipairs(decoded) do --- if type(section) == 'table' and #section >= 2 then --- local name, data = section[1], section[2] --- -- 1. Extract Global PlatformIO Settings if available [core_dir][packages_dir][platforms_dir][default_envs] --- if name == 'platformio' then --- for _, kv in ipairs(data) do --- local key, val = kv[1], kv[2] --- if key ~= nil then --- -- if _G.metadata[key] ~= nil then --- _G.metadata[key] = val --- end --- end --- -- 2. Extract all hardware [envs] like [env:seeed_xiao_esp32c3], skipping generic [env] --- elseif name:match('^env:') then --- local env_name = name:match('^env:(.+)') --- _G.metadata.envs[env_name] = {} --- for _, kv in ipairs(data) do --- _G.metadata.envs[env_name][kv[1]] = kv[2] --- end --- end --- end --- end --- -- assign [active_env] --- if #_G.metadata.default_envs > 0 then --- _G.metadata.active_env = _G.metadata.default_envs[1] or '' --- elseif _G.metadata.envs and next(_G.metadata.envs) ~= '' then --- _G.metadata.active_env = next(_G.metadata.envs) or '' --- end --- --- -- INFO: -- Define Mapping (key in INI, Env Var, Default Subfolder) --- local map = { --- core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, --- packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, --- platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, --- } --- for _, kv in ipairs(map) do --- -- 4.0 Fallback Logic: INI -> Env Var -> Default --- local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') --- -- 5. Expand ${platformio.core_dir} --- if type(result) == 'string' then --- if result:find('${platformio.core_dir}', 1, true) then --- result = result:gsub('%${platformio.core_dir}', _G.metadata.core_dir) --- end --- end --- -- 6. Normalize Slashes for Windows --- -- _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') --- _G.metadata[kv.ini] = result:gsub('\\', '/'):gsub('//+', '/') --- end --- -- return _G.metadata[map[type].ini] --- -- end --- --- if _G.metadata.active_env ~= '' then --- vim.schedule(function() --- vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) --- end) --- get_metadata(1, _G.metadata.active_env) --- else --- vim.schedule(function() --- vim.notify('PIO: no [env:] found, add board first', vim.log.levels.ERROR) --- end) --- end --- end) --- end --- --- -- INFO: --- return { --- refresh = refresh, --- -- INFO: --- get = function(s, k) --- if not cache then --- return nil --- end --- local res = find_in_data(cache, s, k) --- --- -- FALLBACK: If default_envs is missing/empty, find the first hardware [env:xxx] block --- if k == 'default_envs' and not res then --- for _, section in ipairs(cache) do --- if type(section) == 'table' and type(section[1]) == 'string' then --- local name = section[1] --- if name:find('^env:') then --- local fallback = name:match('^env:(.+)') --- if fallback then --- vim.schedule(function() --- vim.notify('PIO: default_envs empty. Using: ' .. fallback, vim.log.levels.INFO) --- end) --- return fallback --- end --- end --- end --- end --- vim.schedule(function() --- vim.notify('PIO: Config Error. Check platformio.ini no env', vim.log.levels.WARN) --- end) --- elseif k == 'default_envs' and res and type(res) == 'table' then --- return res[1] --- else --- return res --- end --- end, --- } --- end)() --- --- -- INFO: --- function _G.get_pio_sdk_info() --- local pio_info = { includes = {}, cc_compiler = '' } --- if vim.fn.filereadable('platformio.ini') == 0 then --- return nil --- end --- --- local handle = io.popen('pio run -t envdump') --- if not handle then --- return nil --- end --- --- local packages_dir, cc_name, toolchain_pkg = '', '', '' --- --- for line in handle:lines() do --- -- 1. Get the global packages directory --- packages_dir = packages_dir ~= '' and packages_dir or line:match("'PROJECT_PACKAGES_DIR': '([^']+)'") --- --- -- 2. Get the compiler executable name (e.g., riscv32-esp-elf-gcc) --- cc_name = cc_name ~= '' and cc_name or line:match("'CC': '([^']+)'") --- --- -- 3. Find the specific toolchain package name from the PACKAGES list --- -- Matches lines like "- toolchain-riscv32-esp @ 14.2.0" --- local pkg = line:match('%- (toolchain%-[^ ]+)') --- if pkg then --- toolchain_pkg = pkg --- end --- --- -- 4. Collect include paths --- local path_list = line:match("'CPPPATH': %[(.+)%]") --- if path_list then --- for path in path_list:gmatch("'([^']+)'") do --- table.insert(pio_info.includes, '-I' .. path) --- end --- end --- end --- handle:close() --- --- -- Construct the absolute path: //bin/ --- if packages_dir and packages_dir ~= '' and toolchain_pkg and toolchain_pkg ~= '' and cc_name ~= '' then --- local full_path = packages_dir .. '/' .. toolchain_pkg .. '/bin/' .. cc_name --- if vim.fn.executable(full_path) == 1 then --- pio_info.cc_compiler = full_path --- end --- end --- --- local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' --- print('get_pio_sdk_info(): final=' .. final) --- -- Normalize paths for the OS and ensure backslashes for Windows if needed --- -- print(vim.inspect(_G.metadata)) --- return (misc.normalize_path(final)) --- -- return _G.metadata.query_driver --- -- return pio_info --- end --- --- -- INFO: --- -- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync --- -- stylua: ignore --- local function start_pio_watcher() --- local dir_path = vim.uv.cwd() --- if not dir_path then return end --- --- -- Create a directory watcher --- local handle = vim.uv.new_fs_event() --- if not handle then return end --- --- -- local last_trigger = 0 --- -- Watch the directory for platformio.ini creation or changes --- handle:start( --- dir_path, --- { --- watch_entry = false, -- watch the file/dir itself --- stat = false, -- use stat to detect changes (slower but more reliable on some FS) --- recursive = false, -- watch subdirectories (if path is a directory) --- }, --- vim.schedule_wrap(function(err, filename, events) --- if err or not events or not events.change then return end --- -- Trigger only if the changed file is platformio.ini --- if filename == 'platformio.ini' and (events.change or events.rename) then --- if debounce_timer then --- debounce_timer:stop() --- debounce_timer:start( --- 500, --- 0, --- vim.schedule_wrap(function() --- pio_manager.refresh(function() --- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) --- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) --- pio_generate_db() --- lsp.lsp_restart('clangd') --- -- end) --- end) end)) end end end)) --- end --- ------------------------------------------------------------------------------------------------------ --- -- INFO: 6. Exported setup function --- function M.init() --- local config = require('platformio').config --- if config.lspClangd.enabled == true then --- vim.notify('PIO setup initialize', vim.log.levels.INFO) --- --- -- activate meta save and upload and env switch --- local metadata = require('platformio.metadata') --- metadata.load_project_config() --- --- ---------------------------------------------------------------------------------------- --- -- INFO: create clangd required files --- ----------------------------------------------------------------------------------------- --- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) --- -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) --- -- boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) --- -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) --- -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') --- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) --- boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) --- --------------------------------------------------------------------------------- --- --- require('platformio.lsp.clangd') --- if config.lspClangd.attach.enabled then --- require('platformio.lsp.attach') --- end --- --- -- Always start the watcher so it can catch a future 'pio init' --- start_pio_watcher() --- --- -- If the file already exists, do an initial sync --- if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then --- pio_manager.refresh(function() --- -- vim.schedule(function() --- -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) --- pio_generate_db() --- lsp.lsp_restart('clangd') --- -- end) --- end) --- end --- end --- end --- --- return M diff --git a/pio_setupold.lua b/pio_setupold.lua deleted file mode 100644 index dbbdf35e..00000000 --- a/pio_setupold.lua +++ /dev/null @@ -1,485 +0,0 @@ --- M = {} --- --- local misc = require('platformio.utils.misc') --- local lsp = require('platformio.lsp.tools') --- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen --- --- -- lua/pio_setup.lua --- -- This module manages PlatformIO project integration, LSP toolchain detection, --- -- and automatic sysroot patching for standard library headers (, etc.) --- --- local debounce_timer = vim.uv.new_timer() --- --- -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) --- -- INFO: --- -- ============================================================================= --- -- UNIVERSAL TOOLCHAIN DETECTION --- -- ============================================================================= --- --- stylua: ignore --- local function get_sysroot_triplet(cc_compiler) --- local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') --- -- Early exit if path is nil or not a directory --- if not bin_path or vim.fn.isdirectory(bin_path) == 0 then --- return nil --- end --- --- -- Normalize backslashes to forward slashes for cross-platform consistency --- bin_path = bin_path:gsub('\\', '/') --- local files = vim.fn.readdir(bin_path) --- local triplet = nil --- --- -- Loop through files to find the compiler and extract the triplet --- for _, name in ipairs(files) do --- -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ --- local match = name:match('^(.*)%-g[c%+][c%+]') --- if match then --- triplet = match --- break --- end --- end --- --- -- Return nil if no compiler was found in the bin directory --- if not triplet then --- return nil --- end --- --- -- toolchain_root is the parent of the 'bin' folder --- local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') --- -- sysroot folder is expected to have the same name as the triplet --- local sysroot = toolchain_root .. '/' .. triplet --- --- -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) --- -- Only return data if the sysroot folder actually exists on disk --- if vim.fn.isdirectory(sysroot) == 1 then --- return { --- triplet = triplet, --- sysroot = sysroot, --- toolchain_root = toolchain_root, --- query_driver = bin_path .. '/' .. triplet .. '-*', --- } --- end --- return nil --- end --- --- --- -- INFO: --- -- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag --- -- stylua: ignore --- local function pio_generate_db() --- vim.schedule(function() vim.notify('PIO: Generating Compile Database...', vim.log.levels.INFO) end) --- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) --- if obj.code ~= 0 then --- vim.schedule(function() --- if obj.code == 127 then --- vim.notify("PIO Manager db: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) --- else --- vim.notify('PIO Manager db: Generating Compile Database failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) --- end --- end) --- return --- end --- vim.schedule(function() vim.notify('PIO: Generating Compile Database successful', vim.log.levels.INFO) end) --- end) --- end --- --- -- INFO: 1. The Core PIO Manager & Generic Extractor --- --- stylua: ignore --- local pio_manager = (function() --- local cache = nil -- Stores the decoded platformio.ini JSON structure --- -- INFO: --- local function find_in_data(data, section_name, key_name) --- -- Safety check: Ensure data is a valid table from a successful JSON decode --- if type(data) ~= 'table' then --- return nil --- end --- --- for _, section in ipairs(data) do --- -- Each section must be a table with at least 2 elements: [1]=name, [2]=content --- if type(section) == 'table' and #section >= 2 then --- local s_id = section[1] -- Section header string --- local s_body = section[2] -- Table of key-value pairs --- --- if s_id == section_name and type(s_body) == 'table' then --- for _, kv in ipairs(s_body) do --- -- Each kv is a table: [1]=key, [2]=value --- if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then --- local val = kv[2] --- -- Treat empty strings or empty tables as nil to trigger fallback logic --- if val == nil or val == '' or (type(val) == 'table' and #val == 0) then --- return nil --- end --- return val --- end --- end --- end --- end --- end --- return nil --- end --- --- -- INFO: ASYNC REFRESH: Fetches the latest config from PlatformIO CLI --- --- stylua: ignore --- local function refresh(callback) --- vim.schedule(function() --- vim.notify('PIO: Fetching Config ...', vim.log.levels.INFO) --- end) --- --- -- INFO: get project metadata --- local function get_metadata(attempts, env) --- local active_env = env or _G.metadata.active_env --- vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(int_obj) --- vim.schedule(function() --- vim.notify('PIO: Fetching metadata ...', vim.log.levels.INFO) --- end) --- --- if int_obj.code ~= 0 then --- -- Schedule notification to avoid error in the system callback thread --- vim.schedule(function() --- if int_obj.code == 127 then --- vim.notify("PIO Manager metadata: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) --- else --- vim.notify('PIO Manager metadata: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) --- end --- end) --- return --- end --- --- if int_obj.code == 0 and int_obj.stdout then --- local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) --- if ok and raw_data then --- local _, data = next(raw_data) --- if data then --- local fallbackFlags = {} --- -- 1. Process Includes --- if data.includes then --- for category, paths in pairs(data.includes) do --- -- If it's a toolchain path, use -isystem to suppress warnings --- -- and tell clangd these are standard libraries --- if category == 'toolchain' then --- local flag = '-isystem' --- for _, path in ipairs(paths) do --- -- table.insert(fallbackFlags, string.format('%q', flag)) --- -- table.insert(fallbackFlags, string.format('%q', path:gsub('\\', '/'))) --- table.insert(fallbackFlags, string.format('%q', flag .. path:gsub('\\', '/'))) --- end --- end --- -- local flag = (category == 'toolchain') and '-isystem' or '-I' --- -- for _, path in ipairs(paths) do --- -- table.insert(fallbackFlags, flag .. path) --- -- end --- end --- end --- -- 2. Process Defines --- if data.defines then --- for _, define in ipairs(data.defines) do --- table.insert(fallbackFlags, string.format('%q', '-D' .. define)) --- end --- end --- --- -- get [cc_compiler]and [falbackFlags] --- -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' --- _G.metadata.cc_compiler = misc.normalize_path(data.cc_path) or '' --- _G.metadata.fallbackFlags = fallbackFlags --- --- -- print(vim.inspect(_G.metadata)) --- if callback then --- vim.schedule(function() --- vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) --- callback() --- end) --- end --- end --- else --- vim.schedule(function() --- vim.notify('PIO: Syncing Environment failed', vim.log.levels.WARN) --- end) --- end --- end --- -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save --- if attempts > 0 then --- vim.defer_fn(function() --- get_metadata(attempts - 1) --- end, 500) --- end --- end) --- end --- --- -- INFO: Setup Base Paths --- local home = os.getenv('HOME') or os.getenv('USERPROFILE') --- --- -- INFO: Try to get explicit value from platformio.ini --- -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' --- -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } --- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) --- if ext_obj.code ~= 0 then --- -- Schedule notification to avoid error in the system callback thread --- vim.schedule(function() --- if ext_obj.code == 127 then --- vim.notify("PIO Manager config: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) --- else --- vim.notify('PIO Manager config: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) --- end --- end) --- return --- end --- _G.metadata.core_dir = '' --- _G.metadata.packages_dir = '' --- _G.metadata.platforms_dir = '' --- _G.metadata.active_env = '' --- _G.metadata.default_envs = {} --- _G.metadata.envs = {} --- --- local decoded = vim.json.decode(ext_obj.stdout) --- for _, section in ipairs(decoded) do --- if type(section) == 'table' and #section >= 2 then --- local name, data = section[1], section[2] --- -- 1. Extract Global PlatformIO Settings if available [core_dir][packages_dir][platforms_dir][default_envs] --- if name == 'platformio' then --- for _, kv in ipairs(data) do --- local key, val = kv[1], kv[2] --- if key ~= nil then --- -- if _G.metadata[key] ~= nil then --- _G.metadata[key] = val --- end --- end --- -- 2. Extract all hardware [envs] like [env:seeed_xiao_esp32c3], skipping generic [env] --- elseif name:match('^env:') then --- local env_name = name:match('^env:(.+)') --- _G.metadata.envs[env_name] = {} --- for _, kv in ipairs(data) do --- _G.metadata.envs[env_name][kv[1]] = kv[2] --- end --- end --- end --- end --- -- assign [active_env] --- if #_G.metadata.default_envs > 0 then --- _G.metadata.active_env = _G.metadata.default_envs[1] or '' --- elseif _G.metadata.envs and #_G.metadata.envs > 0 then --- _G.metadata.active_env = next(_G.metadata.envs) or '' --- end --- --- -- INFO: -- Define Mapping (key in INI, Env Var, Default Subfolder) --- local map = { --- core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, --- packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, --- platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, --- } --- for _, kv in ipairs(map) do --- -- 4.0 Fallback Logic: INI -> Env Var -> Default --- local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') --- -- 5. Expand ${platformio.core_dir} --- if type(result) == 'string' then --- if result:find('${platformio.core_dir}', 1, true) then --- result = result:gsub('%${platformio.core_dir}', _G.metadata.core_dir) --- end --- end --- -- 6. Normalize Slashes for Windows --- -- _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') --- _G.metadata[kv.ini] = result:gsub('\\', '/'):gsub('//+', '/') --- end --- -- return _G.metadata[map[type].ini] --- -- end --- --- if _G.metadata.active_env ~= '' then --- vim.schedule(function() --- vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) --- end) --- get_metadata(1, _G.metadata.active_env) --- else --- vim.schedule(function() --- vim.notify('PIO: no [env:] found, add board first', vim.log.levels.ERROR) --- end) --- end --- end) --- end --- --- -- INFO: --- return { --- refresh = refresh, --- -- INFO: --- get = function(s, k) --- if not cache then --- return nil --- end --- local res = find_in_data(cache, s, k) --- --- -- FALLBACK: If default_envs is missing/empty, find the first hardware [env:xxx] block --- if k == 'default_envs' and not res then --- for _, section in ipairs(cache) do --- if type(section) == 'table' and type(section[1]) == 'string' then --- local name = section[1] --- if name:find('^env:') then --- local fallback = name:match('^env:(.+)') --- if fallback then --- vim.schedule(function() --- vim.notify('PIO: default_envs empty. Using: ' .. fallback, vim.log.levels.INFO) --- end) --- return fallback --- end --- end --- end --- end --- vim.schedule(function() --- vim.notify('PIO: Config Error. Check platformio.ini no env', vim.log.levels.WARN) --- end) --- elseif k == 'default_envs' and res and type(res) == 'table' then --- return res[1] --- else --- return res --- end --- end, --- } --- end)() --- --- -- INFO: --- function _G.get_pio_sdk_info() --- local pio_info = { includes = {}, cc_compiler = '' } --- if vim.fn.filereadable('platformio.ini') == 0 then --- return nil --- end --- --- local handle = io.popen('pio run -t envdump') --- if not handle then --- return nil --- end --- --- local packages_dir, cc_name, toolchain_pkg = '', '', '' --- --- for line in handle:lines() do --- -- 1. Get the global packages directory --- packages_dir = packages_dir ~= '' and packages_dir or line:match("'PROJECT_PACKAGES_DIR': '([^']+)'") --- --- -- 2. Get the compiler executable name (e.g., riscv32-esp-elf-gcc) --- cc_name = cc_name ~= '' and cc_name or line:match("'CC': '([^']+)'") --- --- -- 3. Find the specific toolchain package name from the PACKAGES list --- -- Matches lines like "- toolchain-riscv32-esp @ 14.2.0" --- local pkg = line:match('%- (toolchain%-[^ ]+)') --- if pkg then --- toolchain_pkg = pkg --- end --- --- -- 4. Collect include paths --- local path_list = line:match("'CPPPATH': %[(.+)%]") --- if path_list then --- for path in path_list:gmatch("'([^']+)'") do --- table.insert(pio_info.includes, '-I' .. path) --- end --- end --- end --- handle:close() --- --- -- Construct the absolute path: //bin/ --- if packages_dir and packages_dir ~= '' and toolchain_pkg and toolchain_pkg ~= '' and cc_name ~= '' then --- local full_path = packages_dir .. '/' .. toolchain_pkg .. '/bin/' .. cc_name --- if vim.fn.executable(full_path) == 1 then --- pio_info.cc_compiler = full_path --- end --- end --- --- local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' --- print('get_pio_sdk_info(): final=' .. final) --- -- Normalize paths for the OS and ensure backslashes for Windows if needed --- -- print(vim.inspect(_G.metadata)) --- return (misc.normalize_path(final)) --- -- return _G.metadata.query_driver --- -- return pio_info --- end --- --- -- INFO: --- -- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync --- -- stylua: ignore --- local function start_pio_watcher() --- local dir_path = vim.uv.cwd() --- if not dir_path then return end --- --- -- Create a directory watcher --- local handle = vim.uv.new_fs_event() --- if not handle then return end --- --- -- local last_trigger = 0 --- -- Watch the directory for platformio.ini creation or changes --- handle:start( --- dir_path, --- { --- watch_entry = false, -- watch the file/dir itself --- stat = false, -- use stat to detect changes (slower but more reliable on some FS) --- recursive = false, -- watch subdirectories (if path is a directory) --- }, --- vim.schedule_wrap(function(err, filename, events) --- if err or not events or not events.change then return end --- -- Trigger only if the changed file is platformio.ini --- if filename == 'platformio.ini' and (events.change or events.rename) then --- -- -- ignore events within time --- -- local current_time = vim.uv.now() --- -- -- IGNORE events if they happen within 100ms of the last one --- -- if current_time - last_trigger < 100 then --- -- return --- -- end --- -- last_trigger = current_time --- --- if debounce_timer then --- debounce_timer:stop() --- debounce_timer:start( --- 500, --- 0, --- vim.schedule_wrap(function() --- pio_manager.refresh(function() --- -- vim.schedule(function() --- local status, data = pcall(get_sysroot_triplet, _G.metadata.cc_compiler) --- if status and data and data.triplet and data.triplet ~= '' then --- _G.metadata.triplet = data.triplet --- _G.metadata.sysroot = data.sysroot --- _G.metadata.query_driver = data.query_driver --- _G.metadata.toolchain_root = data.toolchain_root --- end --- -- boilerplate_gen([[.clangd_init_options]], vim.g.platformioRootDir) --- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) --- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) --- --- pio_generate_db() --- lsp.lsp_restart('clangd') --- -- end) --- end) end)) end end end)) --- end --- ------------------------------------------------------------------------------------------------------ --- -- INFO: 6. Exported setup function --- function M.init() --- local config = require('platformio').config --- if config.lspClangd.enabled == true then --- vim.notify('PIO setup initialize', vim.log.levels.INFO) --- ---------------------------------------------------------------------------------------- --- -- INFO: create clangd required files --- ----------------------------------------------------------------------------------------- --- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) --- -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) --- -- boilerplate_gen([[.clangd]], require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) --- -- boilerplate_gen([[.clangd]], vim.fn.stdpath('data')) --- -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') --- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) --- boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) --- --------------------------------------------------------------------------------- --- --- require('platformio.lsp.clangd') --- if config.lspClangd.attach.enabled then --- require('platformio.lsp.attach') --- end --- --- -- Always start the watcher so it can catch a future 'pio init' --- start_pio_watcher() --- --- -- If the file already exists, do an initial sync --- if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then --- pio_manager.refresh(function() --- -- vim.schedule(function() --- -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) --- pio_generate_db() --- lsp.lsp_restart('clangd') --- -- end) --- end) --- end --- end --- end --- --- return M diff --git a/term.lua b/term.lua deleted file mode 100644 index ce278105..00000000 --- a/term.lua +++ /dev/null @@ -1,324 +0,0 @@ -local M = {} - -local is_windows = jit.os == 'Windows' -M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' --- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' --- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' - -local config = require('platformio').config -local pio = require('platformio.utils.pio') - ------------------------------------------------------- -function M.strsplit(inputstr, del) - local t = {} - if type(inputstr) == 'string' and inputstr and inputstr ~= '' then - for str in string.gmatch(inputstr, '([^' .. del .. ']+)') do - table.insert(t, str) - end - end - return t -end - -function M.check_prefix(str, prefix) - return str:sub(1, #prefix) == prefix -end - ------------------------------------------------------- - --- INFO: get current OS enter -function M.enter() - local shell = vim.o.shell - if is_windows then - return vim.fn.executable('pwsh') and '\r' or '\r\n' - elseif shell:find('nu') then - return '\r' - else - return '\n' - end -end - --- INFO: get previous window -local function getPreviousWindow(orig_window) - local prev = { - orig_window = orig_window, - term = nil, --active terminal - cli = nil, --cli terminal - mon = nil, --mon terminal - float = false, --is active terminal direction float - } - local terms = require('toggleterm.terminal').get_all(true) - if #terms ~= 0 then - for i = 1, #terms do - if terms[i].display_name and terms[i].display_name ~= '' and terms[i].display_name:find('pio', 1) then - local name_splt = M.strsplit(terms[i].display_name, ':') - if name_splt[1] == 'piocli' then - prev.cli = terms[i] - if terms[i].window == orig_window then - ---@diagnostic disable-next-line: cast-local-type - prev.orig_window = tonumber(name_splt[2]) -- set orig_window to the previous terminal onrig_window - prev.term = terms[i] - end - if terms[i].direction == 'float' then - prev.float = true - end - elseif name_splt[1] == 'piomon' then - prev.mon = terms[i] - if terms[i].window == orig_window then - ---@diagnostic disable-next-line: cast-local-type - prev.orig_window = tonumber(name_splt[2]) -- set orig_window to the previous terminal onrig_window - prev.term = terms[i] - end - if terms[i].direction == 'float' then - prev.float = true - end - end - end - end - end - return prev -end - ------------------------------------------------------- --- INFO: Send command -local function send(term, cmd) - vim.fn.chansend(term.job_id, cmd .. M.enter()) - if vim.api.nvim_buf_is_loaded(term.bufnr) and vim.api.nvim_buf_is_valid(term.bufnr) then - if term.window and vim.api.nvim_win_is_valid(term.window) then --vim.ui.term_has_open_win(term) then - vim.api.nvim_set_current_win(term.window) -- terminal focus - vim.api.nvim_buf_call(term.bufnr, function() - local mode = vim.api.nvim_get_mode().mode - if mode == 'n' or mode == 'nt' then - vim.cmd('normal! G') -- normal command to Goto bottom of buffer (scroll) - end - end) - end - end -end - ------------------------------------------------------- --- INFO: PioTermClose -local function PioTermClose(t) - local orig_window = tonumber(M.strsplit(t.display_name, ':')[2]) - -- close terminal window - vim.api.nvim_win_close(t.window, true) - - -- go back to previous window - if orig_window and vim.api.nvim_win_is_valid(orig_window) then - vim.api.nvim_set_current_win(orig_window) - else - vim.api.nvim_set_current_win(0) - end -end - ------------------------------------------------------- --- INFO: ToggleTerminal -function M.ToggleTerminal(command, direction) - local status_ok, _ = pcall(require, 'toggleterm') - if not status_ok then - vim.api.nvim_echo({ { 'toggleterm not found!', 'ErrorMsg' } }, true, {}) - return - end - - local title = '' - local pioOpts = {} - - -- INFO: set orig_window to current window, or if available get current toggleterm previous window - local prev = getPreviousWindow(vim.api.nvim_get_current_win()) - local orig_window = prev.orig_window - - if string.find(command, ' monitor') then - if prev.mon then -- INFO: if previous monitor terminal already opened ==> reopen - prev.mon.display_name = 'piomon:' .. orig_window - local win_type = vim.fn.win_gettype(prev.mon.window) - local win_open = win_type == '' or win_type == 'popup' - if prev.mon.window and (win_open and vim.api.nvim_win_get_buf(prev.mon.window) == prev.mon.bufnr) then - vim.api.nvim_set_current_win(prev.mon.window) - else - prev.mon:open() - end - return - end - title = 'Pio Monitor: [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' - pioOpts.display_name = 'piomon:' .. orig_window - pioOpts.id = 98 - pioOpts.on_stdout = nil - else -- INFO: if previous cli terminal already opened ==> reopen - if prev.cli then - prev.cli.display_name = 'piocli:' .. orig_window - local win_type = vim.fn.win_gettype(prev.cli.window) - local win_open = win_type == '' or win_type == 'popup' - if prev.cli.window and (win_open and vim.api.nvim_win_get_buf(prev.cli.window) == prev.cli.bufnr) then - vim.api.nvim_set_current_win(prev.cli.window) - else - prev.cli:open() - end - vim.defer_fn(function() - if command and command ~= '' then - send(prev.cli, command) - end - end, 50) -- 50ms delay, adjust as needed - return - end - title = 'Pio CLI> [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' - pioOpts.display_name = 'piocli:' .. orig_window - pioOpts.id = 99 - - -- INFO: on_stdout - -- on_stdout = stdout_callback, - pioOpts.on_stdout = pio.stdoutFilter - end - pioOpts.direction = direction - ------------------------------------------------------ - - -- INFO: termConfig table start - local termConfig = { - hidden = true, -- Start hidden, we'll open it explicitly - hide_numbers = true, - float_opts = { - winblend = 0, - width = function() - return math.ceil(vim.o.columns * 0.85) - end, - height = function() - return math.ceil(vim.o.lines * 0.85) - end, - -- shell = vim.o.shell, - shell = vim.o.shell, - highlights = { - border = 'FloatBorder', - background = 'NormalFloat', - }, - }, - close_on_exit = false, --closeOnexit, - - -- INFO: on_open() - on_open = function(t) - -- Get properties of the 'Normal' highlight group (background of main editor) - -- local hl = vim.api.nvim_get_hl(0, { name = 'PmenuSel' }) - -- local hl = { bg = '#e4cf0e', fg = '#0012d9' } - local hl = { bg = '#80a3d4', fg = '#000000' } - - if hl then - vim.api.nvim_set_hl(0, 'MyWinBar', { bg = hl.bg, fg = hl.fg }) - - local winBartitle = '%#MyWinBar#' .. title .. '%*' - vim.api.nvim_set_option_value('winbar', winBartitle, { scope = 'local', win = t.window }) - - -- Following necessary to solve that some time winbar not showing - vim.schedule(function() - vim.api.nvim_set_option_value('winbar', winBartitle, { scope = 'local', win = t.window }) - end) - end - vim.keymap.set('t', '', [[k]], { buffer = t.bufnr }) - vim.keymap.set('n', '', [[a]], { buffer = t.bufnr }) - - vim.keymap.set('n', 'q', function() - PioTermClose(t) - end, { desc = 'PioTermClose', buffer = t.bufnr }) - - if config.debug then - local name_splt = M.strsplit(t.display_name, ':') - vim.api.nvim_echo({ - { 'ToggleTerm ', 'MoreMsg' }, - { '(Term name: ' .. name_splt[1] .. ')', 'MoreMsg' }, - { '(Prev win ID: ' .. name_splt[2] .. ')', 'MoreMsg' }, - { '(Term Win ID: ' .. t.window .. ')', 'MoreMsg' }, - { '(Term Buffer#: ' .. t.bufnr .. ')', 'MoreMsg' }, - { '(Term id: ' .. t.id .. ')', 'MoreMsg' }, - { '(Job ID: ' .. t.job_id .. ')', 'MoreMsg' }, - }, true, {}) - end - end, - - -- INFO: on_close() - on_close = function(t) - orig_window = tonumber(M.strsplit(t.display_name, ':')[2]) - ---@diagnostic disable-next-line: param-type-mismatch - if orig_window and vim.api.nvim_win_is_valid(orig_window) then - vim.api.nvim_set_current_win(orig_window) - else - vim.api.nvim_set_current_win(0) - end - end, - - -- -- INFO: on_exit() - -- on_exit = function(_) - -- exit_callback() - -- end, - - -- INFO: on_stdout - -- on_stdout = stdout_callback, - -- on_stdout = pio.stdoutFilter, - - -- INFO: on_create() { - on_create = function(t) - local platformio = vim.api.nvim_create_augroup(M.strsplit(t.display_name, ':')[1], { clear = true }) - - -- INFO: CmdlineLeave - vim.api.nvim_create_autocmd('CmdlineLeave', { - group = platformio, - -- pattern = ':', - buffer = t.bufnr, - callback = function() - if vim.v.event and not vim.v.event.abort and vim.v.event.cmdtype == ':' then - local quit = vim.fn.getcmdline() == 'q' - local quitbang = vim.fn.getcmdline() == 'q!' - if quitbang or quit then - local name_splt = M.strsplit(t.display_name, ':') - if quitbang then - if name_splt[1] == 'piomon' then -- monitor terminal - local exit = vim.api.nvim_replace_termcodes('exit', true, true, true) - send(t, exit) - else -- cli terminal - send(t, 'exit') - end - end - - orig_window = tonumber(name_splt[2]) - vim.schedule(function() - -- go back to previous window - if orig_window and vim.api.nvim_win_is_valid(orig_window) then - vim.api.nvim_set_current_win(orig_window) - else - vim.api.nvim_set_current_win(0) - end - end) - end - end - end, - }) - - -- INFO: BufUnload - vim.api.nvim_create_autocmd('BufUnload', { - group = platformio, - desc = 'toggleterm buffer unloaded', - buffer = t.bufnr, - callback = function(args) - vim.keymap.del('t', '', { buffer = args.buf }) - vim.keymap.del('n', '', { buffer = args.buf }) - - -- clear autommmand when quit - vim.api.nvim_clear_autocmds({ group = M.strsplit(t.display_name, ':')[1] }) - end, - }) - end, - } - -- INFO: termConfig table end - - termConfig = vim.tbl_deep_extend('force', termConfig, pioOpts or {}) - - -- INFO: create new terminal - local terminal = require('toggleterm.terminal').Terminal:new(termConfig) - if prev.term and prev.float then - prev.term:close() - end - terminal:toggle() - vim.defer_fn(function() - if command and command ~= '' then - send(terminal, command) - end - end, 50) -- 50ms delay, adjust as needed sgget -end - -return M ----------------------------------------------------------------------------------------- diff --git a/term2.lua b/term2.lua deleted file mode 100644 index 03668b9b..00000000 --- a/term2.lua +++ /dev/null @@ -1,327 +0,0 @@ -local M = {} - -local is_windows = jit.os == 'Windows' -M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' --- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' --- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' - -M.current_callback = nil - -local config = require('platformio').config -local pio = require('platformio.utils.pio') - ------------------------------------------------------- -function M.strsplit(inputstr, del) - local t = {} - if type(inputstr) == 'string' and inputstr and inputstr ~= '' then - for str in string.gmatch(inputstr, '([^' .. del .. ']+)') do - table.insert(t, str) - end - end - return t -end - -function M.check_prefix(str, prefix) - return str:sub(1, #prefix) == prefix -end - ------------------------------------------------------- - --- INFO: get current OS enter -function M.enter() - local shell = vim.o.shell - if is_windows then - return vim.fn.executable('pwsh') and '\r' or '\r\n' - elseif shell:find('nu') then - return '\r' - else - return '\n' - end -end - --- INFO: get previous window -local function getPreviousWindow(orig_window) - local prev = { - orig_window = orig_window, - term = nil, --active terminal - cli = nil, --cli terminal - mon = nil, --mon terminal - float = false, --is active terminal direction float - } - local terms = require('toggleterm.terminal').get_all(true) - if #terms ~= 0 then - for i = 1, #terms do - if terms[i].display_name and terms[i].display_name ~= '' and terms[i].display_name:find('pio', 1) then - local name_splt = M.strsplit(terms[i].display_name, ':') - if name_splt[1] == 'piocli' then - prev.cli = terms[i] - if terms[i].window == orig_window then - ---@diagnostic disable-next-line: cast-local-type - prev.orig_window = tonumber(name_splt[2]) -- set orig_window to the previous terminal onrig_window - prev.term = terms[i] - end - if terms[i].direction == 'float' then - prev.float = true - end - elseif name_splt[1] == 'piomon' then - prev.mon = terms[i] - if terms[i].window == orig_window then - ---@diagnostic disable-next-line: cast-local-type - prev.orig_window = tonumber(name_splt[2]) -- set orig_window to the previous terminal onrig_window - prev.term = terms[i] - end - if terms[i].direction == 'float' then - prev.float = true - end - end - end - end - end - return prev -end - ------------------------------------------------------- --- INFO: Send command -local function send(term, cmd) - vim.fn.chansend(term.job_id, cmd .. M.enter()) - if vim.api.nvim_buf_is_loaded(term.bufnr) and vim.api.nvim_buf_is_valid(term.bufnr) then - if term.window and vim.api.nvim_win_is_valid(term.window) then --vim.ui.term_has_open_win(term) then - vim.api.nvim_set_current_win(term.window) -- terminal focus - vim.api.nvim_buf_call(term.bufnr, function() - local mode = vim.api.nvim_get_mode().mode - if mode == 'n' or mode == 'nt' then - vim.cmd('normal! G') -- normal command to Goto bottom of buffer (scroll) - end - end) - end - end -end - ------------------------------------------------------- --- INFO: PioTermClose -local function PioTermClose(t) - local orig_window = tonumber(M.strsplit(t.display_name, ':')[2]) - -- close terminal window - vim.api.nvim_win_close(t.window, true) - - -- go back to previous window - if orig_window and vim.api.nvim_win_is_valid(orig_window) then - vim.api.nvim_set_current_win(orig_window) - else - vim.api.nvim_set_current_win(0) - end -end - ------------------------------------------------------- --- INFO: ToggleTerminal -function M.ToggleTerminal(command, direction) - local status_ok, _ = pcall(require, 'toggleterm') - if not status_ok then - vim.api.nvim_echo({ { 'toggleterm not found!', 'ErrorMsg' } }, true, {}) - return - end - - local title = '' - local pioOpts = {} - - -- INFO: set orig_window to current window, or if available get current toggleterm previous window - local prev = getPreviousWindow(vim.api.nvim_get_current_win()) - local orig_window = prev.orig_window - - if string.find(command, ' monitor') then - if prev.mon then -- INFO: if previous monitor terminal already opened ==> reopen - prev.mon.display_name = 'piomon:' .. orig_window - local win_type = vim.fn.win_gettype(prev.mon.window) - local win_open = win_type == '' or win_type == 'popup' - if prev.mon.window and (win_open and vim.api.nvim_win_get_buf(prev.mon.window) == prev.mon.bufnr) then - vim.api.nvim_set_current_win(prev.mon.window) - else - prev.mon:open() - end - return - end - title = 'Pio Monitor: [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' - pioOpts.display_name = 'piomon:' .. orig_window - pioOpts.id = 98 - pioOpts.on_stdout = nil - else -- INFO: if previous cli terminal already opened ==> reopen - if prev.cli then - prev.cli.display_name = 'piocli:' .. orig_window - local win_type = vim.fn.win_gettype(prev.cli.window) - local win_open = win_type == '' or win_type == 'popup' - if prev.cli.window and (win_open and vim.api.nvim_win_get_buf(prev.cli.window) == prev.cli.bufnr) then - vim.api.nvim_set_current_win(prev.cli.window) - else - prev.cli:open() - end - vim.defer_fn(function() - if command and command ~= '' then - send(prev.cli, command) - end - end, 50) -- 50ms delay, adjust as needed - return - end - title = 'Pio CLI> [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' - pioOpts.display_name = 'piocli:' .. orig_window - pioOpts.id = 99 - - -- INFO: on_stdout - -- on_stdout = stdout_callback, - pioOpts.on_stdout = pio.stdoutFilter - end - pioOpts.direction = direction - ------------------------------------------------------ - - -- INFO: termConfig table start - local termConfig = { - hidden = true, -- Start hidden, we'll open it explicitly - hide_numbers = true, - float_opts = { - winblend = 0, - width = function() - return math.ceil(vim.o.columns * 0.85) - end, - height = function() - return math.ceil(vim.o.lines * 0.85) - end, - -- shell = vim.o.shell, - shell = vim.o.shell, - highlights = { - border = 'FloatBorder', - background = 'NormalFloat', - }, - }, - close_on_exit = false, --closeOnexit, - - -- INFO: on_open() - on_open = function(t) - -- Get properties of the 'Normal' highlight group (background of main editor) - -- local hl = vim.api.nvim_get_hl(0, { name = 'PmenuSel' }) - -- local hl = { bg = '#e4cf0e', fg = '#0012d9' } - local hl = { bg = '#80a3d4', fg = '#000000' } - - if hl then - vim.api.nvim_set_hl(0, 'MyWinBar', { bg = hl.bg, fg = hl.fg }) - - local winBartitle = '%#MyWinBar#' .. title .. '%*' - vim.api.nvim_set_option_value('winbar', winBartitle, { scope = 'local', win = t.window }) - - -- Following necessary to solve that some time winbar not showing - vim.schedule(function() - vim.api.nvim_set_option_value('winbar', winBartitle, { scope = 'local', win = t.window }) - end) - end - vim.keymap.set('t', '', [[k]], { buffer = t.bufnr }) - vim.keymap.set('n', '', [[a]], { buffer = t.bufnr }) - - vim.keymap.set('n', 'q', function() - PioTermClose(t) - end, { desc = 'PioTermClose', buffer = t.bufnr }) - - if config.debug then - local name_splt = M.strsplit(t.display_name, ':') - vim.api.nvim_echo({ - { 'ToggleTerm ', 'MoreMsg' }, - { '(Term name: ' .. name_splt[1] .. ')', 'MoreMsg' }, - { '(Prev win ID: ' .. name_splt[2] .. ')', 'MoreMsg' }, - { '(Term Win ID: ' .. t.window .. ')', 'MoreMsg' }, - { '(Term Buffer#: ' .. t.bufnr .. ')', 'MoreMsg' }, - { '(Term id: ' .. t.id .. ')', 'MoreMsg' }, - { '(Job ID: ' .. t.job_id .. ')', 'MoreMsg' }, - }, true, {}) - end - end, - - -- INFO: on_close() - on_close = function(t) - orig_window = tonumber(M.strsplit(t.display_name, ':')[2]) - ---@diagnostic disable-next-line: param-type-mismatch - if orig_window and vim.api.nvim_win_is_valid(orig_window) then - vim.api.nvim_set_current_win(orig_window) - else - vim.api.nvim_set_current_win(0) - end - end, - - -- -- INFO: on_exit() - -- on_exit = function(_) - -- exit_callback() - -- end, - on_exit = function(t, job, exit_code) - if type(M.current_callback) == 'function' then - M.current_callback(t, job, exit_code) - end - end, - - -- INFO: on_stdout - -- on_stdout = stdout_callback, - -- on_stdout = pio.stdoutFilter, - - -- INFO: on_create() { - on_create = function(t) - local platformio = vim.api.nvim_create_augroup(M.strsplit(t.display_name, ':')[1], { clear = true }) - - -- INFO: CmdlineLeave - vim.api.nvim_create_autocmd('CmdlineLeave', { - group = platformio, - -- pattern = ':', - buffer = t.bufnr, - callback = function() - if vim.v.event and not vim.v.event.abort and vim.v.event.cmdtype == ':' then - local quit = vim.fn.getcmdline() == 'q' - local quitbang = vim.fn.getcmdline() == 'q!' - if quitbang or quit then - local name_splt = M.strsplit(t.display_name, ':') - if quitbang then - if name_splt[1] == 'piomon' then -- monitor terminal - local exit = vim.api.nvim_replace_termcodes('exit', true, true, true) - send(t, exit) - else -- cli terminal - send(t, 'exit') - end - end - - orig_window = tonumber(name_splt[2]) - vim.schedule(function() - -- go back to previous window - if orig_window and vim.api.nvim_win_is_valid(orig_window) then - vim.api.nvim_set_current_win(orig_window) - else - vim.api.nvim_set_current_win(0) - end - end) - end - end - end, - }) - - -- INFO: BufUnload - vim.api.nvim_create_autocmd('BufUnload', { - group = platformio, - desc = 'toggleterm buffer unloaded', - buffer = t.bufnr, - callback = function(args) - vim.keymap.del('t', '', { buffer = args.buf }) - vim.keymap.del('n', '', { buffer = args.buf }) - - -- clear autommmand when quit - vim.api.nvim_clear_autocmds({ group = M.strsplit(t.display_name, ':')[1] }) - end, - }) - end, - } - -- INFO: termConfig table end - - termConfig = vim.tbl_deep_extend('force', termConfig, pioOpts or {}) - - -- INFO: create new terminal - local terminal = require('toggleterm.terminal').Terminal:new(termConfig) - if prev.term and prev.float then - prev.term:close() - end - terminal:toggle() - return terminal -end - -return M ----------------------------------------------------------------------------------------- diff --git a/tmp.lua b/tmp.lua deleted file mode 100644 index 1124c5c7..00000000 --- a/tmp.lua +++ /dev/null @@ -1,90 +0,0 @@ --- local function get_safe_hash(data) --- if not data then --- return '' --- end --- return vim.fn.sha256(data) --- end --- -- 4. Execute Compiledb (Using vim.system + Muting) --- function M.run_compiledb() --- if is_ignoring_watcher then --- return --- end --- is_ignoring_watcher = true -- Mute watcher --- --- vim.notify('Generating Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) --- --- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) --- vim.schedule(function() --- is_ignoring_watcher = false -- Unmute --- if obj.code == 0 then --- vim.notify('Compiledb updated', vim.log.levels.INFO, { title = 'PlatformIO' }) --- -- Manual refresh once finished --- pio_manager.refresh(function() --- -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) --- -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) --- -- pio_generate_db() --- lsp.lsp_restart('clangd') --- end) --- else --- vim.notify('Compiledb failed: ' .. (obj.stderr or 'Unknown error'), vim.log.levels.ERROR) --- end --- end) --- end) --- end --- --- -- 5. Bulletproof Watcher (Content-aware & Lock-aware) --- function M.start_pio_watcher() --- local dir_path = vim.uv.cwd() --- local ini_path = dir_path .. '/platformio.ini' --- if not dir_path or vim.fn.filereadable(ini_path) == 0 then --- return --- end --- --- -- Seed the initial hash --- local init_f = io.open(ini_path, 'r') --- if init_f then --- last_ini_hash = get_safe_hash(init_f:read('*a')) --- init_f:close() --- end --- --- local handle = vim.uv.new_fs_event() --- if not handle then --- return --- end --- --- handle:start( --- dir_path, --- { recursive = false }, --- vim.schedule_wrap(function(err, filename) --- if err or is_ignoring_watcher or filename ~= 'platformio.ini' then --- return --- end --- --- -- Safe read (pcall handles Windows file locks during build) --- local ok, content = pcall(function() --- local f = io.open(ini_path, 'r') --- if not f then --- return nil --- end --- local data = f:read('*a') --- f:close() --- return data --- end) --- --- if ok and content then --- local new_hash = get_safe_hash(content) --- if new_hash ~= last_ini_hash then --- last_ini_hash = new_hash --- -- Trigger refresh via your manager --- pio_manager.refresh(function() --- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) --- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) --- -- pio_generate_db() --- M.run_compiledb() --- lsp.lsp_restart('clangd') --- end) --- end --- end --- end) --- ) --- end From 49dcd70be80e2c243a2c6e33434b769768b19915 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 07:32:27 +0300 Subject: [PATCH 0856/1406] update --- lua/platformio/utils/pio.lua | 37 ++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 819e28a3..1293c51c 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -12,6 +12,39 @@ local term = require('platformio.utils.term') local misc = require('platformio.utils.misc') local lsp_restart = require('platformio.lsp.tools').lsp_restart +------------------------------------------------------ +local function format_json(data) + -- 1. Get a guaranteed valid JSON string from Neovim's core + local json = vim.json.encode(data) + + -- 2. Use regex to inject newlines and indentation + -- This is much faster than manual recursion in Lua + local indent = ' ' + local level = 0 + + -- Add newlines after { [ , and before } ] + json = json:gsub('([%[%{%],])', '%1\n') + json = json:gsub('([%]}])', '\n%1') + + local lines = {} + for line in json:gmatch('[^\n]+') do + line = line:gsub('^%s+', '') -- trim existing whitespace + + -- Decrease level if line starts with closing bracket + if line:match('^[%]}]') then + level = level - 1 + end + + table.insert(lines, string.rep(indent, level) .. line) + + -- Increase level if line ends with opening bracket + if line:match('[%[{]$') then + level = level + 1 + end + end + + return table.concat(lines, '\n') +end ------------------------------------------------------ -- stylua: ignore @@ -85,8 +118,8 @@ function M.compile_commandsFix() --M.dbPathsFix() -- 3. Save with Formatting if modified then local start_time = vim.loop.hrtime() - local json_str = vim.json.encode(data) - local pretty = pretty_print(json_str) + -- local json_str = vim.json.encode(data) + local pretty = pretty_print(data) local f = io.open(filename, 'w') if f then From 66b7c4b25b4b17f51b8aaa21781b32444ec0ea7a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 07:41:52 +0300 Subject: [PATCH 0857/1406] update --- lua/platformio/utils/pio.lua | 37 +++++++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 1293c51c..ba9bfd00 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -13,7 +13,7 @@ local misc = require('platformio.utils.misc') local lsp_restart = require('platformio.lsp.tools').lsp_restart ------------------------------------------------------ -local function format_json(data) +local function format_json_fast(data) -- 1. Get a guaranteed valid JSON string from Neovim's core local json = vim.json.encode(data) @@ -118,21 +118,36 @@ function M.compile_commandsFix() --M.dbPathsFix() -- 3. Save with Formatting if modified then local start_time = vim.loop.hrtime() - -- local json_str = vim.json.encode(data) - local pretty = pretty_print(data) + + -- -- local json_str = vim.json.encode(data) + -- local pretty = pretty_print(data) + -- + -- local f = io.open(filename, 'w') + -- if f then + -- f:write(pretty) + -- f:close() + -- + + local ok, formatted = pcall(format_json_fast, data) + if not ok then + print('Formatting failed: ' .. formatted) + return + end local f = io.open(filename, 'w') if f then - f:write(pretty) + f:write(formatted) f:close() - - local end_time = vim.loop.hrtime() - local duration = (end_time - start_time) / 1e6 - print(string.format('Saved %s in %.2fms', filename, duration)) - vim.notify('compiledb: paths fixed', vim.log.levels.INFO) - lsp_restart('clangd') - _G.metadata.isBusy = false + print('Fixed and formatted ' .. filename) end + + local end_time = vim.loop.hrtime() + local duration = (end_time - start_time) / 1e6 + print(string.format('Saved %s in %.2fms', filename, duration)) + vim.notify('compiledb: paths fixed', vim.log.levels.INFO) + lsp_restart('clangd') + _G.metadata.isBusy = false + -- end -- -- Use python to format, then write file -- local formatted = vim.fn.system('python -m json.tool', json_str) -- if vim.v.shell_error == 0 then From 17496fcd1143d9ed3af7dcc1b8c14800492ffe86 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 08:25:09 +0300 Subject: [PATCH 0858/1406] update --- lua/platformio/utils/pio.lua | 42 +++++++++--------------------------- mini_nvimPlatformio.lua | 3 +++ 2 files changed, 13 insertions(+), 32 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index ba9bfd00..f76026af 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -13,7 +13,8 @@ local misc = require('platformio.utils.misc') local lsp_restart = require('platformio.lsp.tools').lsp_restart ------------------------------------------------------ -local function format_json_fast(data) +-- stylua: ignore +local function pretty_json(data) -- 1. Get a guaranteed valid JSON string from Neovim's core local json = vim.json.encode(data) @@ -31,16 +32,12 @@ local function format_json_fast(data) line = line:gsub('^%s+', '') -- trim existing whitespace -- Decrease level if line starts with closing bracket - if line:match('^[%]}]') then - level = level - 1 - end + if line:match('^[%]}]') then level = level - 1 end table.insert(lines, string.rep(indent, level) .. line) -- Increase level if line ends with opening bracket - if line:match('[%[{]$') then - level = level + 1 - end + if line:match('[%[{]$') then level = level + 1 end end return table.concat(lines, '\n') @@ -77,17 +74,14 @@ local function pretty_print(data) return table.concat(buffer) end +-- stylua: ignore function M.compile_commandsFix() --M.dbPathsFix() - local filename = vim.uv.cwd() .. '/compile_commands.json' + local filename = vim.fs.joinpath(vim.uv.cwd(), 'compile_commands.json') local content = vim.fn.readfile(filename) - if #content == 0 then - return - end + if #content == 0 then return end local ok, data = pcall(vim.json.decode, table.concat(content, '\n')) - if not ok or type(data) ~= 'table' then - return - end + if not ok or type(data) ~= 'table' then return end -- 1. Build Path Map (Scan toolchain) local path_map = {} @@ -119,17 +113,8 @@ function M.compile_commandsFix() --M.dbPathsFix() if modified then local start_time = vim.loop.hrtime() - -- -- local json_str = vim.json.encode(data) - -- local pretty = pretty_print(data) - -- - -- local f = io.open(filename, 'w') - -- if f then - -- f:write(pretty) - -- f:close() - -- - - local ok, formatted = pcall(format_json_fast, data) - if not ok then + local jok, formatted = pcall(pretty_print, data) + if not jok then print('Formatting failed: ' .. formatted) return end @@ -147,13 +132,6 @@ function M.compile_commandsFix() --M.dbPathsFix() vim.notify('compiledb: paths fixed', vim.log.levels.INFO) lsp_restart('clangd') _G.metadata.isBusy = false - -- end - -- -- Use python to format, then write file - -- local formatted = vim.fn.system('python -m json.tool', json_str) - -- if vim.v.shell_error == 0 then - -- vim.fn.writefile(vim.split(formatted, '\n'), filename) - -- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) - -- end end end diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 0eb25a83..0473858f 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -98,6 +98,9 @@ local keymap = function(mode, lhs, rhs, opts) vim.keymap.set(mode, lhs, rhs, options) end +--To toggle line wrapping in Neovim +keymap('n', 'w', ':set wrap!', { desc = 'Toggle wrap' }) + keymap('n', 'gll', function() vim.cmd.edit(vim.lsp.log.get_filename()) end, { desc = 'open LSP [l]og' }) From c80d50c3108cc22c16662de3fcec30ed26cafa87 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 08:42:41 +0300 Subject: [PATCH 0859/1406] update --- lua/platformio/utils/pio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f76026af..b6169781 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -45,7 +45,7 @@ end ------------------------------------------------------ -- stylua: ignore -local function pretty_print(data) +local function pretty_print(data) -- 48ms local insert = table.insert local buffer = {} local function format_item(item, current_level) @@ -113,7 +113,7 @@ function M.compile_commandsFix() --M.dbPathsFix() if modified then local start_time = vim.loop.hrtime() - local jok, formatted = pcall(pretty_print, data) + local jok, formatted = pcall(pretty_json, data) if not jok then print('Formatting failed: ' .. formatted) return From 3d7d683f4e993a605571dd3dfb35efae6bf5e6d8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 09:04:40 +0300 Subject: [PATCH 0860/1406] update --- lua/platformio/utils/pio.lua | 66 +++++++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index b6169781..0cc9d5ee 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -12,7 +12,70 @@ local term = require('platformio.utils.term') local misc = require('platformio.utils.misc') local lsp_restart = require('platformio.lsp.tools').lsp_restart +-- iterrative loop +-- stylua: ignore +local function jsonFormat(root_data) + local buffer = {} + -- The stack stores: { value = current_item, level = depth, stage = "start"|"items" } + local stack = { { val = root_data, lvl = 0, stage = 'start' } } + + local function get_indent(lvl) return string.rep(' ', lvl) end + + while #stack > 0 do + local curr = stack[#stack] + local val, lvl = curr.val, curr.lvl + local indent = get_indent(lvl) + + if type(val) == 'table' then + local is_array = (#val > 0 or next(val) == nil) + + if curr.stage == 'start' then + table.insert(buffer, (is_array and '[' or '{') .. '\n') + curr.stage = 'items' + curr.keys = {} + -- Collect keys to iterate deterministically + if is_array then + for i = #val, 1, -1 do table.insert(curr.keys, i) end + else + for k, _ in pairs(val) do table.insert(curr.keys, k) end + end + curr.index = #curr.keys + elseif curr.stage == 'items' then + if curr.index > 0 then + local key = curr.keys[curr.index] + local item = val[key] + + -- Add comma if not the first item + if curr.index < #curr.keys then table.insert(buffer, ',\n') end + + table.insert(buffer, get_indent(lvl + 1)) + if not is_array then table.insert(buffer, '"' .. tostring(key) .. '": ') end + + curr.index = curr.index - 1 + -- Push next item to stack + table.insert(stack, { val = item, lvl = lvl + 1, stage = 'start' }) + else + -- No more items, close the block + table.insert(buffer, '\n' .. indent .. (is_array and ']' or '}')) + table.remove(stack) + end + end + else + -- Primitive values (String, Number, Bool) + local output = '' + if type(val) == 'string' then + output = '"' .. val:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"' + else output = tostring(val) end + table.insert(buffer, output) + table.remove(stack) + end + end + return table.concat(buffer) +end + + ------------------------------------------------------ +-- regex 100ms -- stylua: ignore local function pretty_json(data) -- 1. Get a guaranteed valid JSON string from Neovim's core @@ -44,6 +107,7 @@ local function pretty_json(data) end ------------------------------------------------------ +-- recursion 50ms -- stylua: ignore local function pretty_print(data) -- 48ms local insert = table.insert @@ -113,7 +177,7 @@ function M.compile_commandsFix() --M.dbPathsFix() if modified then local start_time = vim.loop.hrtime() - local jok, formatted = pcall(pretty_json, data) + local jok, formatted = pcall(jsonFormat, data) if not jok then print('Formatting failed: ' .. formatted) return From 8fd58cd2ea6e1bab529ac41b33e12fd57c2bc493 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 09:17:48 +0300 Subject: [PATCH 0861/1406] update --- lua/platformio/utils/pio.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 0cc9d5ee..584b0bac 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -12,7 +12,7 @@ local term = require('platformio.utils.term') local misc = require('platformio.utils.misc') local lsp_restart = require('platformio.lsp.tools').lsp_restart --- iterrative loop +-- iterrative loop 48ms -- stylua: ignore local function jsonFormat(root_data) local buffer = {} @@ -167,7 +167,8 @@ function M.compile_commandsFix() --M.dbPathsFix() local short_name = first_token:gsub('%.exe$', '') if path_map[short_name] then -- Swap first token with full path safely - entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) + -- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) + entry.command = vim.fs.joinpath(path_map[short_name], cmd:sub(#first_token + 1)) modified = true end end From ad21083397af911476c2a2cf0f22792b476f65c6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 09:49:45 +0300 Subject: [PATCH 0862/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 584b0bac..36d4902e 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -167,8 +167,8 @@ function M.compile_commandsFix() --M.dbPathsFix() local short_name = first_token:gsub('%.exe$', '') if path_map[short_name] then -- Swap first token with full path safely + entry.command = misc.normalize_path(path_map[short_name]) .. cmd:sub(#first_token + 1) -- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) - entry.command = vim.fs.joinpath(path_map[short_name], cmd:sub(#first_token + 1)) modified = true end end From 8080cd42f775962a5ca5ded8b61c47679371d85d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 10:09:18 +0300 Subject: [PATCH 0863/1406] update --- lua/platformio/utils/pio.lua | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 36d4902e..ed39fd22 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -16,8 +16,14 @@ local lsp_restart = require('platformio.lsp.tools').lsp_restart -- stylua: ignore local function jsonFormat(root_data) local buffer = {} + + +-- Replace all backslashes with forward slashes +-- The pattern "[\\]+" matches one or more literal backslashes + local formated_data = root_data:gsub("[\\]+", "/") + -- The stack stores: { value = current_item, level = depth, stage = "start"|"items" } - local stack = { { val = root_data, lvl = 0, stage = 'start' } } + local stack = { { val = formated_data, lvl = 0, stage = 'start' } } local function get_indent(lvl) return string.rep(' ', lvl) end From cbf1cae089cfc1310c332bf6b954f798cf64305c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 10:34:42 +0300 Subject: [PATCH 0864/1406] update --- lua/platformio/utils/pio.lua | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index ed39fd22..ac7fe0aa 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -20,10 +20,10 @@ local function jsonFormat(root_data) -- Replace all backslashes with forward slashes -- The pattern "[\\]+" matches one or more literal backslashes - local formated_data = root_data:gsub("[\\]+", "/") + -- local formated_data = root_data:gsub("[\\]+", "/") -- The stack stores: { value = current_item, level = depth, stage = "start"|"items" } - local stack = { { val = formated_data, lvl = 0, stage = 'start' } } + local stack = { { val = root_data, lvl = 0, stage = 'start' } } local function get_indent(lvl) return string.rep(' ', lvl) end @@ -70,7 +70,8 @@ local function jsonFormat(root_data) -- Primitive values (String, Number, Bool) local output = '' if type(val) == 'string' then - output = '"' .. val:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"' + -- output = '"' .. val:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"' + output = '"' .. val:gsub('\\\\', '/'):gsub('\\', '/'):gsub('"', '\\"') .. '"' else output = tostring(val) end table.insert(buffer, output) table.remove(stack) From 96178a1f1d50e71e742d4735c55548a5481d1194 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 12:00:55 +0300 Subject: [PATCH 0865/1406] update --- lua/platformio/utils/misc.lua | 2 +- lua/platformio/utils/pio.lua | 28 +++++++++++++++++----------- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index a55c865e..bf029ea7 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -7,7 +7,7 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' ------------------------------------------------------ function M.normalize_path(path) - return path:gsub('\\', '/'):gsub('//+', '/') + return path:gsub('[\\]+', '/'):gsub('[//]+', '/') end ------------------------------------------------------ diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index ac7fe0aa..4b06db7c 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -70,8 +70,9 @@ local function jsonFormat(root_data) -- Primitive values (String, Number, Bool) local output = '' if type(val) == 'string' then + output = '"' .. val:gsub('"', '\\"') .. '"' -- output = '"' .. val:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"' - output = '"' .. val:gsub('\\\\', '/'):gsub('\\', '/'):gsub('"', '\\"') .. '"' + -- output = '"' .. val:gsub('\\\\', '/'):gsub('\\', '/'):gsub('"', '\\"') .. '"' else output = tostring(val) end table.insert(buffer, output) table.remove(stack) @@ -167,16 +168,21 @@ function M.compile_commandsFix() --M.dbPathsFix() -- 2. Update Entries local modified = false for _, entry in ipairs(data) do - local cmd = entry.command or '' - local first_token = cmd:match('^%S+') -- Get first word before space - - if first_token and not (first_token:sub(1, 1) == '/' or first_token:match('^%a:')) then - local short_name = first_token:gsub('%.exe$', '') - if path_map[short_name] then - -- Swap first token with full path safely - entry.command = misc.normalize_path(path_map[short_name]) .. cmd:sub(#first_token + 1) - -- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) - modified = true + if entry.command then + local compiler, args = entry.command:match("^%s*(%S+)(.*)") + -- local first_token = cmd:match('^%S+') -- Get first word before space + + if compiler and not (compiler():sub(1, 1) == '/' or compiler():match('^%a:')) then + local cmd = entry.command or '' + local short_name = compiler:gsub('%.exe$', '') + if path_map[short_name] then + -- Swap compiler with full path safely + compiler = misc.normalize_path(path_map[short_name]) + entry.command = compiler .. args + -- entry.command = misc.normalize_path(path_map[short_name]) .. cmd:sub(#compiler + 1) + -- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) + modified = true + end end end end From 7422b419e65a4530c221fe7d1fef0ffd4d47a917 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 12:26:38 +0300 Subject: [PATCH 0866/1406] update --- lua/platformio/utils/pio.lua | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 4b06db7c..1237ea47 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -70,9 +70,8 @@ local function jsonFormat(root_data) -- Primitive values (String, Number, Bool) local output = '' if type(val) == 'string' then - output = '"' .. val:gsub('"', '\\"') .. '"' -- output = '"' .. val:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"' - -- output = '"' .. val:gsub('\\\\', '/'):gsub('\\', '/'):gsub('"', '\\"') .. '"' + output = '"' .. val:gsub('\\', '/'):gsub('"', '\\"') .. '"' else output = tostring(val) end table.insert(buffer, output) table.remove(stack) @@ -168,21 +167,16 @@ function M.compile_commandsFix() --M.dbPathsFix() -- 2. Update Entries local modified = false for _, entry in ipairs(data) do - if entry.command then - local compiler, args = entry.command:match("^%s*(%S+)(.*)") - -- local first_token = cmd:match('^%S+') -- Get first word before space - - if compiler and not (compiler():sub(1, 1) == '/' or compiler():match('^%a:')) then - local cmd = entry.command or '' - local short_name = compiler:gsub('%.exe$', '') - if path_map[short_name] then - -- Swap compiler with full path safely - compiler = misc.normalize_path(path_map[short_name]) - entry.command = compiler .. args - -- entry.command = misc.normalize_path(path_map[short_name]) .. cmd:sub(#compiler + 1) - -- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) - modified = true - end + local cmd = entry.command or '' + local first_token = cmd:match('^%S+') -- Get first word before space + + if first_token and not (first_token:sub(1, 1) == '/' or first_token:match('^%a:')) then + local short_name = first_token:gsub('%.exe$', '') + if path_map[short_name] then + -- Swap first token with full path safely + entry.command = misc.normalize_path(path_map[short_name]) .. cmd:sub(#first_token + 1) + -- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) + modified = true end end end From 6a3d9ca4331d3007c56d2d24361d704163ca239f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 12:49:32 +0300 Subject: [PATCH 0867/1406] update --- lua/platformio/utils/misc.lua | 3 ++- lua/platformio/utils/pio.lua | 9 ++------- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index bf029ea7..45225230 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -7,7 +7,8 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' ------------------------------------------------------ function M.normalize_path(path) - return path:gsub('[\\]+', '/'):gsub('[//]+', '/') + -- return path:gsub('[\\]+', '/'):gsub('[//]+', '/') + return path:gsub('[\\/]+', '/') end ------------------------------------------------------ diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 1237ea47..6659e913 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -16,12 +16,6 @@ local lsp_restart = require('platformio.lsp.tools').lsp_restart -- stylua: ignore local function jsonFormat(root_data) local buffer = {} - - --- Replace all backslashes with forward slashes --- The pattern "[\\]+" matches one or more literal backslashes - -- local formated_data = root_data:gsub("[\\]+", "/") - -- The stack stores: { value = current_item, level = depth, stage = "start"|"items" } local stack = { { val = root_data, lvl = 0, stage = 'start' } } @@ -71,7 +65,8 @@ local function jsonFormat(root_data) local output = '' if type(val) == 'string' then -- output = '"' .. val:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"' - output = '"' .. val:gsub('\\', '/'):gsub('"', '\\"') .. '"' + -- output = '"' .. val:gsub('\\', '/'):gsub('"', '\\"') .. '"' + output = '"' .. val:gsub('"', '\\"') .. '"' else output = tostring(val) end table.insert(buffer, output) table.remove(stack) From 3ed1ef7abc3bf84e00336845d14477c25c9563fa Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 13:37:39 +0300 Subject: [PATCH 0868/1406] update --- lua/platformio/boilerplate.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 111b3cd5..2dea07e4 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -49,8 +49,9 @@ extra_scripts = lib_ldf_mode = chain ;Library dependencies Finder ldf build_flags = - -I${platformio.packages_dir}/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0 - -D COMPILATIONDB_INCLUDE_TOOLCHAIN + -I${sysenv.HOMEPATH}/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0 +; -I${platformio.packages_dir}/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0 + -D COMPILATIONDB_INCLUDE_TOOLCHAIN ]], content = function(self) -- local pio = require('platformio.utils.pio') From 9e356074af7224e9e9a18c58db3f02d9f7fd1178 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 13:46:16 +0300 Subject: [PATCH 0869/1406] update --- lua/platformio/utils/pio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 6659e913..f55adbee 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -65,8 +65,8 @@ local function jsonFormat(root_data) local output = '' if type(val) == 'string' then -- output = '"' .. val:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"' - -- output = '"' .. val:gsub('\\', '/'):gsub('"', '\\"') .. '"' - output = '"' .. val:gsub('"', '\\"') .. '"' + output = '"' .. val:gsub('\\', '/'):gsub('"', '\\"') .. '"' + -- output = '"' .. val:gsub('"', '\\"') .. '"' else output = tostring(val) end table.insert(buffer, output) table.remove(stack) From 372b5af54c96a7215ecfcb6c4956ac14e23e6ad4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 14:52:27 +0300 Subject: [PATCH 0870/1406] update --- lua/platformio/pio_setup.lua | 2 +- lua/platformio/utils/misc.lua | 58 ++++++++++++++++++++++++++++++++++- lua/platformio/utils/pio.lua | 51 ++++++++++++++++++++++++------ 3 files changed, 99 insertions(+), 12 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 1161cac1..7134dfb1 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -155,7 +155,7 @@ M.pio_manager = (function() -- get [cc_compiler]and [falbackFlags] -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' - _G.metadata.cc_compiler = misc.normalize_path(data.cc_path) or '' + _G.metadata.cc_compiler = misc.normalizePath(data.cc_path) or '' _G.metadata.fallbackFlags = fallbackFlags pcall(M.get_sysroot_triplet, _G.metadata.cc_compiler) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 45225230..d872d1a6 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -6,7 +6,63 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' ------------------------------------------------------ -function M.normalize_path(path) +--[[ +--INFO: +Targets Windows paths, normalizes slashes, and fixes smashed PlatformIO paths. +Cleans and repairs compiler flags in a command string. +{ "-I", "-L", "-isystem", "-T", "-include" } + +1. Library Paths + -L: Specifies directories to search for library files (.a, .lib, .so). + Example: -L"C:\Users\lib" + -L"C:/Users/lib" + -l (lowercase L): While usually just a name (like -lmath), it can sometimes be a direct path to a specific file. +2. Header Inclusion (Advanced) + -isystem: Similar to -I, but treats the directory as a "system" header (suppresses warnings). PlatformIO uses this heavily for framework headers (Arduino/ESP-IDF). + -include: Forces the compiler to include a specific file before anything else. + Example: -include "C:\project\config.h" + -iquote: Directories for headers wrapped in double quotes "". +3. Output and Debugging + -o: The output path for the compiled object file or binary. + -fdebug-prefix-map=: Used to make builds reproducible by mapping absolute paths to relative ones in the debug symbols. +4. Linker and Frameworks + -T: Path to a linker script (very common in embedded/PlatformIO for memory mapping). + Example: -T"C:\project\ld\esp32.ld" + -F: (macOS/iOS) Path to search for frameworks. +]] +--INFO: +-- stylua: ignore +--- @param cmd string: The raw command string (e.g., from compile_commands.json) +--- @return string: The cleaned command string +function M.normalizeFlags(cmd) + if not cmd or cmd == '' then return '' end + + --INFO: 1. Identify flags that look like paths. + -- Pattern explanation: + -- %- : Matches a literal hyphen (the start of a flag) + -- %S* : Matches zero or more non-space characters + -- \\ : Matches a literal backslash (identifies it as a Windows path) + -- %S* : Matches the rest of the non-space characters in that flag + local cleaned_cmd = cmd:gsub('(%-%S-\\S*)', function(flag) + --INFO: 2. Normalize Slashes + -- Replaces any number of backslashes (single \ or JSON-escaped \\) with one forward slash. + -- Forward slashes are safer and more portable for compilers like GCC/Clang. + flag = flag:gsub('[\\]+', '/') + + -- INFO:3. Heal PlatformIO "Smashed" Paths + -- Fixes the bug where PlatformIO expansions repeat the user home directory. + -- Example: /Users/name/.platformiopackages/toolchain -> /.platformio/packages/toolchain + flag = flag:gsub('/Users/[^/]+%.platformio/packages', '/.platformio/packages') + + return flag + end) + + -- Return only the result string (discarding the replacement count) + return cleaned_cmd +end + +------------------------------------------------------ +function M.normalizePath(path) -- return path:gsub('[\\]+', '/'):gsub('[//]+', '/') return path:gsub('[\\/]+', '/') end diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f55adbee..e012ca5e 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -162,19 +162,50 @@ function M.compile_commandsFix() --M.dbPathsFix() -- 2. Update Entries local modified = false for _, entry in ipairs(data) do - local cmd = entry.command or '' - local first_token = cmd:match('^%S+') -- Get first word before space - - if first_token and not (first_token:sub(1, 1) == '/' or first_token:match('^%a:')) then - local short_name = first_token:gsub('%.exe$', '') - if path_map[short_name] then - -- Swap first token with full path safely - entry.command = misc.normalize_path(path_map[short_name]) .. cmd:sub(#first_token + 1) - -- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) - modified = true + + if entry.directory then + entry.directory = misc.normalizePath(entry.directory) + end + if entry.file then + entry.file = misc.normalizePath(entry.file) + end + if entry.arguments then + entry.arguments = misc.normalizeFlags(entry.arguments) + end + -- + if entry.command then + -- local first_token = cmd:match('^%S+') -- Get first word before space + local compiler, args = entry.command:match("^%s*(%S+)(.*)") + -- Check if it's already a short name (not an absolute path) + if compiler and not (compiler():sub(1, 1) == '/' or compiler():match('^%a:')) then + -- get the file name from the relative path + local short_name = compiler:gsub('%.exe$', '') + if path_map[short_name] then -- if there is full path for this file + -- Swap compiler with full path safely + compiler = misc.normalizePath(path_map[short_name]) + args = misc.normalizeFlags(args) + entry.command = compiler .. args + -- entry.command = misc.normalize_path(path_map[short_name]) .. cmd:sub(#compiler + 1) + -- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) + modified = true + end end end end + -- for _, entry in ipairs(data) do + -- local cmd = entry.command or '' + -- local first_token = cmd:match('^%S+') -- Get first word before space + -- + -- if first_token and not (first_token:sub(1, 1) == '/' or first_token:match('^%a:')) then + -- local short_name = first_token:gsub('%.exe$', '') + -- if path_map[short_name] then + -- -- Swap first token with full path safely + -- entry.command = misc.normalize_path(path_map[short_name]) .. cmd:sub(#first_token + 1) + -- -- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) + -- modified = true + -- end + -- end + -- end -- 3. Save with Formatting if modified then From 97b2e850f83e29eb12fdcfd03e77e0517f5886d7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 16:40:09 +0300 Subject: [PATCH 0871/1406] update --- lua/platformio/boilerplate.lua | 6 +++--- lua/platformio/utils/pio.lua | 6 ++++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 2dea07e4..6c9c516b 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -48,10 +48,10 @@ extra_scripts = lib_ldf_mode = chain ;Library dependencies Finder ldf -build_flags = - -I${sysenv.HOMEPATH}/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0 +;build_flags = +; -I${sysenv.HOMEPATH}/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0 ; -I${platformio.packages_dir}/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0 - -D COMPILATIONDB_INCLUDE_TOOLCHAIN +; -D COMPILATIONDB_INCLUDE_TOOLCHAIN ]], content = function(self) -- local pio = require('platformio.utils.pio') diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index e012ca5e..6bbe6d42 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -176,9 +176,11 @@ function M.compile_commandsFix() --M.dbPathsFix() if entry.command then -- local first_token = cmd:match('^%S+') -- Get first word before space local compiler, args = entry.command:match("^%s*(%S+)(.*)") + print(string.format('compiler = %s', compiler)) + -- Check if it's already a short name (not an absolute path) - if compiler and not (compiler():sub(1, 1) == '/' or compiler():match('^%a:')) then - -- get the file name from the relative path + if compiler and not (compiler:sub(1, 1) == '/' or compiler:match('^%a:')) then + -- get the file name without .exe local short_name = compiler:gsub('%.exe$', '') if path_map[short_name] then -- if there is full path for this file -- Swap compiler with full path safely From 5e1ea94b896f99a58b258c5a78741426cee90b94 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 18:14:51 +0300 Subject: [PATCH 0872/1406] update --- lua/platformio/pio_setup.lua | 15 ++++--- lua/platformio/utils/misc.lua | 82 ++++++++++++++++++++++++----------- lua/platformio/utils/pio.lua | 11 +++-- 3 files changed, 72 insertions(+), 36 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 7134dfb1..f694d9b6 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -28,7 +28,7 @@ function M.get_sysroot_triplet(cc_compiler) -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ local match = name:match('^(.*)%-g[c%+][c%+]') if match then - triplet = match + triplet = misc.normalizePath(match) break end end @@ -39,10 +39,10 @@ function M.get_sysroot_triplet(cc_compiler) end -- toolchain_root is the parent of the 'bin' folder - local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') + local toolchain_root = misc.normalizePath(vim.fn.fnamemodify(bin_path, ':h')) -- sysroot folder is expected to have the same name as the triplet - local sysroot = toolchain_root .. '/' .. triplet - local query_driver = bin_path .. '/' .. triplet .. '-*' + local sysroot = misc.normalizePath(toolchain_root .. '/' .. triplet) + local query_driver = misc.normalizePath(bin_path .. '/' .. triplet .. '-*') -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) -- Only return data if the sysroot folder actually exists on disk @@ -156,7 +156,7 @@ M.pio_manager = (function() -- get [cc_compiler]and [falbackFlags] -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' _G.metadata.cc_compiler = misc.normalizePath(data.cc_path) or '' - _G.metadata.fallbackFlags = fallbackFlags + _G.metadata.fallbackFlags = misc.normalizeFlags(fallbackFlags) pcall(M.get_sysroot_triplet, _G.metadata.cc_compiler) -- print(vim.inspect(_G.metadata)) @@ -225,7 +225,7 @@ M.pio_manager = (function() local key, val = kv[1], kv[2] if key ~= nil then -- if _G.metadata[key] ~= nil then - _G.metadata[key] = val + _G.metadata[key] = misc.normalizePath(val) end end -- 2. Extract all hardware [envs] like [env:seeed_xiao_esp32c3], skipping generic [env] @@ -262,7 +262,8 @@ M.pio_manager = (function() end -- 6. Normalize Slashes for Windows -- _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') - _G.metadata[kv.ini] = result:gsub('\\', '/'):gsub('//+', '/') + -- _G.metadata[kv.ini] = result:gsub('\\', '/'):gsub('//+', '/') + _G.metadata[kv.ini] = misc.normalizePath(result) end -- return _G.metadata[map[type].ini] -- end diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index d872d1a6..ea8edbba 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -5,6 +5,36 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' +function M.normalizeFlags(input) + local path_map = {} + + -- Force input into a table if it's just a single string + local patterns = type(input) == 'table' and input or { input } + + for _, pattern in ipairs(patterns) do + -- Expand ~ or environment variables + local expanded = vim.fn.expand(pattern) + + -- glob returns a table of matching files + local matches = vim.fn.glob(expanded, false, true) + + for _, full_path in ipairs(matches) do + if vim.fn.isdirectory(full_path) == 0 then + -- Normalize slashes and extract filename key + local clean_path = full_path:gsub('\\', '/') + local name = clean_path:match('([^/]+)$'):gsub('%.exe$', '') + + path_map[name] = clean_path + end + end + end + + return path_map +end + + + + ------------------------------------------------------ --[[ --INFO: @@ -34,32 +64,32 @@ Cleans and repairs compiler flags in a command string. -- stylua: ignore --- @param cmd string: The raw command string (e.g., from compile_commands.json) --- @return string: The cleaned command string -function M.normalizeFlags(cmd) - if not cmd or cmd == '' then return '' end - - --INFO: 1. Identify flags that look like paths. - -- Pattern explanation: - -- %- : Matches a literal hyphen (the start of a flag) - -- %S* : Matches zero or more non-space characters - -- \\ : Matches a literal backslash (identifies it as a Windows path) - -- %S* : Matches the rest of the non-space characters in that flag - local cleaned_cmd = cmd:gsub('(%-%S-\\S*)', function(flag) - --INFO: 2. Normalize Slashes - -- Replaces any number of backslashes (single \ or JSON-escaped \\) with one forward slash. - -- Forward slashes are safer and more portable for compilers like GCC/Clang. - flag = flag:gsub('[\\]+', '/') - - -- INFO:3. Heal PlatformIO "Smashed" Paths - -- Fixes the bug where PlatformIO expansions repeat the user home directory. - -- Example: /Users/name/.platformiopackages/toolchain -> /.platformio/packages/toolchain - flag = flag:gsub('/Users/[^/]+%.platformio/packages', '/.platformio/packages') - - return flag - end) - - -- Return only the result string (discarding the replacement count) - return cleaned_cmd -end +-- function M.normalizeFlags(cmd) +-- if not cmd or cmd == '' then return '' end +-- +-- --INFO: 1. Identify flags that look like paths. +-- -- Pattern explanation: +-- -- %- : Matches a literal hyphen (the start of a flag) +-- -- %S* : Matches zero or more non-space characters +-- -- \\ : Matches a literal backslash (identifies it as a Windows path) +-- -- %S* : Matches the rest of the non-space characters in that flag +-- local cleaned_cmd = cmd:gsub('(%-%S-\\S*)', function(flag) +-- --INFO: 2. Normalize Slashes +-- -- Replaces any number of backslashes (single \ or JSON-escaped \\) with one forward slash. +-- -- Forward slashes are safer and more portable for compilers like GCC/Clang. +-- flag = flag:gsub('[\\]+', '/') +-- +-- -- INFO:3. Heal PlatformIO "Smashed" Paths +-- -- Fixes the bug where PlatformIO expansions repeat the user home directory. +-- -- Example: /Users/name/.platformiopackages/toolchain -> /.platformio/packages/toolchain +-- flag = flag:gsub('/Users/[^/]+%.platformio/packages', '/.platformio/packages') +-- +-- return flag +-- end) +-- +-- -- Return only the result string (discarding the replacement count) +-- return cleaned_cmd +-- end ------------------------------------------------------ function M.normalizePath(path) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 6bbe6d42..8e8f24c2 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -14,10 +14,14 @@ local lsp_restart = require('platformio.lsp.tools').lsp_restart -- iterrative loop 48ms -- stylua: ignore -local function jsonFormat(root_data) +local function jsonFormat(wroot_data) local buffer = {} + + -- Force input into a table if it's just a single string + local patterns = type(wroot_data) == "table" and wroot_data or { wroot_data } + -- The stack stores: { value = current_item, level = depth, stage = "start"|"items" } - local stack = { { val = root_data, lvl = 0, stage = 'start' } } + local stack = { { val = patterns, lvl = 0, stage = 'start' } } local function get_indent(lvl) return string.rep(' ', lvl) end @@ -111,7 +115,8 @@ end -- recursion 50ms -- stylua: ignore -local function pretty_print(data) -- 48ms +-- local function pretty_print(data) -- 48ms +function M.pretty_print(data) -- 48ms local insert = table.insert local buffer = {} local function format_item(item, current_level) From eae89aa3b4fe4cc397b15968a8fb5b93afc310d4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 19:39:17 +0300 Subject: [PATCH 0873/1406] update --- lua/platformio/boilerplate.lua | 5 +++-- lua/platformio/lsp/clangd.lua | 10 +++++----- lua/platformio/metadata.lua | 5 +++-- lua/platformio/pio_setup.lua | 6 ++++-- lua/platformio/utils/pio.lua | 23 ++--------------------- 5 files changed, 17 insertions(+), 32 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 6c9c516b..b69c7521 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -1,4 +1,5 @@ --- local misc = require('platformio.utils.misc') +M = {} +M.core_dir = '' local uv = vim.loop local boilerplate = {} @@ -56,7 +57,7 @@ lib_ldf_mode = chain ;Library dependencies Finder ldf content = function(self) -- local pio = require('platformio.utils.pio') -- return string.format(self.template, require('platformio.utils.pio').get_pio_dir('core')) - return string.format(self.template, _G.metadata.core_dir) + return string.format(self.template, M.core_dir) end, } diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua index d1cbc01f..05e07b93 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -119,14 +119,14 @@ function _G.get_clangd_config() end -- 3. Format your template string - local clangd_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) - local formatted_str = string.format(clangd_config, q_driver, f_flags, new_root_dir) + local table_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) + local formatted_str = string.format(table_config, q_driver, f_flags, new_root_dir) -- 4. Load the config table - local cok, table_config = pcall(function() return load('return ' .. formatted_str)() end) + local cok, clangd_config = pcall(function() return load('return ' .. formatted_str)() end) - if cok and table_config then - return table_config + if cok and clangd_config then + return clangd_config end end diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 86a15609..69a65f7f 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,5 +1,6 @@ local M = {} +local pio = require('platformio.utils.pio') local frames = { '⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏' } local frame_idx = 1 @@ -91,7 +92,7 @@ _G.metadata = setmetatable({}, { pcall(function() if _raw_metadata.dbTrigger then vim.notify('Env: dbTrigger', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) - local dbFix = require('platformio.utils.pio').compile_commandsFix + local dbFix = pio.compile_commandsFix dbFix() _raw_metadata.dbTrigger = false else @@ -127,7 +128,7 @@ function M.save_project_config(quiet) if current_hash ~= last_saved_hash then local file = io.open(config_path, 'w') if file then - file:write(current_data) + file:write(pio.jsonFormat(current_data)) file:close() last_saved_hash = current_hash if not quiet then diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index f694d9b6..ed53f1cb 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -2,7 +2,8 @@ M = {} local misc = require('platformio.utils.misc') -- local lsp_restart = require('platformio.lsp.tools').lsp_restart -local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +local boilerplate = require('platformio.boilerplate') +local boilerplate_gen = boilerplate.boilerplate_gen -- local debounce_timer = vim.uv.new_timer() -- INFO: @@ -225,7 +226,7 @@ M.pio_manager = (function() local key, val = kv[1], kv[2] if key ~= nil then -- if _G.metadata[key] ~= nil then - _G.metadata[key] = misc.normalizePath(val) + _G.metadata[key] = (val and val ~= '') and misc.normalizePath(val) or val end end -- 2. Extract all hardware [envs] like [env:seeed_xiao_esp32c3], skipping generic [env] @@ -528,6 +529,7 @@ function M.init() ----------------------------------------------------------------------------------------- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) + boilerplate.core_dir = _G.metadata.core_dir boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 8e8f24c2..2637e378 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -14,11 +14,11 @@ local lsp_restart = require('platformio.lsp.tools').lsp_restart -- iterrative loop 48ms -- stylua: ignore -local function jsonFormat(wroot_data) +function M.jsonFormat(root_data) local buffer = {} -- Force input into a table if it's just a single string - local patterns = type(wroot_data) == "table" and wroot_data or { wroot_data } + local patterns = type(root_data) == "table" and root_data or { root_data } -- The stack stores: { value = current_item, level = depth, stage = "start"|"items" } local stack = { { val = patterns, lvl = 0, stage = 'start' } } @@ -199,21 +199,6 @@ function M.compile_commandsFix() --M.dbPathsFix() end end end - -- for _, entry in ipairs(data) do - -- local cmd = entry.command or '' - -- local first_token = cmd:match('^%S+') -- Get first word before space - -- - -- if first_token and not (first_token:sub(1, 1) == '/' or first_token:match('^%a:')) then - -- local short_name = first_token:gsub('%.exe$', '') - -- if path_map[short_name] then - -- -- Swap first token with full path safely - -- entry.command = misc.normalize_path(path_map[short_name]) .. cmd:sub(#first_token + 1) - -- -- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) - -- modified = true - -- end - -- end - -- end - -- 3. Save with Formatting if modified then local start_time = vim.loop.hrtime() @@ -241,10 +226,6 @@ function M.compile_commandsFix() --M.dbPathsFix() end - - - - -- stylua: ignore -- function M.compile_commandsFix() -- local filename = vim.fs.joinpath(vim.uv.cwd(), 'compile_commands.json') From 5ca1960b85312c568148e2a1ef820236e7542b97 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 19:44:34 +0300 Subject: [PATCH 0874/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index ed53f1cb..b1421de3 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -226,7 +226,7 @@ M.pio_manager = (function() local key, val = kv[1], kv[2] if key ~= nil then -- if _G.metadata[key] ~= nil then - _G.metadata[key] = (val and val ~= '') and misc.normalizePath(val) or val + _G.metadata[key] = (val ~= nil and val ~= '') and misc.normalizePath(val) or val end end -- 2. Extract all hardware [envs] like [env:seeed_xiao_esp32c3], skipping generic [env] From c79756ec1e3b8cff70d87c606cbf7b0e17d1af98 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 20:31:43 +0300 Subject: [PATCH 0875/1406] update --- lua/platformio/pio_setup.lua | 2 +- lua/platformio/utils/pio.lua | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b1421de3..197802e5 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -226,7 +226,7 @@ M.pio_manager = (function() local key, val = kv[1], kv[2] if key ~= nil then -- if _G.metadata[key] ~= nil then - _G.metadata[key] = (val ~= nil and val ~= '') and misc.normalizePath(val) or val +_G.metadata[key] = ((type(val) == 'table' and next(val) ~= nil) or (type(val) == "string" and val ~= '')) and misc.normalizePath(val) or val end end -- 2. Extract all hardware [envs] like [env:seeed_xiao_esp32c3], skipping generic [env] diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 2637e378..1695ba47 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -203,7 +203,7 @@ function M.compile_commandsFix() --M.dbPathsFix() if modified then local start_time = vim.loop.hrtime() - local jok, formatted = pcall(jsonFormat, data) + local jok, formatted = pcall(M.jsonFormat, data) if not jok then print('Formatting failed: ' .. formatted) return From 1166023b8306e6b1abdb57a65aafe33743bb76c2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 20:51:12 +0300 Subject: [PATCH 0876/1406] update --- lua/platformio/utils/pio.lua | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 1695ba47..a2ce634e 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -181,19 +181,22 @@ function M.compile_commandsFix() --M.dbPathsFix() if entry.command then -- local first_token = cmd:match('^%S+') -- Get first word before space local compiler, args = entry.command:match("^%s*(%S+)(.*)") - print(string.format('compiler = %s', compiler)) -- Check if it's already a short name (not an absolute path) if compiler and not (compiler:sub(1, 1) == '/' or compiler:match('^%a:')) then + print(string.format('compiler = %s', compiler)) -- get the file name without .exe - local short_name = compiler:gsub('%.exe$', '') + -- local short_name = compiler:gsub('%.exe$', '') + local short_name = compiler:match('([^/\\\\]+)$'):gsub('%.exe$', '') if path_map[short_name] then -- if there is full path for this file -- Swap compiler with full path safely - compiler = misc.normalizePath(path_map[short_name]) - args = misc.normalizeFlags(args) - entry.command = compiler .. args - -- entry.command = misc.normalize_path(path_map[short_name]) .. cmd:sub(#compiler + 1) - -- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) + local full_compiler_path = misc.normalizePath(path_map[short_name]) + --Quore the path if it contains spaces + if full_compiler_path.find(" ") then + full_compiler_path = '"' .. full_compiler_path .. '"' + end + local argsFormated = misc.normalizeFlags(args) + entry.command = full_compiler_path .. argsFormated modified = true end end From 2b35d6f133d192eadc4fecfddf6e76cf952db03c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 20:58:38 +0300 Subject: [PATCH 0877/1406] update --- lua/platformio/utils/pio.lua | 37 +++++++++++++++--------------------- 1 file changed, 15 insertions(+), 22 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index a2ce634e..0f208f42 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -167,16 +167,9 @@ function M.compile_commandsFix() --M.dbPathsFix() -- 2. Update Entries local modified = false for _, entry in ipairs(data) do - - if entry.directory then - entry.directory = misc.normalizePath(entry.directory) - end - if entry.file then - entry.file = misc.normalizePath(entry.file) - end - if entry.arguments then - entry.arguments = misc.normalizeFlags(entry.arguments) - end + if entry.directory then entry.directory = misc.normalizePath(entry.directory) end + if entry.file then entry.file = misc.normalizePath(entry.file) end + if entry.arguments then entry.arguments = misc.normalizeFlags(entry.arguments) end -- if entry.command then -- local first_token = cmd:match('^%S+') -- Get first word before space @@ -187,18 +180,18 @@ function M.compile_commandsFix() --M.dbPathsFix() print(string.format('compiler = %s', compiler)) -- get the file name without .exe -- local short_name = compiler:gsub('%.exe$', '') - local short_name = compiler:match('([^/\\\\]+)$'):gsub('%.exe$', '') - if path_map[short_name] then -- if there is full path for this file - -- Swap compiler with full path safely - local full_compiler_path = misc.normalizePath(path_map[short_name]) - --Quore the path if it contains spaces - if full_compiler_path.find(" ") then - full_compiler_path = '"' .. full_compiler_path .. '"' - end - local argsFormated = misc.normalizeFlags(args) - entry.command = full_compiler_path .. argsFormated - modified = true - end + -- local short_name = compiler:match('([^/\\\\]+)$'):gsub('%.exe$', '') + -- if path_map[short_name] then -- if there is full path for this file + -- -- Swap compiler with full path safely + -- local full_compiler_path = misc.normalizePath(path_map[short_name]) + -- --Quore the path if it contains spaces + -- if full_compiler_path.find(" ") then + -- full_compiler_path = '"' .. full_compiler_path .. '"' + -- end + -- local argsFormated = misc.normalizeFlags(args) + -- entry.command = full_compiler_path .. argsFormated + -- modified = true + -- end end end end From b56039d1a2c646071c6a7e2456f9f9a090614ca1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 21:03:39 +0300 Subject: [PATCH 0878/1406] update --- lua/platformio/utils/pio.lua | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 0f208f42..ac3fbe8b 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -177,21 +177,22 @@ function M.compile_commandsFix() --M.dbPathsFix() -- Check if it's already a short name (not an absolute path) if compiler and not (compiler:sub(1, 1) == '/' or compiler:match('^%a:')) then - print(string.format('compiler = %s', compiler)) -- get the file name without .exe -- local short_name = compiler:gsub('%.exe$', '') - -- local short_name = compiler:match('([^/\\\\]+)$'):gsub('%.exe$', '') - -- if path_map[short_name] then -- if there is full path for this file - -- -- Swap compiler with full path safely - -- local full_compiler_path = misc.normalizePath(path_map[short_name]) - -- --Quore the path if it contains spaces - -- if full_compiler_path.find(" ") then - -- full_compiler_path = '"' .. full_compiler_path .. '"' - -- end - -- local argsFormated = misc.normalizeFlags(args) - -- entry.command = full_compiler_path .. argsFormated - -- modified = true - -- end + local short_name = compiler:match('([^/\\\\]+)$'):gsub('%.exe$', '') + if path_map[short_name] then -- if there is full path for this file + -- Swap compiler with full path safely + local full_compiler_path = misc.normalizePath(path_map[short_name]) + --Quore the path if it contains spaces + if full_compiler_path.find(" ") then + full_compiler_path = '"' .. full_compiler_path .. '"' + print(string.format('compiler = %s', compiler)) + end + -- local argsFormated = misc.normalizeFlags(args) + -- entry.command = full_compiler_path .. argsFormated + entry.command = full_compiler_path .. args + modified = true + end end end end From d961e865c9ebb4f0275ef0a99cc1d6f03207542d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 21:13:26 +0300 Subject: [PATCH 0879/1406] update --- lua/platformio/utils/pio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index ac3fbe8b..28ab24d3 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -182,12 +182,12 @@ function M.compile_commandsFix() --M.dbPathsFix() local short_name = compiler:match('([^/\\\\]+)$'):gsub('%.exe$', '') if path_map[short_name] then -- if there is full path for this file -- Swap compiler with full path safely - local full_compiler_path = misc.normalizePath(path_map[short_name]) + local full_compiler_path = path_map[short_name] --misc.normalizePath(path_map[short_name]) --Quore the path if it contains spaces if full_compiler_path.find(" ") then full_compiler_path = '"' .. full_compiler_path .. '"' - print(string.format('compiler = %s', compiler)) end + print(string.format('compiler = %s', compiler)) -- local argsFormated = misc.normalizeFlags(args) -- entry.command = full_compiler_path .. argsFormated entry.command = full_compiler_path .. args From d0bd0787eb98399bd67720779ea5b231fbbda855 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 21:19:35 +0300 Subject: [PATCH 0880/1406] update --- lua/platformio/utils/pio.lua | 79 ++++++++++++++++++++++++------------ 1 file changed, 53 insertions(+), 26 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 28ab24d3..640d1b34 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -164,39 +164,66 @@ function M.compile_commandsFix() --M.dbPathsFix() path_map[name] = full_path end - -- 2. Update Entries local modified = false - for _, entry in ipairs(data) do - if entry.directory then entry.directory = misc.normalizePath(entry.directory) end - if entry.file then entry.file = misc.normalizePath(entry.file) end - if entry.arguments then entry.arguments = misc.normalizeFlags(entry.arguments) end - -- - if entry.command then - -- local first_token = cmd:match('^%S+') -- Get first word before space + if entry.command then + -- Extract compiler and everything after it local compiler, args = entry.command:match("^%s*(%S+)(.*)") - - -- Check if it's already a short name (not an absolute path) - if compiler and not (compiler:sub(1, 1) == '/' or compiler:match('^%a:')) then - -- get the file name without .exe - -- local short_name = compiler:gsub('%.exe$', '') - local short_name = compiler:match('([^/\\\\]+)$'):gsub('%.exe$', '') - if path_map[short_name] then -- if there is full path for this file - -- Swap compiler with full path safely - local full_compiler_path = path_map[short_name] --misc.normalizePath(path_map[short_name]) - --Quore the path if it contains spaces - if full_compiler_path.find(" ") then - full_compiler_path = '"' .. full_compiler_path .. '"' + + if compiler then + local is_absolute = compiler:sub(1, 1) == '/' or compiler:match('^%a:') + + if not is_absolute then + local short_name = compiler:match('([^/\\\\]+)$'):gsub('%.exe$', '') + + if path_map[short_name] then + -- Use normalizePath on the new path + local full_compiler_path = misc.normalizePath(path_map[short_name]) + + -- Quote the path if it contains spaces + if full_compiler_path:find(" ") then + full_compiler_path = '"' .. full_compiler_path .. '"' + end + + entry.command = full_compiler_path .. args + modified = true end - print(string.format('compiler = %s', compiler)) - -- local argsFormated = misc.normalizeFlags(args) - -- entry.command = full_compiler_path .. argsFormated - entry.command = full_compiler_path .. args - modified = true end end end end - -- 3. Save with Formatting + -- 2. Update Entries + -- local modified = false + -- for _, entry in ipairs(data) do + -- if entry.directory then entry.directory = misc.normalizePath(entry.directory) end + -- if entry.file then entry.file = misc.normalizePath(entry.file) end + -- if entry.arguments then entry.arguments = misc.normalizeFlags(entry.arguments) end + -- -- + -- if entry.command then + -- -- local first_token = cmd:match('^%S+') -- Get first word before space + -- local compiler, args = entry.command:match("^%s*(%S+)(.*)") + -- + -- -- Check if it's already a short name (not an absolute path) + -- if compiler and not (compiler:sub(1, 1) == '/' or compiler:match('^%a:')) then + -- -- get the file name without .exe + -- -- local short_name = compiler:gsub('%.exe$', '') + -- local short_name = compiler:match('([^/\\\\]+)$'):gsub('%.exe$', '') + -- if path_map[short_name] then -- if there is full path for this file + -- -- Swap compiler with full path safely + -- local full_compiler_path = path_map[short_name] --misc.normalizePath(path_map[short_name]) + -- --Quore the path if it contains spaces + -- if full_compiler_path.find(" ") then + -- full_compiler_path = '"' .. full_compiler_path .. '"' + -- end + -- print(string.format('compiler = %s', compiler)) + -- -- local argsFormated = misc.normalizeFlags(args) + -- -- entry.command = full_compiler_path .. argsFormated + -- entry.command = full_compiler_path .. args + -- modified = true + -- end + -- end + -- end + -- end + -- -- 3. Save with Formatting if modified then local start_time = vim.loop.hrtime() From 35f5abc846342672fe9818a6d1553d15e0876511 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 21:31:37 +0300 Subject: [PATCH 0881/1406] update --- lua/platformio/utils/pio.lua | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 640d1b34..aa66a07d 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -165,25 +165,32 @@ function M.compile_commandsFix() --M.dbPathsFix() end local modified = false - if entry.command then + for _, entry in ipairs(data) do + -- Standard normalization + if entry.directory then entry.directory = misc.normalizePath(entry.directory) end + if entry.file then entry.file = misc.normalizePath(entry.file) end + if entry.arguments then entry.arguments = misc.normalizeFlags(entry.arguments) end + + if entry.command then -- Extract compiler and everything after it local compiler, args = entry.command:match("^%s*(%S+)(.*)") - + if compiler then local is_absolute = compiler:sub(1, 1) == '/' or compiler:match('^%a:') - + if not is_absolute then local short_name = compiler:match('([^/\\\\]+)$'):gsub('%.exe$', '') - + if path_map[short_name] then -- Use normalizePath on the new path local full_compiler_path = misc.normalizePath(path_map[short_name]) - + -- Quote the path if it contains spaces if full_compiler_path:find(" ") then full_compiler_path = '"' .. full_compiler_path .. '"' end - + + print(string.format('ful_compiler_path = %s', full_compiler_path)) entry.command = full_compiler_path .. args modified = true end From d23704cffb5983771492ca8da364ee5a66d99f7a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 21:43:11 +0300 Subject: [PATCH 0882/1406] update --- lua/platformio/metadata.lua | 2 +- lua/platformio/utils/pio.lua | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 69a65f7f..4e5f9aa2 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -128,7 +128,7 @@ function M.save_project_config(quiet) if current_hash ~= last_saved_hash then local file = io.open(config_path, 'w') if file then - file:write(pio.jsonFormat(current_data)) + file:write(pio.pretty_print(current_data)) file:close() last_saved_hash = current_hash if not quiet then diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index aa66a07d..c802fe62 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -117,6 +117,8 @@ end -- stylua: ignore -- local function pretty_print(data) -- 48ms function M.pretty_print(data) -- 48ms + -- Force input into a table if it's just a single string + local patterns = type(data) == "table" and data or { data } local insert = table.insert local buffer = {} local function format_item(item, current_level) @@ -141,7 +143,7 @@ function M.pretty_print(data) -- 48ms insert(buffer, '"' .. item:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"') else insert(buffer, tostring(item)) end end - format_item(data, 0) + format_item(patterns, 0) return table.concat(buffer) end @@ -191,7 +193,9 @@ function M.compile_commandsFix() --M.dbPathsFix() end print(string.format('ful_compiler_path = %s', full_compiler_path)) - entry.command = full_compiler_path .. args + local argsFormated = misc.normalizeFlags(args) + entry.command = full_compiler_path .. argsFormated + -- entry.command = full_compiler_path .. args modified = true end end @@ -234,7 +238,8 @@ function M.compile_commandsFix() --M.dbPathsFix() if modified then local start_time = vim.loop.hrtime() - local jok, formatted = pcall(M.jsonFormat, data) + -- local jok, formatted = pcall(M.jsonFormat, data) + local jok, formatted = pcall(M.pretty_print, data) if not jok then print('Formatting failed: ' .. formatted) return From f81c83d739e3094da89f6270cdf20ea8c1cd05f1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 21 Apr 2026 21:50:59 +0300 Subject: [PATCH 0883/1406] update --- lua/platformio/metadata.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 4e5f9aa2..8c382baa 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -128,7 +128,8 @@ function M.save_project_config(quiet) if current_hash ~= last_saved_hash then local file = io.open(config_path, 'w') if file then - file:write(pio.pretty_print(current_data)) + -- file:write(pio.pretty_print(current_data)) + file:write(pio.jsonFormat(current_data)) file:close() last_saved_hash = current_hash if not quiet then From 70fdc8ad9f9eaf7354fe2df66c6d0dae56ee9438 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 04:38:47 +0300 Subject: [PATCH 0884/1406] update --- lua/platformio/metadata.lua | 5 +++-- lua/platformio/utils/pio.lua | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 8c382baa..abeaabf4 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -118,7 +118,7 @@ _G.metadata = setmetatable({}, { -- 3. Save Logic (Uses sha256 for stability) function M.save_project_config(quiet) - if vim.fn.filereadable('platformio.ini') == 0 then + if vim.fn.filereadable(config_path) == 0 then return end @@ -128,8 +128,9 @@ function M.save_project_config(quiet) if current_hash ~= last_saved_hash then local file = io.open(config_path, 'w') if file then + file:write(pio.pretty_json(current_data)) -- file:write(pio.pretty_print(current_data)) - file:write(pio.jsonFormat(current_data)) + -- file:write(pio.jsonFormat(current_data)) file:close() last_saved_hash = current_hash if not quiet then diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index c802fe62..3d7a46a3 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -83,7 +83,7 @@ end ------------------------------------------------------ -- regex 100ms -- stylua: ignore -local function pretty_json(data) +function M.pretty_json(data) -- 1. Get a guaranteed valid JSON string from Neovim's core local json = vim.json.encode(data) From d22925649d40affbc8c503aa712549435eefbf2f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 04:47:01 +0300 Subject: [PATCH 0885/1406] update --- lua/platformio/metadata.lua | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index abeaabf4..4e8a0dfc 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -122,15 +122,16 @@ function M.save_project_config(quiet) return end - local current_data = vim.json.encode(_raw_metadata) + local current_data = pio.pretty_json(_raw_metadata) + -- local current_data = vim.json.encode(_raw_metadata) local current_hash = vim.fn.sha256(current_data) if current_hash ~= last_saved_hash then local file = io.open(config_path, 'w') if file then - file:write(pio.pretty_json(current_data)) + -- file:write(pio.pretty_json(current_data)) -- file:write(pio.pretty_print(current_data)) - -- file:write(pio.jsonFormat(current_data)) + file:write(pio.jsonFormat(current_data)) file:close() last_saved_hash = current_hash if not quiet then From e445158e3dc804183149c595bb5aef82e9f13d5b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 05:03:22 +0300 Subject: [PATCH 0886/1406] update --- lua/platformio/utils/pio.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 3d7a46a3..eadf7a6d 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -194,8 +194,8 @@ function M.compile_commandsFix() --M.dbPathsFix() print(string.format('ful_compiler_path = %s', full_compiler_path)) local argsFormated = misc.normalizeFlags(args) - entry.command = full_compiler_path .. argsFormated - -- entry.command = full_compiler_path .. args + -- entry.command = full_compiler_path .. argsFormated + entry.command = full_compiler_path .. args modified = true end end @@ -238,8 +238,8 @@ function M.compile_commandsFix() --M.dbPathsFix() if modified then local start_time = vim.loop.hrtime() - -- local jok, formatted = pcall(M.jsonFormat, data) - local jok, formatted = pcall(M.pretty_print, data) + local jok, formatted = pcall(M.jsonFormat, data) + -- local jok, formatted = pcall(M.pretty_print, data) if not jok then print('Formatting failed: ' .. formatted) return From dc478d5f76f0c1b57430cc268055aa6a4297b4fc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 05:15:42 +0300 Subject: [PATCH 0887/1406] update --- lua/platformio/utils/pio.lua | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index eadf7a6d..d98e6bc4 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -167,6 +167,7 @@ function M.compile_commandsFix() --M.dbPathsFix() end local modified = false + local prntFlags = true for _, entry in ipairs(data) do -- Standard normalization if entry.directory then entry.directory = misc.normalizePath(entry.directory) end @@ -191,8 +192,10 @@ function M.compile_commandsFix() --M.dbPathsFix() if full_compiler_path:find(" ") then full_compiler_path = '"' .. full_compiler_path .. '"' end - - print(string.format('ful_compiler_path = %s', full_compiler_path)) + if prntFlags then + print(string.format('ful_compiler_path = %s flags=%s', full_compiler_path, args)) + prntFlags = false + end local argsFormated = misc.normalizeFlags(args) -- entry.command = full_compiler_path .. argsFormated entry.command = full_compiler_path .. args From 0c8e9bf78feeec8d116c479adb3fd073046ca27e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 06:11:42 +0300 Subject: [PATCH 0888/1406] update --- lua/platformio/utils/misc.lua | 2 +- lua/platformio/utils/pio.lua | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index ea8edbba..8e89759b 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -142,7 +142,7 @@ function M.set_platformioRootDir() end function M.cd_pioini() - M.set_platformioRootDir() + -- M.set_platformioRootDir() vim.cmd('cd ' .. vim.g.platformioRootDir) end diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index d98e6bc4..4ed1e460 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -385,6 +385,9 @@ end ------------------------------------------------------ -- INFO: ToggleTerminal commands Sequencer +-- Semicolon (;): Runs the next command regardless of whether the first one succeeded. +-- Success Operator (&&): Runs the second command only if the first succeeds. +-- Fail Operator (||): Runs if any of the previous commands fail --- stylua: ignore M.run_sequence = function(tasks) -- Reset local state for new run From 396bde72475860078ad306d6bcc3886efb11321d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 06:22:55 +0300 Subject: [PATCH 0889/1406] update --- mini_nvimPlatformio.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 0473858f..12438b1e 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -420,7 +420,8 @@ end ----------------------------------------------------------------------------------------- local pioConfig = { lspClangd = { - enabled = true, + enabled = false, + -- enabled = true, attach = { enabled = true, keymaps = true, From dc70d73bace6592b436b8801e3590a10ed5b1d69 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 06:43:42 +0300 Subject: [PATCH 0890/1406] update --- lua/platformio/utils/pio.lua | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 4ed1e460..b34723e3 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -173,6 +173,7 @@ function M.compile_commandsFix() --M.dbPathsFix() if entry.directory then entry.directory = misc.normalizePath(entry.directory) end if entry.file then entry.file = misc.normalizePath(entry.file) end if entry.arguments then entry.arguments = misc.normalizeFlags(entry.arguments) end + if entry.output then entry.output = misc.normalizeFlags(entry.output) end if entry.command then -- Extract compiler and everything after it @@ -193,10 +194,11 @@ function M.compile_commandsFix() --M.dbPathsFix() full_compiler_path = '"' .. full_compiler_path .. '"' end if prntFlags then - print(string.format('ful_compiler_path = %s flags=%s', full_compiler_path, args)) + print(string.format('ful_compiler_path = %s', full_compiler_path)) + -- print(string.format('ful_compiler_path = %s flags=%s', full_compiler_path, args)) prntFlags = false end - local argsFormated = misc.normalizeFlags(args) + -- local argsFormated = misc.normalizeFlags(args) -- entry.command = full_compiler_path .. argsFormated entry.command = full_compiler_path .. args modified = true From 4476f27b6d66533eaa92863a810e653e25064664 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 07:23:12 +0300 Subject: [PATCH 0891/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index b34723e3..b4e98955 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -173,7 +173,7 @@ function M.compile_commandsFix() --M.dbPathsFix() if entry.directory then entry.directory = misc.normalizePath(entry.directory) end if entry.file then entry.file = misc.normalizePath(entry.file) end if entry.arguments then entry.arguments = misc.normalizeFlags(entry.arguments) end - if entry.output then entry.output = misc.normalizeFlags(entry.output) end + if entry.output then entry.output = misc.normalizePath(entry.output) end if entry.command then -- Extract compiler and everything after it From 373adebd485863bef193c7867039ffdb73963eed Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 07:55:35 +0300 Subject: [PATCH 0892/1406] update --- lua/platformio/metadata.lua | 54 +++++++++++++++++++++++++++++++------ 1 file changed, 46 insertions(+), 8 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 4e8a0dfc..20e0959f 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -122,25 +122,63 @@ function M.save_project_config(quiet) return end - local current_data = pio.pretty_json(_raw_metadata) - -- local current_data = vim.json.encode(_raw_metadata) + -- local current_data = pio.pretty_json(_raw_metadata) + local ok, current_data = pcall(vim.json.encode, _raw_metadata) + if not ok then + print('Error encoding JSON: ' .. current_data) + return + end local current_hash = vim.fn.sha256(current_data) if current_hash ~= last_saved_hash then - local file = io.open(config_path, 'w') - if file then - -- file:write(pio.pretty_json(current_data)) - -- file:write(pio.pretty_print(current_data)) - file:write(pio.jsonFormat(current_data)) - file:close() + local status = vim.fn.writefile({ current_data }, config_path) + if status == 0 then last_saved_hash = current_hash if not quiet then vim.notify('Config synced', vim.log.levels.INFO, { title = 'PlatformIO' }) end + else + vim.notify('Could not open file for writing') end + -- local file = io.open(config_path, 'w') + -- if file then + -- -- file:write(pio.pretty_json(current_data)) + -- -- file:write(pio.pretty_print(current_data)) + -- file:write(pio.jsonFormat(current_data)) + -- file:close() + -- last_saved_hash = current_hash + -- if not quiet then + -- vim.notify('Config synced', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- end + -- end end end +function M.save_table_to_json(data, filepath) + -- 1. Convert Lua table to JSON string + local ok, json_string = pcall(vim.json.encode, data) + if not ok then + print('Error encoding JSON: ' .. json_string) + return + end + local status + vim.fn.writefile({ json_string }, filepath) + if status == 0 then + vim.notify('Saved to ' .. filepath, 2) + else + vim.notify('Could not open file for writing') + end + + -- 2. Open file for writing ("w" mode overwrites) + -- local f = io.open(filepath, "w") + -- if f then + -- f:write(json_string) + -- f:close() + -- print("Saved to " .. filepath) + -- else + -- print("Could not open file for writing") + -- end +end -- 4. Load Logic (Populates proxy safely) function M.load_project_config() if vim.fn.filereadable(config_path) == 1 then From 9370f5374bef499f33b5c7aa237cd61d51e12561 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 07:56:28 +0300 Subject: [PATCH 0893/1406] update --- mini_nvimPlatformio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 12438b1e..508563b2 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -420,8 +420,8 @@ end ----------------------------------------------------------------------------------------- local pioConfig = { lspClangd = { - enabled = false, - -- enabled = true, + -- enabled = false, + enabled = true, attach = { enabled = true, keymaps = true, From fa30b0640703a76446c7e5c2f0d56bd88f3930f6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 08:36:53 +0300 Subject: [PATCH 0894/1406] update --- lua/platformio/metadata.lua | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 20e0959f..55af3621 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -53,10 +53,10 @@ end -- return ok and status or '' -- end ------------------------------------------------------------------------------------------------------- --- 1. Internal State & Defaults local last_saved_hash = '' local config_path = vim.fs.joinpath(vim.uv.cwd(), '.project_config.json') +-- 1. Internal State & Defaults local _raw_metadata = { isBusy = false, envs = {}, @@ -73,7 +73,6 @@ local _raw_metadata = { fallbackFlags = {}, dbTrigger = false, } - -- 2. The Reactive Proxy Wrapper -- Any write to _G.metadata.key = val triggers this logic _G.metadata = setmetatable({}, { @@ -118,16 +117,16 @@ _G.metadata = setmetatable({}, { -- 3. Save Logic (Uses sha256 for stability) function M.save_project_config(quiet) - if vim.fn.filereadable(config_path) == 0 then + if vim.fn.filereadable('platformio.ini') == 0 then return end - -- local current_data = pio.pretty_json(_raw_metadata) local ok, current_data = pcall(vim.json.encode, _raw_metadata) if not ok then print('Error encoding JSON: ' .. current_data) return end + local current_hash = vim.fn.sha256(current_data) if current_hash ~= last_saved_hash then From 8a446d583d2f2aefd82e476b8598cf8eff0b9801 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 10:44:18 +0300 Subject: [PATCH 0895/1406] update --- lua/platformio/metadata.lua | 115 +++++-------- lua/platformio/utils/misc.lua | 299 ++++++++++++++++++++++++++++------ lua/platformio/utils/pio.lua | 139 +--------------- plugin/platformio.lua | 4 +- 4 files changed, 301 insertions(+), 256 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 55af3621..62092160 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -56,8 +56,9 @@ end local last_saved_hash = '' local config_path = vim.fs.joinpath(vim.uv.cwd(), '.project_config.json') +--INFO: -- 1. Internal State & Defaults -local _raw_metadata = { +local _pio_metadata = { isBusy = false, envs = {}, active_env = '', @@ -76,12 +77,12 @@ local _raw_metadata = { -- 2. The Reactive Proxy Wrapper -- Any write to _G.metadata.key = val triggers this logic _G.metadata = setmetatable({}, { - __index = _raw_metadata, + __index = _pio_metadata, __newindex = function(_, key, value) - if _raw_metadata[key] == value then + if _pio_metadata[key] == value then return end -- Performance check - _raw_metadata[key] = value + _pio_metadata[key] = value -- Trigger background actions vim.schedule(function() @@ -89,11 +90,11 @@ _G.metadata = setmetatable({}, { if key == 'toolchain_root' then vim.notify('Env: ' .. value, vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) pcall(function() - if _raw_metadata.dbTrigger then + if _pio_metadata.dbTrigger then vim.notify('Env: dbTrigger', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) local dbFix = pio.compile_commandsFix dbFix() - _raw_metadata.dbTrigger = false + _pio_metadata.dbTrigger = false else local LspRestart = require('platformio.utils.lsp').lsp_restart LspRestart('clangd') @@ -103,34 +104,30 @@ _G.metadata = setmetatable({}, { elseif key == 'active_env' then -- Force global statusline so it doesn't get pushed around by Trouble or splits vim.o.laststatus = 3 - - -- Using luaeval with escaped quotes is the "bulletproof" Linux method - -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("_G.get_pio_status()")}%* %y %p%% %l:%c' - - -- Ensure your custom layout is the final word - -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' - -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{get(b:,"pio_env","")}%* %y %p%% %l:%c' end end) end, }) +--INFO: -- 3. Save Logic (Uses sha256 for stability) function M.save_project_config(quiet) if vim.fn.filereadable('platformio.ini') == 0 then return end - -- local current_data = pio.pretty_json(_raw_metadata) - local ok, current_data = pcall(vim.json.encode, _raw_metadata) + -- local json_data = pio.pretty_json(_pio_metadata) + local ok, json_data = pcall(vim.json.encode, _pio_metadata) if not ok then - print('Error encoding JSON: ' .. current_data) + print('Error encoding JSON: ' .. json_data) return end + local pretty_json = vim.misc.async_shell_cmd + local current_hash = vim.fn.sha256(json_data) - local current_hash = vim.fn.sha256(current_data) - + -- file:write(pio.jsonFormat(json_data)) if current_hash ~= last_saved_hash then - local status = vim.fn.writefile({ current_data }, config_path) + -- local status = vim.fn.writefile({ json_data }, config_path) + local status, _ = vim.misc.writeFile({ json_data }, config_path) if status == 0 then last_saved_hash = current_hash if not quiet then @@ -139,66 +136,44 @@ function M.save_project_config(quiet) else vim.notify('Could not open file for writing') end - -- local file = io.open(config_path, 'w') - -- if file then - -- -- file:write(pio.pretty_json(current_data)) - -- -- file:write(pio.pretty_print(current_data)) - -- file:write(pio.jsonFormat(current_data)) - -- file:close() - -- last_saved_hash = current_hash - -- if not quiet then - -- vim.notify('Config synced', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- end - -- end end end -function M.save_table_to_json(data, filepath) - -- 1. Convert Lua table to JSON string - local ok, json_string = pcall(vim.json.encode, data) - if not ok then - print('Error encoding JSON: ' .. json_string) - return - end - local status - vim.fn.writefile({ json_string }, filepath) - if status == 0 then - vim.notify('Saved to ' .. filepath, 2) - else - vim.notify('Could not open file for writing') - end - - -- 2. Open file for writing ("w" mode overwrites) - -- local f = io.open(filepath, "w") - -- if f then - -- f:write(json_string) - -- f:close() - -- print("Saved to " .. filepath) - -- else - -- print("Could not open file for writing") - -- end -end +--INFO: -- 4. Load Logic (Populates proxy safely) function M.load_project_config() - if vim.fn.filereadable(config_path) == 1 then - local file = io.open(config_path, 'r') - if file then - local content = file:read('*a') - file:close() - local ok, decoded = pcall(vim.json.decode, content) - if ok and type(decoded) == 'table' then - -- We update _raw_metadata directly to avoid triggering - -- 50+ notifications/restarts during the initial load loop - for k, v in pairs(decoded) do - _raw_metadata[k] = v - end - last_saved_hash = vim.fn.sha256(content) - return + -- if vim.fn.filereadable(config_path) == 1 then + -- local file = io.open(config_path, 'r') + -- if file then + -- local content = file:read('*a') + -- file:close() + -- local ok, decoded = pcall(vim.json.decode, content) + -- if ok and type(decoded) == 'table' then + -- -- We update _pio_metadata directly to avoid triggering + -- -- 50+ notifications/restarts during the initial load loop + -- for k, v in pairs(decoded) do + -- _pio_metadata[k] = v + -- end + -- last_saved_hash = vim.fn.sha256(content) + -- return + -- end + -- end + -- end + local json_data = vim.misc.readFile(config_path) + if json_data then + local ok, table_data = pcall(vim.json.decode, json_data) + if ok and type(table_data) == 'table' then + -- We update _pio_metadata directly to avoid triggering + -- 50+ notifications/restarts during the initial load loop + for k, v in pairs(table_data) do + _pio_metadata[k] = v end + last_saved_hash = vim.fn.sha256(json_data) + return end end -- If no file, initialize hash with defaults - last_saved_hash = vim.fn.sha256(vim.json.encode(_raw_metadata)) + last_saved_hash = vim.fn.sha256(vim.json.encode(_pio_metadata)) end -- 5. Helper for ToggleTerm / Commands diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 8e89759b..ca55cb6a 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -1,47 +1,239 @@ local M = {} -local is_windows = jit.os == 'Windows' -M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' +M.is_windows = jit.os == 'Windows' + +M.devNul = M.is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' -function M.normalizeFlags(input) - local path_map = {} +-- iterrative loop 48ms +-- stylua: ignore +function M.jsonFormat(root_data) + local buffer = {} -- Force input into a table if it's just a single string - local patterns = type(input) == 'table' and input or { input } + local patterns = type(root_data) == "table" and root_data or { root_data } + + -- The stack stores: { value = current_item, level = depth, stage = "start"|"items" } + local stack = { { val = patterns, lvl = 0, stage = 'start' } } + + local function get_indent(lvl) return string.rep(' ', lvl) end + + while #stack > 0 do + local curr = stack[#stack] + local val, lvl = curr.val, curr.lvl + local indent = get_indent(lvl) + + if type(val) == 'table' then + local is_array = (#val > 0 or next(val) == nil) + + if curr.stage == 'start' then + table.insert(buffer, (is_array and '[' or '{') .. '\n') + curr.stage = 'items' + curr.keys = {} + -- Collect keys to iterate deterministically + if is_array then + for i = #val, 1, -1 do table.insert(curr.keys, i) end + else + for k, _ in pairs(val) do table.insert(curr.keys, k) end + end + curr.index = #curr.keys + elseif curr.stage == 'items' then + if curr.index > 0 then + local key = curr.keys[curr.index] + local item = val[key] + + -- Add comma if not the first item + if curr.index < #curr.keys then table.insert(buffer, ',\n') end + + table.insert(buffer, get_indent(lvl + 1)) + if not is_array then table.insert(buffer, '"' .. tostring(key) .. '": ') end + + curr.index = curr.index - 1 + -- Push next item to stack + table.insert(stack, { val = item, lvl = lvl + 1, stage = 'start' }) + else + -- No more items, close the block + table.insert(buffer, '\n' .. indent .. (is_array and ']' or '}')) + table.remove(stack) + end + end + else + -- Primitive values (String, Number, Bool) + local output = '' + if type(val) == 'string' then + -- output = '"' .. val:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"' + output = '"' .. val:gsub('\\', '/'):gsub('"', '\\"') .. '"' + -- output = '"' .. val:gsub('"', '\\"') .. '"' + else output = tostring(val) end + table.insert(buffer, output) + table.remove(stack) + end + end + return table.concat(buffer) +end - for _, pattern in ipairs(patterns) do - -- Expand ~ or environment variables - local expanded = vim.fn.expand(pattern) - -- glob returns a table of matching files - local matches = vim.fn.glob(expanded, false, true) +------------------------------------------------------ +-- regex 100ms +-- stylua: ignore +function M.pretty_json(data) + -- 1. Get a guaranteed valid JSON string from Neovim's core + local json = data --vim.json.encode(data) + + -- 2. Use regex to inject newlines and indentation + -- This is much faster than manual recursion in Lua + local indent = ' ' + local level = 0 + + -- Add newlines after { [ , and before } ] + json = json:gsub('([%[%{%],])', '%1\n') + json = json:gsub('([%]}])', '\n%1') + + local lines = {} + for line in json:gmatch('[^\n]+') do + line = line:gsub('^%s+', '') -- trim existing whitespace - for _, full_path in ipairs(matches) do - if vim.fn.isdirectory(full_path) == 0 then - -- Normalize slashes and extract filename key - local clean_path = full_path:gsub('\\', '/') - local name = clean_path:match('([^/]+)$'):gsub('%.exe$', '') + -- Decrease level if line starts with closing bracket + if line:match('^[%]}]') then level = level - 1 end + + table.insert(lines, string.rep(indent, level) .. line) + + -- Increase level if line ends with opening bracket + if line:match('[%[{]$') then level = level + 1 end + end + return(lines) + -- return table.concat(lines, '\n') +end +------------------------------------------------------ - path_map[name] = clean_path +-- recursion 50ms +-- stylua: ignore +-- local function pretty_print(data) -- 48ms +function M.pretty_print(data) -- 48ms + -- Force input into a table if it's just a single string + local patterns = type(data) == "table" and data or { data } + local insert = table.insert + local buffer = {} + local function format_item(item, current_level) + local indent = string.rep(' ', current_level) + local next_indent = string.rep(' ', current_level + 1) + if type(item) == 'table' then + local is_array = #item > 0 + local opener = is_array and '[' or '{' + local closer = is_array and ']' or '}' + insert(buffer, opener .. '\n') + local first = true + for k, v in pairs(item) do + if not first then insert(buffer, ',\n') end + insert(buffer, next_indent) + if not is_array then insert(buffer, '"' .. k .. '": ') end + format_item(v, current_level + 1) + first = false end - end + insert(buffer, '\n' .. indent .. closer) + elseif type(item) == 'string' then + -- Basic escaping for the string content + insert(buffer, '"' .. item:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"') + else insert(buffer, tostring(item)) end + end + format_item(patterns, 0) + return table.concat(buffer) +end + +--INFO: +-- Example Usage +-- local content = readFile("compile_commands.json") +-- if content then local data = vim.json.decode(content) end +-- stylua: ignore +function M.readFile(path) + local uv = vim.uv or vim.loop -- Support older and newer Neovim versions + + -- 1. Open the file (r = read-only) + -- 438 is the octal for 0666 (standard permissions) + local fd, err = uv.fs_open(path, 'r', 438) + if not fd or err then return nil, 'readFile: Open error: ' .. err end + + -- 2. Get file stats to find out how many bytes to read + local stat, stat_err = uv.fs_fstat(fd) + if not stat or stat_err then + uv.fs_close(fd) + return nil, 'readFile: Stat error: ' .. stat_err end - return path_map + -- 3. Read the entire content + -- fd, length, offset + local content, read_err = uv.fs_read(fd, stat.size, 0) + + -- 4. ALWAYS close the file descriptor + uv.fs_close(fd) + + if read_err then return nil, 'readFile: Read error: ' .. read_err end + + return content end +--INFO: +-- Example +-- local ok, err = writeFiile(path, json) +-- if ok then print("Write complete!") end +-- stylua: ignore +function M.writeFile(data, path) + local uv = vim.uv or vim.loop + + -- 1. Open file for writing + -- 'w' = open for writing (creates if doesn't exist, truncates if it does) + -- 438 is octal 0666 (standard read/write permissions) + local fd, err = uv.fs_open(path, 'w', 438) + if not fd or err then return nil, 'writeFile: Open error: ' .. err end + + -- 2. Write the data + -- fd, data, offset (0 to start at beginning) + local _, write_err = uv.fs_write(fd, data, 0) + + -- 3. ALWAYS close the file descriptor + uv.fs_close(fd) + if write_err then return nil, 'writeFile: Write error: ' .. write_err end + return true +end + +--INFO: +--- stylua: ignore +-- function M.normalizeFlags(input) +-- local path_map = {} +-- +-- -- Force input into a table if it's just a single string +-- local patterns = type(input) == 'table' and input or { input } +-- +-- for _, pattern in ipairs(patterns) do +-- -- Expand ~ or environment variables +-- local expanded = vim.fn.expand(pattern) +-- +-- -- glob returns a table of matching files +-- local matches = vim.fn.glob(expanded, false, true) +-- +-- for _, full_path in ipairs(matches) do +-- if vim.fn.isdirectory(full_path) == 0 then +-- -- Normalize slashes and extract filename key +-- local clean_path = full_path:gsub('\\', '/') +-- local name = clean_path:match('([^/]+)$'):gsub('%.exe$', '') +-- +-- path_map[name] = clean_path +-- end +-- end +-- end +-- +-- return path_map +-- end ------------------------------------------------------ + --[[ ---INFO: Targets Windows paths, normalizes slashes, and fixes smashed PlatformIO paths. Cleans and repairs compiler flags in a command string. { "-I", "-L", "-isystem", "-T", "-include" } - 1. Library Paths -L: Specifies directories to search for library files (.a, .lib, .so). Example: -L"C:\Users\lib" @@ -60,43 +252,47 @@ Cleans and repairs compiler flags in a command string. Example: -T"C:\project\ld\esp32.ld" -F: (macOS/iOS) Path to search for frameworks. ]] ---INFO: -- stylua: ignore --- @param cmd string: The raw command string (e.g., from compile_commands.json) --- @return string: The cleaned command string --- function M.normalizeFlags(cmd) --- if not cmd or cmd == '' then return '' end --- --- --INFO: 1. Identify flags that look like paths. --- -- Pattern explanation: --- -- %- : Matches a literal hyphen (the start of a flag) --- -- %S* : Matches zero or more non-space characters --- -- \\ : Matches a literal backslash (identifies it as a Windows path) --- -- %S* : Matches the rest of the non-space characters in that flag --- local cleaned_cmd = cmd:gsub('(%-%S-\\S*)', function(flag) --- --INFO: 2. Normalize Slashes --- -- Replaces any number of backslashes (single \ or JSON-escaped \\) with one forward slash. --- -- Forward slashes are safer and more portable for compilers like GCC/Clang. --- flag = flag:gsub('[\\]+', '/') --- --- -- INFO:3. Heal PlatformIO "Smashed" Paths --- -- Fixes the bug where PlatformIO expansions repeat the user home directory. --- -- Example: /Users/name/.platformiopackages/toolchain -> /.platformio/packages/toolchain --- flag = flag:gsub('/Users/[^/]+%.platformio/packages', '/.platformio/packages') --- --- return flag --- end) --- --- -- Return only the result string (discarding the replacement count) --- return cleaned_cmd --- end +--INFO: +function M.normalizeFlags(cmd) + if not cmd or cmd == '' then + return '' + end + --1. Identify flags that look like paths. + -- Pattern explanation: + -- %- : Matches a literal hyphen (the start of a flag) + -- %S* : Matches zero or more non-space characters + -- \\ : Matches a literal backslash (identifies it as a Windows path) + -- %S* : Matches the rest of the non-space characters in that flag + local cleaned_cmd = cmd:gsub('(%-%S-\\S*)', function(flag) + --2. Normalize Slashes + -- Replaces any number of backslashes (single \ or JSON-escaped \\) with one forward slash. + -- Forward slashes are safer and more portable for compilers like GCC/Clang. + flag = flag:gsub('[\\]+', '/') + + --3. Heal PlatformIO "Smashed" Paths + -- Fixes the bug where PlatformIO expansions repeat the user home directory. + -- Example: /Users/name/.platformiopackages/toolchain -> /.platformio/packages/toolchain + flag = flag:gsub('/Users/[^/]+%.platformio/packages', '/.platformio/packages') + + return flag + end) + + -- Return only the result string (discarding the replacement count) + return cleaned_cmd +end + +--INFO: ------------------------------------------------------ function M.normalizePath(path) -- return path:gsub('[\\]+', '/'):gsub('[//]+', '/') return path:gsub('[\\/]+', '/') end +--INFO: ------------------------------------------------------ function M.strsplit(inputstr, del) local t = {} @@ -108,16 +304,19 @@ function M.strsplit(inputstr, del) return t end +--INFO: function M.check_prefix(str, prefix) return str:sub(1, #prefix) == prefix end +--INFO: local function pathmul(n) return '..' .. string.rep('/..', n) end local paths = { '.', '..', pathmul(1), pathmul(2), pathmul(3), pathmul(4), pathmul(5) } +--INFO: function M.file_exists(name) local f = io.open(name, 'r') if f ~= nil then @@ -128,6 +327,7 @@ function M.file_exists(name) end end +--INFO: function M.set_platformioRootDir() if vim.g.platformioRootDir ~= nil then return @@ -141,11 +341,13 @@ function M.set_platformioRootDir() vim.notify('Could not find platformio.ini, run :Pioinit to create a new project', vim.log.levels.ERROR) end +--INFO: function M.cd_pioini() -- M.set_platformioRootDir() vim.cmd('cd ' .. vim.g.platformioRootDir) end +--INFO: function M.pio_install_check() local handle = (jit.os == 'Windows') and assert(io.popen('where.exe pio 2>./nul')) or assert(io.popen('which pio 2>/dev/null')) local pio_path = assert(handle:read('*a')) @@ -158,6 +360,7 @@ function M.pio_install_check() return true end +--INFO: function M.async_shell_cmd(cmd, callback) local output = {} @@ -181,6 +384,7 @@ function M.async_shell_cmd(cmd, callback) }) end +--INFO: function M.shell_cmd_blocking(command) local handle = io.popen(command, 'r') if not handle then @@ -193,6 +397,7 @@ function M.shell_cmd_blocking(command) return result end +--INFO: function M.gitignore_lsp_configs(config_file) local gitignore_path = vim.fs.joinpath(vim.g.platformioRootDir, '.gitignore') local file = io.open(gitignore_path, 'r') diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index b4e98955..2ae986b8 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -1,4 +1,5 @@ local M = {} +local misc = vim.misc -- local sep = package.config:sub(1, 1) -- Dynamic OS separator (\ or /) M.selected_framework = '' @@ -9,144 +10,8 @@ local pio_buffer = '' -- Persistent stream buffer -- to fix require loop, this value is set in plugin/platformio local term = require('platformio.utils.term') -local misc = require('platformio.utils.misc') local lsp_restart = require('platformio.lsp.tools').lsp_restart --- iterrative loop 48ms --- stylua: ignore -function M.jsonFormat(root_data) - local buffer = {} - - -- Force input into a table if it's just a single string - local patterns = type(root_data) == "table" and root_data or { root_data } - - -- The stack stores: { value = current_item, level = depth, stage = "start"|"items" } - local stack = { { val = patterns, lvl = 0, stage = 'start' } } - - local function get_indent(lvl) return string.rep(' ', lvl) end - - while #stack > 0 do - local curr = stack[#stack] - local val, lvl = curr.val, curr.lvl - local indent = get_indent(lvl) - - if type(val) == 'table' then - local is_array = (#val > 0 or next(val) == nil) - - if curr.stage == 'start' then - table.insert(buffer, (is_array and '[' or '{') .. '\n') - curr.stage = 'items' - curr.keys = {} - -- Collect keys to iterate deterministically - if is_array then - for i = #val, 1, -1 do table.insert(curr.keys, i) end - else - for k, _ in pairs(val) do table.insert(curr.keys, k) end - end - curr.index = #curr.keys - elseif curr.stage == 'items' then - if curr.index > 0 then - local key = curr.keys[curr.index] - local item = val[key] - - -- Add comma if not the first item - if curr.index < #curr.keys then table.insert(buffer, ',\n') end - - table.insert(buffer, get_indent(lvl + 1)) - if not is_array then table.insert(buffer, '"' .. tostring(key) .. '": ') end - - curr.index = curr.index - 1 - -- Push next item to stack - table.insert(stack, { val = item, lvl = lvl + 1, stage = 'start' }) - else - -- No more items, close the block - table.insert(buffer, '\n' .. indent .. (is_array and ']' or '}')) - table.remove(stack) - end - end - else - -- Primitive values (String, Number, Bool) - local output = '' - if type(val) == 'string' then - -- output = '"' .. val:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"' - output = '"' .. val:gsub('\\', '/'):gsub('"', '\\"') .. '"' - -- output = '"' .. val:gsub('"', '\\"') .. '"' - else output = tostring(val) end - table.insert(buffer, output) - table.remove(stack) - end - end - return table.concat(buffer) -end - - ------------------------------------------------------- --- regex 100ms --- stylua: ignore -function M.pretty_json(data) - -- 1. Get a guaranteed valid JSON string from Neovim's core - local json = vim.json.encode(data) - - -- 2. Use regex to inject newlines and indentation - -- This is much faster than manual recursion in Lua - local indent = ' ' - local level = 0 - - -- Add newlines after { [ , and before } ] - json = json:gsub('([%[%{%],])', '%1\n') - json = json:gsub('([%]}])', '\n%1') - - local lines = {} - for line in json:gmatch('[^\n]+') do - line = line:gsub('^%s+', '') -- trim existing whitespace - - -- Decrease level if line starts with closing bracket - if line:match('^[%]}]') then level = level - 1 end - - table.insert(lines, string.rep(indent, level) .. line) - - -- Increase level if line ends with opening bracket - if line:match('[%[{]$') then level = level + 1 end - end - - return table.concat(lines, '\n') -end ------------------------------------------------------- - --- recursion 50ms --- stylua: ignore --- local function pretty_print(data) -- 48ms -function M.pretty_print(data) -- 48ms - -- Force input into a table if it's just a single string - local patterns = type(data) == "table" and data or { data } - local insert = table.insert - local buffer = {} - local function format_item(item, current_level) - local indent = string.rep(' ', current_level) - local next_indent = string.rep(' ', current_level + 1) - if type(item) == 'table' then - local is_array = #item > 0 - local opener = is_array and '[' or '{' - local closer = is_array and ']' or '}' - insert(buffer, opener .. '\n') - local first = true - for k, v in pairs(item) do - if not first then insert(buffer, ',\n') end - insert(buffer, next_indent) - if not is_array then insert(buffer, '"' .. k .. '": ') end - format_item(v, current_level + 1) - first = false - end - insert(buffer, '\n' .. indent .. closer) - elseif type(item) == 'string' then - -- Basic escaping for the string content - insert(buffer, '"' .. item:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"') - else insert(buffer, tostring(item)) end - end - format_item(patterns, 0) - return table.concat(buffer) -end - -- stylua: ignore function M.compile_commandsFix() --M.dbPathsFix() local filename = vim.fs.joinpath(vim.uv.cwd(), 'compile_commands.json') @@ -243,7 +108,7 @@ function M.compile_commandsFix() --M.dbPathsFix() if modified then local start_time = vim.loop.hrtime() - local jok, formatted = pcall(M.jsonFormat, data) + local jok, formatted = pcall(vim.misc.jsonFormat, data) -- local jok, formatted = pcall(M.pretty_print, data) if not jok then print('Formatting failed: ' .. formatted) diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 874a2d8b..ffa38182 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -7,9 +7,9 @@ -- -1: Zero or one argument (like ?, explicitly). local piolsserial = require('platformio.piolsserial') -local misc = require('platformio.utils.misc') local pio = require('platformio.utils.pio') local meta = require('platformio.metadata') +vim.misc = require('platformio.utils.misc') -- Statusline: Using luaeval for best cross-platform stability vim.o.laststatus = 3 @@ -154,7 +154,7 @@ vim.api.nvim_create_user_command('PioTermList', function() if #terms ~= 0 then for i = 1, #terms do if terms[i].display_name and terms[i].display_name ~= '' and terms[i].display_name:find('pio', 1) then - local termtype = misc.strsplit(terms[i].display_name, ':')[1] + local termtype = vim.misc.strsplit(terms[i].display_name, ':')[1] table.insert(toggleterm_list, { term = terms[i], termtype = termtype, -- Store the terminal type [piomon or piocli] From 42ff88d2463193ab90a4a85a9bc581be26204ba0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 11:12:28 +0300 Subject: [PATCH 0896/1406] update --- lua/platformio/metadata.lua | 26 +++++++++--------- lua/platformio/utils/misc.lua | 8 +++--- tmp.lua | 51 +++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 17 deletions(-) create mode 100644 tmp.lua diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 62092160..a7216749 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -121,8 +121,8 @@ function M.save_project_config(quiet) print('Error encoding JSON: ' .. json_data) return end - local pretty_json = vim.misc.async_shell_cmd - local current_hash = vim.fn.sha256(json_data) + local pretty_json = vim.misc.pretty_print(json_data) + local current_hash = vim.fn.sha256(pretty_json) -- file:write(pio.jsonFormat(json_data)) if current_hash ~= last_saved_hash then @@ -159,17 +159,19 @@ function M.load_project_config() -- end -- end -- end - local json_data = vim.misc.readFile(config_path) - if json_data then - local ok, table_data = pcall(vim.json.decode, json_data) - if ok and type(table_data) == 'table' then - -- We update _pio_metadata directly to avoid triggering - -- 50+ notifications/restarts during the initial load loop - for k, v in pairs(table_data) do - _pio_metadata[k] = v + if vim.fn.filereadable(config_path) == 1 then + local json_data = vim.misc.readFile(config_path) + if json_data then + local ok, table_data = pcall(vim.json.decode, json_data) + if ok and type(table_data) == 'table' then + -- We update _pio_metadata directly to avoid triggering + -- 50+ notifications/restarts during the initial load loop + for k, v in pairs(table_data) do + _pio_metadata[k] = v + end + last_saved_hash = vim.fn.sha256(json_data) + return end - last_saved_hash = vim.fn.sha256(json_data) - return end end -- If no file, initialize hash with defaults diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index ca55cb6a..31e9bbf7 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -79,7 +79,7 @@ end -- stylua: ignore function M.pretty_json(data) -- 1. Get a guaranteed valid JSON string from Neovim's core - local json = data --vim.json.encode(data) + local json = vim.json.encode(data) -- 2. Use regex to inject newlines and indentation -- This is much faster than manual recursion in Lua @@ -102,8 +102,7 @@ function M.pretty_json(data) -- Increase level if line ends with opening bracket if line:match('[%[{]$') then level = level + 1 end end - return(lines) - -- return table.concat(lines, '\n') + return table.concat(lines, '\n') end ------------------------------------------------------ @@ -112,7 +111,6 @@ end -- local function pretty_print(data) -- 48ms function M.pretty_print(data) -- 48ms -- Force input into a table if it's just a single string - local patterns = type(data) == "table" and data or { data } local insert = table.insert local buffer = {} local function format_item(item, current_level) @@ -137,7 +135,7 @@ function M.pretty_print(data) -- 48ms insert(buffer, '"' .. item:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"') else insert(buffer, tostring(item)) end end - format_item(patterns, 0) + format_item(data, 0) return table.concat(buffer) end diff --git a/tmp.lua b/tmp.lua new file mode 100644 index 00000000..a4e48ab4 --- /dev/null +++ b/tmp.lua @@ -0,0 +1,51 @@ +function M.pretty_print_json_string(json_str) + -- 1. Convert JSON string to Lua table + local ok, data = pcall(vim.json.decode, json_str) + if not ok then + print('Error: Invalid JSON string provided') + return json_str + end + + local insert = table.insert + local buffer = {} + + local function format_item(item, current_level) + local indent = string.rep(' ', current_level) + local next_indent = string.rep(' ', current_level + 1) + + if type(item) == 'table' then + -- Check if empty table should be {} or [] + -- In Lua, an empty table from vim.json.decode is ambiguous, + -- but usually, we treat it as an array for compile_commands.json + local is_array = #item > 0 or (next(item) == nil and true) + local opener = is_array and '[' or '{' + local closer = is_array and ']' or '}' + + insert(buffer, opener .. '\n') + local first = true + + -- Use pairs for objects, ipairs for arrays + local iterator = is_array and ipairs(item) or pairs(item) + for k, v in iterator do + if not first then + insert(buffer, ',\n') + end + insert(buffer, next_indent) + if not is_array then + insert(buffer, '"' .. k .. '": ') + end + format_item(v, current_level + 1) + first = false + end + insert(buffer, '\n' .. indent .. closer) + elseif type(item) == 'string' then + -- JSON escaping + insert(buffer, '"' .. item:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"') + else + insert(buffer, tostring(item)) + end + end + + format_item(data, 0) + return table.concat(buffer) +end From 02d97bff5e7490c0ca3be742d2096069968561ce Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 11:13:53 +0300 Subject: [PATCH 0897/1406] update --- lua/platformio/metadata.lua | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index a7216749..4be33b86 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -160,17 +160,19 @@ function M.load_project_config() -- end -- end if vim.fn.filereadable(config_path) == 1 then - local json_data = vim.misc.readFile(config_path) - if json_data then - local ok, table_data = pcall(vim.json.decode, json_data) - if ok and type(table_data) == 'table' then - -- We update _pio_metadata directly to avoid triggering - -- 50+ notifications/restarts during the initial load loop - for k, v in pairs(table_data) do - _pio_metadata[k] = v + if vim.fn.filereadable(config_path) == 1 then + local json_data = vim.misc.readFile(config_path) + if json_data then + local ok, table_data = pcall(vim.json.decode, json_data) + if ok and type(table_data) == 'table' then + -- We update _pio_metadata directly to avoid triggering + -- 50+ notifications/restarts during the initial load loop + for k, v in pairs(table_data) do + _pio_metadata[k] = v + end + last_saved_hash = vim.fn.sha256(json_data) + return end - last_saved_hash = vim.fn.sha256(json_data) - return end end end From 28fa4fce66a1888d41971314050a3dd43816c863 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 11:20:41 +0300 Subject: [PATCH 0898/1406] update --- lua/platformio/metadata.lua | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 4be33b86..a7216749 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -160,19 +160,17 @@ function M.load_project_config() -- end -- end if vim.fn.filereadable(config_path) == 1 then - if vim.fn.filereadable(config_path) == 1 then - local json_data = vim.misc.readFile(config_path) - if json_data then - local ok, table_data = pcall(vim.json.decode, json_data) - if ok and type(table_data) == 'table' then - -- We update _pio_metadata directly to avoid triggering - -- 50+ notifications/restarts during the initial load loop - for k, v in pairs(table_data) do - _pio_metadata[k] = v - end - last_saved_hash = vim.fn.sha256(json_data) - return + local json_data = vim.misc.readFile(config_path) + if json_data then + local ok, table_data = pcall(vim.json.decode, json_data) + if ok and type(table_data) == 'table' then + -- We update _pio_metadata directly to avoid triggering + -- 50+ notifications/restarts during the initial load loop + for k, v in pairs(table_data) do + _pio_metadata[k] = v end + last_saved_hash = vim.fn.sha256(json_data) + return end end end From 4251caa6b50cb13722c05b38ac6988bddb89d1e8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 13:36:40 +0300 Subject: [PATCH 0899/1406] update --- plugin/platformio.lua | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/plugin/platformio.lua b/plugin/platformio.lua index ffa38182..227f7a57 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -8,7 +8,6 @@ local piolsserial = require('platformio.piolsserial') local pio = require('platformio.utils.pio') -local meta = require('platformio.metadata') vim.misc = require('platformio.utils.misc') -- Statusline: Using luaeval for best cross-platform stability @@ -17,16 +16,11 @@ vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("require(\'platformio.meta vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) -- Simple timer to animate the spinner if M.is_busy -vim.fn.timer_start(100, function() - if meta.is_busy then - vim.cmd('redrawstatus') - end -end, { ['repeat'] = -1 }) - --- We use luaeval to call the getter we defined in pio.lua (or metadata.lua) --- vim.o.laststatus = 3 --- -- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' --- vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("require(\'platformio.metadata\').get_pio_status()")} %y %p%% %l:%c' +-- vim.fn.timer_start(100, function() +-- if meta.is_busy then +-- vim.cmd('redrawstatus') +-- end +-- end, { ['repeat'] = -1 }) -- Pioinit vim.api.nvim_create_user_command('Pioinit', function() From d15380ed06fe6598bbfed549b16894b96614d0a9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 13:53:23 +0300 Subject: [PATCH 0900/1406] update --- plugin/platformio.lua | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 227f7a57..8a7b9a67 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -8,7 +8,17 @@ local piolsserial = require('platformio.piolsserial') local pio = require('platformio.utils.pio') -vim.misc = require('platformio.utils.misc') + +-- - Only requires the module the FIRST time you actually try to use vim.pf +setmetatable(vim, { + __index = function(t, k) + if k == 'misc' then + t.misc = require('platformio.utils.misc') + return t.misc + end + end, +}) +-- vim.misc = require('platformio.utils.misc') -- Statusline: Using luaeval for best cross-platform stability vim.o.laststatus = 3 From 14547538704eef81727aa41672a3ff9f3dc69a6c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 14:11:40 +0300 Subject: [PATCH 0901/1406] update --- mini_nvimPlatformio.lua | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 508563b2..200d3c61 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -205,25 +205,34 @@ local plugins = { version = '*', dependencies = 'nvim-tree/nvim-web-devicons', config = function() + require('bufferline').setup({ + options = { + mode = 'buffers', -- set to "tabs" to only show standard vim tabs + separator_style = 'thin', -- options: "slant" | "slope" | "thick" | "thin" + always_show_bufferline = true, + show_buffer_close_icons = true, + show_close_icon = true, + color_icons = true, + + -- Add this if you use NvimTree or Neo-tree to prevent overlap + offsets = { + { + filetype = 'NvimTree', + text = 'File Explorer', + text_align = 'left', + separator = true, + }, + }, + }, + }) require('bufferline').setup({}) end, - options = { - -- mode = 'buffers', -- set to "tabs" to only show tabpages instead - offsets = { - { - filetype = 'NvimTree', - text = 'File Explorer', - text_align = 'left', -- options: "left", "center", "right" - separator = true, - }, - }, - }, -- config = true, -- config = true is shorthand for config = function() require('bufferline').setup() end }, { 'nvim-tree/nvim-tree.lua', - version = '*', + -- version = '*', lazy = false, dependencies = 'nvim-tree/nvim-web-devicons', config = function() From 6aa8ff708b35717e6b1069aecf942a857bbaec34 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 14:13:28 +0300 Subject: [PATCH 0902/1406] update --- mini_nvimPlatformio.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 200d3c61..cd0b4258 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -202,7 +202,6 @@ local plugins = { }, { 'akinsho/bufferline.nvim', - version = '*', dependencies = 'nvim-tree/nvim-web-devicons', config = function() require('bufferline').setup({ From e1ce6338bbfa5b05ba4d5e92a410ea31efb42349 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 14:47:32 +0300 Subject: [PATCH 0903/1406] update --- mini_nvimPlatformio.lua | 161 +++++++++++++++++++++++++--------------- 1 file changed, 102 insertions(+), 59 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index cd0b4258..5d8d879c 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -53,16 +53,11 @@ else vim.opt.shellquote = '' vim.opt.shellxquote = '' end --- Define a custom highlight group --- vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#A6E22E', bold = true }) --- vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) --- vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#e0af68', bold = true }) --- fg = text color, bg = background color -vim.api.nvim_set_hl(0, 'PioStatus', { - fg = '#e0af68', -- Dark text - bg = '#11111b', - bold = true, -}) +-- vim.api.nvim_set_hl(0, 'PioStatus', { +-- fg = '#e0af68', -- Dark text +-- bg = '#11111b', +-- bold = true, +-- }) ---------------------------------------------------------------------------------------- -- INFO: Set diagnostic config vim.diagnostic.config({ @@ -121,7 +116,6 @@ keymap('n', '', ':vertical resize +2') keymap('n', 'bb', ':bprevious', { desc = '[B]efore Buffer' }) keymap('n', 'ba', ':bnext', { desc = '[A]fter Buffer' }) keymap('n', 'bs', ':ball', { desc = '[S]how AllOpened Buffers' }) -keymap('n', 'bp', 'BufferLineTogglePin', { desc = 'Toggle Pin' }) -- keymap('n', 'bd', 'bdelete', { desc = '[D]elete Buffer' }) keymap('n', 'bd', function() @@ -140,16 +134,16 @@ keymap('n', 'bd', function() pcall(vim.api.nvim_buf_delete, bufnr, { force = false }) end, { desc = '[D]elete Buffer' }) -keymap('n', 'bP', 'BufferLineGroupClose ungrouped', { desc = 'Delete Non-Pinned Buffers' }) -keymap('n', 'bo', 'BufferLineCloseOthers', { desc = 'Delete Other Buffers' }) -keymap('n', 'br', 'BufferLineCloseRight', { desc = 'Delete Buffers to the Right' }) -keymap('n', 'bl', 'BufferLineCloseLeft', { desc = 'Delete Buffers to the Left' }) -keymap('n', '', 'BufferLineCyclePrev', { desc = 'Prev Buffer' }) -keymap('n', '', 'BufferLineCycleNext', { desc = 'Next Buffer' }) -keymap('n', '[b', 'BufferLineCyclePrev', { desc = 'Prev Buffer' }) -keymap('n', ']b', 'BufferLineCycleNext', { desc = 'Next Buffer' }) -keymap('n', '[B', 'BufferLineMovePrev', { desc = 'Move buffer prev' }) -keymap('n', ']B', 'BufferLineMoveNext', { desc = 'Move buffer next' }) +-- keymap('n', 'bP', 'BufferLineGroupClose ungrouped', { desc = 'Delete Non-Pinned Buffers' }) +-- keymap('n', 'bo', 'BufferLineCloseOthers', { desc = 'Delete Other Buffers' }) +-- keymap('n', 'br', 'BufferLineCloseRight', { desc = 'Delete Buffers to the Right' }) +-- keymap('n', 'bl', 'BufferLineCloseLeft', { desc = 'Delete Buffers to the Left' }) +-- keymap('n', '', 'BufferLineCyclePrev', { desc = 'Prev Buffer' }) +-- keymap('n', '', 'BufferLineCycleNext', { desc = 'Next Buffer' }) +-- keymap('n', '[b', 'BufferLineCyclePrev', { desc = 'Prev Buffer' }) +-- keymap('n', ']b', 'BufferLineCycleNext', { desc = 'Next Buffer' }) +-- keymap('n', '[B', 'BufferLineMovePrev', { desc = 'Move buffer prev' }) +-- keymap('n', ']B', 'BufferLineMoveNext', { desc = 'Move buffer next' }) keymap('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) keymap('n', '\\', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) @@ -200,32 +194,65 @@ local plugins = { }, }, }, + + -- Recommended: Minimal statusline/tabline { - 'akinsho/bufferline.nvim', - dependencies = 'nvim-tree/nvim-web-devicons', - config = function() - require('bufferline').setup({ - options = { - mode = 'buffers', -- set to "tabs" to only show standard vim tabs - separator_style = 'thin', -- options: "slant" | "slope" | "thick" | "thin" - always_show_bufferline = true, - show_buffer_close_icons = true, - show_close_icon = true, - color_icons = true, - - -- Add this if you use NvimTree or Neo-tree to prevent overlap - offsets = { - { - filetype = 'NvimTree', - text = 'File Explorer', - text_align = 'left', - separator = true, + 'nvim-lualine/lualine.nvim', + dependencies = { + 'nvim-tree/nvim-web-devicons', + config = function() + require('lualine').setup({ + options = { + globalstatus = true, -- Single statusline for all windows + }, + -- This replaces the visual part of bufferline + tabline = { + lualine_a = { + { + 'buffers', + show_filename_only = true, + hide_filename_extension = false, + show_modified_status = true, + mode = 0, -- 0: Shows buffer name + max_length = vim.o.columns, + filetype_names = { + NvimTree = 'Explorer', + TelescopePrompt = 'Telescope', + }, + }, }, }, - }, - }) - require('bufferline').setup({}) - end, + }) + end, + }, + }, + + { + -- 'akinsho/bufferline.nvim', + -- dependencies = 'nvim-tree/nvim-web-devicons', + -- config = function() + -- require('bufferline').setup({ + -- options = { + -- mode = 'buffers', -- set to "tabs" to only show standard vim tabs + -- separator_style = 'thin', -- options: "slant" | "slope" | "thick" | "thin" + -- always_show_bufferline = true, + -- show_buffer_close_icons = true, + -- show_close_icon = true, + -- color_icons = true, + -- + -- -- Add this if you use NvimTree or Neo-tree to prevent overlap + -- offsets = { + -- { + -- filetype = 'NvimTree', + -- text = 'File Explorer', + -- text_align = 'left', + -- separator = true, + -- }, + -- }, + -- }, + -- }) + -- require('bufferline').setup({}) + -- end, -- config = true, -- config = true is shorthand for config = function() require('bufferline').setup() end }, @@ -288,6 +315,11 @@ local plugins = { dependencies = { { 'akinsho/toggleterm.nvim' }, { 'nvim-telescope/telescope.nvim' }, + -- { + -- 'nvim-telescope/telescope.nvim', + -- tag = '0.1.8', + -- dependencies = { 'nvim-lua/plenary.nvim' }, + -- }, { 'nvim-telescope/telescope-ui-select.nvim' }, { 'nvim-lua/plenary.nvim' }, { 'folke/which-key.nvim' }, @@ -304,6 +336,32 @@ local plugins = { } ---------------------------------------------------------------------------------------- +-- 1. Import the actions module (This is the missing part!) +local actions = require('telescope.actions') +require('telescope').setup({ + defaults = { + mappings = { + i = { + [''] = actions.delete_buffer, -- Delete buffer in insert mode + }, + n = { + ['dd'] = actions.delete_buffer, -- Delete buffer in normal mode + }, + }, + }, + pickers = { + buffers = { + show_all_buffers = true, + sort_lastused = true, + theme = 'dropdown', -- Compact look + previewer = false, -- Disable preview for a faster feel + }, + }, +}) + +-- Keymap to open the buffer list +vim.keymap.set('n', 'fb', 'Telescope buffers', { desc = 'Find Buffers' }) + ---------------------------------------------------------------------------------------- -- INFO: Install/config plugins require('lazy').setup(plugins, { @@ -342,21 +400,6 @@ vim.api.nvim_create_autocmd('User', { end, }) --- INFO: refreshes the statusline whenever you enter a C/C++ file --- vim.api.nvim_create_autocmd({ 'BufEnter', 'FileType' }, { --- pattern = { 'c', 'cpp', 'objc', 'objcpp', 'h', 'hpp' }, --- callback = function() --- -- Assuming your module is required as 'pio' --- if _G.metadata then --- -- 1. Run your refresh logic --- require('platformio.metadata').refresh_statusline() --- --- -- 2. Force an immediate visual repaint of the status bar --- -- This is the 'secret sauce' for %{ } expressions --- vim.cmd('redrawstatus') --- end --- end, --- }) ---------------------------------------------------------------------------------------- -- INFO: set up python nvim venv (virtual environment 'nenv'), activaten. local platformio_core_dir, pynvim_env, pynvim_python, pynvim_lib, pynvim_bin, pynvim_activate From cda2feea08f019eba06e681d7fcc0d870d66aa69 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 14:54:57 +0300 Subject: [PATCH 0904/1406] update --- mini_nvimPlatformio.lua | 40 ++++++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 5d8d879c..cf80e707 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -338,27 +338,31 @@ local plugins = { -- 1. Import the actions module (This is the missing part!) local actions = require('telescope.actions') -require('telescope').setup({ - defaults = { - mappings = { - i = { - [''] = actions.delete_buffer, -- Delete buffer in insert mode - }, - n = { - ['dd'] = actions.delete_buffer, -- Delete buffer in normal mode +local telescope = require('telescope') +local tok, telescope = pcall(require, 'telescope') +if tok then + -- print("here" .. vim.inspect(pioConfig)) + telescope.setup({ + defaults = { + mappings = { + i = { + [''] = actions.delete_buffer, -- Delete buffer in insert mode + }, + n = { + ['dd'] = actions.delete_buffer, -- Delete buffer in normal mode + }, }, }, - }, - pickers = { - buffers = { - show_all_buffers = true, - sort_lastused = true, - theme = 'dropdown', -- Compact look - previewer = false, -- Disable preview for a faster feel + pickers = { + buffers = { + show_all_buffers = true, + sort_lastused = true, + theme = 'dropdown', -- Compact look + previewer = false, -- Disable preview for a faster feel + }, }, - }, -}) - + }) +end -- Keymap to open the buffer list vim.keymap.set('n', 'fb', 'Telescope buffers', { desc = 'Find Buffers' }) From b59ef1a416b19ce68a3de10dce9fca514835dacc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 15:00:26 +0300 Subject: [PATCH 0905/1406] update --- mini_nvimPlatformio.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index cf80e707..0186a7b6 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -336,11 +336,11 @@ local plugins = { } ---------------------------------------------------------------------------------------- --- 1. Import the actions module (This is the missing part!) -local actions = require('telescope.actions') -local telescope = require('telescope') local tok, telescope = pcall(require, 'telescope') if tok then + -- 1. Import the actions module (This is the missing part!) + local actions = require('telescope.actions') + local telescope = require('telescope') -- print("here" .. vim.inspect(pioConfig)) telescope.setup({ defaults = { From 6a1a14a21f1d38308275c4159bcd2f88ad382c2a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 15:02:05 +0300 Subject: [PATCH 0906/1406] update --- mini_nvimPlatformio.lua | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 0186a7b6..d2243289 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -53,11 +53,11 @@ else vim.opt.shellquote = '' vim.opt.shellxquote = '' end --- vim.api.nvim_set_hl(0, 'PioStatus', { --- fg = '#e0af68', -- Dark text --- bg = '#11111b', --- bold = true, --- }) +vim.api.nvim_set_hl(0, 'PioStatus', { + fg = '#e0af68', -- Dark text + bg = '#11111b', + bold = true, +}) ---------------------------------------------------------------------------------------- -- INFO: Set diagnostic config vim.diagnostic.config({ From 44f7d58c2bf7639830a2ced001dba05facde73b2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 15:05:45 +0300 Subject: [PATCH 0907/1406] update --- mini_nvimPlatformio.lua | 59 ++++++++++++++++++++--------------------- 1 file changed, 29 insertions(+), 30 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index d2243289..a6dc8621 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -336,36 +336,6 @@ local plugins = { } ---------------------------------------------------------------------------------------- -local tok, telescope = pcall(require, 'telescope') -if tok then - -- 1. Import the actions module (This is the missing part!) - local actions = require('telescope.actions') - local telescope = require('telescope') - -- print("here" .. vim.inspect(pioConfig)) - telescope.setup({ - defaults = { - mappings = { - i = { - [''] = actions.delete_buffer, -- Delete buffer in insert mode - }, - n = { - ['dd'] = actions.delete_buffer, -- Delete buffer in normal mode - }, - }, - }, - pickers = { - buffers = { - show_all_buffers = true, - sort_lastused = true, - theme = 'dropdown', -- Compact look - previewer = false, -- Disable preview for a faster feel - }, - }, - }) -end --- Keymap to open the buffer list -vim.keymap.set('n', 'fb', 'Telescope buffers', { desc = 'Find Buffers' }) - ---------------------------------------------------------------------------------------- -- INFO: Install/config plugins require('lazy').setup(plugins, { @@ -473,6 +443,35 @@ end ---------------------------------------------------------------------------------------- -- INFO: configure nvim-platformio and load ----------------------------------------------------------------------------------------- +local tok, telescope = pcall(require, 'telescope') +if tok then + -- 1. Import the actions module (This is the missing part!) + local actions = require('telescope.actions') + -- local telescope = require('telescope') + -- print("here" .. vim.inspect(pioConfig)) + telescope.setup({ + defaults = { + mappings = { + i = { + [''] = actions.delete_buffer, -- Delete buffer in insert mode + }, + n = { + ['dd'] = actions.delete_buffer, -- Delete buffer in normal mode + }, + }, + }, + pickers = { + buffers = { + show_all_buffers = true, + sort_lastused = true, + theme = 'dropdown', -- Compact look + previewer = false, -- Disable preview for a faster feel + }, + }, + }) +end +-- Keymap to open the buffer list +vim.keymap.set('n', 'fb', 'Telescope buffers', { desc = 'Find Buffers' }) local pioConfig = { lspClangd = { -- enabled = false, From f3646114e2e3f4dd18a368fc9cd92d521d4b4a4f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 15:10:29 +0300 Subject: [PATCH 0908/1406] update --- mini_nvimPlatformio.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index a6dc8621..27be8ac5 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -53,6 +53,7 @@ else vim.opt.shellquote = '' vim.opt.shellxquote = '' end +vim.hl = vim.highlight vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#e0af68', -- Dark text bg = '#11111b', From 955b3899b59cf9e90bb4cf2ba9e695165710c2d3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 15:54:07 +0300 Subject: [PATCH 0909/1406] update --- plugin/platformio.lua | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 8a7b9a67..e093c585 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -6,9 +6,6 @@ -- +: At least one argument. -- -1: Zero or one argument (like ?, explicitly). -local piolsserial = require('platformio.piolsserial') -local pio = require('platformio.utils.pio') - -- - Only requires the module the FIRST time you actually try to use vim.pf setmetatable(vim, { __index = function(t, k) @@ -19,6 +16,8 @@ setmetatable(vim, { end, }) -- vim.misc = require('platformio.utils.misc') +local piolsserial = require('platformio.piolsserial') +local pio = require('platformio.utils.pio') -- Statusline: Using luaeval for best cross-platform stability vim.o.laststatus = 3 From eed30ba203870897fd69dcf5f1647e97f0b2227b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 15:56:47 +0300 Subject: [PATCH 0910/1406] update --- plugin/platformio.lua | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/plugin/platformio.lua b/plugin/platformio.lua index e093c585..9fbdc8a2 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -7,15 +7,15 @@ -- -1: Zero or one argument (like ?, explicitly). -- - Only requires the module the FIRST time you actually try to use vim.pf -setmetatable(vim, { - __index = function(t, k) - if k == 'misc' then - t.misc = require('platformio.utils.misc') - return t.misc - end - end, -}) --- vim.misc = require('platformio.utils.misc') +-- setmetatable(vim, { +-- __index = function(t, k) +-- if k == 'misc' then +-- t.misc = require('platformio.utils.misc') +-- return t.misc +-- end +-- end, +-- }) +vim.misc = require('platformio.utils.misc') local piolsserial = require('platformio.piolsserial') local pio = require('platformio.utils.pio') From 12aefb34b807489b3ec83d8ad5dccc1cadffb49d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 18:11:09 +0300 Subject: [PATCH 0911/1406] update --- lua/platformio/metadata.lua | 38 ++----- lua/platformio/pio_setup.lua | 140 +++++++++++++++++-------- lua/platformio/utils/misc.lua | 8 +- tmp.lua | 187 +++++++++++++++++++++++++--------- 4 files changed, 252 insertions(+), 121 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index a7216749..7ea5f818 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -23,35 +23,6 @@ function M.get_pio_status() end return string.format(' [ %s ] ', active) end --- _G.get_pio_status = function() --- -- Add a manual check for the metatable if it exists --- local val = _G.metadata and _G.metadata.active_env --- if val and val ~= '' then --- return ' [ ' .. val .. '] ' --- end --- return '' --- end --- _G.get_pio_status = function() --- if _G.metadata and _G.metadata.active_env ~= '' then --- return ' [ ' .. _G.metadata.active_env .. '] ' --- end --- return '' --- end --- Move the %#PioStatus# and %* outside of the curly braces --- vim.o.statusline = '%f %m %r %= %#PioStatus#%{v:lua.get_pio_status()}%* %y %p%% %l:%c' - --- The Statusline Getter (used by the UI) --- function M.get_pio_status() --- -- Using pcall ensures that if 'require' or 'metadata' fails, --- -- the statusline just shows nothing instead of throwing an error. --- local ok, status = pcall(function() --- if _G.metadata and _G.metadata.active_env and _G.metadata.active_env ~= '' then --- return string.format(' [ %s ] ', _G.metadata.active_env) --- end --- return '' --- end) --- return ok and status or '' --- end ------------------------------------------------------------------------------------------------------- local last_saved_hash = '' local config_path = vim.fs.joinpath(vim.uv.cwd(), '.project_config.json') @@ -68,6 +39,15 @@ local _pio_metadata = { platforms_dir = '', query_driver = '', cc_compiler = '', + includes_build = {}, + includes_comaptlib = {}, + includes_toolchain = {}, + cc_path = '', + cc_flags = {}, + cxx_path = '', + cxx_flags = {}, + gdb_path = '', + defines = {}, triplet = '', toolchain_root = '', sysroot = '', diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 197802e5..718f4fa8 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -62,15 +62,16 @@ function M.get_sysroot_triplet(cc_compiler) return nil end - -- INFO: 1. The Core PIO Manager & Generic Extractor --- stylua: ignore +--- stylua: ignore M.pio_manager = (function() local cache = nil -- Stores the decoded platformio.ini JSON structure -- INFO: local function find_in_data(data, section_name, key_name) -- Safety check: Ensure data is a valid table from a successful JSON decode - if type(data) ~= 'table' then return nil end + if type(data) ~= 'table' then + return nil + end for _, section in ipairs(data) do -- Each section must be a table with at least 2 elements: [1]=name, [2]=content @@ -97,7 +98,6 @@ M.pio_manager = (function() end -- INFO: ASYNC REFRESH: Fetches the latest config from PlatformIO CLI - --- stylua: ignore local function refresh(callback) vim.schedule(function() vim.notify('PIO: Fetching Config ...', vim.log.levels.INFO) @@ -127,46 +127,104 @@ M.pio_manager = (function() if ok and raw_data then local _, data = next(raw_data) if data then - local fallbackFlags = {} - -- 1. Process Includes - if data.includes then - for category, paths in pairs(data.includes) do - -- If it's a toolchain path, use -isystem to suppress warnings - -- and tell clangd these are standard libraries - if category == 'toolchain' then - local flag = '-isystem' - for _, path in ipairs(paths) do - -- table.insert(fallbackFlags, string.format('%q', flag)) - -- table.insert(fallbackFlags, string.format('%q', path:gsub('\\', '/'))) - table.insert(fallbackFlags, string.format('%q', flag .. path:gsub('\\', '/'))) - end + -- 1. Process cc_compiler + if data.cc_path then + _G.metadata.query_driver = '' + _G.metadata.includes_build = {} + _G.metadata.includes_comaptlib = {} + _G.metadata.includes_toolchain = {} + _G.metadata.cc_flags = {} + _G.metadata.cxx_path = '' + _G.metadata.cxx_flags = {} + _G.metadata.gdb_path = '' + _G.metadata.defines = {} + _G.metadata.triplet = '' + _G.metadata.toolchain_root = '' + _G.metadata.sysroot = '' + _G.metadata.cc_compiler = misc.normalizePath(data.cc_path) or '' + _G.metadata.cc_path = misc.normalizePath(data.cc_path) or '' + + -- 2. Process cc_flags + if data.cc_flags then + local cc_flags = {} + for _, flag in ipairs(data.cc_flags) do + table.insert(cc_flags, string.format('%q', flag)) end - -- local flag = (category == 'toolchain') and '-isystem' or '-I' - -- for _, path in ipairs(paths) do - -- table.insert(fallbackFlags, flag .. path) - -- end + _G.metadata.cc_flags = cc_flags end - end - -- 2. Process Defines - if data.defines then - for _, define in ipairs(data.defines) do - table.insert(fallbackFlags, string.format('%q', '-D' .. define)) + + -- 3. Process cxx_compiler + if data.cxx_path then + _G.metadata.cxx_path = misc.normalizePath(data.cxx_path) or '' + end + + -- 4. Process cxx_flags + if data.cxx_flags then + local cxx_flags = {} + for _, flag in ipairs(data.cxx_flags) do + table.insert(cxx_flags, string.format('%q', flag)) + end + _G.metadata.cxx_flags = cxx_flags + end + + -- 5. Process gdb_path + if data.gdb_path then + _G.metadata.gdb_path = misc.normalizePath(data.gdb_path) or '' end - end - -- get [cc_compiler]and [falbackFlags] - -- _G.metadata.query_driver = misc.normalize_path(env.cc_compiler:match('(.*[/\\])') .. '*') or '**' - _G.metadata.cc_compiler = misc.normalizePath(data.cc_path) or '' - _G.metadata.fallbackFlags = misc.normalizeFlags(fallbackFlags) - - pcall(M.get_sysroot_triplet, _G.metadata.cc_compiler) - -- print(vim.inspect(_G.metadata)) - -- if callback then - -- vim.schedule(function() - -- vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) - -- callback() - -- end) - -- end + -- 6. Process Defines + if data.defines then + local defines = {} + for _, define in ipairs(data.defines) do + table.insert(defines, string.format('%q', define)) + end + _G.metadata.defines = defines + end + + -- 7. Process Includes + if data.includes then + for category, paths in pairs(data.includes) do + -- 7.1 Process Includes_build + if category == 'build' then + local includes_build = {} + local flag = '-I' + for _, path in ipairs(paths) do + table.insert(includes_build, string.format('%q', flag .. misc.normalizePath(path))) + end + _G.metadata.includes_build = includes_build + end + + -- 7.2 Process includes_toolchain + if category == 'toolchain' then + local includes_toolchain = {} + local flag = '-isystem' + for _, path in ipairs(paths) do + table.insert(includes_toolchain, string.format('%q', flag .. misc.normalizePath(path))) + end + _G.metadata.includes_toolchain = includes_toolchain + end + + -- 7.3 Process includes_compatlib + if category == 'compatlib' then + local includes_compatlib = {} + local flag = '-isystem' + for _, path in ipairs(paths) do + table.insert(includes_compatlib, string.format('%q', flag .. misc.normalizePath(path))) + end + _G.metadata.includes_build = includes_compatlib + end + end + end + + pcall(M.get_sysroot_triplet, _G.metadata.cc_compiler) + -- print(vim.inspect(_G.metadata)) + -- if callback then + -- vim.schedule(function() + -- vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) + -- callback() + -- end) + -- end + end end else vim.schedule(function() @@ -226,7 +284,7 @@ M.pio_manager = (function() local key, val = kv[1], kv[2] if key ~= nil then -- if _G.metadata[key] ~= nil then -_G.metadata[key] = ((type(val) == 'table' and next(val) ~= nil) or (type(val) == "string" and val ~= '')) and misc.normalizePath(val) or val + _G.metadata[key] = ((type(val) == 'table' and next(val) ~= nil) or (type(val) == 'string' and val ~= '')) and misc.normalizePath(val) or val end end -- 2. Extract all hardware [envs] like [env:seeed_xiao_esp32c3], skipping generic [env] diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 31e9bbf7..d3a3d97b 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -251,11 +251,11 @@ Cleans and repairs compiler flags in a command string. -F: (macOS/iOS) Path to search for frameworks. ]] -- stylua: ignore ---- @param cmd string: The raw command string (e.g., from compile_commands.json) +--- @param flags string: The raw command string (e.g., from compile_commands.json) --- @return string: The cleaned command string --INFO: -function M.normalizeFlags(cmd) - if not cmd or cmd == '' then +function M.normalizeFlags(flags) + if not flags or flags == '' then return '' end @@ -265,7 +265,7 @@ function M.normalizeFlags(cmd) -- %S* : Matches zero or more non-space characters -- \\ : Matches a literal backslash (identifies it as a Windows path) -- %S* : Matches the rest of the non-space characters in that flag - local cleaned_cmd = cmd:gsub('(%-%S-\\S*)', function(flag) + local cleaned_cmd = flags:gsub('(%-%S-\\S*)', function(flag) --2. Normalize Slashes -- Replaces any number of backslashes (single \ or JSON-escaped \\) with one forward slash. -- Forward slashes are safer and more portable for compilers like GCC/Clang. diff --git a/tmp.lua b/tmp.lua index a4e48ab4..fade3c9d 100644 --- a/tmp.lua +++ b/tmp.lua @@ -1,51 +1,144 @@ -function M.pretty_print_json_string(json_str) - -- 1. Convert JSON string to Lua table - local ok, data = pcall(vim.json.decode, json_str) - if not ok then - print('Error: Invalid JSON string provided') - return json_str - end - - local insert = table.insert - local buffer = {} - - local function format_item(item, current_level) - local indent = string.rep(' ', current_level) - local next_indent = string.rep(' ', current_level + 1) - - if type(item) == 'table' then - -- Check if empty table should be {} or [] - -- In Lua, an empty table from vim.json.decode is ambiguous, - -- but usually, we treat it as an array for compile_commands.json - local is_array = #item > 0 or (next(item) == nil and true) - local opener = is_array and '[' or '{' - local closer = is_array and ']' or '}' - - insert(buffer, opener .. '\n') - local first = true - - -- Use pairs for objects, ipairs for arrays - local iterator = is_array and ipairs(item) or pairs(item) - for k, v in iterator do - if not first then - insert(buffer, ',\n') +local function get_metadata(attempts, env) + local active_env = env or _G.metadata.active_env + vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(int_obj) + vim.schedule(function() + vim.notify('PIO: Fetching metadata ...', vim.log.levels.INFO) + + if int_obj.code ~= 0 then + -- Schedule notification to avoid error in the system callback thread + vim.schedule(function() + if int_obj.code == 127 then + vim.notify("PIO Manager metadata: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + else + vim.notify('PIO Manager metadata: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + end + end) + return + end + + if int_obj.code == 0 and int_obj.stdout then + local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) + if ok and raw_data then + local _, data = next(raw_data) + if data then + -- 2. Process cc_compiler + if data.cc_path then + _G.metadata.query_driver = '' + _G.metadata.includes_build = {} + _G.metadata.includes_comaptlib = {} + _G.metadata.includes_toolchain = {} + _G.metadata.cc_flags = {} + _G.metadata.cxx_path = '' + _G.metadata.cxx_flags = {} + _G.metadata.gdb_path = '' + _G.metadata.defines = {} + _G.metadata.triplet = '' + _G.metadata.toolchain_root = '' + _G.metadata.sysroot = '' + _G.metadata.cc_compiler = misc.normalizePath(data.cc_path) or '' + _G.metadata.cc_path = misc.normalizePath(data.cc_path) or '' + + -- 1. Process Includes + if data.includes then + for category, paths in pairs(data.includes) do + -- 1.1 Process Includes_build + if category == 'build' then + local includes_build = {} + local flag = '-I' + for _, path in ipairs(paths) do + table.insert(includes_build, string.format('%q', flag .. misc.normalizePath(path))) + end + _G.metadata.includes_build = includes_build + end + + -- 1.2 Process includes_toolchain + if category == 'toolchain' then + local includes_toolchain = {} + local flag = '-isystem' + for _, path in ipairs(paths) do + table.insert(includes_toolchain, string.format('%q', flag .. misc.normalizePath(path))) + end + _G.metadata.includes_toolchain = includes_toolchain + end + + -- 1.3 Process includes_compatlib + if category == 'compatlib' then + local includes_compatlib = {} + local flag = '-isystem' + for _, path in ipairs(paths) do + table.insert(includes_compatlib, string.format('%q', flag .. misc.normalizePath(path))) + end + _G.metadata.includes_build = includes_compatlib + end + end + end + + -- 3. Process cc_flags + if data.cc_flags then + local cc_flags = {} + for _, flag in ipairs(data.cc_flags) do + table.insert(cc_flags, string.format('%q', flag)) + end + _G.metadata.cc_flags = cc_flags + end + + -- 4. Process cxx_compiler + if data.cxx_path then + _G.metadata.cxx_path = misc.normalizePath(data.cxx_path) or '' + end + + -- 5. Process cxx_flags + if data.cxx_flags then + local cxx_flags = {} + for _, flag in ipairs(data.cxx_flags) do + table.insert(cxx_flags, string.format('%q', flag)) + end + _G.metadata.cxx_flags = cxx_flags + end + + -- 6. Process gdb_path + if data.gdb_path then + _G.metadata.gdb_path = misc.normalizePath(data.gdb_path) or '' + end + + -- 7. Process Defines + if data.defines then + local defines = {} + for _, define in ipairs(data.defines) do + table.insert(defines, string.format('%q', define)) + end + _G.metadata.defines = defines + end + + pcall(M.get_sysroot_triplet, _G.metadata.cc_compiler) + -- print(vim.inspect(_G.metadata)) + -- if callback then + -- vim.schedule(function() + -- vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) + -- callback() + -- end) + -- end + end + end + else + vim.schedule(function() + vim.notify('PIO: Syncing Environment failed', vim.log.levels.WARN) + end) end - insert(buffer, next_indent) - if not is_array then - insert(buffer, '"' .. k .. '": ') + end + -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save + if attempts > 0 then + vim.defer_fn(function() + get_metadata(attempts - 1) + end, 500) + else + if callback then + vim.schedule(function() + vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) + callback() + end) end - format_item(v, current_level + 1) - first = false end - insert(buffer, '\n' .. indent .. closer) - elseif type(item) == 'string' then - -- JSON escaping - insert(buffer, '"' .. item:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"') - else - insert(buffer, tostring(item)) - end - end - - format_item(data, 0) - return table.concat(buffer) + end) + end) end From 4c057213961771236b99e70e418a4bfec60672cb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 19:54:58 +0300 Subject: [PATCH 0912/1406] update --- lua/platformio/boilerplate.lua | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index b69c7521..15f4cc9c 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -49,9 +49,12 @@ extra_scripts = lib_ldf_mode = chain ;Library dependencies Finder ldf -;build_flags = -; -I${sysenv.HOMEPATH}/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0 -; -I${platformio.packages_dir}/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0 +build_flags = + -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0 + -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0/riscv32-esp-elf + -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include + -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include-fixed + -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include ; -D COMPILATIONDB_INCLUDE_TOOLCHAIN ]], content = function(self) From a1f8eaabede6fccc7fd863b4a1c86f63c7f7d897 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 20:49:23 +0300 Subject: [PATCH 0913/1406] update --- lua/platformio/boilerplate.lua | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 15f4cc9c..7534105f 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -87,6 +87,7 @@ boilerplate['.clangd_config'] = { "--fallback-style=llvm", "--log=error", "--pch-storage=memory", + "--check-gcc-install", "--pretty", "--ranking-model=decision_forest", "--sync", @@ -158,6 +159,9 @@ boilerplate['.clangd'] = { -- template = [[ content = [[ CompileFlags: + Add: + - "-target" + - "riscv32-esp-els" Remove: - "-fno-fat-lto-objects" - "-fno%%-fat%%-lto%%-objects" From fd845fada6fdeb0e90523664cef450487600b7c8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 20:56:34 +0300 Subject: [PATCH 0914/1406] update --- lua/platformio/boilerplate.lua | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 7534105f..e76d6853 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -160,9 +160,12 @@ boilerplate['.clangd'] = { content = [[ CompileFlags: Add: + - "-xc++" + - "--include-directory=C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0" + - "--include-directory=C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0/riscv32-esp-elf" + Remove: - "-target" - "riscv32-esp-els" - Remove: - "-fno-fat-lto-objects" - "-fno%%-fat%%-lto%%-objects" - "-fno%%-canonical%%-system%%-headers" From 25b0f0fc71403525bbe5e7b2c21cff4382b4b268 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 21:02:18 +0300 Subject: [PATCH 0915/1406] update --- lua/platformio/boilerplate.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index e76d6853..44d46557 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -87,7 +87,6 @@ boilerplate['.clangd_config'] = { "--fallback-style=llvm", "--log=error", "--pch-storage=memory", - "--check-gcc-install", "--pretty", "--ranking-model=decision_forest", "--sync", From b7c69235303e4d1d686f8728408b9168d82731a6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 21:10:54 +0300 Subject: [PATCH 0916/1406] update --- lua/platformio/boilerplate.lua | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 44d46557..9d23a3df 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -146,6 +146,11 @@ clangd end, } +-- - "--include-directory=C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0" +-- - "--include-directory=C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0/riscv32-esp-elf" +-- +-- - "-target" +-- - "riscv32-esp-els" -- -- Add: -- - %q -- - %q @@ -160,11 +165,7 @@ boilerplate['.clangd'] = { CompileFlags: Add: - "-xc++" - - "--include-directory=C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0" - - "--include-directory=C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0/riscv32-esp-elf" Remove: - - "-target" - - "riscv32-esp-els" - "-fno-fat-lto-objects" - "-fno%%-fat%%-lto%%-objects" - "-fno%%-canonical%%-system%%-headers" From f4a66b079517ba2ec441aa06e856db0053bfe425 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 21:27:05 +0300 Subject: [PATCH 0917/1406] update --- lua/platformio/boilerplate.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 9d23a3df..f2f840d2 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -146,11 +146,11 @@ clangd end, } +-- Add: +-- - "-xc++" -- - "--include-directory=C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0" -- - "--include-directory=C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0/riscv32-esp-elf" -- --- - "-target" --- - "riscv32-esp-els" -- -- Add: -- - %q -- - %q @@ -163,9 +163,9 @@ boilerplate['.clangd'] = { -- template = [[ content = [[ CompileFlags: - Add: - - "-xc++" Remove: + - "-target" + - "riscv32-esp-els" - "-fno-fat-lto-objects" - "-fno%%-fat%%-lto%%-objects" - "-fno%%-canonical%%-system%%-headers" From edffa753825a294c50763bd4c953102bf8a6d744 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 21:35:28 +0300 Subject: [PATCH 0918/1406] update --- lua/platformio/boilerplate.lua | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index f2f840d2..1e39a61f 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -49,12 +49,12 @@ extra_scripts = lib_ldf_mode = chain ;Library dependencies Finder ldf -build_flags = - -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0 - -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0/riscv32-esp-elf - -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include - -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include-fixed - -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include +;build_flags = +; -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0 +; -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0/riscv32-esp-elf +; -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include +; -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include-fixed +; -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include ; -D COMPILATIONDB_INCLUDE_TOOLCHAIN ]], content = function(self) From 8eba14923c86a3c88f010af52dbe25df3e90c08e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 22:01:19 +0300 Subject: [PATCH 0919/1406] update --- lua/platformio/lsp/clangd.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua index 05e07b93..460879d8 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -126,6 +126,7 @@ function _G.get_clangd_config() local cok, clangd_config = pcall(function() return load('return ' .. formatted_str)() end) if cok and clangd_config then + print(clangd_config) return clangd_config end end From 6667dba87e51138da1bc8cff6e93876197766f17 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 22:07:39 +0300 Subject: [PATCH 0920/1406] update --- lua/platformio/lsp/clangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua index 460879d8..9a6f786a 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -126,7 +126,7 @@ function _G.get_clangd_config() local cok, clangd_config = pcall(function() return load('return ' .. formatted_str)() end) if cok and clangd_config then - print(clangd_config) + print(vim.inspect(clangd_config)) return clangd_config end end From dc74caefaa014633d29264a228b217baf746f58c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 22:38:05 +0300 Subject: [PATCH 0921/1406] update --- lua/platformio/lsp/clangd.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua index 9a6f786a..fa4e31a3 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -109,8 +109,9 @@ function _G.get_clangd_config() -- 2. Run your toolchain detection if _G.metadata and _G.metadata.cc_compiler and _G.metadata.cc_compiler ~= '' then if _G.metadata.triplet and _G.metadata.triplet ~= '' then - local include_flags = table.concat(_G.metadata.fallbackFlags, ", ") - f_flags = string.format([["-std=c++17", "--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, include_flags) + -- local include_flags = table.concat(_G.metadata.fallbackFlags, ", ") + local includes_toolchain = table.concat(_G.metadata.includes_toolchain, ", ") + f_flags = string.format([["-std=c++17", "--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, includes_toolchain) -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) From d4da16c0b5e9cbde44436f34b9d9dd565e372e00 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 22:48:20 +0300 Subject: [PATCH 0922/1406] update --- lua/platformio/lsp/clangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua index fa4e31a3..8a1fff65 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -111,7 +111,7 @@ function _G.get_clangd_config() if _G.metadata.triplet and _G.metadata.triplet ~= '' then -- local include_flags = table.concat(_G.metadata.fallbackFlags, ", ") local includes_toolchain = table.concat(_G.metadata.includes_toolchain, ", ") - f_flags = string.format([["-std=c++17", "--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, includes_toolchain) + f_flags = string.format([["-std=c++17", "-xc++", "--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, includes_toolchain) -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) From 0a0d71718f8fa2dfb63f60171f52c9970473ee8c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 22:59:09 +0300 Subject: [PATCH 0923/1406] update --- lua/platformio/boilerplate.lua | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 1e39a61f..2bb64959 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -162,6 +162,10 @@ boilerplate['.clangd'] = { read = false, -- template = [[ content = [[ +Index: + background: Build + External: + File: .clangd_index CompileFlags: Remove: - "-target" From ee096225593126de90ffa1bfeb8878bc24b9c0ce Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 23:02:36 +0300 Subject: [PATCH 0924/1406] update --- lua/platformio/lsp/clangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua index 8a1fff65..26c286fd 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -121,7 +121,7 @@ function _G.get_clangd_config() -- 3. Format your template string local table_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) - local formatted_str = string.format(table_config, q_driver, f_flags, new_root_dir) + local formatted_str = string.format(table_config, q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) -- 4. Load the config table local cok, clangd_config = pcall(function() return load('return ' .. formatted_str)() end) From c818b53169439c1a30af0fee19484fd0a4fcb55a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 23:13:01 +0300 Subject: [PATCH 0925/1406] update --- lua/platformio/boilerplate.lua | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 2bb64959..58cd4d30 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -167,6 +167,9 @@ Index: External: File: .clangd_index CompileFlags: + Add: + - "-xc++" + - "-std=c++17" Remove: - "-target" - "riscv32-esp-els" From 06f7ba8e83abc3515cf92757c851c5ac19ea3f50 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 23:15:37 +0300 Subject: [PATCH 0926/1406] update --- lua/platformio/boilerplate.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 58cd4d30..9b0d20c9 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -168,8 +168,10 @@ Index: File: .clangd_index CompileFlags: Add: + Add: - "-xc++" - "-std=c++17" + - "-D__cplusplus=201703L" # Manually define the C++ macro Remove: - "-target" - "riscv32-esp-els" From 123d5a447adebdddefb8b27e722f5eb596446f82 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 23:34:06 +0300 Subject: [PATCH 0927/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/lsp/clangd.lua | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 9b0d20c9..aee41625 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -174,7 +174,7 @@ CompileFlags: - "-D__cplusplus=201703L" # Manually define the C++ macro Remove: - "-target" - - "riscv32-esp-els" + - "riscv32-esp-elf" - "-fno-fat-lto-objects" - "-fno%%-fat%%-lto%%-objects" - "-fno%%-canonical%%-system%%-headers" diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua index 26c286fd..2d351401 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -111,7 +111,7 @@ function _G.get_clangd_config() if _G.metadata.triplet and _G.metadata.triplet ~= '' then -- local include_flags = table.concat(_G.metadata.fallbackFlags, ", ") local includes_toolchain = table.concat(_G.metadata.includes_toolchain, ", ") - f_flags = string.format([["-std=c++17", "-xc++", "--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, includes_toolchain) + f_flags = string.format([["-std=c++17", "-xc++", "-D__cplusplus=201703L", "--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, includes_toolchain) -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) From 04938cddae3b75891b154993f41c1d657c3ed726 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 23:42:08 +0300 Subject: [PATCH 0928/1406] update --- lua/platformio/boilerplate.lua | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index aee41625..2f06be66 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -162,16 +162,16 @@ boilerplate['.clangd'] = { read = false, -- template = [[ content = [[ -Index: - background: Build - External: - File: .clangd_index CompileFlags: Add: - Add: - "-xc++" - "-std=c++17" - - "-D__cplusplus=201703L" # Manually define the C++ macro + - "-D__cplusplus=201703L" + - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0" + - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0/riscv32-esp-elf" + - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include" + - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include-fixed" + - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include" Remove: - "-target" - "riscv32-esp-elf" @@ -208,6 +208,10 @@ Diagnostics: - "bugprone-*" - "hicpp-vararg" - "modernize-*" +Index: + background: Build + External: + File: .clangd_index ]], -- content = function(self) -- local sysroot = '--sysroot=' .. _G.metadata.sysroot From a191d998aaa7fb368d45e1bd7088435c2eadd2ff Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 23:49:38 +0300 Subject: [PATCH 0929/1406] update --- lua/platformio/boilerplate.lua | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 2f06be66..a26f7432 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -209,9 +209,15 @@ Diagnostics: - "hicpp-vararg" - "modernize-*" Index: - background: Build + Background: Build External: File: .clangd_index +CompileFlags: + Add: + Add: + - "-xc++" + - "-std=c++17" + - "-D__cplusplus=201703L" # Manually define the C++ macro ]], -- content = function(self) -- local sysroot = '--sysroot=' .. _G.metadata.sysroot From ac48cef788c40a24c2c6ca1254e8f9e1a89de2d8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 22 Apr 2026 23:59:04 +0300 Subject: [PATCH 0930/1406] update --- lua/platformio/lsp/clangd.lua | 2 +- lua/platformio/pio_setup.lua | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua index 2d351401..661c9c92 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -127,7 +127,7 @@ function _G.get_clangd_config() local cok, clangd_config = pcall(function() return load('return ' .. formatted_str)() end) if cok and clangd_config then - print(vim.inspect(clangd_config)) + -- print(vim.inspect(clangd_config)) return clangd_config end end diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 718f4fa8..e8f13e4f 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -586,6 +586,7 @@ function M.init() -- INFO: create clangd required files ----------------------------------------------------------------------------------------- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) boilerplate.core_dir = _G.metadata.core_dir boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) From 67e25072de1f0265da2968b24e783e0614a3dd77 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 00:05:55 +0300 Subject: [PATCH 0931/1406] update --- lua/platformio/pio_setup.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index e8f13e4f..e63cb92d 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -587,6 +587,7 @@ function M.init() ----------------------------------------------------------------------------------------- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') + print(vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) boilerplate.core_dir = _G.metadata.core_dir boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) From 735e3249103184852042e1de62b459b1bc4e9955 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 00:06:41 +0300 Subject: [PATCH 0932/1406] update --- lua/platformio/metadata.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 7ea5f818..ce4c77e5 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -66,7 +66,7 @@ _G.metadata = setmetatable({}, { -- Trigger background actions vim.schedule(function() - M.save_project_config(true) + -- M.save_project_config(true) if key == 'toolchain_root' then vim.notify('Env: ' .. value, vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) pcall(function() From e1ca6c913086017ded0f82c4875fe183ef574c4f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 00:19:32 +0300 Subject: [PATCH 0933/1406] update --- lua/platformio/pio_setup.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index e63cb92d..d075a7e7 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -586,8 +586,9 @@ function M.init() -- INFO: create clangd required files ----------------------------------------------------------------------------------------- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') - print(vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') + -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') + boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') + print(vim.env.XDG_CONFIG_HOME .. '/clangd', '/config.yaml') -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) boilerplate.core_dir = _G.metadata.core_dir boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) From 504c54574f98b884eb49ad147d626aa285b613d7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 00:23:45 +0300 Subject: [PATCH 0934/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index d075a7e7..b8c47026 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -588,7 +588,7 @@ function M.init() boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') - print(vim.env.XDG_CONFIG_HOME .. '/clangd', '/config.yaml') + print(vim.env.XDG_CONFIG_HOME .. '/clangd' .. '/config.yaml') -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) boilerplate.core_dir = _G.metadata.core_dir boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) From b35944d69f3969f091e592bd33da40a2122370c5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 04:45:10 +0300 Subject: [PATCH 0935/1406] update --- mini_nvimPlatformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 27be8ac5..f1a1dfdb 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -393,7 +393,7 @@ else end --Toolchain inclusion forced in Global Environment -vim.uv.os_setenv('PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN', 'true') +-- vim.uv.os_setenv('PLATFORMIO_SETTING_COMPILATIONDB_INCLUDE_TOOLCHAIN', 'true') vim.uv.os_setenv('PLATFORMIO_CORE_DIR', platformio_core_dir) vim.g.python_host_prog = pynvim_python vim.g.python3_host_prog = pynvim_python From 92541468d203f1fc1921cb3c4f85087958520f4d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 04:48:36 +0300 Subject: [PATCH 0936/1406] update --- lua/platformio/boilerplate.lua | 6 ------ 1 file changed, 6 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index a26f7432..cd602093 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -212,12 +212,6 @@ Index: Background: Build External: File: .clangd_index -CompileFlags: - Add: - Add: - - "-xc++" - - "-std=c++17" - - "-D__cplusplus=201703L" # Manually define the C++ macro ]], -- content = function(self) -- local sysroot = '--sysroot=' .. _G.metadata.sysroot From b7775f45643b1983b7512a1b8ede6c7a52cd99bf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 04:58:23 +0300 Subject: [PATCH 0937/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index cd602093..4754ab9c 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -85,7 +85,7 @@ boilerplate['.clangd_config'] = { "--completion-style=detailed", "--header-insertion=iwyu", "--fallback-style=llvm", - "--log=error", + "--log=verbose", "--pch-storage=memory", "--pretty", "--ranking-model=decision_forest", From 8d776b2237111ec58bebd35d9277b341f45d2f7b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 05:35:09 +0300 Subject: [PATCH 0938/1406] update --- lua/platformio/lsp/clangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua index 661c9c92..d5f72bf4 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -115,7 +115,7 @@ function _G.get_clangd_config() -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) - q_driver = _G.metadata.query_driver -- use with "--query-driver=%s" + q_driver = _G.metadata.query_driver .. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" end end From 51c583d80b0f95177732732d83617536545ed0c6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 06:22:43 +0300 Subject: [PATCH 0939/1406] update --- lua/platformio/boilerplate.lua | 74 ++++++++++----- lua/platformio/lsp/clangd.lua | 5 +- tmp.lua | 169 +++++---------------------------- 3 files changed, 78 insertions(+), 170 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 4754ab9c..77699462 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -145,16 +145,57 @@ clangd return string.format(self.template, _G.metadata.query_driver or '**') end, } +-- CompileFlags: +-- Add: +-- - "-xc++" +-- - "-std=c++17" +-- - "-D__cplusplus=201703L" +-- - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0" +-- - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0/riscv32-esp-elf" +-- - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include" +-- - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include-fixed" +-- - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include" +-- Remove: +-- - "-target" +-- - "riscv32-esp-elf" +-- - "-fno-fat-lto-objects" +-- - "-fno%%-fat%%-lto%%-objects" +-- - "-fno%%-canonical%%-system%%-headers" +-- - "-misc-definitions-in-headers" +-- - "-fno-tree-switch-conversion" +-- - "-mtext-section-literals" +-- - "-mlong-calls" +-- - "-mlongcalls" +-- - "-fstrict-volatile-bitfields" +-- - "-free*" +-- - "-fipa-pta*" +-- - "-march=*" +-- - "-mabi=*" +-- - "-mcpu=*" +-- Diagnostics: +-- Suppress: +-- - "misc-definitions-in-headers" +-- - "pp_including_mainfile_in_preamble" +-- - "misc-unused-using-decls" +-- - "unused-includes" +-- ClangTidy: +-- Remove: +-- - "readability-*" +-- - "cert-err58-cpp" +-- - "llvmlibc-*" +-- - "fuchsia-*" +-- - "hicpp-avoid-c-arrays" +-- - "cppcoreguidelines-*" +-- - "llvm-*" +-- - "google-*" +-- - "bugprone-*" +-- - "hicpp-vararg" +-- - "modernize-*" +-- Index: +-- Background: Build +-- External: +-- File: .clangd_index --- Add: --- - "-xc++" --- - "--include-directory=C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0" --- - "--include-directory=C:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0/riscv32-esp-elf" --- --- -- Add: --- - %q --- - %q --- - "riscv32-esp-elf" -- INFO: .clangd -- boilerplate['.clangd'] = { boilerplate['.clangd'] = { @@ -163,18 +204,7 @@ boilerplate['.clangd'] = { -- template = [[ content = [[ CompileFlags: - Add: - - "-xc++" - - "-std=c++17" - - "-D__cplusplus=201703L" - - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0" - - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0/riscv32-esp-elf" - - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include" - - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include-fixed" - - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include" Remove: - - "-target" - - "riscv32-esp-elf" - "-fno-fat-lto-objects" - "-fno%%-fat%%-lto%%-objects" - "-fno%%-canonical%%-system%%-headers" @@ -208,10 +238,6 @@ Diagnostics: - "bugprone-*" - "hicpp-vararg" - "modernize-*" -Index: - Background: Build - External: - File: .clangd_index ]], -- content = function(self) -- local sysroot = '--sysroot=' .. _G.metadata.sysroot diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua index d5f72bf4..a6a1e763 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -115,13 +115,14 @@ function _G.get_clangd_config() -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) - q_driver = _G.metadata.query_driver .. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" + q_driver = '**' --_G.metadata.query_driver .. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" end end -- 3. Format your template string local table_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) - local formatted_str = string.format(table_config, q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) + -- local formatted_str = string.format(table_config, q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) + local formatted_str = string.format(table_config, q_driver, '', vim.misc.normalizePath(new_root_dir)) -- 4. Load the config table local cok, clangd_config = pcall(function() return load('return ' .. formatted_str)() end) diff --git a/tmp.lua b/tmp.lua index fade3c9d..2c43aef6 100644 --- a/tmp.lua +++ b/tmp.lua @@ -1,144 +1,25 @@ -local function get_metadata(attempts, env) - local active_env = env or _G.metadata.active_env - vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(int_obj) - vim.schedule(function() - vim.notify('PIO: Fetching metadata ...', vim.log.levels.INFO) - - if int_obj.code ~= 0 then - -- Schedule notification to avoid error in the system callback thread - vim.schedule(function() - if int_obj.code == 127 then - vim.notify("PIO Manager metadata: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) - else - vim.notify('PIO Manager metadata: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) - end - end) - return - end - - if int_obj.code == 0 and int_obj.stdout then - local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) - if ok and raw_data then - local _, data = next(raw_data) - if data then - -- 2. Process cc_compiler - if data.cc_path then - _G.metadata.query_driver = '' - _G.metadata.includes_build = {} - _G.metadata.includes_comaptlib = {} - _G.metadata.includes_toolchain = {} - _G.metadata.cc_flags = {} - _G.metadata.cxx_path = '' - _G.metadata.cxx_flags = {} - _G.metadata.gdb_path = '' - _G.metadata.defines = {} - _G.metadata.triplet = '' - _G.metadata.toolchain_root = '' - _G.metadata.sysroot = '' - _G.metadata.cc_compiler = misc.normalizePath(data.cc_path) or '' - _G.metadata.cc_path = misc.normalizePath(data.cc_path) or '' - - -- 1. Process Includes - if data.includes then - for category, paths in pairs(data.includes) do - -- 1.1 Process Includes_build - if category == 'build' then - local includes_build = {} - local flag = '-I' - for _, path in ipairs(paths) do - table.insert(includes_build, string.format('%q', flag .. misc.normalizePath(path))) - end - _G.metadata.includes_build = includes_build - end - - -- 1.2 Process includes_toolchain - if category == 'toolchain' then - local includes_toolchain = {} - local flag = '-isystem' - for _, path in ipairs(paths) do - table.insert(includes_toolchain, string.format('%q', flag .. misc.normalizePath(path))) - end - _G.metadata.includes_toolchain = includes_toolchain - end - - -- 1.3 Process includes_compatlib - if category == 'compatlib' then - local includes_compatlib = {} - local flag = '-isystem' - for _, path in ipairs(paths) do - table.insert(includes_compatlib, string.format('%q', flag .. misc.normalizePath(path))) - end - _G.metadata.includes_build = includes_compatlib - end - end - end - - -- 3. Process cc_flags - if data.cc_flags then - local cc_flags = {} - for _, flag in ipairs(data.cc_flags) do - table.insert(cc_flags, string.format('%q', flag)) - end - _G.metadata.cc_flags = cc_flags - end - - -- 4. Process cxx_compiler - if data.cxx_path then - _G.metadata.cxx_path = misc.normalizePath(data.cxx_path) or '' - end - - -- 5. Process cxx_flags - if data.cxx_flags then - local cxx_flags = {} - for _, flag in ipairs(data.cxx_flags) do - table.insert(cxx_flags, string.format('%q', flag)) - end - _G.metadata.cxx_flags = cxx_flags - end - - -- 6. Process gdb_path - if data.gdb_path then - _G.metadata.gdb_path = misc.normalizePath(data.gdb_path) or '' - end - - -- 7. Process Defines - if data.defines then - local defines = {} - for _, define in ipairs(data.defines) do - table.insert(defines, string.format('%q', define)) - end - _G.metadata.defines = defines - end - - pcall(M.get_sysroot_triplet, _G.metadata.cc_compiler) - -- print(vim.inspect(_G.metadata)) - -- if callback then - -- vim.schedule(function() - -- vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) - -- callback() - -- end) - -- end - end - end - else - vim.schedule(function() - vim.notify('PIO: Syncing Environment failed', vim.log.levels.WARN) - end) - end - end - -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save - if attempts > 0 then - vim.defer_fn(function() - get_metadata(attempts - 1) - end, 500) - else - if callback then - vim.schedule(function() - vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) - callback() - end) - end - end - end) - end) -end +-- Detect OS and Home directory dynamically +local is_windows = vim.loop.os_uname().version:find('Windows') +local home = os.getenv('HOME') or os.getenv('USERPROFILE') +local username = os.getenv('USERNAME') or os.getenv('USER') + +-- Build a list of common compiler paths +local drivers = { + 'C:/Program Files/LLVM/bin/*', -- Windows Clang + 'C:/msys64/*/bin/*', -- Windows MinGW (MSYS2) + home .. '/.platformio/packages/*/bin/*', -- PlatformIO (Both OS) + '/usr/bin/*', -- Linux standard + '/usr/local/bin/*', -- Linux local +} + +require('lspconfig').clangd.setup({ + cmd = { + 'clangd', + '--background-index', + '--clang-tidy', + '--offset-encoding=utf-16', + -- Combine all paths into one comma-separated string + '--query-driver=' .. table.concat(drivers, ','), + }, + -- Other standard config options... +}) From f9fc7180d91aebf863854339cce7b450fc6623ad Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 06:47:58 +0300 Subject: [PATCH 0940/1406] update --- lua/platformio/boilerplate.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 77699462..61c20bc5 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -205,6 +205,8 @@ boilerplate['.clangd'] = { content = [[ CompileFlags: Remove: + - "-target" + - "riscv32-esp-elf" - "-fno-fat-lto-objects" - "-fno%%-fat%%-lto%%-objects" - "-fno%%-canonical%%-system%%-headers" From 36e53ca21ce75c2976afedc622e4989b4138a815 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 07:07:55 +0300 Subject: [PATCH 0941/1406] update --- lua/platformio/boilerplate.lua | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 61c20bc5..6bd82f98 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -205,8 +205,7 @@ boilerplate['.clangd'] = { content = [[ CompileFlags: Remove: - - "-target" - - "riscv32-esp-elf" + - "-target*" - "-fno-fat-lto-objects" - "-fno%%-fat%%-lto%%-objects" - "-fno%%-canonical%%-system%%-headers" From c9ca500d2d5b5d2354300f8f58d1e0c479e1ea56 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 07:53:42 +0300 Subject: [PATCH 0942/1406] update --- lua/platformio/boilerplate.lua | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 6bd82f98..0acc6f31 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -75,7 +75,7 @@ boilerplate['.clangd_config'] = { content = [[ { cmd = { - "clangd", + "c:/esp-clangd/bin/clangd.exe", "--all-scopes-completion", "--background-index", "--clang-tidy", @@ -205,7 +205,9 @@ boilerplate['.clangd'] = { content = [[ CompileFlags: Remove: - - "-target*" + - "-target=*" + - "-target" + - "riscv32-esp-elf" - "-fno-fat-lto-objects" - "-fno%%-fat%%-lto%%-objects" - "-fno%%-canonical%%-system%%-headers" From 9f44787ad9385b6b4e09473634c07a796bccb3c7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 07:55:18 +0300 Subject: [PATCH 0943/1406] update --- lua/platformio/boilerplate.lua | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 0acc6f31..a1f620dd 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -156,6 +156,7 @@ clangd -- - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include-fixed" -- - "-isystemC:/Users/batoaqaa/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include" -- Remove: +-- - "-target=*" -- - "-target" -- - "riscv32-esp-elf" -- - "-fno-fat-lto-objects" @@ -205,9 +206,6 @@ boilerplate['.clangd'] = { content = [[ CompileFlags: Remove: - - "-target=*" - - "-target" - - "riscv32-esp-elf" - "-fno-fat-lto-objects" - "-fno%%-fat%%-lto%%-objects" - "-fno%%-canonical%%-system%%-headers" From 4054dad3546d78a7974ad4c876d58bce4384c01b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 08:08:57 +0300 Subject: [PATCH 0944/1406] update --- lua/platformio/boilerplate.lua | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index a1f620dd..dfdbda4a 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -205,6 +205,9 @@ boilerplate['.clangd'] = { -- template = [[ content = [[ CompileFlags: + Add: + - "-xc++" + - "-std=gnu++17" Remove: - "-fno-fat-lto-objects" - "-fno%%-fat%%-lto%%-objects" From 3b26e151f69490e383d1077e7ff45c912d450f27 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 08:37:58 +0300 Subject: [PATCH 0945/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index dfdbda4a..0b8b444e 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -75,7 +75,7 @@ boilerplate['.clangd_config'] = { content = [[ { cmd = { - "c:/esp-clangd/bin/clangd.exe", + "clangd", "--all-scopes-completion", "--background-index", "--clang-tidy", From ce5982b4f73528b493ad918938cbf0fbbf3d5057 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 08:39:55 +0300 Subject: [PATCH 0946/1406] update --- lua/platformio/lsp/clangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua index a6a1e763..5cfbc2a4 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -128,7 +128,7 @@ function _G.get_clangd_config() local cok, clangd_config = pcall(function() return load('return ' .. formatted_str)() end) if cok and clangd_config then - -- print(vim.inspect(clangd_config)) + print(vim.inspect(clangd_config)) return clangd_config end end From b2dec47c6d0d7a6816034ede5279c95ec4e2f0a5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 12:47:51 +0300 Subject: [PATCH 0947/1406] update --- lua/platformio/pioinit.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 5a0b4fa3..0f21a2fa 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -64,10 +64,10 @@ local function pick_framework(board_details) -- cb = function () vim.notify('Pioinit: Pass', vim.log.levels.INFO) end cb = pio.handlePioinitPass, }, - { - cmd = 'pio run -t compiledb', - cb = pio.handleDb, - }, + -- { + -- cmd = 'pio run -t compiledb', + -- cb = pio.handleDb, + -- }, -- { -- cmd = 'echo _CMMNDS_":"DONE', -- cb = function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end From 8e14f2256332840b437f7a284c62a1fdd13125e7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 12:50:13 +0300 Subject: [PATCH 0948/1406] update --- lua/platformio/lsp/clangd.lua | 2 +- mini_nvimPlatformio.lua | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua index 5cfbc2a4..a6a1e763 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -128,7 +128,7 @@ function _G.get_clangd_config() local cok, clangd_config = pcall(function() return load('return ' .. formatted_str)() end) if cok and clangd_config then - print(vim.inspect(clangd_config)) + -- print(vim.inspect(clangd_config)) return clangd_config end end diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index f1a1dfdb..e49402f4 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -273,9 +273,9 @@ local plugins = { }, }, -- Optional: If you also want to hide it from the tree view entirely - filters = { - custom = { '^\\.cache$', '^\\.pio$' }, - }, + -- filters = { + -- custom = { '^\\.cache$', '^\\.pio$' }, + -- }, }) end, }, From b885a2559dd657be2834ddad5092108836012c99 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 18:17:22 +0300 Subject: [PATCH 0949/1406] update --- lua/platformio/pioinit.lua | 71 ++++++------ lua/platformio/utils/pio.lua | 205 ++++++++++++++++++++++++++--------- mini_nvimPlatformio.lua | 5 + tmp.lua | 143 ++++++++++++++++++++---- 4 files changed, 318 insertions(+), 106 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 0f21a2fa..93a13bb2 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -43,41 +43,48 @@ local boardentry_maker = function(opts) end end --- stylua: ignore +--- stylua: ignore local function pick_framework(board_details) local opts = {} - pickers.new(opts, { - prompt_title = 'frameworks', - finder = finders.new_table({ - results = board_details['frameworks'], - }), - attach_mappings = function(prompt_bufnr, _) - actions.select_default:replace(function() - actions.close(prompt_bufnr) - local selection = action_state.get_selected_entry() + pickers + .new(opts, { + prompt_title = 'frameworks', + finder = finders.new_table({ + results = board_details['frameworks'], + }), + attach_mappings = function(prompt_bufnr, _) + actions.select_default:replace(function() + actions.close(prompt_bufnr) + local selection = action_state.get_selected_entry() - local pio = require('platformio.utils.pio') - pio.selected_framework = selection[1] - pio.run_sequence({ - { - cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', - -- cb = function () vim.notify('Pioinit: Pass', vim.log.levels.INFO) end - cb = pio.handlePioinitPass, - }, - -- { - -- cmd = 'pio run -t compiledb', - -- cb = pio.handleDb, - -- }, - -- { - -- cmd = 'echo _CMMNDS_":"DONE', - -- cb = function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end - -- }, - }) - end) - return true - end, - sorter = telescope_conf.generic_sorter(opts), - }):find() + local pio = require('platformio.utils.pio') + pio.selected_framework = selection[1] + pio.run_sequence({ + cmnds = { + 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', + 'pio run -t compiledb', + }, + cb = pio.handlePioinit, + -- { + -- cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', + -- -- cb = function () vim.notify('Pioinit: Pass', vim.log.levels.INFO) end + -- cb = pio.handlePioinitPass, + -- }, + -- { + -- cmd = 'pio run -t compiledb', + -- cb = pio.handleDb, + -- }, + -- { + -- cmd = 'echo _CMMNDS_":"DONE', + -- cb = function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end + -- }, + }) + end) + return true + end, + sorter = telescope_conf.generic_sorter(opts), + }) + :find() end -- stylua: ignore diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 2ae986b8..8e03901d 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -5,7 +5,6 @@ local misc = vim.misc M.selected_framework = '' M.is_processing = false M.queue = {} -local pio_buffer = '' -- Persistent stream buffer -- to fix require loop, this value is set in plugin/platformio @@ -204,9 +203,15 @@ end -- _G.metadata.isBusy = false -- M.process_queue() ------------------------------------------------------- --- INFO: ToggleTerminal commands sequencer + + + + + +local pio_buffer = '' -- Persistent stream buffer +local callBack = nil +local commandPassed = 0 ------------------------------------------------------ -- INFO: ToggleTerminal commands stdout filter -- stylua: ignore @@ -221,27 +226,15 @@ function M.stdoutcallback(_, _, data) for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end for status in pio_buffer:gmatch('_CMMNDS_:(%a+)') do - if status then - -- if status == 'PASS' then - -- pio_buffer = data[#data] - -- vim.schedule(function() M.process_queue() end) - -- elseif status == 'FAIL' then - -- end + if callBack and status then if status == 'PASS' then - -- 4. Store the last element as the new partial buffer for the next call + -- Store the last element as the new partial buffer for the next call pio_buffer = data[#data] - local task = table.remove(M.queue, 1) - if task then vim.schedule(task) end + vim.schedule(function() callBack('PASS') end) elseif status == 'DONE' then - pio_buffer = '' - M.queue = {} -- Clear queue on any other status - local task = table.remove(M.queue, 1) - if task then vim.schedule(task) end + vim.schedule(function() callBack('DONE') end) elseif status == 'FAIL' then - pio_buffer = '' - M.queue = {} -- Clear queue on any other status (failure) - local task = table.remove(M.queue, 1) - if task then vim.schedule(task) end + vim.schedule(function() callBack('DONE') end) end break end @@ -250,48 +243,157 @@ function M.stdoutcallback(_, _, data) if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end end ------------------------------------------------------- --- INFO: ToggleTerminal commands Sequencer --- Semicolon (;): Runs the next command regardless of whether the first one succeeded. --- Success Operator (&&): Runs the second command only if the first succeeds. --- Fail Operator (||): Runs if any of the previous commands fail ---- stylua: ignore +-- stylua: ignore M.run_sequence = function(tasks) - -- Reset local state for new run M.queue = {} - pio_buffer = '' - local full_cmd = '' + callBack = tasks.cb -- 1. Save the callback in a local variable + local commands = tasks.cmnds + local done = ' && echo _CMMNDS_":"DONE' local pass = ' && echo _CMMNDS_":"PASS' local fail = ' || echo _CMMNDS_":"FAIL' -- - for _, task in ipairs(tasks) do - table.insert(M.queue, task.cb) - local part = string.format('%s %s', task.cmd, pass) - if full_cmd == '' then - full_cmd = part - else - full_cmd = full_cmd .. ' && ' .. part - end + for i, cmd in ipairs(commands) do + local full_cmd = '' + if i == #commands then full_cmd = cmd .. done .. fail + else full_cmd = cmd .. pass .. fail end + table.insert(M.queue, full_cmd) end - full_cmd = full_cmd .. done .. fail - - table.insert(M.queue, function() - vim.notify('Pioinit: Done', vim.log.levels.INFO) - term.stdout_callback = nil - end) - - table.insert(M.queue, function() - vim.notify('Pioinit: Failed', vim.log.levels.INFO) + vim.schedule(function() + if callBack then callBack('INIT') end end) +end - -- full_cmd = full_cmd .. ' || ' .. fail - _G.metadata.isBusy = true - -- local ToggleTerminal = require('platformio.utils.term').ToggleTerminal - term.stdout_callback = M.stdoutcallback - term.ToggleTerminal(full_cmd, 'float') +-- Handle after pioinit execution +function M.handlePioinit(result) + if result == 'INIT' then + commandPassed = 0 + _G.metadata.isBusy = true + pio_buffer = '' + local full_cmd = table.remove(M.queue, 1) + term.stdout_callback = M.stdoutcallback + term.ToggleTerminal(full_cmd, 'float') + elseif result == 'PASS' then + commandPassed = commandPassed + 1 + if commandPassed == 1 then + vim.schedule(function() + vim.notify('Pioinit: commandPassed', vim.log.levels.INFO) + local pio_manager = require('platformio.pio_setup').pio_manager + pio_manager.refresh(function() + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + boilerplate_gen([[.clangd]], _G.metadata.core_dir) + end) + end) + -- elseif commandPassed == 2 then + end + local full_cmd = table.remove(M.queue, 1) + term.ToggleTerminal(full_cmd, 'float') + elseif result == 'DONE' then + pio_buffer = '' + M.queue = {} -- Clear queue on any other status (failure) + term.stdout_callback = nil + vim.schedule(function() + vim.notify('compiledb: Pass', vim.log.levels.INFO) + vim.misc.gitignore_lsp_configs('compile_commands.json') + _G.metadata.dbTrigger = true + end) + elseif result == 'FAIL' then + pio_buffer = '' + M.queue = {} -- Clear queue on any other status (failure) + term.stdout_callback = nil + end end +------------------------------------------------------ +-- INFO: ToggleTerminal commands sequencer + +-- local pio_buffer = '' -- Persistent stream buffer +-- ------------------------------------------------------ +-- -- INFO: ToggleTerminal commands stdout filter +-- -- stylua: ignore +-- function M.stdoutcallback(_, _, data) +-- if #M.queue == 0 then return end +-- +-- -- 1. attach partial buffer from previous data last line to 1st line +-- pio_buffer = pio_buffer .. data[1] +-- -- 2. If the chunk has more than one element, we've encountered newlines +-- if #data > 1 then +-- -- 3. Process any "middle" lines which are guaranteed to be complete +-- for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end +-- +-- for status in pio_buffer:gmatch('_CMMNDS_:(%a+)') do +-- if status then +-- -- if status == 'PASS' then +-- -- pio_buffer = data[#data] +-- -- vim.schedule(function() M.process_queue() end) +-- -- elseif status == 'FAIL' then +-- -- end +-- if status == 'PASS' then +-- -- 4. Store the last element as the new partial buffer for the next call +-- pio_buffer = data[#data] +-- local task = table.remove(M.queue, 1) +-- if task then vim.schedule(task) end +-- elseif status == 'DONE' then +-- pio_buffer = '' +-- M.queue = {} -- Clear queue on any other status +-- local task = table.remove(M.queue, 1) +-- if task then vim.schedule(task) end +-- elseif status == 'FAIL' then +-- pio_buffer = '' +-- M.queue = {} -- Clear queue on any other status (failure) +-- local task = table.remove(M.queue, 1) +-- if task then vim.schedule(task) end +-- end +-- break +-- end +-- end +-- end +-- if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end +-- end +-- +-- ------------------------------------------------------ +-- -- INFO: ToggleTerminal commands Sequencer +-- -- Semicolon (;): Runs the next command regardless of whether the first one succeeded. +-- -- Success Operator (&&): Runs the second command only if the first succeeds. +-- -- Fail Operator (||): Runs if any of the previous commands fail +-- --- stylua: ignore +-- M.run_sequence = function(tasks) +-- -- Reset local state for new run +-- M.queue = {} +-- pio_buffer = '' +-- local full_cmd = '' +-- local done = ' && echo _CMMNDS_":"DONE' +-- local pass = ' && echo _CMMNDS_":"PASS' +-- local fail = ' || echo _CMMNDS_":"FAIL' +-- -- +-- for _, task in ipairs(tasks) do +-- table.insert(M.queue, task.cb) +-- local part = string.format('%s %s', task.cmd, pass) +-- if full_cmd == '' then +-- full_cmd = part +-- else +-- full_cmd = full_cmd .. ' && ' .. part +-- end +-- end +-- full_cmd = full_cmd .. done .. fail +-- +-- table.insert(M.queue, function() +-- vim.notify('Pioinit: Done', vim.log.levels.INFO) +-- term.stdout_callback = nil +-- end) +-- +-- table.insert(M.queue, function() +-- vim.notify('Pioinit: Failed', vim.log.levels.INFO) +-- end) +-- +-- -- full_cmd = full_cmd .. ' || ' .. fail +-- _G.metadata.isBusy = true +-- -- local ToggleTerminal = require('platformio.utils.term').ToggleTerminal +-- term.stdout_callback = M.stdoutcallback +-- term.ToggleTerminal(full_cmd, 'float') +-- end +-- -- { -- cmd = 'echo _CMMNDS_":"DONE', -- cb = function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end @@ -305,6 +407,7 @@ function M.handleDb() _G.metadata.dbTrigger = true end +------------------------------------------------------ ------------------------------------------------------ -- Handle after pioinit execution function M.handlePioinitPass() diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index e49402f4..46d72f64 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -221,6 +221,11 @@ local plugins = { TelescopePrompt = 'Telescope', }, }, + buffers_color = { + -- Same values as the general color option can be used here. + active = 'lualine_{section}_normal', -- Color for active buffer. + inactive = 'lualine_{section}_inactive', -- Color for inactive buffer. + }, }, }, }) diff --git a/tmp.lua b/tmp.lua index 2c43aef6..65047d31 100644 --- a/tmp.lua +++ b/tmp.lua @@ -1,25 +1,122 @@ --- Detect OS and Home directory dynamically -local is_windows = vim.loop.os_uname().version:find('Windows') -local home = os.getenv('HOME') or os.getenv('USERPROFILE') -local username = os.getenv('USERNAME') or os.getenv('USER') +local term = require('platformio.utils.term') +local pio_buffer = '' -- Persistent stream buffer +local callBack = nil +local commandPassed = 0 +------------------------------------------------------ +-- INFO: ToggleTerminal commands stdout filter +-- stylua: ignore +function M.stdoutcallback(_, _, data) + if #M.queue == 0 then return end --- Build a list of common compiler paths -local drivers = { - 'C:/Program Files/LLVM/bin/*', -- Windows Clang - 'C:/msys64/*/bin/*', -- Windows MinGW (MSYS2) - home .. '/.platformio/packages/*/bin/*', -- PlatformIO (Both OS) - '/usr/bin/*', -- Linux standard - '/usr/local/bin/*', -- Linux local -} + -- 1. attach partial buffer from previous data last line to 1st line + pio_buffer = pio_buffer .. data[1] + -- 2. If the chunk has more than one element, we've encountered newlines + if #data > 1 then + -- 3. Process any "middle" lines which are guaranteed to be complete + for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end -require('lspconfig').clangd.setup({ - cmd = { - 'clangd', - '--background-index', - '--clang-tidy', - '--offset-encoding=utf-16', - -- Combine all paths into one comma-separated string - '--query-driver=' .. table.concat(drivers, ','), - }, - -- Other standard config options... -}) + for status in pio_buffer:gmatch('_CMMNDS_:(%a+)') do + if callBack and status then + if status == 'PASS' then + -- Store the last element as the new partial buffer for the next call + pio_buffer = data[#data] + vim.schedule(function() callBack('PASS') end) + elseif status == 'DONE' then + vim.schedule(function() callBack('DONE') end) + elseif status == 'FAIL' then + vim.schedule(function() callBack('DONE') end) + end + break + end + end + end + if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end +end + +-- stylua: ignore +M.run_sequence = function(tasks) + M.queue = {} + callBack = tasks.cb -- 1. Save the callback in a local variable + local commands = tasks.cmnds + + local done = ' && echo _CMMNDS_":"DONE' + local pass = ' && echo _CMMNDS_":"PASS' + local fail = ' || echo _CMMNDS_":"FAIL' + -- + for i, cmd in ipairs(commands) do + local full_cmd = '' + if i == #commands then full_cmd = cmd .. done .. fail + else full_cmd = cmd .. pass .. fail end + table.insert(M.queue, full_cmd) + end + vim.schedule(function() + if callBack then callBack('INIT') end + end) +end + +-- Handle after pioinit execution +function M.handlePioinit(result) + if result == 'INIT' then + commandPassed = 0 + _G.metadata.isBusy = true + pio_buffer = '' + local full_cmd = table.remove(M.queue, 1) + term.stdout_callback = M.stdoutcallback + term.ToggleTerminal(full_cmd, 'float') + elseif result == 'PASS' then + commandPassed = commandPassed + 1 + if commandPassed == 1 then + vim.schedule(function() + vim.notify('Pioinit: commandPassed', vim.log.levels.INFO) + local pio_manager = require('platformio.pio_setup').pio_manager + pio_manager.refresh(function() + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + boilerplate_gen([[.clangd]], _G.metadata.core_dir) + end) + end) + -- elseif commandPassed == 2 then + end + local full_cmd = table.remove(M.queue, 1) + term.ToggleTerminal(full_cmd, 'float') + elseif result == 'DONE' then + pio_buffer = '' + M.queue = {} -- Clear queue on any other status (failure) + term.stdout_callback = nil + vim.schedule(function() + vim.notify('compiledb: Pass', vim.log.levels.INFO) + vim.misc.gitignore_lsp_configs('compile_commands.json') + _G.metadata.dbTrigger = true + end) + elseif result == 'FAIL' then + pio_buffer = '' + M.queue = {} -- Clear queue on any other status (failure) + term.stdout_callback = nil + end +end + +-- -- Detect OS and Home directory dynamically +-- local is_windows = vim.loop.os_uname().version:find('Windows') +-- local home = os.getenv('HOME') or os.getenv('USERPROFILE') +-- local username = os.getenv('USERNAME') or os.getenv('USER') +-- +-- -- Build a list of common compiler paths +-- local drivers = { +-- 'C:/Program Files/LLVM/bin/*', -- Windows Clang +-- 'C:/msys64/*/bin/*', -- Windows MinGW (MSYS2) +-- home .. '/.platformio/packages/*/bin/*', -- PlatformIO (Both OS) +-- '/usr/bin/*', -- Linux standard +-- '/usr/local/bin/*', -- Linux local +-- } +-- +-- require('lspconfig').clangd.setup({ +-- cmd = { +-- 'clangd', +-- '--background-index', +-- '--clang-tidy', +-- '--offset-encoding=utf-16', +-- -- Combine all paths into one comma-separated string +-- '--query-driver=' .. table.concat(drivers, ','), +-- }, +-- -- Other standard config options... +-- }) From 0024478c94b6c0a25cb783adcb9b5e0eb9922c9e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 18:56:36 +0300 Subject: [PATCH 0950/1406] update --- lua/platformio/utils/pio.lua | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 8e03901d..f091d198 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -1,4 +1,6 @@ local M = {} + +-- to fix require loop, this value is set in plugin/platformio local misc = vim.misc -- local sep = package.config:sub(1, 1) -- Dynamic OS separator (\ or /) @@ -6,8 +8,6 @@ M.selected_framework = '' M.is_processing = false M.queue = {} --- to fix require loop, this value is set in plugin/platformio - local term = require('platformio.utils.term') local lsp_restart = require('platformio.lsp.tools').lsp_restart @@ -42,7 +42,6 @@ function M.compile_commandsFix() --M.dbPathsFix() if entry.command then -- Extract compiler and everything after it local compiler, args = entry.command:match("^%s*(%S+)(.*)") - if compiler then local is_absolute = compiler:sub(1, 1) == '/' or compiler:match('^%a:') @@ -289,15 +288,15 @@ function M.handlePioinit(result) end local full_cmd = table.remove(M.queue, 1) term.ToggleTerminal(full_cmd, 'float') - elseif result == 'DONE' then + elseif result == 'DONE' then -- compile_commands.json created pio_buffer = '' M.queue = {} -- Clear queue on any other status (failure) term.stdout_callback = nil - vim.schedule(function() - vim.notify('compiledb: Pass', vim.log.levels.INFO) - vim.misc.gitignore_lsp_configs('compile_commands.json') - _G.metadata.dbTrigger = true - end) + -- vim.schedule(function() + vim.notify('compiledb: Pass', vim.log.levels.INFO) + vim.misc.gitignore_lsp_configs('compile_commands.json') + _G.metadata.dbTrigger = true + -- end) elseif result == 'FAIL' then pio_buffer = '' M.queue = {} -- Clear queue on any other status (failure) From 31a779256ce43ac20ff4cc462d18c393f41c7796 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 19:01:03 +0300 Subject: [PATCH 0951/1406] update --- lua/platformio/utils/pio.lua | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f091d198..66d931fc 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -275,15 +275,15 @@ function M.handlePioinit(result) elseif result == 'PASS' then commandPassed = commandPassed + 1 if commandPassed == 1 then - vim.schedule(function() - vim.notify('Pioinit: commandPassed', vim.log.levels.INFO) - local pio_manager = require('platformio.pio_setup').pio_manager - pio_manager.refresh(function() - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - boilerplate_gen([[.clangd]], _G.metadata.core_dir) - end) + -- vim.schedule(function() + vim.notify('Pioinit: commandPassed', vim.log.levels.INFO) + local pio_manager = require('platformio.pio_setup').pio_manager + pio_manager.refresh(function() + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + boilerplate_gen([[.clangd]], _G.metadata.core_dir) end) + -- end) -- elseif commandPassed == 2 then end local full_cmd = table.remove(M.queue, 1) From 8d3a36085869576b183acdeeff10a408b554dd50 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 20:35:38 +0300 Subject: [PATCH 0952/1406] update --- lua/platformio/utils/pio.lua | 55 +++++++++++++++++++++--------------- 1 file changed, 33 insertions(+), 22 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 66d931fc..08db94d4 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -213,33 +213,44 @@ local callBack = nil local commandPassed = 0 ------------------------------------------------------ -- INFO: ToggleTerminal commands stdout filter --- stylua: ignore +--- stylua: ignore function M.stdoutcallback(_, _, data) - if #M.queue == 0 then return end + if #M.queue == 0 then + return + end -- 1. attach partial buffer from previous data last line to 1st line pio_buffer = pio_buffer .. data[1] -- 2. If the chunk has more than one element, we've encountered newlines if #data > 1 then -- 3. Process any "middle" lines which are guaranteed to be complete - for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end + for i = 2, #data - 1 do + pio_buffer = pio_buffer .. data[i] + end for status in pio_buffer:gmatch('_CMMNDS_:(%a+)') do if callBack and status then if status == 'PASS' then -- Store the last element as the new partial buffer for the next call pio_buffer = data[#data] - vim.schedule(function() callBack('PASS') end) - elseif status == 'DONE' then - vim.schedule(function() callBack('DONE') end) - elseif status == 'FAIL' then - vim.schedule(function() callBack('DONE') end) end + -- vim.schedule(function() callBack('PASS') end) + -- callBack('PASS') + -- elseif status == 'DONE' then + -- callBack('PASS') + -- vim.schedule(function() callBack('DONE') end) + -- elseif status == 'FAIL' then + -- callBack('PASS') + callBack(status) + -- vim.schedule(function() callBack('DONE') end) + -- end break end end end - if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end + if #pio_buffer > 10000 then + pio_buffer = pio_buffer:sub(-5000) + end end -- stylua: ignore @@ -275,15 +286,15 @@ function M.handlePioinit(result) elseif result == 'PASS' then commandPassed = commandPassed + 1 if commandPassed == 1 then - -- vim.schedule(function() - vim.notify('Pioinit: commandPassed', vim.log.levels.INFO) - local pio_manager = require('platformio.pio_setup').pio_manager - pio_manager.refresh(function() - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - boilerplate_gen([[.clangd]], _G.metadata.core_dir) + vim.schedule(function() + vim.notify('Pioinit: commandPassed', vim.log.levels.INFO) + local pio_manager = require('platformio.pio_setup').pio_manager + pio_manager.refresh(function() + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + boilerplate_gen([[.clangd]], _G.metadata.core_dir) + end) end) - -- end) -- elseif commandPassed == 2 then end local full_cmd = table.remove(M.queue, 1) @@ -292,11 +303,11 @@ function M.handlePioinit(result) pio_buffer = '' M.queue = {} -- Clear queue on any other status (failure) term.stdout_callback = nil - -- vim.schedule(function() - vim.notify('compiledb: Pass', vim.log.levels.INFO) - vim.misc.gitignore_lsp_configs('compile_commands.json') - _G.metadata.dbTrigger = true - -- end) + vim.schedule(function() + vim.notify('compiledb: Pass', vim.log.levels.INFO) + vim.misc.gitignore_lsp_configs('compile_commands.json') + _G.metadata.dbTrigger = true + end) elseif result == 'FAIL' then pio_buffer = '' M.queue = {} -- Clear queue on any other status (failure) From abc7c22adbf31c10048cf35a4803de091ea4307b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 20:39:17 +0300 Subject: [PATCH 0953/1406] update --- mini_nvimPlatformio.lua | 5 ----- 1 file changed, 5 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 46d72f64..e49402f4 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -221,11 +221,6 @@ local plugins = { TelescopePrompt = 'Telescope', }, }, - buffers_color = { - -- Same values as the general color option can be used here. - active = 'lualine_{section}_normal', -- Color for active buffer. - inactive = 'lualine_{section}_inactive', -- Color for inactive buffer. - }, }, }, }) From 5e8fc3c2a0a70026e56c5be2cbd454203f005801 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 20:56:58 +0300 Subject: [PATCH 0954/1406] update --- lua/platformio/metadata.lua | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index ce4c77e5..b45a6f75 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -73,7 +73,11 @@ _G.metadata = setmetatable({}, { if _pio_metadata.dbTrigger then vim.notify('Env: dbTrigger', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) local dbFix = pio.compile_commandsFix - dbFix() + local ok, _ = pcall(dbFix) + if not ok then + print('Env: dbTrigger') + end + -- dbFix() _pio_metadata.dbTrigger = false else local LspRestart = require('platformio.utils.lsp').lsp_restart From 3c12de80579343968b01fac0cb28ac9f6773aa43 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 22:11:45 +0300 Subject: [PATCH 0955/1406] update --- lua/platformio/pio_setup.lua | 341 ++++++++++++++++++++++++---------- lua/platformio/utils/misc.lua | 52 ++---- 2 files changed, 258 insertions(+), 135 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b8c47026..ecbe26fe 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -10,14 +10,12 @@ local boilerplate_gen = boilerplate.boilerplate_gen -- ============================================================================= -- UNIVERSAL TOOLCHAIN DETECTION -- ============================================================================= ---- stylua: ignore +-- stylua: ignore function M.get_sysroot_triplet(cc_compiler) local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') -- Early exit if path is nil or not a directory - if not bin_path or vim.fn.isdirectory(bin_path) == 0 then - return nil - end + if not bin_path or vim.fn.isdirectory(bin_path) == 0 then return nil end -- Normalize backslashes to forward slashes for cross-platform consistency bin_path = bin_path:gsub('\\', '/') @@ -28,16 +26,12 @@ function M.get_sysroot_triplet(cc_compiler) for _, name in ipairs(files) do -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ local match = name:match('^(.*)%-g[c%+][c%+]') - if match then - triplet = misc.normalizePath(match) - break + if match then triplet = misc.normalizePath(match) break end end -- Return nil if no compiler was found in the bin directory - if not triplet then - return nil - end + if not triplet then return nil end -- toolchain_root is the parent of the 'bin' folder local toolchain_root = misc.normalizePath(vim.fn.fnamemodify(bin_path, ':h')) @@ -62,16 +56,243 @@ function M.get_sysroot_triplet(cc_compiler) return nil end +-- -- INFO: 1. The Core PIO Manager & Generic Extractor +-- --- stylua: ignore +-- M.pio_manager = (function() +-- local cache = nil -- Stores the decoded platformio.ini JSON structure +-- -- INFO: +-- local function find_in_data(data, section_name, key_name) +-- -- Safety check: Ensure data is a valid table from a successful JSON decode +-- if type(data) ~= 'table' then +-- return nil +-- end +-- +-- for _, section in ipairs(data) do +-- -- Each section must be a table with at least 2 elements: [1]=name, [2]=content +-- if section and type(section) == 'table' and #section >= 2 then +-- local s_id = section[1] -- Section header string +-- local s_body = section[2] -- Table of key-value pairs +-- +-- if s_id == section_name and type(s_body) == 'table' then +-- for _, kv in ipairs(s_body) do +-- -- Each kv is a table: [1]=key, [2]=value +-- if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then +-- local val = kv[2] +-- -- Treat empty strings or empty tables as nil to trigger fallback logic +-- if val == nil or val == '' or (type(val) == 'table' and #val == 0) then +-- return nil +-- end +-- return val +-- end +-- end +-- end +-- end +-- end +-- return nil +-- end +-- +-- -- INFO: ASYNC REFRESH: Fetches the latest config from PlatformIO CLI +-- local function refresh(callback) +-- vim.schedule(function() +-- vim.notify('PIO: Fetching Config ...', vim.log.levels.INFO) +-- end) +-- +-- -- INFO: get project metadata +-- +-- local function get_metadata(attempts, env) +-- local active_env = env or (_G.metadata and _G.metadata.active_env) +-- if not active_env then +-- return +-- end +-- +-- vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(obj) +-- vim.schedule(function() +-- -- 1. Robust Error Check +-- if obj.code ~= 0 then +-- if attempts > 0 then +-- return vim.defer_fn(function() +-- get_metadata(attempts - 1, env) +-- end, 500) +-- end +-- local msg = obj.code == 127 and 'pio command not found' or (obj.stderr or 'Unknown error') +-- return vim.notify('PIO Manager: ' .. msg, vim.log.levels.ERROR) +-- end +-- +-- -- 2. Decode and Guard +-- local ok, raw_data = pcall(vim.json.decode, obj.stdout or '') +-- local _, data = next(raw_data or {}) +-- if not ok or not data then +-- return vim.notify('PIO: Failed to parse metadata JSON', vim.log.levels.WARN) +-- end +-- +-- -- 3. Optimized mapping helper +-- local function map_list(list, prefix) +-- local out = {} +-- for _, v in ipairs(list or {}) do +-- local path = misc.normalizePath(v) or v +-- table.insert(out, string.format('%q', (prefix or '') .. path)) +-- end +-- return out +-- end +-- +-- -- 4. Process Data & Reset State +-- local meta = _G.metadata +-- -- Reset keys +-- meta.cc_path, meta.cxx_path, meta.gdb_path = '', '', '' +-- meta.cc_flags, meta.cxx_flags, meta.defines = {}, {}, {} +-- meta.includes_build, meta.includes_toolchain, meta.includes_cometaaptlib = {}, {}, {} +-- +-- -- Assign paths +-- meta.cc_path = misc.normetaalizePath(data.cc_path) or '' +-- meta.cc_cometapiler = meta.cc_path +-- meta.cxx_path = misc.normetaalizePath(data.cxx_path) or '' +-- meta.gdb_path = misc.normetaalizePath(data.gdb_path) or '' +-- +-- -- Assign flags/defines +-- meta.cc_flags = map_list(data.cc_flags) +-- meta.cxx_flags = map_list(data.cxx_flags) +-- meta.defines = map_list(data.defines) +-- +-- -- Assign Includes +-- local inc = data.includes or {} +-- meta.includes_build = map_list(inc.build, '-I') +-- meta.includes_toolchain = map_list(inc.toolchain, '-isystemeta') +-- meta.includes_cometaaptlib = map_list(inc.cometapatlib, '-isystemeta') +-- +-- -- 5. Finalize +-- pcall(meta.get_sysroot_triplet, meta.cc_cometapiler) +-- +-- if callback then +-- vim.notify('PIO: metadata successful', vim.log.levels.INFO) +-- callback() +-- end +-- end) +-- end) +-- end +-- +-- ------------------ +-- +-- local hometae = os.getenv('HOmetaE') or os.getenv('USERPROFILE') or '' +-- +-- vim.systemeta({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) +-- vim.schedule(function() +-- -- 1. Error Handling +-- if obj.code ~= 0 then +-- local metasg = obj.code == 127 and 'pio cometametaand not found' or (obj.stderr or 'Unknown') +-- return vim.notify('PIO Config Error: ' .. metasg, vim.log.levels.ERROR) +-- end +-- +-- -- 2. State Reset +-- local meta = _G.metadata +-- for _, key in ipairs({ 'core_dir', 'packages_dir', 'platformetas_dir', 'active_env' }) do +-- meta[key] = '' +-- end +-- meta.default_envs, meta.envs = {}, {} +-- +-- -- 3. Decode JSON +-- local ok, decoded = pcall(vim.json.decode, obj.stdout or '[]') +-- if not ok or type(decoded) ~= 'table' then +-- return vim.notify('PIO: Failed to decode config JSON', vim.log.levels.WARN) +-- end +-- +-- -- 4. Parse Sections +-- for _, section in ipairs(decoded) do +-- local name, data = section[1], section[2] +-- if name == 'platformetaio' then +-- for _, kv in ipairs(data or {}) do +-- local k, v = kv[1], kv[2] +-- if k and v and v ~= '' then +-- meta[k] = (type(v) == 'string') and misc.normetaalizePath(v) or v +-- end +-- end +-- elseif type(name) == 'string' and name:match('^env:') then +-- local env_name = name:match('^env:(.+)') +-- meta.envs[env_name] = {} +-- for _, kv in ipairs(data or {}) do +-- meta.envs[env_name][kv[1]] = kv[2] +-- end +-- end +-- end +-- +-- -- 5. Determetaine Active Environmetaent +-- meta.active_env = meta.default_envs[1] or next(meta.envs) or '' +-- +-- -- 6. Fallback & Path Expansion Logic +-- local dir_metaap = { +-- { id = 'core_dir', env = 'PLATFORmetaIO_CORE_DIR', sub = '/.platformetaio' }, +-- { id = 'packages_dir', env = 'PLATFORmetaIO_PACKAGES_DIR', sub = '/.platformetaio/packages' }, +-- { id = 'platformetas_dir', env = 'PLATFORmetaIO_PLATFORmetaS_DIR', sub = '/.platformetaio/platformetas' }, +-- } +-- +-- for _, dir in ipairs(dir_metaap) do +-- local val = meta[dir.id] +-- if not val or val == '' then +-- val = os.getenv(dir.env) or (hometae .. dir.sub) +-- end +-- +-- if type(val) == 'string' then +-- -- Expand internal variables +-- val = val:gsub('%%${platformetaio.core_dir}', meta.core_dir or '') +-- meta[dir.id] = misc.normetaalizePath(val) +-- end +-- end +-- +-- -- 7. Finalize / Chain to metadata +-- if meta.active_env ~= '' then +-- vim.notify('PIO: Config fetched: ' .. meta.active_env, vim.log.levels.INFO) +-- get_metadata(1, meta.active_env) +-- else +-- vim.notify('PIO: No [env:] found. Please add a board.', vim.log.levels.ERROR) +-- end +-- end) +-- end) +-- end +-- -- INFO: +-- return { +-- refresh = refresh, +-- -- INFO: +-- get = function(s, k) +-- if not cache then +-- return nil +-- end +-- local res = find_in_data(cache, s, k) +-- +-- -- FALLBACK: If default_envs is missing/empty, find the first hardware [env:xxx] block +-- if k == 'default_envs' and not res then +-- for _, section in ipairs(cache) do +-- if type(section) == 'table' and type(section[1]) == 'string' then +-- local name = section[1] +-- if name:find('^env:') then +-- local fallback = name:match('^env:(.+)') +-- if fallback then +-- vim.schedule(function() +-- vim.notify('PIO: default_envs empty. Using: ' .. fallback, vim.log.levels.INFO) +-- end) +-- return fallback +-- end +-- end +-- end +-- end +-- vim.schedule(function() +-- vim.notify('PIO: Config Error. Check platformio.ini no env', vim.log.levels.WARN) +-- end) +-- elseif k == 'default_envs' and res and type(res) == 'table' then +-- return res[1] +-- else +-- return res +-- end +-- end, +-- } +-- end)() + -- INFO: 1. The Core PIO Manager & Generic Extractor ---- stylua: ignore +-- stylua: ignore M.pio_manager = (function() local cache = nil -- Stores the decoded platformio.ini JSON structure -- INFO: local function find_in_data(data, section_name, key_name) -- Safety check: Ensure data is a valid table from a successful JSON decode - if type(data) ~= 'table' then - return nil - end + if type(data) ~= 'table' then return nil end for _, section in ipairs(data) do -- Each section must be a table with at least 2 elements: [1]=name, [2]=content @@ -85,9 +306,7 @@ M.pio_manager = (function() if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then local val = kv[2] -- Treat empty strings or empty tables as nil to trigger fallback logic - if val == nil or val == '' or (type(val) == 'table' and #val == 0) then - return nil - end + if val == nil or val == '' or (type(val) == 'table' and #val == 0) then return nil end return val end end @@ -99,9 +318,7 @@ M.pio_manager = (function() -- INFO: ASYNC REFRESH: Fetches the latest config from PlatformIO CLI local function refresh(callback) - vim.schedule(function() - vim.notify('PIO: Fetching Config ...', vim.log.levels.INFO) - end) + vim.schedule(function() vim.notify('PIO: Fetching Config ...', vim.log.levels.INFO) end) -- INFO: get project metadata local function get_metadata(attempts, env) @@ -379,88 +596,7 @@ M.pio_manager = (function() } end)() --- -- INFO: --- function _G.get_pio_sdk_info() --- local pio_info = { includes = {}, cc_compiler = '' } --- if vim.fn.filereadable('platformio.ini') == 0 then --- return nil --- end --- --- local handle = io.popen('pio run -t envdump') --- if not handle then --- return nil --- end --- --- local packages_dir, cc_name, toolchain_pkg = '', '', '' --- --- for line in handle:lines() do --- -- 1. Get the global packages directory --- packages_dir = packages_dir ~= '' and packages_dir or line:match("'PROJECT_PACKAGES_DIR': '([^']+)'") --- --- -- 2. Get the compiler executable name (e.g., riscv32-esp-elf-gcc) --- cc_name = cc_name ~= '' and cc_name or line:match("'CC': '([^']+)'") --- --- -- 3. Find the specific toolchain package name from the PACKAGES list --- -- Matches lines like "- toolchain-riscv32-esp @ 14.2.0" --- local pkg = line:match('%- (toolchain%-[^ ]+)') --- if pkg then --- toolchain_pkg = pkg --- end --- --- -- 4. Collect include paths --- local path_list = line:match("'CPPPATH': %[(.+)%]") --- if path_list then --- for path in path_list:gmatch("'([^']+)'") do --- table.insert(pio_info.includes, '-I' .. path) --- end --- end --- end --- handle:close() --- --- -- Construct the absolute path: //bin/ --- if packages_dir and packages_dir ~= '' and toolchain_pkg and toolchain_pkg ~= '' and cc_name ~= '' then --- local full_path = packages_dir .. '/' .. toolchain_pkg .. '/bin/' .. cc_name --- if vim.fn.executable(full_path) == 1 then --- pio_info.cc_compiler = full_path --- end --- end --- --- local final = packages_dir .. '/' .. toolchain_pkg .. '/bin/*' --- print('get_pio_sdk_info(): final=' .. final) --- -- Normalize paths for the OS and ensure backslashes for Windows if needed --- -- print(vim.inspect(_G.metadata)) --- return (misc.normalize_path(final)) --- -- return _G.metadata.query_driver --- -- return pio_info --- end - --- INFO: --- FILE WATCHER: Listens for changes in platformio.ini to trigger auto-sync ---- stylua: ignore ----------------------------------------------------------------------------------------------- -- INFO: --- DATABASE PATCHER: Generates compile_commands.json and injects the --sysroot flag --- stylua: ignore --- local function pio_generate_db() --- vim.schedule(function() vim.notify('PIO: Generating Compile DB ...', vim.log.levels.INFO) end) --- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) --- vim.schedule(function() --- if obj.code ~= 0 then --- if obj.code == 127 then --- vim.notify("PIO Manager db: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) --- else --- vim.notify('PIO Manager db: Generating Compile DB failed (' .. obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) --- end --- return --- end --- vim.notify('PIO: Generating Compile DB successful', vim.log.levels.INFO) --- end) --- end) --- end - -local dir_path = vim.uv.cwd() -local ini_file = vim.fs.joinpath(dir_path, 'platformio.ini') - -- 1. Helper: Unified hashing for change detection local function get_hash(path) if vim.fn.filereadable(path) == 0 then @@ -501,6 +637,9 @@ function M.run_compiledb() end) end +local dir_path = vim.uv.cwd() +local ini_file = vim.fs.joinpath(dir_path, 'platformio.ini') +-- INFO: -- 4. Simple Watcher: Only triggers if the FILE CONTENT changed function M.start_watcher() if not dir_path or vim.fn.filereadable(ini_file) == 0 then diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index d3a3d97b..ba7baebb 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -6,6 +6,8 @@ M.devNul = M.is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' +------------------------------------------------------ +--INFO: -- iterrative loop 48ms -- stylua: ignore function M.jsonFormat(root_data) @@ -73,8 +75,8 @@ function M.jsonFormat(root_data) return table.concat(buffer) end - ------------------------------------------------------ +--INFO: -- regex 100ms -- stylua: ignore function M.pretty_json(data) @@ -104,8 +106,9 @@ function M.pretty_json(data) end return table.concat(lines, '\n') end ------------------------------------------------------- +------------------------------------------------------ +--INFO: -- recursion 50ms -- stylua: ignore -- local function pretty_print(data) -- 48ms @@ -139,6 +142,7 @@ function M.pretty_print(data) -- 48ms return table.concat(buffer) end +------------------------------------------------------ --INFO: -- Example Usage -- local content = readFile("compile_commands.json") @@ -171,6 +175,7 @@ function M.readFile(path) return content end +------------------------------------------------------ --INFO: -- Example -- local ok, err = writeFiile(path, json) @@ -197,37 +202,7 @@ function M.writeFile(data, path) return true end ---INFO: ---- stylua: ignore --- function M.normalizeFlags(input) --- local path_map = {} --- --- -- Force input into a table if it's just a single string --- local patterns = type(input) == 'table' and input or { input } --- --- for _, pattern in ipairs(patterns) do --- -- Expand ~ or environment variables --- local expanded = vim.fn.expand(pattern) --- --- -- glob returns a table of matching files --- local matches = vim.fn.glob(expanded, false, true) --- --- for _, full_path in ipairs(matches) do --- if vim.fn.isdirectory(full_path) == 0 then --- -- Normalize slashes and extract filename key --- local clean_path = full_path:gsub('\\', '/') --- local name = clean_path:match('([^/]+)$'):gsub('%.exe$', '') --- --- path_map[name] = clean_path --- end --- end --- end --- --- return path_map --- end - ------------------------------------------------------ - --[[ Targets Windows paths, normalizes slashes, and fixes smashed PlatformIO paths. Cleans and repairs compiler flags in a command string. @@ -283,15 +258,15 @@ function M.normalizeFlags(flags) return cleaned_cmd end ---INFO: ------------------------------------------------------ +--INFO: function M.normalizePath(path) -- return path:gsub('[\\]+', '/'):gsub('[//]+', '/') return path:gsub('[\\/]+', '/') end ---INFO: ------------------------------------------------------ +--INFO: function M.strsplit(inputstr, del) local t = {} if type(inputstr) == 'string' and inputstr and inputstr ~= '' then @@ -302,11 +277,13 @@ function M.strsplit(inputstr, del) return t end +------------------------------------------------------ --INFO: function M.check_prefix(str, prefix) return str:sub(1, #prefix) == prefix end +------------------------------------------------------ --INFO: local function pathmul(n) return '..' .. string.rep('/..', n) @@ -314,6 +291,7 @@ end local paths = { '.', '..', pathmul(1), pathmul(2), pathmul(3), pathmul(4), pathmul(5) } +------------------------------------------------------ --INFO: function M.file_exists(name) local f = io.open(name, 'r') @@ -325,6 +303,7 @@ function M.file_exists(name) end end +------------------------------------------------------ --INFO: function M.set_platformioRootDir() if vim.g.platformioRootDir ~= nil then @@ -339,12 +318,14 @@ function M.set_platformioRootDir() vim.notify('Could not find platformio.ini, run :Pioinit to create a new project', vim.log.levels.ERROR) end +------------------------------------------------------ --INFO: function M.cd_pioini() -- M.set_platformioRootDir() vim.cmd('cd ' .. vim.g.platformioRootDir) end +------------------------------------------------------ --INFO: function M.pio_install_check() local handle = (jit.os == 'Windows') and assert(io.popen('where.exe pio 2>./nul')) or assert(io.popen('which pio 2>/dev/null')) @@ -358,6 +339,7 @@ function M.pio_install_check() return true end +------------------------------------------------------ --INFO: function M.async_shell_cmd(cmd, callback) local output = {} @@ -382,6 +364,7 @@ function M.async_shell_cmd(cmd, callback) }) end +------------------------------------------------------ --INFO: function M.shell_cmd_blocking(command) local handle = io.popen(command, 'r') @@ -395,6 +378,7 @@ function M.shell_cmd_blocking(command) return result end +------------------------------------------------------ --INFO: function M.gitignore_lsp_configs(config_file) local gitignore_path = vim.fs.joinpath(vim.g.platformioRootDir, '.gitignore') From 7992b23579d2e4c190a26d33e994d480276b1502 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 23 Apr 2026 22:22:01 +0300 Subject: [PATCH 0956/1406] update --- lua/platformio/pio_setup.lua | 229 ----------------------------------- 1 file changed, 229 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index ecbe26fe..7ca4cea1 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -56,235 +56,6 @@ function M.get_sysroot_triplet(cc_compiler) return nil end --- -- INFO: 1. The Core PIO Manager & Generic Extractor --- --- stylua: ignore --- M.pio_manager = (function() --- local cache = nil -- Stores the decoded platformio.ini JSON structure --- -- INFO: --- local function find_in_data(data, section_name, key_name) --- -- Safety check: Ensure data is a valid table from a successful JSON decode --- if type(data) ~= 'table' then --- return nil --- end --- --- for _, section in ipairs(data) do --- -- Each section must be a table with at least 2 elements: [1]=name, [2]=content --- if section and type(section) == 'table' and #section >= 2 then --- local s_id = section[1] -- Section header string --- local s_body = section[2] -- Table of key-value pairs --- --- if s_id == section_name and type(s_body) == 'table' then --- for _, kv in ipairs(s_body) do --- -- Each kv is a table: [1]=key, [2]=value --- if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then --- local val = kv[2] --- -- Treat empty strings or empty tables as nil to trigger fallback logic --- if val == nil or val == '' or (type(val) == 'table' and #val == 0) then --- return nil --- end --- return val --- end --- end --- end --- end --- end --- return nil --- end --- --- -- INFO: ASYNC REFRESH: Fetches the latest config from PlatformIO CLI --- local function refresh(callback) --- vim.schedule(function() --- vim.notify('PIO: Fetching Config ...', vim.log.levels.INFO) --- end) --- --- -- INFO: get project metadata --- --- local function get_metadata(attempts, env) --- local active_env = env or (_G.metadata and _G.metadata.active_env) --- if not active_env then --- return --- end --- --- vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(obj) --- vim.schedule(function() --- -- 1. Robust Error Check --- if obj.code ~= 0 then --- if attempts > 0 then --- return vim.defer_fn(function() --- get_metadata(attempts - 1, env) --- end, 500) --- end --- local msg = obj.code == 127 and 'pio command not found' or (obj.stderr or 'Unknown error') --- return vim.notify('PIO Manager: ' .. msg, vim.log.levels.ERROR) --- end --- --- -- 2. Decode and Guard --- local ok, raw_data = pcall(vim.json.decode, obj.stdout or '') --- local _, data = next(raw_data or {}) --- if not ok or not data then --- return vim.notify('PIO: Failed to parse metadata JSON', vim.log.levels.WARN) --- end --- --- -- 3. Optimized mapping helper --- local function map_list(list, prefix) --- local out = {} --- for _, v in ipairs(list or {}) do --- local path = misc.normalizePath(v) or v --- table.insert(out, string.format('%q', (prefix or '') .. path)) --- end --- return out --- end --- --- -- 4. Process Data & Reset State --- local meta = _G.metadata --- -- Reset keys --- meta.cc_path, meta.cxx_path, meta.gdb_path = '', '', '' --- meta.cc_flags, meta.cxx_flags, meta.defines = {}, {}, {} --- meta.includes_build, meta.includes_toolchain, meta.includes_cometaaptlib = {}, {}, {} --- --- -- Assign paths --- meta.cc_path = misc.normetaalizePath(data.cc_path) or '' --- meta.cc_cometapiler = meta.cc_path --- meta.cxx_path = misc.normetaalizePath(data.cxx_path) or '' --- meta.gdb_path = misc.normetaalizePath(data.gdb_path) or '' --- --- -- Assign flags/defines --- meta.cc_flags = map_list(data.cc_flags) --- meta.cxx_flags = map_list(data.cxx_flags) --- meta.defines = map_list(data.defines) --- --- -- Assign Includes --- local inc = data.includes or {} --- meta.includes_build = map_list(inc.build, '-I') --- meta.includes_toolchain = map_list(inc.toolchain, '-isystemeta') --- meta.includes_cometaaptlib = map_list(inc.cometapatlib, '-isystemeta') --- --- -- 5. Finalize --- pcall(meta.get_sysroot_triplet, meta.cc_cometapiler) --- --- if callback then --- vim.notify('PIO: metadata successful', vim.log.levels.INFO) --- callback() --- end --- end) --- end) --- end --- --- ------------------ --- --- local hometae = os.getenv('HOmetaE') or os.getenv('USERPROFILE') or '' --- --- vim.systemeta({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) --- vim.schedule(function() --- -- 1. Error Handling --- if obj.code ~= 0 then --- local metasg = obj.code == 127 and 'pio cometametaand not found' or (obj.stderr or 'Unknown') --- return vim.notify('PIO Config Error: ' .. metasg, vim.log.levels.ERROR) --- end --- --- -- 2. State Reset --- local meta = _G.metadata --- for _, key in ipairs({ 'core_dir', 'packages_dir', 'platformetas_dir', 'active_env' }) do --- meta[key] = '' --- end --- meta.default_envs, meta.envs = {}, {} --- --- -- 3. Decode JSON --- local ok, decoded = pcall(vim.json.decode, obj.stdout or '[]') --- if not ok or type(decoded) ~= 'table' then --- return vim.notify('PIO: Failed to decode config JSON', vim.log.levels.WARN) --- end --- --- -- 4. Parse Sections --- for _, section in ipairs(decoded) do --- local name, data = section[1], section[2] --- if name == 'platformetaio' then --- for _, kv in ipairs(data or {}) do --- local k, v = kv[1], kv[2] --- if k and v and v ~= '' then --- meta[k] = (type(v) == 'string') and misc.normetaalizePath(v) or v --- end --- end --- elseif type(name) == 'string' and name:match('^env:') then --- local env_name = name:match('^env:(.+)') --- meta.envs[env_name] = {} --- for _, kv in ipairs(data or {}) do --- meta.envs[env_name][kv[1]] = kv[2] --- end --- end --- end --- --- -- 5. Determetaine Active Environmetaent --- meta.active_env = meta.default_envs[1] or next(meta.envs) or '' --- --- -- 6. Fallback & Path Expansion Logic --- local dir_metaap = { --- { id = 'core_dir', env = 'PLATFORmetaIO_CORE_DIR', sub = '/.platformetaio' }, --- { id = 'packages_dir', env = 'PLATFORmetaIO_PACKAGES_DIR', sub = '/.platformetaio/packages' }, --- { id = 'platformetas_dir', env = 'PLATFORmetaIO_PLATFORmetaS_DIR', sub = '/.platformetaio/platformetas' }, --- } --- --- for _, dir in ipairs(dir_metaap) do --- local val = meta[dir.id] --- if not val or val == '' then --- val = os.getenv(dir.env) or (hometae .. dir.sub) --- end --- --- if type(val) == 'string' then --- -- Expand internal variables --- val = val:gsub('%%${platformetaio.core_dir}', meta.core_dir or '') --- meta[dir.id] = misc.normetaalizePath(val) --- end --- end --- --- -- 7. Finalize / Chain to metadata --- if meta.active_env ~= '' then --- vim.notify('PIO: Config fetched: ' .. meta.active_env, vim.log.levels.INFO) --- get_metadata(1, meta.active_env) --- else --- vim.notify('PIO: No [env:] found. Please add a board.', vim.log.levels.ERROR) --- end --- end) --- end) --- end --- -- INFO: --- return { --- refresh = refresh, --- -- INFO: --- get = function(s, k) --- if not cache then --- return nil --- end --- local res = find_in_data(cache, s, k) --- --- -- FALLBACK: If default_envs is missing/empty, find the first hardware [env:xxx] block --- if k == 'default_envs' and not res then --- for _, section in ipairs(cache) do --- if type(section) == 'table' and type(section[1]) == 'string' then --- local name = section[1] --- if name:find('^env:') then --- local fallback = name:match('^env:(.+)') --- if fallback then --- vim.schedule(function() --- vim.notify('PIO: default_envs empty. Using: ' .. fallback, vim.log.levels.INFO) --- end) --- return fallback --- end --- end --- end --- end --- vim.schedule(function() --- vim.notify('PIO: Config Error. Check platformio.ini no env', vim.log.levels.WARN) --- end) --- elseif k == 'default_envs' and res and type(res) == 'table' then --- return res[1] --- else --- return res --- end --- end, --- } --- end)() - -- INFO: 1. The Core PIO Manager & Generic Extractor -- stylua: ignore M.pio_manager = (function() From 22b5960f4528ee5cd767181fdb0d1798e136eb93 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 14:59:46 +0300 Subject: [PATCH 0957/1406] update --- lua/platformio/pio_setup.lua | 416 ++++++++++---------------------- lua/platformio/utils/pio.lua | 11 +- tmp.lua | 445 ++++++++++++++++++++++++++--------- 3 files changed, 470 insertions(+), 402 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 7ca4cea1..633cd60a 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -56,316 +56,160 @@ function M.get_sysroot_triplet(cc_compiler) return nil end --- INFO: 1. The Core PIO Manager & Generic Extractor -- stylua: ignore -M.pio_manager = (function() - local cache = nil -- Stores the decoded platformio.ini JSON structure - -- INFO: - local function find_in_data(data, section_name, key_name) - -- Safety check: Ensure data is a valid table from a successful JSON decode - if type(data) ~= 'table' then return nil end - - for _, section in ipairs(data) do - -- Each section must be a table with at least 2 elements: [1]=name, [2]=content - if section and type(section) == 'table' and #section >= 2 then - local s_id = section[1] -- Section header string - local s_body = section[2] -- Table of key-value pairs - - if s_id == section_name and type(s_body) == 'table' then - for _, kv in ipairs(s_body) do - -- Each kv is a table: [1]=key, [2]=value - if type(kv) == 'table' and #kv >= 2 and kv[1] == key_name then - local val = kv[2] - -- Treat empty strings or empty tables as nil to trigger fallback logic - if val == nil or val == '' or (type(val) == 'table' and #val == 0) then return nil end - return val - end - end +-- INFO: ASYNC REFRESH: Fetches the latest config from PlatformIO CLI +function M.pio_refresh(callback) + vim.notify('PIO: Fetching PIO config ...', vim.log.levels.INFO) + -- stylua: ignore + + local function get_metadata(attempts, env) + local meta = _G.metadata + local active_env = env or meta.active_env + if not active_env or active_env == "" then return end + + -- Helper: Internal logic to apply data to _G.metadata + local function apply_metadata(data) + if not data then return false end + local norm = function(p) return misc.normalizePath(p) or "" end + local quote_map = function(list, prefix) + local res = {} + for _, v in ipairs(list or {}) do + local val = prefix and (prefix .. norm(v)) or v + table.insert(res, string.format('%q', val)) end + return res end + + meta.cc_path = norm(data.cc_path) + meta.cc_compiler = meta.cc_path + meta.cxx_path = norm(data.cxx_path) + meta.gdb_path = norm(data.gdb_path) + meta.cc_flags = quote_map(data.cc_flags) + meta.cxx_flags = quote_map(data.cxx_flags) + meta.defines = quote_map(data.defines) + + local inc = data.includes or {} + meta.includes_build = quote_map(inc.build, "-I") + meta.includes_toolchain = quote_map(inc.toolchain, "-isystem") + meta.includes_compatlib = quote_map(inc.compatlib, "-isystem") + + pcall(M.get_sysroot_triplet, meta.cc_compiler) + if callback then callback() end + return true end - return nil - end - -- INFO: ASYNC REFRESH: Fetches the latest config from PlatformIO CLI - local function refresh(callback) - vim.schedule(function() vim.notify('PIO: Fetching Config ...', vim.log.levels.INFO) end) - - -- INFO: get project metadata - local function get_metadata(attempts, env) - local active_env = env or _G.metadata.active_env - vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(int_obj) - vim.schedule(function() - vim.notify('PIO: Fetching metadata ...', vim.log.levels.INFO) - - if int_obj.code ~= 0 then - -- Schedule notification to avoid error in the system callback thread - vim.schedule(function() - if int_obj.code == 127 then - vim.notify("PIO Manager metadata: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) - else - vim.notify('PIO Manager metadata: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) - end - end) - return - end + -- 1. Try Fast Path: Read idedata.json directly + local idedata_path = string.format("%s/.pio/build/%s/idedata.json", vim.uv.cwd(), active_env) + local content = vim.misc.readFile(idedata_path) -- Assuming this is your custom helper - if int_obj.code == 0 and int_obj.stdout then - local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) - if ok and raw_data then - local _, data = next(raw_data) - if data then - -- 1. Process cc_compiler - if data.cc_path then - _G.metadata.query_driver = '' - _G.metadata.includes_build = {} - _G.metadata.includes_comaptlib = {} - _G.metadata.includes_toolchain = {} - _G.metadata.cc_flags = {} - _G.metadata.cxx_path = '' - _G.metadata.cxx_flags = {} - _G.metadata.gdb_path = '' - _G.metadata.defines = {} - _G.metadata.triplet = '' - _G.metadata.toolchain_root = '' - _G.metadata.sysroot = '' - _G.metadata.cc_compiler = misc.normalizePath(data.cc_path) or '' - _G.metadata.cc_path = misc.normalizePath(data.cc_path) or '' - - -- 2. Process cc_flags - if data.cc_flags then - local cc_flags = {} - for _, flag in ipairs(data.cc_flags) do - table.insert(cc_flags, string.format('%q', flag)) - end - _G.metadata.cc_flags = cc_flags - end - - -- 3. Process cxx_compiler - if data.cxx_path then - _G.metadata.cxx_path = misc.normalizePath(data.cxx_path) or '' - end - - -- 4. Process cxx_flags - if data.cxx_flags then - local cxx_flags = {} - for _, flag in ipairs(data.cxx_flags) do - table.insert(cxx_flags, string.format('%q', flag)) - end - _G.metadata.cxx_flags = cxx_flags - end - - -- 5. Process gdb_path - if data.gdb_path then - _G.metadata.gdb_path = misc.normalizePath(data.gdb_path) or '' - end - - -- 6. Process Defines - if data.defines then - local defines = {} - for _, define in ipairs(data.defines) do - table.insert(defines, string.format('%q', define)) - end - _G.metadata.defines = defines - end - - -- 7. Process Includes - if data.includes then - for category, paths in pairs(data.includes) do - -- 7.1 Process Includes_build - if category == 'build' then - local includes_build = {} - local flag = '-I' - for _, path in ipairs(paths) do - table.insert(includes_build, string.format('%q', flag .. misc.normalizePath(path))) - end - _G.metadata.includes_build = includes_build - end - - -- 7.2 Process includes_toolchain - if category == 'toolchain' then - local includes_toolchain = {} - local flag = '-isystem' - for _, path in ipairs(paths) do - table.insert(includes_toolchain, string.format('%q', flag .. misc.normalizePath(path))) - end - _G.metadata.includes_toolchain = includes_toolchain - end - - -- 7.3 Process includes_compatlib - if category == 'compatlib' then - local includes_compatlib = {} - local flag = '-isystem' - for _, path in ipairs(paths) do - table.insert(includes_compatlib, string.format('%q', flag .. misc.normalizePath(path))) - end - _G.metadata.includes_build = includes_compatlib - end - end - end - - pcall(M.get_sysroot_triplet, _G.metadata.cc_compiler) - -- print(vim.inspect(_G.metadata)) - -- if callback then - -- vim.schedule(function() - -- vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) - -- callback() - -- end) - -- end - end - end - else - vim.schedule(function() - vim.notify('PIO: Syncing Environment failed', vim.log.levels.WARN) - end) - end - end - -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save - if attempts > 0 then - vim.defer_fn(function() - get_metadata(attempts - 1) - end, 500) - else - if callback then - vim.schedule(function() - vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) - callback() - end) - end - end - end) - end) + if content then + local ok, decoded = pcall(vim.json.decode, content) + if ok and apply_metadata(decoded) then + vim.notify('PIO: Metadata loaded from cache', vim.log.levels.INFO) + return + end end - -- INFO: Setup Base Paths - local home = os.getenv('HOME') or os.getenv('USERPROFILE') - - -- INFO: Try to get explicit value from platformio.ini - -- HELPER: Navigates the specific nested list format used by 'pio project config --json-output' - -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } - vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) + -- 2. Fallback Path: Call PIO CLI + vim.notify('PIO: Fetching metadata via CLI...', vim.log.levels.INFO) + vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(obj) vim.schedule(function() - if ext_obj.code ~= 0 then - -- Schedule notification to avoid error in the system callback thread - if ext_obj.code == 127 then - vim.notify("PIO Manager config: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) - else - vim.notify('PIO Manager config: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) + if obj.code ~= 0 then + if attempts > 0 then + vim.defer_fn(function() get_metadata(attempts - 1, env) end, 500) end return end - _G.metadata.core_dir = '' - _G.metadata.packages_dir = '' - _G.metadata.platforms_dir = '' - _G.metadata.active_env = '' - _G.metadata.default_envs = {} - _G.metadata.envs = {} + local ok, raw_data = pcall(vim.json.decode, obj.stdout or "") + -- PIO CLI wraps the env data in a table keyed by env name + local _, data = next(raw_data or {}) + + if ok and apply_metadata(data) then + vim.notify('PIO: Metadata sync successful', vim.log.levels.INFO) + else + vim.notify("PIO: Failed to parse CLI output", vim.log.levels.WARN) + end + end) + end) + end + -- + ---------------- + -- stylua: ignore + -- INFO: get project config + local function fetch_config() + local meta = _G.metadata + local home = (os.getenv('HOME') or os.getenv('USERPROFILE') or ""):gsub('[\\/]+$', '') + + vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) + vim.schedule(function() + -- 1. Check Execution + if obj.code ~= 0 then + local msg = obj.code == 127 and "'pio' not found" or (obj.stderr or "Unknown Error") + return vim.notify("PIO Config Error: " .. msg, vim.log.levels.ERROR) + end + + -- 2. Decode JSON safely + local ok, decoded = pcall(vim.json.decode, obj.stdout or "") + if not ok or type(decoded) ~= "table" then + return vim.notify("PIO: Failed to decode config JSON", vim.log.levels.ERROR) + end + + -- Reset core structure + meta.envs = {} + meta.default_envs = {} - local decoded = vim.json.decode(ext_obj.stdout) + -- 3. Parse Sections for _, section in ipairs(decoded) do - if type(section) == 'table' and #section >= 2 then - local name, data = section[1], section[2] - -- 1. Extract Global PlatformIO Settings if available [core_dir][packages_dir][platforms_dir][default_envs] - if name == 'platformio' then - for _, kv in ipairs(data) do - local key, val = kv[1], kv[2] - if key ~= nil then - -- if _G.metadata[key] ~= nil then - _G.metadata[key] = ((type(val) == 'table' and next(val) ~= nil) or (type(val) == 'string' and val ~= '')) and misc.normalizePath(val) or val - end - end - -- 2. Extract all hardware [envs] like [env:seeed_xiao_esp32c3], skipping generic [env] - elseif name:match('^env:') then - local env_name = name:match('^env:(.+)') - _G.metadata.envs[env_name] = {} - for _, kv in ipairs(data) do - _G.metadata.envs[env_name][kv[1]] = kv[2] - end + local name, data = section[1], section[2] + if name == 'platformio' then + for _, kv in ipairs(data) do + meta[kv[1]] = kv[2] + end + elseif name:match('^env:') then + local env_name = name:match('^env:(.+)') + meta.envs[env_name] = {} + for _, kv in ipairs(data) do + meta.envs[env_name][kv[1]] = kv[2] end end end - -- assign [active_env] - if #_G.metadata.default_envs > 0 then - _G.metadata.active_env = _G.metadata.default_envs[1] or '' - elseif _G.metadata.envs and next(_G.metadata.envs) ~= '' then - _G.metadata.active_env = next(_G.metadata.envs) or '' - end - -- INFO: -- Define Mapping (key in INI, Env Var, Default Subfolder) - local map = { - core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, - packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, - platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, + -- 4. Assign active_env + meta.active_env = meta.default_envs[1] or next(meta.envs) or "" + + -- 5. Resolve Paths (INI -> Env -> Default) + local path_map = { + { key = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, + { key = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, + { key = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, } - for _, kv in ipairs(map) do - -- 4.0 Fallback Logic: INI -> Env Var -> Default - local result = _G.metadata[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') - -- 5. Expand ${platformio.core_dir} - if type(result) == 'string' then - if result:find('${platformio.core_dir}', 1, true) then - result = result:gsub('%${platformio.core_dir}', _G.metadata.core_dir) - end + + for _, item in ipairs(path_map) do + local val = meta[item.key] + -- Fallback chain + if not val or val == "" then + val = os.getenv(item.env) or (home .. item.sub) + end + -- Expand variables and Normalize + if type(val) == "string" then + val = val:gsub('%%${platformio.core_dir}', meta.core_dir or "") + meta[item.key] = misc.normalizePath(val) end - -- 6. Normalize Slashes for Windows - -- _G.metadata[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') - -- _G.metadata[kv.ini] = result:gsub('\\', '/'):gsub('//+', '/') - _G.metadata[kv.ini] = misc.normalizePath(result) end - -- return _G.metadata[map[type].ini] - -- end - if _G.metadata.active_env ~= '' then - vim.schedule(function() - vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) - end) - get_metadata(1, _G.metadata.active_env) + -- 6. Trigger next step + if meta.active_env ~= "" then + vim.notify('PIO: Config sync successful', vim.log.levels.INFO) + get_metadata(1, meta.active_env) else - vim.schedule(function() - vim.notify('PIO: no [env:] found, add board first', vim.log.levels.ERROR) - end) + vim.notify('PIO: No [env:] found. Please add a board.', vim.log.levels.ERROR) end end) end) end - - -- INFO: - return { - refresh = refresh, - -- INFO: - get = function(s, k) - if not cache then - return nil - end - local res = find_in_data(cache, s, k) - - -- FALLBACK: If default_envs is missing/empty, find the first hardware [env:xxx] block - if k == 'default_envs' and not res then - for _, section in ipairs(cache) do - if type(section) == 'table' and type(section[1]) == 'string' then - local name = section[1] - if name:find('^env:') then - local fallback = name:match('^env:(.+)') - if fallback then - vim.schedule(function() - vim.notify('PIO: default_envs empty. Using: ' .. fallback, vim.log.levels.INFO) - end) - return fallback - end - end - end - end - vim.schedule(function() - vim.notify('PIO: Config Error. Check platformio.ini no env', vim.log.levels.WARN) - end) - elseif k == 'default_envs' and res and type(res) == 'table' then - return res[1] - else - return res - end - end, - } -end)() + fetch_config() +end -- INFO: -- 1. Helper: Unified hashing for change detection @@ -394,7 +238,7 @@ function M.run_compiledb() dbFix() vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) -- Use pcall in case M.refresh is defined elsewhere - -- pio_manager.refresh(function() + -- pio_refresh(function() -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) -- pio_generate_db() @@ -432,7 +276,7 @@ function M.start_watcher() local new_hash = get_hash(ini_file) if new_hash and new_hash ~= current_ini_hash then current_ini_hash = new_hash - M.pio_manager.refresh(function() + M.pio_refresh(function() -- pio_generate_db() -- M.run_compiledb() M.run_compiledb() -- Smart: Auto-update DB if config changes @@ -472,7 +316,7 @@ end -- 500, -- 0, -- vim.schedule_wrap(function() --- pio_manager.refresh(function() +-- pio_refresh(function() -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) -- -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') @@ -518,7 +362,7 @@ function M.init() -- If the file already exists, do an initial sync if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then - M.pio_manager.refresh(function() + M.pio_refresh(function() -- vim.schedule(function() -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) -- pio_generate_db() diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 08db94d4..3e2eba8a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -22,7 +22,6 @@ function M.compile_commandsFix() --M.dbPathsFix() -- 1. Build Path Map (Scan toolchain) local path_map = {} - local pio_binaries = _G.metadata.query_driver or '/bin/*' -- local pio_binaries = (_G.metadata.toolchain_root or "") .. '/bin/*' for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do @@ -210,7 +209,6 @@ end local pio_buffer = '' -- Persistent stream buffer local callBack = nil -local commandPassed = 0 ------------------------------------------------------ -- INFO: ToggleTerminal commands stdout filter --- stylua: ignore @@ -274,6 +272,7 @@ M.run_sequence = function(tasks) end) end +local commandPassed = 0 -- Handle after pioinit execution function M.handlePioinit(result) if result == 'INIT' then @@ -288,8 +287,8 @@ function M.handlePioinit(result) if commandPassed == 1 then vim.schedule(function() vim.notify('Pioinit: commandPassed', vim.log.levels.INFO) - local pio_manager = require('platformio.pio_setup').pio_manager - pio_manager.refresh(function() + local pio_refresh = require('platformio.pio_setup').pio_refresh + pio_refresh(function() local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') boilerplate_gen([[.clangd]], _G.metadata.core_dir) @@ -422,8 +421,8 @@ end -- Handle after pioinit execution function M.handlePioinitPass() vim.notify('Pioinit: Pass', vim.log.levels.INFO) - local pio_manager = require('platformio.pio_setup').pio_manager - pio_manager.refresh(function() + local pio_refresh = require('platformio.pio_setup').pio_refresh + pio_refresh(function() local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') boilerplate_gen([[.clangd]], _G.metadata.core_dir) diff --git a/tmp.lua b/tmp.lua index 65047d31..00331e86 100644 --- a/tmp.lua +++ b/tmp.lua @@ -1,122 +1,347 @@ -local term = require('platformio.utils.term') -local pio_buffer = '' -- Persistent stream buffer -local callBack = nil -local commandPassed = 0 ------------------------------------------------------- --- INFO: ToggleTerminal commands stdout filter --- stylua: ignore -function M.stdoutcallback(_, _, data) - if #M.queue == 0 then return end - - -- 1. attach partial buffer from previous data last line to 1st line - pio_buffer = pio_buffer .. data[1] - -- 2. If the chunk has more than one element, we've encountered newlines - if #data > 1 then - -- 3. Process any "middle" lines which are guaranteed to be complete - for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end - - for status in pio_buffer:gmatch('_CMMNDS_:(%a+)') do - if callBack and status then - if status == 'PASS' then - -- Store the last element as the new partial buffer for the next call - pio_buffer = data[#data] - vim.schedule(function() callBack('PASS') end) - elseif status == 'DONE' then - vim.schedule(function() callBack('DONE') end) - elseif status == 'FAIL' then - vim.schedule(function() callBack('DONE') end) +-- local meta = _G.metadata +-- INFO: get project metadata +-- local function get_metadata(attempts, env) +-- local active_env = env or meta.active_env +-- vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(int_obj) +-- vim.schedule(function() +-- vim.notify('PIO: Fetching metadata ...', vim.log.levels.INFO) +-- -- +-- if int_obj.code ~= 0 then +-- -- Schedule notification to avoid error in the system callback thread +-- vim.schedule(function() +-- if int_obj.code == 127 then +-- vim.notify("PIO Manager metadata: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) +-- else +-- vim.notify('PIO Manager metadata: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) +-- end +-- end) +-- return +-- end +-- -- +-- if int_obj.code == 0 and int_obj.stdout then +-- local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) +-- if ok and raw_data then +-- local _, data = next(raw_data) +-- if data then +-- -- 1. Process cc_compiler +-- if data.cc_path then +-- meta.query_driver = '' +-- meta.includes_build = {} +-- meta.includes_comaptlib = {} +-- meta.includes_toolchain = {} +-- meta.cc_flags = {} +-- meta.cxx_path = '' +-- meta.cxx_flags = {} +-- meta.gdb_path = '' +-- meta.defines = {} +-- meta.triplet = '' +-- meta.toolchain_root = '' +-- meta.sysroot = '' +-- meta.cc_compiler = misc.normalizePath(data.cc_path) or '' +-- meta.cc_path = misc.normalizePath(data.cc_path) or '' +-- -- +-- -- 2. Process cc_flags +-- if data.cc_flags then +-- local cc_flags = {} +-- for _, flag in ipairs(data.cc_flags) do +-- table.insert(cc_flags, string.format('%q', flag)) +-- end +-- meta.cc_flags = cc_flags +-- end +-- -- +-- -- 3. Process cxx_compiler +-- if data.cxx_path then +-- meta.cxx_path = misc.normalizePath(data.cxx_path) or '' +-- end +-- -- +-- -- 4. Process cxx_flags +-- if data.cxx_flags then +-- local cxx_flags = {} +-- for _, flag in ipairs(data.cxx_flags) do +-- table.insert(cxx_flags, string.format('%q', flag)) +-- end +-- meta.cxx_flags = cxx_flags +-- end +-- -- +-- -- 5. Process gdb_path +-- if data.gdb_path then +-- meta.gdb_path = misc.normalizePath(data.gdb_path) or '' +-- end +-- -- +-- -- 6. Process Defines +-- if data.defines then +-- local defines = {} +-- for _, define in ipairs(data.defines) do +-- table.insert(defines, string.format('%q', define)) +-- end +-- meta.defines = defines +-- end +-- -- +-- -- 7. Process Includes +-- if data.includes then +-- for category, paths in pairs(data.includes) do +-- -- 7.1 Process Includes_build +-- if category == 'build' then +-- local includes_build = {} +-- local flag = '-I' +-- for _, path in ipairs(paths) do +-- table.insert(includes_build, string.format('%q', flag .. misc.normalizePath(path))) +-- end +-- meta.includes_build = includes_build +-- end +-- -- +-- -- 7.2 Process includes_toolchain +-- if category == 'toolchain' then +-- local includes_toolchain = {} +-- local flag = '-isystem' +-- for _, path in ipairs(paths) do +-- table.insert(includes_toolchain, string.format('%q', flag .. misc.normalizePath(path))) +-- end +-- meta.includes_toolchain = includes_toolchain +-- end +-- -- +-- -- 7.3 Process includes_compatlib +-- if category == 'compatlib' then +-- local includes_compatlib = {} +-- local flag = '-isystem' +-- for _, path in ipairs(paths) do +-- table.insert(includes_compatlib, string.format('%q', flag .. misc.normalizePath(path))) +-- end +-- meta.includes_build = includes_compatlib +-- end +-- end +-- end +-- -- +-- pcall(M.get_sysroot_triplet, meta.cc_compiler) +-- end +-- end +-- else +-- vim.schedule(function() +-- vim.notify('PIO: Syncing Environment failed', vim.log.levels.WARN) +-- end) +-- end +-- end +-- -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save +-- if attempts > 0 then +-- vim.defer_fn(function() +-- get_metadata(attempts - 1) +-- end, 500) +-- else +-- if callback then +-- vim.schedule(function() +-- vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) +-- callback() +-- end) +-- end +-- end +-- end) +-- end) +-- end + +local function fetch_config() -- INFO: Setup Base Paths + local meta = _G.metadata + local home = os.getenv('HOME') or os.getenv('USERPROFILE') + -- + -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } + vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) + vim.schedule(function() + if ext_obj.code ~= 0 then + -- Schedule notification to avoid error in the system callback thread + if ext_obj.code == 127 then + vim.notify("PIO Manager config: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) + else + vim.notify('PIO Manager config: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) end - break + return end - end - end - if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end -end --- stylua: ignore -M.run_sequence = function(tasks) - M.queue = {} - callBack = tasks.cb -- 1. Save the callback in a local variable - local commands = tasks.cmnds + meta.core_dir = '' + meta.packages_dir = '' + meta.platforms_dir = '' + meta.active_env = '' + meta.default_envs = {} + meta.envs = {} - local done = ' && echo _CMMNDS_":"DONE' - local pass = ' && echo _CMMNDS_":"PASS' - local fail = ' || echo _CMMNDS_":"FAIL' - -- - for i, cmd in ipairs(commands) do - local full_cmd = '' - if i == #commands then full_cmd = cmd .. done .. fail - else full_cmd = cmd .. pass .. fail end - table.insert(M.queue, full_cmd) - end - vim.schedule(function() - if callBack then callBack('INIT') end + local decoded = vim.json.decode(ext_obj.stdout) + for _, section in ipairs(decoded) do + if type(section) == 'table' and #section >= 2 then + local name, data = section[1], section[2] + -- 1. Extract Global PlatformIO Settings if available [core_dir][packages_dir][platforms_dir][default_envs] + if name == 'platformio' then + for _, kv in ipairs(data) do + local key, val = kv[1], kv[2] + if key ~= nil then + -- if meta[key] ~= nil then + meta[key] = ((type(val) == 'table' and next(val) ~= nil) or (type(val) == 'string' and val ~= '')) and misc.normalizePath(val) or val + end + end + -- 2. Extract all hardware [envs] like [env:seeed_xiao_esp32c3], skipping generic [env] + elseif name:match('^env:') then + local env_name = name:match('^env:(.+)') + meta.envs[env_name] = {} + for _, kv in ipairs(data) do + meta.envs[env_name][kv[1]] = kv[2] + end + end + end + end + -- assign [active_env] + if #meta.default_envs > 0 then + meta.active_env = meta.default_envs[1] or '' + elseif meta.envs and next(meta.envs) ~= '' then + meta.active_env = next(meta.envs) or '' + end + + -- INFO: -- Define Mapping (key in INI, Env Var, Default Subfolder) + local map = { + core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, + packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, + platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, + } + for _, kv in ipairs(map) do + -- 4.0 Fallback Logic: INI -> Env Var -> Default + local result = meta[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') + -- 5. Expand ${platformio.core_dir} + if type(result) == 'string' then + if result:find('${platformio.core_dir}', 1, true) then + result = result:gsub('%${platformio.core_dir}', meta.core_dir) + end + end + -- 6. Normalize Slashes for Windows + -- meta[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') + -- meta[kv.ini] = result:gsub('\\', '/'):gsub('//+', '/') + meta[kv.ini] = misc.normalizePath(result) + end + -- return meta[map[type].ini] + -- end + + if meta.active_env ~= '' then + vim.schedule(function() + vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) + end) + get_metadata(1, meta.active_env) + else + vim.schedule(function() + vim.notify('PIO: no [env:] found, add board first', vim.log.levels.ERROR) + end) + end + end) end) end --- Handle after pioinit execution -function M.handlePioinit(result) - if result == 'INIT' then - commandPassed = 0 - _G.metadata.isBusy = true - pio_buffer = '' - local full_cmd = table.remove(M.queue, 1) - term.stdout_callback = M.stdoutcallback - term.ToggleTerminal(full_cmd, 'float') - elseif result == 'PASS' then - commandPassed = commandPassed + 1 - if commandPassed == 1 then +local function get_metadata(attempts, env) + vim.notify('PIO: Fetching metadata...', vim.log.levels.INFO) + --"C:\Users\batoaqaa\AppData\Local\ahmed\test\.pio\build\seeed_xiao_esp32c3\idedata.json" + local active_env = env or _G.metadata.active_env + local filename = vim.uv.cwd() .. '/.pio/build/' .. active_env .. '/idedata.json' + local content = vim.misc.readFile(filename) + if content then + -- 2. JSON Decoding + local ok, data = pcall(vim.json.decode, content or '') + if not ok or not data then + vim.notify('PIO: Failed to parse metadata JSON', vim.log.levels.WARN) + return + end + + -- 3. Update Global Metadata (Resetting with defaults) + local meta = _G.metadata + local norm = function(p) + return misc.normalizePath(p) or '' + end + local quote_map = function(list, prefix) + local res = {} + for _, v in ipairs(list or {}) do + table.insert(res, string.format('%q', (prefix or '') .. (prefix and norm(v) or v))) + end + return res + end + + -- Overwrite/Refresh Meta safely + meta.cc_path = norm(data.cc_path) + meta.cc_compiler = meta.cc_path + meta.cxx_path = norm(data.cxx_path) + meta.gdb_path = norm(data.gdb_path) + + meta.cc_flags = quote_map(data.cc_flags) + meta.cxx_flags = quote_map(data.cxx_flags) + meta.defines = quote_map(data.defines) + + -- 4. Process Includes + local inc = data.includes or {} + meta.includes_build = quote_map(inc.build, '-I') + meta.includes_toolchain = quote_map(inc.toolchain, '-isystem') + meta.includes_compatlib = quote_map(inc.compatlib, '-isystem') + + -- 5. Finalize + pcall(M.get_sysroot_triplet, meta.cc_compiler) + + if callback then + vim.notify('PIO: Metadata sync successful', vim.log.levels.INFO) + callback() + end + else + vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(obj) vim.schedule(function() - vim.notify('Pioinit: commandPassed', vim.log.levels.INFO) - local pio_manager = require('platformio.pio_setup').pio_manager - pio_manager.refresh(function() - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - boilerplate_gen([[.clangd]], _G.metadata.core_dir) - end) + -- 1. Error Handling + if obj.code ~= 0 then + local msg = obj.code == 127 and "'pio' not found" or (obj.stderr or 'Unknown Error') + vim.notify('PIO Metadata Error: ' .. msg, vim.log.levels.WARN) + + -- Retry Logic + if attempts > 0 then + vim.defer_fn(function() + get_metadata(attempts - 1, env) + end, 500) + end + return + end + + -- 2. JSON Decoding + local ok, raw_data = pcall(vim.json.decode, obj.stdout or '') + local _, data = next(raw_data or {}) + + if not ok or not data then + vim.notify('PIO: Failed to parse metadata JSON', vim.log.levels.WARN) + return + end + + -- 3. Update Global Metadata (Resetting with defaults) + local meta = _G.metadata + local norm = function(p) + return misc.normalizePath(p) or '' + end + local quote_map = function(list, prefix) + local res = {} + for _, v in ipairs(list or {}) do + table.insert(res, string.format('%q', (prefix or '') .. (prefix and norm(v) or v))) + end + return res + end + + -- Overwrite/Refresh Meta safely + meta.cc_path = norm(data.cc_path) + meta.cc_compiler = meta.cc_path + meta.cxx_path = norm(data.cxx_path) + meta.gdb_path = norm(data.gdb_path) + + meta.cc_flags = quote_map(data.cc_flags) + meta.cxx_flags = quote_map(data.cxx_flags) + meta.defines = quote_map(data.defines) + + -- 4. Process Includes + local inc = data.includes or {} + meta.includes_build = quote_map(inc.build, '-I') + meta.includes_toolchain = quote_map(inc.toolchain, '-isystem') + meta.includes_compatlib = quote_map(inc.compatlib, '-isystem') + + -- 5. Finalize + pcall(M.get_sysroot_triplet, meta.cc_compiler) + + if callback then + vim.notify('PIO: Metadata sync successful', vim.log.levels.INFO) + callback() + end end) - -- elseif commandPassed == 2 then - end - local full_cmd = table.remove(M.queue, 1) - term.ToggleTerminal(full_cmd, 'float') - elseif result == 'DONE' then - pio_buffer = '' - M.queue = {} -- Clear queue on any other status (failure) - term.stdout_callback = nil - vim.schedule(function() - vim.notify('compiledb: Pass', vim.log.levels.INFO) - vim.misc.gitignore_lsp_configs('compile_commands.json') - _G.metadata.dbTrigger = true end) - elseif result == 'FAIL' then - pio_buffer = '' - M.queue = {} -- Clear queue on any other status (failure) - term.stdout_callback = nil end end - --- -- Detect OS and Home directory dynamically --- local is_windows = vim.loop.os_uname().version:find('Windows') --- local home = os.getenv('HOME') or os.getenv('USERPROFILE') --- local username = os.getenv('USERNAME') or os.getenv('USER') --- --- -- Build a list of common compiler paths --- local drivers = { --- 'C:/Program Files/LLVM/bin/*', -- Windows Clang --- 'C:/msys64/*/bin/*', -- Windows MinGW (MSYS2) --- home .. '/.platformio/packages/*/bin/*', -- PlatformIO (Both OS) --- '/usr/bin/*', -- Linux standard --- '/usr/local/bin/*', -- Linux local --- } --- --- require('lspconfig').clangd.setup({ --- cmd = { --- 'clangd', --- '--background-index', --- '--clang-tidy', --- '--offset-encoding=utf-16', --- -- Combine all paths into one comma-separated string --- '--query-driver=' .. table.concat(drivers, ','), --- }, --- -- Other standard config options... --- }) From 92ba6deb06b8755a13191f03dec5e62cb449227c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 15:13:01 +0300 Subject: [PATCH 0958/1406] update --- lua/platformio/utils/pio.lua | 49 ++++++++---------------------------- 1 file changed, 10 insertions(+), 39 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 3e2eba8a..977cdf70 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -29,6 +29,7 @@ function M.compile_commandsFix() --M.dbPathsFix() path_map[name] = full_path end + -- 2. Update Entries local modified = false local prntFlags = true for _, entry in ipairs(data) do @@ -69,38 +70,6 @@ function M.compile_commandsFix() --M.dbPathsFix() end end end - -- 2. Update Entries - -- local modified = false - -- for _, entry in ipairs(data) do - -- if entry.directory then entry.directory = misc.normalizePath(entry.directory) end - -- if entry.file then entry.file = misc.normalizePath(entry.file) end - -- if entry.arguments then entry.arguments = misc.normalizeFlags(entry.arguments) end - -- -- - -- if entry.command then - -- -- local first_token = cmd:match('^%S+') -- Get first word before space - -- local compiler, args = entry.command:match("^%s*(%S+)(.*)") - -- - -- -- Check if it's already a short name (not an absolute path) - -- if compiler and not (compiler:sub(1, 1) == '/' or compiler:match('^%a:')) then - -- -- get the file name without .exe - -- -- local short_name = compiler:gsub('%.exe$', '') - -- local short_name = compiler:match('([^/\\\\]+)$'):gsub('%.exe$', '') - -- if path_map[short_name] then -- if there is full path for this file - -- -- Swap compiler with full path safely - -- local full_compiler_path = path_map[short_name] --misc.normalizePath(path_map[short_name]) - -- --Quore the path if it contains spaces - -- if full_compiler_path.find(" ") then - -- full_compiler_path = '"' .. full_compiler_path .. '"' - -- end - -- print(string.format('compiler = %s', compiler)) - -- -- local argsFormated = misc.normalizeFlags(args) - -- -- entry.command = full_compiler_path .. argsFormated - -- entry.command = full_compiler_path .. args - -- modified = true - -- end - -- end - -- end - -- end -- -- 3. Save with Formatting if modified then local start_time = vim.loop.hrtime() @@ -288,11 +257,13 @@ function M.handlePioinit(result) vim.schedule(function() vim.notify('Pioinit: commandPassed', vim.log.levels.INFO) local pio_refresh = require('platformio.pio_setup').pio_refresh - pio_refresh(function() - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - boilerplate_gen([[.clangd]], _G.metadata.core_dir) - end) + vim.defer_fn(function() + pio_refresh(function() + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + boilerplate_gen([[.clangd]], _G.metadata.core_dir) + end) + end, 500) end) -- elseif commandPassed == 2 then end @@ -302,11 +273,11 @@ function M.handlePioinit(result) pio_buffer = '' M.queue = {} -- Clear queue on any other status (failure) term.stdout_callback = nil - vim.schedule(function() + vim.defer_fn(function() vim.notify('compiledb: Pass', vim.log.levels.INFO) vim.misc.gitignore_lsp_configs('compile_commands.json') _G.metadata.dbTrigger = true - end) + end, 500) elseif result == 'FAIL' then pio_buffer = '' M.queue = {} -- Clear queue on any other status (failure) From 43e6323f0dc56ce386a82f14e35e40f0acbf7495 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 15:18:38 +0300 Subject: [PATCH 0959/1406] update --- lua/platformio/pio_setup.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 633cd60a..ac3b2af2 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -60,8 +60,8 @@ end -- INFO: ASYNC REFRESH: Fetches the latest config from PlatformIO CLI function M.pio_refresh(callback) vim.notify('PIO: Fetching PIO config ...', vim.log.levels.INFO) - -- stylua: ignore + -- stylua: ignore local function get_metadata(attempts, env) local meta = _G.metadata local active_env = env or meta.active_env @@ -100,7 +100,8 @@ function M.pio_refresh(callback) -- 1. Try Fast Path: Read idedata.json directly local idedata_path = string.format("%s/.pio/build/%s/idedata.json", vim.uv.cwd(), active_env) - local content = vim.misc.readFile(idedata_path) -- Assuming this is your custom helper + print(idedata_path) + local content = vim.misc.readFile(idedata_path) if content then local ok, decoded = pcall(vim.json.decode, content) From a8ab187562bd544cef9a8827cff2416d7580860b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 15:23:36 +0300 Subject: [PATCH 0960/1406] update --- lua/platformio/pio_setup.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index ac3b2af2..ec33009d 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -99,7 +99,8 @@ function M.pio_refresh(callback) end -- 1. Try Fast Path: Read idedata.json directly - local idedata_path = string.format("%s/.pio/build/%s/idedata.json", vim.uv.cwd(), active_env) + local idedata_path = vim.fs.joinpath(vim.uv.cwd(), '.pio/build', active_env, 'idedata.json') + -- local idedata_path = string.format("%s/.pio/build/%s/idedata.json", vim.uv.cwd(), active_env) print(idedata_path) local content = vim.misc.readFile(idedata_path) From d553b8644ea38a451b42801380276acdf675d2ed Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 16:56:38 +0300 Subject: [PATCH 0961/1406] update --- lua/platformio/metadata.lua | 1 + lua/platformio/pio_setup.lua | 104 ++++++++++++++++++++--------- lua/platformio/utils/misc.lua | 6 ++ tmp1.lua | 122 ++++++++++++++++++++++++++++++++++ 4 files changed, 203 insertions(+), 30 deletions(-) create mode 100644 tmp1.lua diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index b45a6f75..497c292e 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -53,6 +53,7 @@ local _pio_metadata = { sysroot = '', fallbackFlags = {}, dbTrigger = false, + last_checksum = '', -- Used to track changes } -- 2. The Reactive Proxy Wrapper -- Any write to _G.metadata.key = val triggers this logic diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index ec33009d..43023279 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -57,20 +57,34 @@ function M.get_sysroot_triplet(cc_compiler) end -- stylua: ignore --- INFO: ASYNC REFRESH: Fetches the latest config from PlatformIO CLI function M.pio_refresh(callback) vim.notify('PIO: Fetching PIO config ...', vim.log.levels.INFO) -- stylua: ignore + -- INFO:------------------------------------------------- + -- get pio project metadata info + --------------------------------------------------------- local function get_metadata(attempts, env) local meta = _G.metadata local active_env = env or meta.active_env - if not active_env or active_env == "" then return end + if not active_env or active_env == '' then + return + end + + -- Set up file paths + local build_dir = vim.misc.joinPath(vim.uv.cwd(), '.pio', 'build', active_env) + local checksum_path = vim.misc.joinPath(build_dir, 'project.checksum') + local idedata_path = vim.misc.joinPath(build_dir, 'idedata.json') - -- Helper: Internal logic to apply data to _G.metadata - local function apply_metadata(data) + --------------------------------------------------------- + -- INTERNAL PROCESSOR: Applies parsed data to _G.metadata + --------------------------------------------------------- + local function apply_metadata(data, checksum) if not data then return false end - local norm = function(p) return misc.normalizePath(p) or "" end + + local norm = function(p) return vim.misc.normalizePath(p) or '' end + + -- Helper for flags/defines to keep order and formatting local quote_map = function(list, prefix) local res = {} for _, v in ipairs(list or {}) do @@ -80,65 +94,95 @@ function M.pio_refresh(callback) return res end + -- 1. Base Paths & Compilers meta.cc_path = norm(data.cc_path) meta.cc_compiler = meta.cc_path meta.cxx_path = norm(data.cxx_path) meta.gdb_path = norm(data.gdb_path) + + -- 2. Flags & Defines meta.cc_flags = quote_map(data.cc_flags) meta.cxx_flags = quote_map(data.cxx_flags) meta.defines = quote_map(data.defines) + -- 3. Includes (Build, Toolchain, Compatlib) local inc = data.includes or {} - meta.includes_build = quote_map(inc.build, "-I") - meta.includes_toolchain = quote_map(inc.toolchain, "-isystem") - meta.includes_compatlib = quote_map(inc.compatlib, "-isystem") - + meta.includes_build = quote_map(inc.build, '-I') + meta.includes_toolchain = quote_map(inc.toolchain, '-isystem') + meta.includes_compatlib = quote_map(inc.compatlib, '-isystem') + meta.last_checksum = checksum pcall(M.get_sysroot_triplet, meta.cc_compiler) + if callback then callback() end return true end - -- 1. Try Fast Path: Read idedata.json directly - local idedata_path = vim.fs.joinpath(vim.uv.cwd(), '.pio/build', active_env, 'idedata.json') - -- local idedata_path = string.format("%s/.pio/build/%s/idedata.json", vim.uv.cwd(), active_env) - print(idedata_path) - local content = vim.misc.readFile(idedata_path) - - if content then - local ok, decoded = pcall(vim.json.decode, content) - if ok and apply_metadata(decoded) then - vim.notify('PIO: Metadata loaded from cache', vim.log.levels.INFO) - return + --------------------------------------------------------- + -- STEP 1: Fast Checksum Check + --------------------------------------------------------- + local current_checksum = vim.misc.readFile(checksum_path) + if current_checksum and current_checksum ~= '' then + if current_checksum == meta.last_checksum then return end -- Already updated + + -- STEP 2: Cache Path (idedata.json exists and checksum changed) + local content = vim.misc.readFile(idedata_path) + if content then + local ok, decoded = pcall(vim.json.decode, content) + if ok and apply_metadata(decoded, current_checksum) then + vim.notify('PIO: Metadata synced from cache', vim.log.levels.INFO) + return + end end end - -- 2. Fallback Path: Call PIO CLI - vim.notify('PIO: Fetching metadata via CLI...', vim.log.levels.INFO) + --------------------------------------------------------- + -- STEP 3: Auto-Initialize (If files are missing) + --------------------------------------------------------- + if not current_checksum then + vim.notify('PIO: Initializing project metadata...', vim.log.levels.WARN) + vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env }, { text = true }, function(obj) + vim.schedule(function() + if obj.code == 0 then + get_metadata(attempts, active_env) -- Recursive call after files created + else + vim.notify('PIO: Initialization failed. Build project manually.', vim.log.levels.ERROR) + end + end) + end) + return + end + + --------------------------------------------------------- + -- STEP 4: Standard CLI Fallback (The Slow Path) + --------------------------------------------------------- + vim.notify('PIO: Fetching fresh metadata...', vim.log.levels.INFO) vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(obj) vim.schedule(function() if obj.code ~= 0 then if attempts > 0 then vim.defer_fn(function() get_metadata(attempts - 1, env) end, 500) + return end - return + return vim.notify('PIO Metadata Error: ' .. (obj.stderr or 'Unknown'), vim.log.levels.WARN) end - local ok, raw_data = pcall(vim.json.decode, obj.stdout or "") - -- PIO CLI wraps the env data in a table keyed by env name + local ok, raw_data = pcall(vim.json.decode, obj.stdout or '') local _, data = next(raw_data or {}) - if ok and apply_metadata(data) then + if ok and apply_metadata(data, current_checksum) then vim.notify('PIO: Metadata sync successful', vim.log.levels.INFO) else - vim.notify("PIO: Failed to parse CLI output", vim.log.levels.WARN) + vim.notify('PIO: Failed to parse metadata output', vim.log.levels.WARN) end end) end) end - -- - ---------------- + ------------------------------------------------------------------------------------------------------------- + + -- INFO:------------------------------------------------- + -- get pio project config info + --------------------------------------------------------- -- stylua: ignore - -- INFO: get project config local function fetch_config() local meta = _G.metadata local home = (os.getenv('HOME') or os.getenv('USERPROFILE') or ""):gsub('[\\/]+$', '') diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index ba7baebb..8da361ae 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -6,6 +6,12 @@ M.devNul = M.is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' +--INFO: +-- Version-Safe Path Joining (Fallback for Neovim < 0.10.0) +-- stylua: ignore +M.joinPath = vim.fs.joinpath or function(...) + return table.concat({ ... }, '/'):gsub('//+', '/') +end ------------------------------------------------------ --INFO: -- iterrative loop 48ms diff --git a/tmp1.lua b/tmp1.lua new file mode 100644 index 00000000..ebb2c410 --- /dev/null +++ b/tmp1.lua @@ -0,0 +1,122 @@ +local function get_metadata(attempts, env) + local meta = _G.metadata + local active_env = env or meta.active_env + if not active_env or active_env == '' then + return + end + + -- Set up file paths + local build_dir = vim.misc.joinPath(vim.uv.cwd(), '.pio', 'build', active_env) + local checksum_path = vim.misc.joinPath(build_dir, 'project.checksum') + local idedata_path = vim.misc.joinPath(build_dir, 'idedata.json') + + --------------------------------------------------------- + -- INTERNAL PROCESSOR: Applies parsed data to _G.metadata + --------------------------------------------------------- + local function apply_metadata(data, checksum) + if not data then + return false + end + + local norm = function(p) + return vim.misc.normalizePath(p) or '' + end + + local quote_map = function(list, prefix) + local res = {} + for _, v in ipairs(list or {}) do + local val = prefix and (prefix .. norm(v)) or v + table.insert(res, string.format('%q', val)) + end + return res + end + + -- 1. Base Paths & Compilers + meta.cc_path = norm(data.cc_path) + meta.cc_compiler = meta.cc_path + meta.cxx_path = norm(data.cxx_path) + meta.gdb_path = norm(data.gdb_path) + + -- 2. Flags & Defines + meta.cc_flags = quote_map(data.cc_flags) + meta.cxx_flags = quote_map(data.cxx_flags) + meta.defines = quote_map(data.defines) + + -- 3. Includes (Build, Toolchain, Compatlib) + local inc = data.includes or {} + meta.includes_build = quote_map(inc.build, '-I') + meta.includes_toolchain = quote_map(inc.toolchain, '-isystem') + meta.includes_compatlib = quote_map(inc.compatlib, '-isystem') + meta.last_checksum = checksum + pcall(M.get_sysroot_triplet, meta.cc_compiler) + + if callback then + callback() + end + return true + end + + --------------------------------------------------------- + -- STEP 1: Fast Checksum Check + --------------------------------------------------------- + local current_checksum = vim.misc.readFile(checksum_path) + if current_checksum and current_checksum ~= '' then + if current_checksum == meta.last_checksum then + return + end -- Already updated + + -- STEP 2: Cache Path (idedata.json exists and checksum changed) + local content = vim.misc.readFile(idedata_path) + if content then + local ok, decoded = pcall(vim.json.decode, content) + if ok and apply_metadata(decoded, current_checksum) then + vim.notify('PIO: Metadata synced from cache', vim.log.levels.INFO) + return + end + end + end + + --------------------------------------------------------- + -- STEP 3: Auto-Initialize (If files are missing) + --------------------------------------------------------- + if not current_checksum then + vim.notify('PIO: Initializing project metadata...', vim.log.levels.WARN) + vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env }, { text = true }, function(obj) + vim.schedule(function() + if obj.code == 0 then + get_metadata(attempts, active_env) -- Recursive call after files created + else + vim.notify('PIO: Initialization failed. Build project manually.', vim.log.levels.ERROR) + end + end) + end) + return + end + + --------------------------------------------------------- + -- STEP 4: Standard CLI Fallback (The Slow Path) + --------------------------------------------------------- + vim.notify('PIO: Fetching fresh metadata...', vim.log.levels.INFO) + vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(obj) + vim.schedule(function() + if obj.code ~= 0 then + if attempts > 0 then + vim.defer_fn(function() + get_metadata(attempts - 1, env) + end, 500) + return + end + return vim.notify('PIO Metadata Error: ' .. (obj.stderr or 'Unknown'), vim.log.levels.WARN) + end + + local ok, raw_data = pcall(vim.json.decode, obj.stdout or '') + local _, data = next(raw_data or {}) + + if ok and apply_metadata(data, current_checksum) then + vim.notify('PIO: Metadata sync successful', vim.log.levels.INFO) + else + vim.notify('PIO: Failed to parse metadata output', vim.log.levels.WARN) + end + end) + end) +end From 3c75007cb1393fd569aaa640be02415cb0cb6df5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 17:24:26 +0300 Subject: [PATCH 0962/1406] update --- lua/platformio/pio_setup.lua | 26 +++++++++++++------------- lua/platformio/utils/pio.lua | 23 ++++++++++++----------- 2 files changed, 25 insertions(+), 24 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 43023279..42d1da5e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -138,19 +138,19 @@ function M.pio_refresh(callback) --------------------------------------------------------- -- STEP 3: Auto-Initialize (If files are missing) --------------------------------------------------------- - if not current_checksum then - vim.notify('PIO: Initializing project metadata...', vim.log.levels.WARN) - vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env }, { text = true }, function(obj) - vim.schedule(function() - if obj.code == 0 then - get_metadata(attempts, active_env) -- Recursive call after files created - else - vim.notify('PIO: Initialization failed. Build project manually.', vim.log.levels.ERROR) - end - end) - end) - return - end + -- if not current_checksum then + -- vim.notify('PIO: Initializing project metadata...', vim.log.levels.WARN) + -- vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env }, { text = true }, function(obj) + -- vim.schedule(function() + -- if obj.code == 0 then + -- get_metadata(attempts, active_env) -- Recursive call after files created + -- else + -- vim.notify('PIO: Initialization failed. Build project manually.', vim.log.levels.ERROR) + -- end + -- end) + -- end) + -- return + -- end --------------------------------------------------------- -- STEP 4: Standard CLI Fallback (The Slow Path) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 977cdf70..571f54f2 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -256,14 +256,9 @@ function M.handlePioinit(result) if commandPassed == 1 then vim.schedule(function() vim.notify('Pioinit: commandPassed', vim.log.levels.INFO) - local pio_refresh = require('platformio.pio_setup').pio_refresh - vim.defer_fn(function() - pio_refresh(function() - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - boilerplate_gen([[.clangd]], _G.metadata.core_dir) - end) - end, 500) + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') + boilerplate_gen([[.clangd]], _G.metadata.core_dir) end) -- elseif commandPassed == 2 then end @@ -273,11 +268,17 @@ function M.handlePioinit(result) pio_buffer = '' M.queue = {} -- Clear queue on any other status (failure) term.stdout_callback = nil + + local pio_refresh = require('platformio.pio_setup').pio_refresh vim.defer_fn(function() - vim.notify('compiledb: Pass', vim.log.levels.INFO) - vim.misc.gitignore_lsp_configs('compile_commands.json') - _G.metadata.dbTrigger = true + pio_refresh(function() + vim.notify('compiledb: Pass', vim.log.levels.INFO) + vim.misc.gitignore_lsp_configs('compile_commands.json') + _G.metadata.dbTrigger = true + end) end, 500) + + vim.defer_fn(function() end, 500) elseif result == 'FAIL' then pio_buffer = '' M.queue = {} -- Clear queue on any other status (failure) From a27e5edfe0a522f9d1d9fceecf498f5b1226db4f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 17:31:50 +0300 Subject: [PATCH 0963/1406] update --- lua/platformio/utils/pio.lua | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 571f54f2..2e63519d 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -270,15 +270,13 @@ function M.handlePioinit(result) term.stdout_callback = nil local pio_refresh = require('platformio.pio_setup').pio_refresh - vim.defer_fn(function() - pio_refresh(function() - vim.notify('compiledb: Pass', vim.log.levels.INFO) - vim.misc.gitignore_lsp_configs('compile_commands.json') - _G.metadata.dbTrigger = true - end) - end, 500) - - vim.defer_fn(function() end, 500) + -- vim.defer_fn(function() + pio_refresh(function() + vim.notify('compiledb: Pass', vim.log.levels.INFO) + vim.misc.gitignore_lsp_configs('compile_commands.json') + _G.metadata.dbTrigger = true + end) + -- end, 500) elseif result == 'FAIL' then pio_buffer = '' M.queue = {} -- Clear queue on any other status (failure) From 599d0435a2daf8e4aebd11e6ee7f73373651e918 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 17:35:05 +0300 Subject: [PATCH 0964/1406] update --- lua/platformio/utils/pio.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 2e63519d..3e8833a5 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -276,7 +276,6 @@ function M.handlePioinit(result) vim.misc.gitignore_lsp_configs('compile_commands.json') _G.metadata.dbTrigger = true end) - -- end, 500) elseif result == 'FAIL' then pio_buffer = '' M.queue = {} -- Clear queue on any other status (failure) From bcf55b48bf7537b5b1c9396192c27fcbfccf089b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 17:37:19 +0300 Subject: [PATCH 0965/1406] update --- lua/platformio/utils/pio.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 3e8833a5..8c5a821c 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -265,6 +265,7 @@ function M.handlePioinit(result) local full_cmd = table.remove(M.queue, 1) term.ToggleTerminal(full_cmd, 'float') elseif result == 'DONE' then -- compile_commands.json created + vim.notify('compiledb: Pass', vim.log.levels.INFO) pio_buffer = '' M.queue = {} -- Clear queue on any other status (failure) term.stdout_callback = nil From 549e9856ded316479b175aa0223047b02ad703ef Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 17:41:51 +0300 Subject: [PATCH 0966/1406] update --- lua/platformio/utils/pio.lua | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 8c5a821c..549ff740 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -265,17 +265,19 @@ function M.handlePioinit(result) local full_cmd = table.remove(M.queue, 1) term.ToggleTerminal(full_cmd, 'float') elseif result == 'DONE' then -- compile_commands.json created - vim.notify('compiledb: Pass', vim.log.levels.INFO) - pio_buffer = '' - M.queue = {} -- Clear queue on any other status (failure) - term.stdout_callback = nil - - local pio_refresh = require('platformio.pio_setup').pio_refresh - -- vim.defer_fn(function() - pio_refresh(function() + vim.schedule(function() vim.notify('compiledb: Pass', vim.log.levels.INFO) - vim.misc.gitignore_lsp_configs('compile_commands.json') - _G.metadata.dbTrigger = true + pio_buffer = '' + M.queue = {} -- Clear queue on any other status (failure) + term.stdout_callback = nil + + local pio_refresh = require('platformio.pio_setup').pio_refresh + -- vim.defer_fn(function() + pio_refresh(function() + vim.notify('compiledb: Pass', vim.log.levels.INFO) + vim.misc.gitignore_lsp_configs('compile_commands.json') + _G.metadata.dbTrigger = true + end) end) elseif result == 'FAIL' then pio_buffer = '' From 3f87a9466da6a63d8174fc286aff0859d189fb86 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 17:49:43 +0300 Subject: [PATCH 0967/1406] update --- lua/platformio/utils/pio.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 549ff740..f2097250 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -244,6 +244,7 @@ end local commandPassed = 0 -- Handle after pioinit execution function M.handlePioinit(result) + vim.notify(result, vim.log.levels.INFO) if result == 'INIT' then commandPassed = 0 _G.metadata.isBusy = true From e93eca734bd482ad908003f3525bfe169e8b9ddf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 17:54:13 +0300 Subject: [PATCH 0968/1406] update --- lua/platformio/utils/pio.lua | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f2097250..0fd00733 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -208,7 +208,10 @@ function M.stdoutcallback(_, _, data) -- vim.schedule(function() callBack('DONE') end) -- elseif status == 'FAIL' then -- callBack('PASS') - callBack(status) + -- callBack(status) + vim.schedule(function() + callBack(status) + end) -- vim.schedule(function() callBack('DONE') end) -- end break From 82a219b5f211a90d5e11243155636e3ccba6107c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 17:56:26 +0300 Subject: [PATCH 0969/1406] update --- lua/platformio/utils/pio.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 0fd00733..5cd0928d 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -197,10 +197,10 @@ function M.stdoutcallback(_, _, data) for status in pio_buffer:gmatch('_CMMNDS_:(%a+)') do if callBack and status then - if status == 'PASS' then - -- Store the last element as the new partial buffer for the next call - pio_buffer = data[#data] - end + pio_buffer = data[#data] + -- if status == 'PASS' then + -- -- Store the last element as the new partial buffer for the next call + -- end -- vim.schedule(function() callBack('PASS') end) -- callBack('PASS') -- elseif status == 'DONE' then From e3c733130369ddb677b368f098dd6bacd0562b62 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 18:07:01 +0300 Subject: [PATCH 0970/1406] update --- lua/platformio/utils/pio.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 5cd0928d..a0a6ed35 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -266,6 +266,7 @@ function M.handlePioinit(result) end) -- elseif commandPassed == 2 then end + pio_buffer = '' local full_cmd = table.remove(M.queue, 1) term.ToggleTerminal(full_cmd, 'float') elseif result == 'DONE' then -- compile_commands.json created From fb88ca371134e122c5725201d4368cd6cb4901f4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 18:16:58 +0300 Subject: [PATCH 0971/1406] update --- lua/platformio/pio_setup.lua | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 42d1da5e..860ede4d 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -325,7 +325,9 @@ function M.start_watcher() M.pio_refresh(function() -- pio_generate_db() -- M.run_compiledb() - M.run_compiledb() -- Smart: Auto-update DB if config changes + + -- M.run_compiledb() -- Smart: Auto-update DB if config changes + -- lsp_restart('clangd') end) end @@ -413,7 +415,9 @@ function M.init() -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) -- pio_generate_db() -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) - M.run_compiledb() -- Smart: Auto-update DB if config changes + + -- M.run_compiledb() -- Smart: Auto-update DB if config changes + -- lsp_restart('clangd') -- end) end) From b33b7cc693e043506ce40c8dd09ea0850b001211 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 18:18:43 +0300 Subject: [PATCH 0972/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index a0a6ed35..73f44925 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -259,7 +259,7 @@ function M.handlePioinit(result) commandPassed = commandPassed + 1 if commandPassed == 1 then vim.schedule(function() - vim.notify('Pioinit: commandPassed', vim.log.levels.INFO) + vim.notify('Pioinit: commandPassed ..', vim.log.levels.INFO) local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') boilerplate_gen([[.clangd]], _G.metadata.core_dir) From 3572cbb4efa68b9ccec2470b36e717ca2b130cbe Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 18:47:50 +0300 Subject: [PATCH 0973/1406] update --- lua/platformio/utils/pio.lua | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 73f44925..0b247d56 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -176,22 +176,19 @@ end -local pio_buffer = '' -- Persistent stream buffer local callBack = nil ------------------------------------------------------ -- INFO: ToggleTerminal commands stdout filter --- stylua: ignore function M.stdoutcallback(_, _, data) - if #M.queue == 0 then - return - end + local pio_buffer = '' -- Persistent stream buffer -- 1. attach partial buffer from previous data last line to 1st line pio_buffer = pio_buffer .. data[1] -- 2. If the chunk has more than one element, we've encountered newlines if #data > 1 then -- 3. Process any "middle" lines which are guaranteed to be complete - for i = 2, #data - 1 do + for i = 2, #data do pio_buffer = pio_buffer .. data[i] end @@ -218,9 +215,9 @@ function M.stdoutcallback(_, _, data) end end end - if #pio_buffer > 10000 then - pio_buffer = pio_buffer:sub(-5000) - end + -- if #pio_buffer > 10000 then + -- pio_buffer = pio_buffer:sub(-5000) + -- end end -- stylua: ignore @@ -251,7 +248,7 @@ function M.handlePioinit(result) if result == 'INIT' then commandPassed = 0 _G.metadata.isBusy = true - pio_buffer = '' + -- pio_buffer = '' local full_cmd = table.remove(M.queue, 1) term.stdout_callback = M.stdoutcallback term.ToggleTerminal(full_cmd, 'float') @@ -266,13 +263,13 @@ function M.handlePioinit(result) end) -- elseif commandPassed == 2 then end - pio_buffer = '' + -- pio_buffer = '' local full_cmd = table.remove(M.queue, 1) term.ToggleTerminal(full_cmd, 'float') elseif result == 'DONE' then -- compile_commands.json created vim.schedule(function() vim.notify('compiledb: Pass', vim.log.levels.INFO) - pio_buffer = '' + -- pio_buffer = '' M.queue = {} -- Clear queue on any other status (failure) term.stdout_callback = nil @@ -285,7 +282,7 @@ function M.handlePioinit(result) end) end) elseif result == 'FAIL' then - pio_buffer = '' + -- pio_buffer = '' M.queue = {} -- Clear queue on any other status (failure) term.stdout_callback = nil end From 3353f521c498344648be7418727d1dbdb9ab127f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 19:47:46 +0300 Subject: [PATCH 0974/1406] update --- lua/platformio/pio_setup.lua | 8 ++------ lua/platformio/utils/misc.lua | 37 +++++++++++++++++++++++++---------- lua/platformio/utils/pio.lua | 25 +++++++++++------------ 3 files changed, 42 insertions(+), 28 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 860ede4d..42d1da5e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -325,9 +325,7 @@ function M.start_watcher() M.pio_refresh(function() -- pio_generate_db() -- M.run_compiledb() - - -- M.run_compiledb() -- Smart: Auto-update DB if config changes - + M.run_compiledb() -- Smart: Auto-update DB if config changes -- lsp_restart('clangd') end) end @@ -415,9 +413,7 @@ function M.init() -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) -- pio_generate_db() -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) - - -- M.run_compiledb() -- Smart: Auto-update DB if config changes - + M.run_compiledb() -- Smart: Auto-update DB if config changes -- lsp_restart('clangd') -- end) end) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 8da361ae..f0f1a157 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -187,27 +187,44 @@ end -- local ok, err = writeFiile(path, json) -- if ok then print("Write complete!") end -- stylua: ignore -function M.writeFile(data, path) +function M.writeFile(path, data, opts) local uv = vim.uv or vim.loop + opts = opts or {} + -- opts.overwrite: boolean (default true) + -- opts.mkdir: boolean (default true) + + -- 1. Check if file exists and handle overwrite flag + local stat = uv.fs_stat(path) + if stat and opts.overwrite == false then + return nil, 'writeFile: File already exists and overwrite is disabled' + end - -- 1. Open file for writing - -- 'w' = open for writing (creates if doesn't exist, truncates if it does) - -- 438 is octal 0666 (standard read/write permissions) - local fd, err = uv.fs_open(path, 'w', 438) - if not fd or err then return nil, 'writeFile: Open error: ' .. err end + -- 2. Ensure folder exists (mkdir -p logic) + if opts.mkdir ~= false then + local parent = vim.fn.fnamemodify(path, ':h') + if uv.fs_stat(parent) == nil then + -- 448 is octal 0700 (user read/write/execute) + -- Using vim.fn.mkdir is easier for recursive creation + vim.fn.mkdir(parent, 'p') + end + end - -- 2. Write the data - -- fd, data, offset (0 to start at beginning) + -- 3. Open file for writing + -- 'w' truncates existing, 'wx' fails if exists (extra safety) + local flags = opts.overwrite == false and 'wx' or 'w' + local fd, err = uv.fs_open(path, flags, 438) + if not fd then return nil, 'writeFile: Open error: ' .. (err or 'unknown') end + + -- 4. Write data local _, write_err = uv.fs_write(fd, data, 0) - -- 3. ALWAYS close the file descriptor + -- 5. ALWAYS close uv.fs_close(fd) if write_err then return nil, 'writeFile: Write error: ' .. write_err end return true end - ------------------------------------------------------ --[[ Targets Windows paths, normalizes slashes, and fixes smashed PlatformIO paths. diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 0b247d56..4bd4d9e2 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -17,6 +17,7 @@ function M.compile_commandsFix() --M.dbPathsFix() local content = vim.fn.readfile(filename) if #content == 0 then return end + local start_time = vim.loop.hrtime() local ok, data = pcall(vim.json.decode, table.concat(content, '\n')) if not ok or type(data) ~= 'table' then return end @@ -61,8 +62,6 @@ function M.compile_commandsFix() --M.dbPathsFix() -- print(string.format('ful_compiler_path = %s flags=%s', full_compiler_path, args)) prntFlags = false end - -- local argsFormated = misc.normalizeFlags(args) - -- entry.command = full_compiler_path .. argsFormated entry.command = full_compiler_path .. args modified = true end @@ -72,7 +71,7 @@ function M.compile_commandsFix() --M.dbPathsFix() end -- -- 3. Save with Formatting if modified then - local start_time = vim.loop.hrtime() + -- local start_time = vim.loop.hrtime() local jok, formatted = pcall(vim.misc.jsonFormat, data) -- local jok, formatted = pcall(M.pretty_print, data) @@ -81,20 +80,22 @@ function M.compile_commandsFix() --M.dbPathsFix() return end - local f = io.open(filename, 'w') - if f then - f:write(formatted) - f:close() - print('Fixed and formatted ' .. filename) - end + local wk, err = M.writeFile(filename, formatted, { overwrite = true, mkdir = true }) + if not wk then print(err) end + + -- local f = io.open(filename, 'w') + -- if f then + -- f:write(formatted) + -- f:close() + -- print('Fixed and formatted ' .. filename) + -- end local end_time = vim.loop.hrtime() local duration = (end_time - start_time) / 1e6 - print(string.format('Saved %s in %.2fms', filename, duration)) - vim.notify('compiledb: paths fixed', vim.log.levels.INFO) + vim.notify(string.format('compiledb: paths fixed in %.2fms', duration), vim.log.levels.INFO) lsp_restart('clangd') - _G.metadata.isBusy = false end + _G.metadata.isBusy = false end From 49b40c9fde9090249d919b96f03016364397b12d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 19:52:02 +0300 Subject: [PATCH 0975/1406] update --- lua/platformio/utils/pio.lua | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 4bd4d9e2..2f9a4987 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -249,7 +249,6 @@ function M.handlePioinit(result) if result == 'INIT' then commandPassed = 0 _G.metadata.isBusy = true - -- pio_buffer = '' local full_cmd = table.remove(M.queue, 1) term.stdout_callback = M.stdoutcallback term.ToggleTerminal(full_cmd, 'float') @@ -257,7 +256,7 @@ function M.handlePioinit(result) commandPassed = commandPassed + 1 if commandPassed == 1 then vim.schedule(function() - vim.notify('Pioinit: commandPassed ..', vim.log.levels.INFO) + vim.notify('Pioinit: Done ..', vim.log.levels.INFO) local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') boilerplate_gen([[.clangd]], _G.metadata.core_dir) @@ -269,23 +268,21 @@ function M.handlePioinit(result) term.ToggleTerminal(full_cmd, 'float') elseif result == 'DONE' then -- compile_commands.json created vim.schedule(function() - vim.notify('compiledb: Pass', vim.log.levels.INFO) - -- pio_buffer = '' - M.queue = {} -- Clear queue on any other status (failure) + vim.notify('compiledb: Done', vim.log.levels.INFO) + M.queue = {} term.stdout_callback = nil - local pio_refresh = require('platformio.pio_setup').pio_refresh -- vim.defer_fn(function() pio_refresh(function() - vim.notify('compiledb: Pass', vim.log.levels.INFO) + vim.notify('metadata: refreshed', vim.log.levels.INFO) vim.misc.gitignore_lsp_configs('compile_commands.json') _G.metadata.dbTrigger = true end) end) elseif result == 'FAIL' then - -- pio_buffer = '' - M.queue = {} -- Clear queue on any other status (failure) + M.queue = {} term.stdout_callback = nil + _G.metadata.isBusy = false end end From bb25a5727ecdeba74b5bdc937a774695c700aed4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 20:34:36 +0300 Subject: [PATCH 0976/1406] update --- lua/platformio/metadata.lua | 2 +- lua/platformio/pio_setup.lua | 2 +- lua/platformio/utils/pio.lua | 94 ------------------------------------ 3 files changed, 2 insertions(+), 96 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 497c292e..89acb907 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -40,7 +40,7 @@ local _pio_metadata = { query_driver = '', cc_compiler = '', includes_build = {}, - includes_comaptlib = {}, + includes_compatlib = {}, includes_toolchain = {}, cc_path = '', cc_flags = {}, diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 42d1da5e..89b1dbe0 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -89,7 +89,7 @@ function M.pio_refresh(callback) local res = {} for _, v in ipairs(list or {}) do local val = prefix and (prefix .. norm(v)) or v - table.insert(res, string.format('%q', val)) + table.insert(res, string.format('%s', val)) end return res end diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 2f9a4987..143d1050 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -245,7 +245,6 @@ end local commandPassed = 0 -- Handle after pioinit execution function M.handlePioinit(result) - vim.notify(result, vim.log.levels.INFO) if result == 'INIT' then commandPassed = 0 _G.metadata.isBusy = true @@ -286,99 +285,6 @@ function M.handlePioinit(result) end end ------------------------------------------------------- --- INFO: ToggleTerminal commands sequencer - --- local pio_buffer = '' -- Persistent stream buffer --- ------------------------------------------------------ --- -- INFO: ToggleTerminal commands stdout filter --- -- stylua: ignore --- function M.stdoutcallback(_, _, data) --- if #M.queue == 0 then return end --- --- -- 1. attach partial buffer from previous data last line to 1st line --- pio_buffer = pio_buffer .. data[1] --- -- 2. If the chunk has more than one element, we've encountered newlines --- if #data > 1 then --- -- 3. Process any "middle" lines which are guaranteed to be complete --- for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end --- --- for status in pio_buffer:gmatch('_CMMNDS_:(%a+)') do --- if status then --- -- if status == 'PASS' then --- -- pio_buffer = data[#data] --- -- vim.schedule(function() M.process_queue() end) --- -- elseif status == 'FAIL' then --- -- end --- if status == 'PASS' then --- -- 4. Store the last element as the new partial buffer for the next call --- pio_buffer = data[#data] --- local task = table.remove(M.queue, 1) --- if task then vim.schedule(task) end --- elseif status == 'DONE' then --- pio_buffer = '' --- M.queue = {} -- Clear queue on any other status --- local task = table.remove(M.queue, 1) --- if task then vim.schedule(task) end --- elseif status == 'FAIL' then --- pio_buffer = '' --- M.queue = {} -- Clear queue on any other status (failure) --- local task = table.remove(M.queue, 1) --- if task then vim.schedule(task) end --- end --- break --- end --- end --- end --- if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end --- end --- --- ------------------------------------------------------ --- -- INFO: ToggleTerminal commands Sequencer --- -- Semicolon (;): Runs the next command regardless of whether the first one succeeded. --- -- Success Operator (&&): Runs the second command only if the first succeeds. --- -- Fail Operator (||): Runs if any of the previous commands fail --- --- stylua: ignore --- M.run_sequence = function(tasks) --- -- Reset local state for new run --- M.queue = {} --- pio_buffer = '' --- local full_cmd = '' --- local done = ' && echo _CMMNDS_":"DONE' --- local pass = ' && echo _CMMNDS_":"PASS' --- local fail = ' || echo _CMMNDS_":"FAIL' --- -- --- for _, task in ipairs(tasks) do --- table.insert(M.queue, task.cb) --- local part = string.format('%s %s', task.cmd, pass) --- if full_cmd == '' then --- full_cmd = part --- else --- full_cmd = full_cmd .. ' && ' .. part --- end --- end --- full_cmd = full_cmd .. done .. fail --- --- table.insert(M.queue, function() --- vim.notify('Pioinit: Done', vim.log.levels.INFO) --- term.stdout_callback = nil --- end) --- --- table.insert(M.queue, function() --- vim.notify('Pioinit: Failed', vim.log.levels.INFO) --- end) --- --- -- full_cmd = full_cmd .. ' || ' .. fail --- _G.metadata.isBusy = true --- -- local ToggleTerminal = require('platformio.utils.term').ToggleTerminal --- term.stdout_callback = M.stdoutcallback --- term.ToggleTerminal(full_cmd, 'float') --- end --- --- { --- cmd = 'echo _CMMNDS_":"DONE', --- cb = function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end --- }, ------------------------------------------------------ -- Handle after 'pio run -t compiledb' execution function M.handleDb() From f727c86d26542a84958cb99ddb797eeb34fc6f79 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 20:49:16 +0300 Subject: [PATCH 0977/1406] update --- lua/platformio/metadata.lua | 2 +- lua/platformio/pio_setup.lua | 6 +++--- lua/platformio/utils/pio.lua | 20 +++++++++----------- 3 files changed, 13 insertions(+), 15 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 89acb907..6c727b8a 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -76,7 +76,7 @@ _G.metadata = setmetatable({}, { local dbFix = pio.compile_commandsFix local ok, _ = pcall(dbFix) if not ok then - print('Env: dbTrigger') + print('Env: dbTrigger, fail to call dbFix') end -- dbFix() _pio_metadata.dbTrigger = false diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 89b1dbe0..8dfc371c 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -57,8 +57,8 @@ function M.get_sysroot_triplet(cc_compiler) end -- stylua: ignore -function M.pio_refresh(callback) - vim.notify('PIO: Fetching PIO config ...', vim.log.levels.INFO) +function M.pio_refreh(callback) + vim.notify('PIO: Config sync ...', vim.log.levels.INFO) -- stylua: ignore -- INFO:------------------------------------------------- @@ -155,7 +155,7 @@ function M.pio_refresh(callback) --------------------------------------------------------- -- STEP 4: Standard CLI Fallback (The Slow Path) --------------------------------------------------------- - vim.notify('PIO: Fetching fresh metadata...', vim.log.levels.INFO) + vim.notify('PIO: Metadata sync ...', vim.log.levels.INFO) vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(obj) vim.schedule(function() if obj.code ~= 0 then diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 143d1050..f30557ba 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -58,7 +58,6 @@ function M.compile_commandsFix() --M.dbPathsFix() full_compiler_path = '"' .. full_compiler_path .. '"' end if prntFlags then - print(string.format('ful_compiler_path = %s', full_compiler_path)) -- print(string.format('ful_compiler_path = %s flags=%s', full_compiler_path, args)) prntFlags = false end @@ -80,15 +79,15 @@ function M.compile_commandsFix() --M.dbPathsFix() return end - local wk, err = M.writeFile(filename, formatted, { overwrite = true, mkdir = true }) - if not wk then print(err) end + -- local wk, err = M.writeFile(filename, formatted, { overwrite = true, mkdir = true }) + -- if not wk then print(err) end - -- local f = io.open(filename, 'w') - -- if f then - -- f:write(formatted) - -- f:close() - -- print('Fixed and formatted ' .. filename) - -- end + local f = io.open(filename, 'w') + if f then + f:write(formatted) + f:close() + print('Fixed and formatted ' .. filename) + end local end_time = vim.loop.hrtime() local duration = (end_time - start_time) / 1e6 @@ -267,13 +266,12 @@ function M.handlePioinit(result) term.ToggleTerminal(full_cmd, 'float') elseif result == 'DONE' then -- compile_commands.json created vim.schedule(function() - vim.notify('compiledb: Done', vim.log.levels.INFO) + vim.notify('compiledb: Done ..', vim.log.levels.INFO) M.queue = {} term.stdout_callback = nil local pio_refresh = require('platformio.pio_setup').pio_refresh -- vim.defer_fn(function() pio_refresh(function() - vim.notify('metadata: refreshed', vim.log.levels.INFO) vim.misc.gitignore_lsp_configs('compile_commands.json') _G.metadata.dbTrigger = true end) From 558de0269aa7a432273babadcb9ff0a3423ecf50 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 20:58:46 +0300 Subject: [PATCH 0978/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 8dfc371c..a0b9fe2e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -57,7 +57,7 @@ function M.get_sysroot_triplet(cc_compiler) end -- stylua: ignore -function M.pio_refreh(callback) +function M.pio_refresh(callback) vim.notify('PIO: Config sync ...', vim.log.levels.INFO) -- stylua: ignore From d3e4dac5a9aa568e01d2fe680738bb55a53c4980 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 21:03:07 +0300 Subject: [PATCH 0979/1406] update --- lua/platformio/utils/pio.lua | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f30557ba..b0acf589 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -79,15 +79,15 @@ function M.compile_commandsFix() --M.dbPathsFix() return end - -- local wk, err = M.writeFile(filename, formatted, { overwrite = true, mkdir = true }) - -- if not wk then print(err) end - - local f = io.open(filename, 'w') - if f then - f:write(formatted) - f:close() - print('Fixed and formatted ' .. filename) - end + local wk, err = M.writeFile(filename, formatted, { overwrite = true, mkdir = true }) + if not wk then print(err) end + + -- local f = io.open(filename, 'w') + -- if f then + -- f:write(formatted) + -- f:close() + -- print('Fixed and formatted ' .. filename) + -- end local end_time = vim.loop.hrtime() local duration = (end_time - start_time) / 1e6 From 9ee340d785351916f7449642e2ecc1c7117d5ad3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 21:17:35 +0300 Subject: [PATCH 0980/1406] update --- lua/platformio/utils/pio.lua | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index b0acf589..f6141687 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -11,6 +11,10 @@ M.queue = {} local term = require('platformio.utils.term') local lsp_restart = require('platformio.lsp.tools').lsp_restart +-- INFO: +-- ============================================================================= +-- UNIVERSAL TOOLCHAIN DETECTION +-- ============================================================================= -- stylua: ignore function M.compile_commandsFix() --M.dbPathsFix() local filename = vim.fs.joinpath(vim.uv.cwd(), 'compile_commands.json') @@ -79,7 +83,7 @@ function M.compile_commandsFix() --M.dbPathsFix() return end - local wk, err = M.writeFile(filename, formatted, { overwrite = true, mkdir = true }) + local wk, err = vim.misc.writeFile(filename, formatted, { overwrite = true, mkdir = true }) if not wk then print(err) end -- local f = io.open(filename, 'w') From 6e43db171c1fd63cd8d77bcef7f66e5d68626157 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 22:12:14 +0300 Subject: [PATCH 0981/1406] update --- lua/platformio/pio_setup.lua | 31 +++--- lua/platformio/pioinit.lua | 13 --- lua/platformio/piolib.lua | 10 +- lua/platformio/utils/pio.lua | 199 ++++++++--------------------------- 4 files changed, 61 insertions(+), 192 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index a0b9fe2e..2fc89646 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -283,6 +283,12 @@ function M.run_compiledb() local dbFix = require('platformio.utils.pio').compile_commandsFix dbFix() vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) + + M.pio_refresh(function() + -- pio_generate_db() + -- M.run_compiledb() + -- lsp_restart('clangd') + end) -- Use pcall in case M.refresh is defined elsewhere -- pio_refresh(function() -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) @@ -322,12 +328,7 @@ function M.start_watcher() local new_hash = get_hash(ini_file) if new_hash and new_hash ~= current_ini_hash then current_ini_hash = new_hash - M.pio_refresh(function() - -- pio_generate_db() - -- M.run_compiledb() - M.run_compiledb() -- Smart: Auto-update DB if config changes - -- lsp_restart('clangd') - end) + M.run_compiledb() -- Smart: Auto-update DB if config changes end end) ) @@ -408,15 +409,15 @@ function M.init() -- If the file already exists, do an initial sync if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then - M.pio_refresh(function() - -- vim.schedule(function() - -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - -- pio_generate_db() - -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) - M.run_compiledb() -- Smart: Auto-update DB if config changes - -- lsp_restart('clangd') - -- end) - end) + M.run_compiledb() -- Smart: Auto-update DB if config changes + -- M.pio_refresh(function() + -- -- vim.schedule(function() + -- -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) + -- -- pio_generate_db() + -- -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) + -- -- lsp_restart('clangd') + -- -- end) + -- end) end end end diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 93a13bb2..d0a44ce2 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -65,19 +65,6 @@ local function pick_framework(board_details) 'pio run -t compiledb', }, cb = pio.handlePioinit, - -- { - -- cmd = 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', - -- -- cb = function () vim.notify('Pioinit: Pass', vim.log.levels.INFO) end - -- cb = pio.handlePioinitPass, - -- }, - -- { - -- cmd = 'pio run -t compiledb', - -- cb = pio.handleDb, - -- }, - -- { - -- cmd = 'echo _CMMNDS_":"DONE', - -- cb = function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end - -- }, }) end) return true diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 2d10de83..735679fc 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -63,17 +63,9 @@ local function pick_library(json_data) local pio = require('platformio.utils.pio') pio.run_sequence({ { - cmd = 'pio pkg install --library "' .. pkg_name .. '"', + cmnds = {'pio pkg install --library "' .. pkg_name .. '"'}, cb = function () vim.notify('Piolib: Done', vim.log.levels.INFO) end }, - -- { - -- cmd = 'pio run -t compiledb', - -- cb = pio.handleDb, - -- }, - -- { - -- cmd = 'echo _CMMNDS_":"LAST', - -- cb = function () vim.notify('Pioinit: Done', vim.log.levels.INFO) end - -- }, }) end) return true diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f6141687..746bb40a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -74,8 +74,6 @@ function M.compile_commandsFix() --M.dbPathsFix() end -- -- 3. Save with Formatting if modified then - -- local start_time = vim.loop.hrtime() - local jok, formatted = pcall(vim.misc.jsonFormat, data) -- local jok, formatted = pcall(M.pretty_print, data) if not jok then @@ -86,13 +84,6 @@ function M.compile_commandsFix() --M.dbPathsFix() local wk, err = vim.misc.writeFile(filename, formatted, { overwrite = true, mkdir = true }) if not wk then print(err) end - -- local f = io.open(filename, 'w') - -- if f then - -- f:write(formatted) - -- f:close() - -- print('Fixed and formatted ' .. filename) - -- end - local end_time = vim.loop.hrtime() local duration = (end_time - start_time) / 1e6 vim.notify(string.format('compiledb: paths fixed in %.2fms', duration), vim.log.levels.INFO) @@ -101,129 +92,38 @@ function M.compile_commandsFix() --M.dbPathsFix() _G.metadata.isBusy = false end - --- stylua: ignore --- function M.compile_commandsFix() --- local filename = vim.fs.joinpath(vim.uv.cwd(), 'compile_commands.json') --- if vim.fn.filereadable(filename) == 0 then return end --- --- -- 1. Read and Decode (Atomic read) --- local content = table.concat(vim.fn.readfile(filename), "\n") --- local ok, data = pcall(vim.json.decode, content) --- if not ok or type(data) ~= 'table' then return end --- --- -- 2. Build Path Map (Dynamic OS Separator) --- local sep = package.config:sub(1,1) --- local path_map = {} --- local toolchain = (_G.metadata and _G.metadata.toolchain_root or "") --- --- if toolchain ~= "" then --- local bin_glob = vim.fs.joinpath(toolchain, "bin", "*") --- for _, full_path in ipairs(vim.fn.glob(bin_glob, false, true)) do --- -- Correct regex for both / and \ --- local name = full_path:match("([^" .. sep .. "/]+)$"):gsub("%.exe$", "") --- path_map[name] = full_path --- end --- end --- --- -- 3. Update Entries --- local modified = false --- for _, entry in ipairs(data) do --- local cmd = entry.command or "" --- local first_token = cmd:match("^%S+") --- --- if first_token then --- -- Check if it's already absolute (starts with / or C:) --- local is_abs = first_token:sub(1,1) == '/' or first_token:match("^%a:") --- if not is_abs then --- local name = first_token:gsub("%.exe$", "") --- if path_map[name] then --- entry.command = path_map[name] .. cmd:sub(#first_token + 1) --- modified = true --- end --- end --- end --- end --- --- if modified then --- -- 1. Encode with 2-space indentation (This creates \n characters in the string) --- local ok, json_str = pcall(vim.json.encode, data, { indent = " " }) --- --- if ok and json_str then --- -- 2. FORCE SPLIT: Turn the one long string into a List of lines --- -- The { plain = true } ensures we split on the literal \n --- local lines = vim.split(json_str, "\n", { plain = true }) --- --- -- 3. Use writefile: --- -- Linux: joins table with \n --- -- Windows: joins table with \r\n (Fixing your single-line issue!) --- local status = vim.fn.writefile(lines, filename, 's') --- --- if status == 0 then --- vim.cmd("checktime " .. vim.fn.fnameescape(filename)) --- vim.notify("PIO: Fixed paths and line endings", 2) --- end --- end --- end --- lsp_restart('clangd') --- _G.metadata.isBusy = false --- -- M.process_queue() --- end - - -- lsp_restart('clangd') - -- _G.metadata.isBusy = false - -- M.process_queue() - - - - - - - local callBack = nil +local pio_buffer = '' -- Persistent stream buffer ------------------------------------------------------ -- INFO: ToggleTerminal commands stdout filter ---- stylua: ignore +-- stylua: ignore function M.stdoutcallback(_, _, data) - local pio_buffer = '' -- Persistent stream buffer + if not data then return end - -- 1. attach partial buffer from previous data last line to 1st line - pio_buffer = pio_buffer .. data[1] - -- 2. If the chunk has more than one element, we've encountered newlines - if #data > 1 then - -- 3. Process any "middle" lines which are guaranteed to be complete - for i = 2, #data do - pio_buffer = pio_buffer .. data[i] - end + -- 1. Combine the last partial line with the new first line + local lines_to_process = pio_buffer .. data[1] - for status in pio_buffer:gmatch('_CMMNDS_:(%a+)') do - if callBack and status then - pio_buffer = data[#data] - -- if status == 'PASS' then - -- -- Store the last element as the new partial buffer for the next call - -- end - -- vim.schedule(function() callBack('PASS') end) - -- callBack('PASS') - -- elseif status == 'DONE' then - -- callBack('PASS') - -- vim.schedule(function() callBack('DONE') end) - -- elseif status == 'FAIL' then - -- callBack('PASS') - -- callBack(status) - vim.schedule(function() - callBack(status) - end) - -- vim.schedule(function() callBack('DONE') end) - -- end - break - end - end + -- 2. If there are newlines, we have complete lines to check + if #data > 1 then + -- Join all complete parts (everything except the very last partial line) + for i = 2, #data - 1 do lines_to_process = lines_to_process .. data[i] end + + -- 3. Search for the status in the complete chunk + local status = lines_to_process:match('_CMMNDS_:(%a+)') + if status and callBack then vim.schedule(function() callBack(status) end) end + -- save the trailing part for the next chunk + pio_buffer = data[#data] + else + -- Only one element in data means no newline yet; just update the partial buffer + pio_buffer = lines_to_process end - -- if #pio_buffer > 10000 then - -- pio_buffer = pio_buffer:sub(-5000) - -- end + + -- 4. Safety Trim (Prevents memory leaks if no newline ever comes) + if #pio_buffer > 5000 then pio_buffer = pio_buffer:sub(-2500) end end +------------------------------------------------------ +-- INFO: commands sequencer -- stylua: ignore M.run_sequence = function(tasks) M.queue = {} @@ -240,15 +140,14 @@ M.run_sequence = function(tasks) else full_cmd = cmd .. pass .. fail end table.insert(M.queue, full_cmd) end - vim.schedule(function() - if callBack then callBack('INIT') end - end) + vim.schedule(function() if callBack then callBack('INIT') end end) end -local commandPassed = 0 +------------------------------------------------------ -- Handle after pioinit execution +local commandPassed = 0 function M.handlePioinit(result) - if result == 'INIT' then + if result == 'INIT' then -- initialize commandPassed = 0 _G.metadata.isBusy = true local full_cmd = table.remove(M.queue, 1) @@ -263,18 +162,16 @@ function M.handlePioinit(result) boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') boilerplate_gen([[.clangd]], _G.metadata.core_dir) end) - -- elseif commandPassed == 2 then + -- elseif commandPassed == 2 then -- if you sned more than 2 commands you need this end - -- pio_buffer = '' local full_cmd = table.remove(M.queue, 1) term.ToggleTerminal(full_cmd, 'float') - elseif result == 'DONE' then -- compile_commands.json created + elseif result == 'DONE' then -- result of the last command vim.schedule(function() vim.notify('compiledb: Done ..', vim.log.levels.INFO) M.queue = {} term.stdout_callback = nil local pio_refresh = require('platformio.pio_setup').pio_refresh - -- vim.defer_fn(function() pio_refresh(function() vim.misc.gitignore_lsp_configs('compile_commands.json') _G.metadata.dbTrigger = true @@ -287,31 +184,23 @@ function M.handlePioinit(result) end end ------------------------------------------------------- --- Handle after 'pio run -t compiledb' execution -function M.handleDb() - vim.notify('compiledb: Pass', vim.log.levels.INFO) - misc.gitignore_lsp_configs('compile_commands.json') - -- M.compile_commandsFix() - _G.metadata.dbTrigger = true -end - ------------------------------------------------------- ------------------------------------------------------- --- Handle after pioinit execution -function M.handlePioinitPass() - vim.notify('Pioinit: Pass', vim.log.levels.INFO) - local pio_refresh = require('platformio.pio_setup').pio_refresh - pio_refresh(function() - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - boilerplate_gen([[.clangd]], _G.metadata.core_dir) - end) -end ------------------------------------------------------ -- Handle after piolib execution -function M.handlePiolib() - vim.notify('Piolib: Success', vim.log.levels.INFO) +function M.handlePiolib(result) + if result == 'INIT' then -- initialize + commandPassed = 0 + _G.metadata.isBusy = true + local full_cmd = table.remove(M.queue, 1) + term.stdout_callback = M.stdoutcallback + term.ToggleTerminal(full_cmd, 'float') + -- elseif result == 'PASS' then + elseif result == 'DONE' then -- result of the only and the last command + vim.notify('Piolib: Success', vim.log.levels.INFO) + elseif result == 'FAIL' then + M.queue = {} + term.stdout_callback = nil + _G.metadata.isBusy = false + end end return M From 192f84dd7422a2fdcb2bdd009892562d2ea4c3fd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 22:26:13 +0300 Subject: [PATCH 0982/1406] update --- lua/platformio/pio_setup.lua | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 2fc89646..9ee75d43 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -280,11 +280,10 @@ function M.run_compiledb() vim.schedule(function() -- _G.metadata.isBusy = false if obj.code == 0 then - local dbFix = require('platformio.utils.pio').compile_commandsFix - dbFix() - vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) - M.pio_refresh(function() + local dbFix = require('platformio.utils.pio').compile_commandsFix + dbFix() + vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) -- pio_generate_db() -- M.run_compiledb() -- lsp_restart('clangd') From 01bcbd9ef8e2a83d8c667d641cb47456da9abcec Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 24 Apr 2026 22:34:26 +0300 Subject: [PATCH 0983/1406] update --- mini_nvimPlatformio.lua | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index e49402f4..463f9d81 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -470,6 +470,32 @@ if tok then }, }, }) + + -- Enable Telescope extensions if they are installed + pcall(require('telescope').load_extension, 'fzf') + pcall(require('telescope').load_extension, 'ui-select') + + -- See `:help telescope.builtin` + local builtin = require('telescope.builtin') + vim.keymap.set('n', 'sh', builtin.help_tags, { desc = 'Search [H]elp' }) + vim.keymap.set('n', 'sk', builtin.keymaps, { desc = 'Search [K]eymaps' }) + vim.keymap.set('n', 'sf', builtin.find_files, { desc = 'Search [F]iles' }) + vim.keymap.set('n', 'ss', builtin.builtin, { desc = 'Search [S]elect Telescope' }) + vim.keymap.set('n', 'sw', builtin.grep_string, { desc = 'Search current [W]ord' }) + vim.keymap.set('n', 'sg', builtin.live_grep, { desc = 'Search by [G]rep' }) + vim.keymap.set('n', 'sd', builtin.diagnostics, { desc = 'Search [D]iagnostics' }) + vim.keymap.set('n', 'sr', builtin.resume, { desc = 'Search [R]esume' }) + vim.keymap.set('n', 's.', builtin.oldfiles, { desc = 'Search Recent Files ("." for repeat)' }) + vim.keymap.set('n', '', builtin.buffers, { desc = '[ ] Find existing buffers' }) + + -- Slightly advanced example of overriding default behavior and theme + vim.keymap.set('n', '/', function() + -- You can pass additional configuration to Telescope to change the theme, layout, etc. + builtin.current_buffer_fuzzy_find(require('telescope.themes').get_dropdown({ + winblend = 10, + previewer = false, + })) + end, { desc = '[/] Fuzzily search in current buffer' }) end -- Keymap to open the buffer list vim.keymap.set('n', 'fb', 'Telescope buffers', { desc = 'Find Buffers' }) From 1c397603d25b6c6c84e1c1c041a102d289057f22 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 01:29:15 +0300 Subject: [PATCH 0984/1406] update --- lua/platformio/pio_setup.lua | 154 ++++++++++++++++++++++++++++------- tmp1.lua | 122 --------------------------- 2 files changed, 126 insertions(+), 150 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 9ee75d43..f079c2d7 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,6 +1,5 @@ M = {} -local misc = require('platformio.utils.misc') -- local lsp_restart = require('platformio.lsp.tools').lsp_restart local boilerplate = require('platformio.boilerplate') local boilerplate_gen = boilerplate.boilerplate_gen @@ -26,7 +25,7 @@ function M.get_sysroot_triplet(cc_compiler) for _, name in ipairs(files) do -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ local match = name:match('^(.*)%-g[c%+][c%+]') - if match then triplet = misc.normalizePath(match) break + if match then triplet = vim.misc.normalizePath(match) break end end @@ -34,10 +33,10 @@ function M.get_sysroot_triplet(cc_compiler) if not triplet then return nil end -- toolchain_root is the parent of the 'bin' folder - local toolchain_root = misc.normalizePath(vim.fn.fnamemodify(bin_path, ':h')) + local toolchain_root = vim.misc.normalizePath(vim.fn.fnamemodify(bin_path, ':h')) -- sysroot folder is expected to have the same name as the triplet - local sysroot = misc.normalizePath(toolchain_root .. '/' .. triplet) - local query_driver = misc.normalizePath(bin_path .. '/' .. triplet .. '-*') + local sysroot = vim.misc.normalizePath(toolchain_root .. '/' .. triplet) + local query_driver = vim.misc.normalizePath(bin_path .. '/' .. triplet .. '-*') -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) -- Only return data if the sysroot folder actually exists on disk @@ -72,9 +71,10 @@ function M.pio_refresh(callback) end -- Set up file paths - local build_dir = vim.misc.joinPath(vim.uv.cwd(), '.pio', 'build', active_env) + local build_dir = vim.misc.joinPath(vim.uv.cwd(), '.pio', 'build') + local build_env_dir = vim.misc.joinPath(build_dir, active_env) local checksum_path = vim.misc.joinPath(build_dir, 'project.checksum') - local idedata_path = vim.misc.joinPath(build_dir, 'idedata.json') + local idedata_path = vim.misc.joinPath(build_env_dir, 'idedata.json') --------------------------------------------------------- -- INTERNAL PROCESSOR: Applies parsed data to _G.metadata @@ -240,7 +240,7 @@ function M.pio_refresh(callback) -- Expand variables and Normalize if type(val) == "string" then val = val:gsub('%%${platformio.core_dir}', meta.core_dir or "") - meta[item.key] = misc.normalizePath(val) + meta[item.key] = vim.misc.normalizePath(val) end end @@ -267,6 +267,7 @@ local function get_hash(path) return ok and vim.fn.sha256(table.concat(data, '\n')) or nil end +_G.metadata.isBusy = false -- 2. Smart Save/Load: Uses JSON and Hashing -- 3. Robust Execution: Mutes watcher and handles LSP restart function M.run_compiledb() @@ -303,37 +304,134 @@ function M.run_compiledb() end) end -local dir_path = vim.uv.cwd() -local ini_file = vim.fs.joinpath(dir_path, 'platformio.ini') --- INFO: --- 4. Simple Watcher: Only triggers if the FILE CONTENT changed -function M.start_watcher() - if not dir_path or vim.fn.filereadable(ini_file) == 0 then - return - end - local current_ini_hash = get_hash(ini_file) - _G.metadata.isBusy = false +-- Store handles globally within the module so we can stop them +local uv = vim.uv or vim.loop +M.watcher_handles = {} + +local function watch_file(full_path, callback) + local handle = uv.new_fs_event() + local parent_dir = vim.fn.fnamemodify(full_path, ':h') + local target_file = vim.fn.fnamemodify(full_path, ':t') - local handle = vim.uv.new_fs_event() if handle then handle:start( - dir_path, - { recursive = false }, - vim.schedule_wrap(function(err, fname, events) - if err or fname ~= 'platformio.ini' or _G.metadata.isBusy or not events or not (events.change or events.renamce) then - return + parent_dir, + {}, + vim.schedule_wrap(function(err, filename, events) + -- handle:start(parent_dir, {}, function(err, filename) + -- if err then + if err or filename ~= target_file or _G.metadata.isBusy or not events or not (events.change or events.renamce) then + return handle:stop() + -- return end - local new_hash = get_hash(ini_file) - if new_hash and new_hash ~= current_ini_hash then - current_ini_hash = new_hash - M.run_compiledb() -- Smart: Auto-update DB if config changes + if filename == target_file then + vim.schedule(callback) end end) ) + return handle + end +end + +function M.start_watchers() + -- Clean up any existing watchers first to prevent duplicates + M.stop_watchers() + + local project_root = vim.uv.cwd() -- Use dynamic CWD instead of hardcoded path + local active_env = _G.metadata.active_env or 'default' + + local targets = { + { -- watcher for platformio.ini + path = vim.misc.joinPath(project_root, 'platformio.ini'), + current_ini_hash = '', + cb = function(self) + local new_hash = get_hash(self.path) or '' + if new_hash and new_hash ~= self.current_ini_hash then + self.current_ini_hash = new_hash + M.run_compiledb() -- Smart: Auto-update DB if config changes + end + -- fetch_config() + end, + }, + { -- watcher for ./.pio/build/projct.checksum + checksum_path = vim.misc.joinPath(project_root, '.pio/build', 'project.checksum'), + idedata_path = vim.misc.joinPath(project_root, '.pio/build', active_env, 'idedata.json'), + cb = function(self) + -- Set up file paths + --------------------------------------------------------- + -- STEP 1: Fast Checksum Check + --------------------------------------------------------- + local current_checksum = vim.misc.readFile(self.checksum_path) + if current_checksum and current_checksum ~= '' then + if current_checksum == _G.metadata.last_checksum then + return + end -- Already updated + + -- STEP 2: Cache Path (idedata.json exists and checksum changed) + -- local content = vim.misc.readFile(self.idedata_path) + -- if content then + M.pio_refresh(function() + local dbFix = require('platformio.utils.pio').compile_commandsFix + dbFix() + vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) + end) + -- end + end + -- get_metadata(0) + end, + }, + } + targets[1].current_ini_hash = get_hash(targets[1].path) or '' + + for _, target in ipairs(targets) do + local h = watch_file(target.path, target.cb) + table.insert(M.watcher_handles, h) + end +end + +function M.stop_watchers() + for _, handle in ipairs(M.watcher_handles) do + handle:stop() end + M.watcher_handles = {} end +-- local dir_path = vim.uv.cwd() +-- local ini_file = vim.misc.joinPath(dir_path, 'platformio.ini') +-- -- INFO: +-- -- 4. Simple Watcher: Only triggers if the FILE CONTENT changed +-- function M.start_watcher() +-- if not dir_path or vim.fn.filereadable(ini_file) == 0 then +-- return +-- end +-- local current_ini_hash = get_hash(ini_file) +-- _G.metadata.isBusy = false +-- +-- local handle = vim.uv.new_fs_event() +-- if handle then +-- handle:start( +-- dir_path, +-- { recursive = false }, +-- vim.schedule_wrap(function(err, fname, events) +-- if err or fname ~= 'platformio.ini' or _G.metadata.isBusy or not events or not (events.change or events.renamce) then +-- return handle:stop() +-- end +-- +-- if _G.metadata.isBusy then +-- return +-- end +-- +-- local new_hash = get_hash(ini_file) +-- if new_hash and new_hash ~= current_ini_hash then +-- current_ini_hash = new_hash +-- M.run_compiledb() -- Smart: Auto-update DB if config changes +-- end +-- end) +-- ) +-- end +-- end + ---------------------------------------------------------------------------------------------- -- local function start_pio_watcher() -- local dir_path = vim.uv.cwd() diff --git a/tmp1.lua b/tmp1.lua index ebb2c410..e69de29b 100644 --- a/tmp1.lua +++ b/tmp1.lua @@ -1,122 +0,0 @@ -local function get_metadata(attempts, env) - local meta = _G.metadata - local active_env = env or meta.active_env - if not active_env or active_env == '' then - return - end - - -- Set up file paths - local build_dir = vim.misc.joinPath(vim.uv.cwd(), '.pio', 'build', active_env) - local checksum_path = vim.misc.joinPath(build_dir, 'project.checksum') - local idedata_path = vim.misc.joinPath(build_dir, 'idedata.json') - - --------------------------------------------------------- - -- INTERNAL PROCESSOR: Applies parsed data to _G.metadata - --------------------------------------------------------- - local function apply_metadata(data, checksum) - if not data then - return false - end - - local norm = function(p) - return vim.misc.normalizePath(p) or '' - end - - local quote_map = function(list, prefix) - local res = {} - for _, v in ipairs(list or {}) do - local val = prefix and (prefix .. norm(v)) or v - table.insert(res, string.format('%q', val)) - end - return res - end - - -- 1. Base Paths & Compilers - meta.cc_path = norm(data.cc_path) - meta.cc_compiler = meta.cc_path - meta.cxx_path = norm(data.cxx_path) - meta.gdb_path = norm(data.gdb_path) - - -- 2. Flags & Defines - meta.cc_flags = quote_map(data.cc_flags) - meta.cxx_flags = quote_map(data.cxx_flags) - meta.defines = quote_map(data.defines) - - -- 3. Includes (Build, Toolchain, Compatlib) - local inc = data.includes or {} - meta.includes_build = quote_map(inc.build, '-I') - meta.includes_toolchain = quote_map(inc.toolchain, '-isystem') - meta.includes_compatlib = quote_map(inc.compatlib, '-isystem') - meta.last_checksum = checksum - pcall(M.get_sysroot_triplet, meta.cc_compiler) - - if callback then - callback() - end - return true - end - - --------------------------------------------------------- - -- STEP 1: Fast Checksum Check - --------------------------------------------------------- - local current_checksum = vim.misc.readFile(checksum_path) - if current_checksum and current_checksum ~= '' then - if current_checksum == meta.last_checksum then - return - end -- Already updated - - -- STEP 2: Cache Path (idedata.json exists and checksum changed) - local content = vim.misc.readFile(idedata_path) - if content then - local ok, decoded = pcall(vim.json.decode, content) - if ok and apply_metadata(decoded, current_checksum) then - vim.notify('PIO: Metadata synced from cache', vim.log.levels.INFO) - return - end - end - end - - --------------------------------------------------------- - -- STEP 3: Auto-Initialize (If files are missing) - --------------------------------------------------------- - if not current_checksum then - vim.notify('PIO: Initializing project metadata...', vim.log.levels.WARN) - vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env }, { text = true }, function(obj) - vim.schedule(function() - if obj.code == 0 then - get_metadata(attempts, active_env) -- Recursive call after files created - else - vim.notify('PIO: Initialization failed. Build project manually.', vim.log.levels.ERROR) - end - end) - end) - return - end - - --------------------------------------------------------- - -- STEP 4: Standard CLI Fallback (The Slow Path) - --------------------------------------------------------- - vim.notify('PIO: Fetching fresh metadata...', vim.log.levels.INFO) - vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(obj) - vim.schedule(function() - if obj.code ~= 0 then - if attempts > 0 then - vim.defer_fn(function() - get_metadata(attempts - 1, env) - end, 500) - return - end - return vim.notify('PIO Metadata Error: ' .. (obj.stderr or 'Unknown'), vim.log.levels.WARN) - end - - local ok, raw_data = pcall(vim.json.decode, obj.stdout or '') - local _, data = next(raw_data or {}) - - if ok and apply_metadata(data, current_checksum) then - vim.notify('PIO: Metadata sync successful', vim.log.levels.INFO) - else - vim.notify('PIO: Failed to parse metadata output', vim.log.levels.WARN) - end - end) - end) -end From 4c9672da034ee929ef5bae0eaa60a2174e07b77b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 01:31:38 +0300 Subject: [PATCH 0985/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index f079c2d7..994e504e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -502,7 +502,7 @@ function M.init() -- Always start the watcher so it can catch a future 'pio init' -- M.start_pio_watcher() - M.start_watcher() + M.start_watchers() -- If the file already exists, do an initial sync if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then From e1754db7dbda89497fc2c2bb1a8108e87998e235 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 01:47:23 +0300 Subject: [PATCH 0986/1406] update --- lua/platformio/metadata.lua | 2 +- lua/platformio/pio_setup.lua | 1 - lua/platformio/utils/pio.lua | 6 +++++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 6c727b8a..14a7b68a 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -69,7 +69,7 @@ _G.metadata = setmetatable({}, { vim.schedule(function() -- M.save_project_config(true) if key == 'toolchain_root' then - vim.notify('Env: ' .. value, vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) + -- vim.notify('Env: ' .. value, vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) pcall(function() if _pio_metadata.dbTrigger then vim.notify('Env: dbTrigger', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 994e504e..d9696a0d 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -486,7 +486,6 @@ function M.init() boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') - print(vim.env.XDG_CONFIG_HOME .. '/clangd' .. '/config.yaml') -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) boilerplate.core_dir = _G.metadata.core_dir boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 746bb40a..c6bea134 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -174,7 +174,11 @@ function M.handlePioinit(result) local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() vim.misc.gitignore_lsp_configs('compile_commands.json') - _G.metadata.dbTrigger = true + -- _G.metadata.dbTrigger = true + local ok, _ = pcall(M.compile_commandsFix) + if not ok then + print('Env: dbTrigger, fail to call dbFix') + end end) end) elseif result == 'FAIL' then From 5c5d45797dd853586a11af73244a5ecd71200786 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 01:57:01 +0300 Subject: [PATCH 0987/1406] update --- lua/platformio/metadata.lua | 2 +- lua/platformio/utils/lsp.lua | 15 --------------- 2 files changed, 1 insertion(+), 16 deletions(-) delete mode 100644 lua/platformio/utils/lsp.lua diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 14a7b68a..cf7bf464 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -81,7 +81,7 @@ _G.metadata = setmetatable({}, { -- dbFix() _pio_metadata.dbTrigger = false else - local LspRestart = require('platformio.utils.lsp').lsp_restart + local LspRestart = require('platformio.lsp.tools').lsp_restart LspRestart('clangd') vim.notify('Env: LspRestart', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) end diff --git a/lua/platformio/utils/lsp.lua b/lua/platformio/utils/lsp.lua deleted file mode 100644 index 58463023..00000000 --- a/lua/platformio/utils/lsp.lua +++ /dev/null @@ -1,15 +0,0 @@ -local M = {} - ---- stylua: ignore -function M.lsp_restart(name) - -- vim.schedule_wrap(function() - local clangConfig = _G.get_clangd_config() - -- print(vim.inspect(clangConfig)) - vim.lsp.config(name, clangConfig) - vim.lsp.enable(name, false) - vim.lsp.enable(name, true) - vim.cmd('checktime') - -- end) -end - -return M From f08f88b6d15be88eb4168512c82fc65a4f573c59 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 02:02:46 +0300 Subject: [PATCH 0988/1406] update --- lua/platformio/metadata.lua | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index cf7bf464..126bfcb4 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -70,22 +70,22 @@ _G.metadata = setmetatable({}, { -- M.save_project_config(true) if key == 'toolchain_root' then -- vim.notify('Env: ' .. value, vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) - pcall(function() - if _pio_metadata.dbTrigger then - vim.notify('Env: dbTrigger', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) - local dbFix = pio.compile_commandsFix - local ok, _ = pcall(dbFix) - if not ok then - print('Env: dbTrigger, fail to call dbFix') - end - -- dbFix() - _pio_metadata.dbTrigger = false - else - local LspRestart = require('platformio.lsp.tools').lsp_restart - LspRestart('clangd') - vim.notify('Env: LspRestart', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) - end - end) + -- pcall(function() + -- if _pio_metadata.dbTrigger then + -- vim.notify('Env: dbTrigger', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) + -- local dbFix = pio.compile_commandsFix + -- local ok, _ = pcall(dbFix) + -- if not ok then + -- print('Env: dbTrigger, fail to call dbFix') + -- end + -- -- dbFix() + -- _pio_metadata.dbTrigger = false + -- else + -- local LspRestart = require('platformio.lsp.tools').lsp_restart + -- LspRestart('clangd') + -- vim.notify('Env: LspRestart', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) + -- end + -- end) elseif key == 'active_env' then -- Force global statusline so it doesn't get pushed around by Trouble or splits vim.o.laststatus = 3 From 63e41cafaa4410f73374a2a3e8cf5bb8d879d3a1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 02:09:29 +0300 Subject: [PATCH 0989/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index d9696a0d..d23cfb26 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -267,7 +267,7 @@ local function get_hash(path) return ok and vim.fn.sha256(table.concat(data, '\n')) or nil end -_G.metadata.isBusy = false +-- _G.metadata.isBusy = false -- 2. Smart Save/Load: Uses JSON and Hashing -- 3. Robust Execution: Mutes watcher and handles LSP restart function M.run_compiledb() From 6f3ee533f76c88e44223214356e630ba11a7e914 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 06:42:57 +0300 Subject: [PATCH 0990/1406] update --- lua/platformio/metadata.lua | 2 +- lua/platformio/pio_setup.lua | 24 +-- lua/platformio/utils/misc.lua | 8 +- tmp.lua | 347 ---------------------------------- 4 files changed, 14 insertions(+), 367 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 126bfcb4..64b02da1 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -145,7 +145,7 @@ function M.load_project_config() -- end -- end if vim.fn.filereadable(config_path) == 1 then - local json_data = vim.misc.readFile(config_path) + local _, json_data = vim.misc.readFile(config_path) if json_data then local ok, table_data = pcall(vim.json.decode, json_data) if ok and type(table_data) == 'table' then diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index d23cfb26..0fe32da0 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -120,12 +120,12 @@ function M.pio_refresh(callback) --------------------------------------------------------- -- STEP 1: Fast Checksum Check --------------------------------------------------------- - local current_checksum = vim.misc.readFile(checksum_path) + local _, current_checksum = vim.misc.readFile(checksum_path) if current_checksum and current_checksum ~= '' then if current_checksum == meta.last_checksum then return end -- Already updated -- STEP 2: Cache Path (idedata.json exists and checksum changed) - local content = vim.misc.readFile(idedata_path) + local _, content = vim.misc.readFile(idedata_path) if content then local ok, decoded = pcall(vim.json.decode, content) if ok and apply_metadata(decoded, current_checksum) then @@ -142,7 +142,7 @@ function M.pio_refresh(callback) -- vim.notify('PIO: Initializing project metadata...', vim.log.levels.WARN) -- vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env }, { text = true }, function(obj) -- vim.schedule(function() - -- if obj.code == 0 then + -- if obj.code == 0 thenl -- get_metadata(attempts, active_env) -- Recursive call after files created -- else -- vim.notify('PIO: Initialization failed. Build project manually.', vim.log.levels.ERROR) @@ -170,7 +170,7 @@ function M.pio_refresh(callback) local _, data = next(raw_data or {}) if ok and apply_metadata(data, current_checksum) then - vim.notify('PIO: Metadata sync successful', vim.log.levels.INFO) + vim.notify('PIO: Metadata synced from CLI', vim.log.levels.INFO) else vim.notify('PIO: Failed to parse metadata output', vim.log.levels.WARN) end @@ -263,8 +263,10 @@ local function get_hash(path) if vim.fn.filereadable(path) == 0 then return nil end - local ok, data = pcall(vim.fn.readfile, path) -- readfile is safer than io.open - return ok and vim.fn.sha256(table.concat(data, '\n')) or nil + -- local ok, data = pcall(vim.fn.readfile, path) -- readfile is safer than io.open + -- return ok and vim.fn.sha256(table.concat(data, '\n')) or nil + local ok, data = vim.misc.readFile(path) -- readfile is safer than io.open + return (ok and data) and vim.fn.sha256(data) or '' end -- _G.metadata.isBusy = false @@ -358,27 +360,19 @@ function M.start_watchers() checksum_path = vim.misc.joinPath(project_root, '.pio/build', 'project.checksum'), idedata_path = vim.misc.joinPath(project_root, '.pio/build', active_env, 'idedata.json'), cb = function(self) - -- Set up file paths - --------------------------------------------------------- - -- STEP 1: Fast Checksum Check - --------------------------------------------------------- - local current_checksum = vim.misc.readFile(self.checksum_path) + local _, current_checksum = vim.misc.readFile(self.checksum_path) if current_checksum and current_checksum ~= '' then if current_checksum == _G.metadata.last_checksum then return end -- Already updated -- STEP 2: Cache Path (idedata.json exists and checksum changed) - -- local content = vim.misc.readFile(self.idedata_path) - -- if content then M.pio_refresh(function() local dbFix = require('platformio.utils.pio').compile_commandsFix dbFix() vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) end) - -- end end - -- get_metadata(0) end, }, } diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index f0f1a157..fb9f3b52 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -160,13 +160,13 @@ function M.readFile(path) -- 1. Open the file (r = read-only) -- 438 is the octal for 0666 (standard permissions) local fd, err = uv.fs_open(path, 'r', 438) - if not fd or err then return nil, 'readFile: Open error: ' .. err end + if not fd or err then return false, 'readFile: Open error: ' .. err end -- 2. Get file stats to find out how many bytes to read local stat, stat_err = uv.fs_fstat(fd) if not stat or stat_err then uv.fs_close(fd) - return nil, 'readFile: Stat error: ' .. stat_err + return false, 'readFile: Stat error: ' .. stat_err end -- 3. Read the entire content @@ -176,9 +176,9 @@ function M.readFile(path) -- 4. ALWAYS close the file descriptor uv.fs_close(fd) - if read_err then return nil, 'readFile: Read error: ' .. read_err end + if read_err then return false, 'readFile: Read error: ' .. read_err end - return content + return true, content end ------------------------------------------------------ diff --git a/tmp.lua b/tmp.lua index 00331e86..e69de29b 100644 --- a/tmp.lua +++ b/tmp.lua @@ -1,347 +0,0 @@ --- local meta = _G.metadata --- INFO: get project metadata --- local function get_metadata(attempts, env) --- local active_env = env or meta.active_env --- vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(int_obj) --- vim.schedule(function() --- vim.notify('PIO: Fetching metadata ...', vim.log.levels.INFO) --- -- --- if int_obj.code ~= 0 then --- -- Schedule notification to avoid error in the system callback thread --- vim.schedule(function() --- if int_obj.code == 127 then --- vim.notify("PIO Manager metadata: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) --- else --- vim.notify('PIO Manager metadata: Failed to fetch metadata(' .. int_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) --- end --- end) --- return --- end --- -- --- if int_obj.code == 0 and int_obj.stdout then --- local ok, raw_data = pcall(vim.json.decode, int_obj.stdout) --- if ok and raw_data then --- local _, data = next(raw_data) --- if data then --- -- 1. Process cc_compiler --- if data.cc_path then --- meta.query_driver = '' --- meta.includes_build = {} --- meta.includes_comaptlib = {} --- meta.includes_toolchain = {} --- meta.cc_flags = {} --- meta.cxx_path = '' --- meta.cxx_flags = {} --- meta.gdb_path = '' --- meta.defines = {} --- meta.triplet = '' --- meta.toolchain_root = '' --- meta.sysroot = '' --- meta.cc_compiler = misc.normalizePath(data.cc_path) or '' --- meta.cc_path = misc.normalizePath(data.cc_path) or '' --- -- --- -- 2. Process cc_flags --- if data.cc_flags then --- local cc_flags = {} --- for _, flag in ipairs(data.cc_flags) do --- table.insert(cc_flags, string.format('%q', flag)) --- end --- meta.cc_flags = cc_flags --- end --- -- --- -- 3. Process cxx_compiler --- if data.cxx_path then --- meta.cxx_path = misc.normalizePath(data.cxx_path) or '' --- end --- -- --- -- 4. Process cxx_flags --- if data.cxx_flags then --- local cxx_flags = {} --- for _, flag in ipairs(data.cxx_flags) do --- table.insert(cxx_flags, string.format('%q', flag)) --- end --- meta.cxx_flags = cxx_flags --- end --- -- --- -- 5. Process gdb_path --- if data.gdb_path then --- meta.gdb_path = misc.normalizePath(data.gdb_path) or '' --- end --- -- --- -- 6. Process Defines --- if data.defines then --- local defines = {} --- for _, define in ipairs(data.defines) do --- table.insert(defines, string.format('%q', define)) --- end --- meta.defines = defines --- end --- -- --- -- 7. Process Includes --- if data.includes then --- for category, paths in pairs(data.includes) do --- -- 7.1 Process Includes_build --- if category == 'build' then --- local includes_build = {} --- local flag = '-I' --- for _, path in ipairs(paths) do --- table.insert(includes_build, string.format('%q', flag .. misc.normalizePath(path))) --- end --- meta.includes_build = includes_build --- end --- -- --- -- 7.2 Process includes_toolchain --- if category == 'toolchain' then --- local includes_toolchain = {} --- local flag = '-isystem' --- for _, path in ipairs(paths) do --- table.insert(includes_toolchain, string.format('%q', flag .. misc.normalizePath(path))) --- end --- meta.includes_toolchain = includes_toolchain --- end --- -- --- -- 7.3 Process includes_compatlib --- if category == 'compatlib' then --- local includes_compatlib = {} --- local flag = '-isystem' --- for _, path in ipairs(paths) do --- table.insert(includes_compatlib, string.format('%q', flag .. misc.normalizePath(path))) --- end --- meta.includes_build = includes_compatlib --- end --- end --- end --- -- --- pcall(M.get_sysroot_triplet, meta.cc_compiler) --- end --- end --- else --- vim.schedule(function() --- vim.notify('PIO: Syncing Environment failed', vim.log.levels.WARN) --- end) --- end --- end --- -- RETRY LOGIC: Handles "Error 1" (file busy) or temporary syntax errors during save --- if attempts > 0 then --- vim.defer_fn(function() --- get_metadata(attempts - 1) --- end, 500) --- else --- if callback then --- vim.schedule(function() --- vim.notify('PIO: Fetching metadata successful', vim.log.levels.INFO) --- callback() --- end) --- end --- end --- end) --- end) --- end - -local function fetch_config() -- INFO: Setup Base Paths - local meta = _G.metadata - local home = os.getenv('HOME') or os.getenv('USERPROFILE') - -- - -- The format is typically: { { "section_name", { {"key", "value"}, ... } }, ... } - vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(ext_obj) - vim.schedule(function() - if ext_obj.code ~= 0 then - -- Schedule notification to avoid error in the system callback thread - if ext_obj.code == 127 then - vim.notify("PIO Manager config: 'pio' command not found. Ensure PlatformIO Core is installed.", vim.log.levels.ERROR) - else - vim.notify('PIO Manager config: Failed to fetch config (' .. ext_obj.stderr or 'Unknown Error' .. ')', vim.log.levels.WARN) - end - return - end - - meta.core_dir = '' - meta.packages_dir = '' - meta.platforms_dir = '' - meta.active_env = '' - meta.default_envs = {} - meta.envs = {} - - local decoded = vim.json.decode(ext_obj.stdout) - for _, section in ipairs(decoded) do - if type(section) == 'table' and #section >= 2 then - local name, data = section[1], section[2] - -- 1. Extract Global PlatformIO Settings if available [core_dir][packages_dir][platforms_dir][default_envs] - if name == 'platformio' then - for _, kv in ipairs(data) do - local key, val = kv[1], kv[2] - if key ~= nil then - -- if meta[key] ~= nil then - meta[key] = ((type(val) == 'table' and next(val) ~= nil) or (type(val) == 'string' and val ~= '')) and misc.normalizePath(val) or val - end - end - -- 2. Extract all hardware [envs] like [env:seeed_xiao_esp32c3], skipping generic [env] - elseif name:match('^env:') then - local env_name = name:match('^env:(.+)') - meta.envs[env_name] = {} - for _, kv in ipairs(data) do - meta.envs[env_name][kv[1]] = kv[2] - end - end - end - end - -- assign [active_env] - if #meta.default_envs > 0 then - meta.active_env = meta.default_envs[1] or '' - elseif meta.envs and next(meta.envs) ~= '' then - meta.active_env = next(meta.envs) or '' - end - - -- INFO: -- Define Mapping (key in INI, Env Var, Default Subfolder) - local map = { - core = { ini = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, - packages = { ini = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, - platforms = { ini = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, - } - for _, kv in ipairs(map) do - -- 4.0 Fallback Logic: INI -> Env Var -> Default - local result = meta[kv.ini] or os.getenv(kv.env or (home .. kv.sub)):gsub('[\\/]+$', '') - -- 5. Expand ${platformio.core_dir} - if type(result) == 'string' then - if result:find('${platformio.core_dir}', 1, true) then - result = result:gsub('%${platformio.core_dir}', meta.core_dir) - end - end - -- 6. Normalize Slashes for Windows - -- meta[kv.ini] = misc.normalize_path(result) --core_dir:gsub('\\', '/'):gsub('//+', '/') - -- meta[kv.ini] = result:gsub('\\', '/'):gsub('//+', '/') - meta[kv.ini] = misc.normalizePath(result) - end - -- return meta[map[type].ini] - -- end - - if meta.active_env ~= '' then - vim.schedule(function() - vim.notify('PIO: Fetching config successful', vim.log.levels.INFO) - end) - get_metadata(1, meta.active_env) - else - vim.schedule(function() - vim.notify('PIO: no [env:] found, add board first', vim.log.levels.ERROR) - end) - end - end) - end) -end - -local function get_metadata(attempts, env) - vim.notify('PIO: Fetching metadata...', vim.log.levels.INFO) - --"C:\Users\batoaqaa\AppData\Local\ahmed\test\.pio\build\seeed_xiao_esp32c3\idedata.json" - local active_env = env or _G.metadata.active_env - local filename = vim.uv.cwd() .. '/.pio/build/' .. active_env .. '/idedata.json' - local content = vim.misc.readFile(filename) - if content then - -- 2. JSON Decoding - local ok, data = pcall(vim.json.decode, content or '') - if not ok or not data then - vim.notify('PIO: Failed to parse metadata JSON', vim.log.levels.WARN) - return - end - - -- 3. Update Global Metadata (Resetting with defaults) - local meta = _G.metadata - local norm = function(p) - return misc.normalizePath(p) or '' - end - local quote_map = function(list, prefix) - local res = {} - for _, v in ipairs(list or {}) do - table.insert(res, string.format('%q', (prefix or '') .. (prefix and norm(v) or v))) - end - return res - end - - -- Overwrite/Refresh Meta safely - meta.cc_path = norm(data.cc_path) - meta.cc_compiler = meta.cc_path - meta.cxx_path = norm(data.cxx_path) - meta.gdb_path = norm(data.gdb_path) - - meta.cc_flags = quote_map(data.cc_flags) - meta.cxx_flags = quote_map(data.cxx_flags) - meta.defines = quote_map(data.defines) - - -- 4. Process Includes - local inc = data.includes or {} - meta.includes_build = quote_map(inc.build, '-I') - meta.includes_toolchain = quote_map(inc.toolchain, '-isystem') - meta.includes_compatlib = quote_map(inc.compatlib, '-isystem') - - -- 5. Finalize - pcall(M.get_sysroot_triplet, meta.cc_compiler) - - if callback then - vim.notify('PIO: Metadata sync successful', vim.log.levels.INFO) - callback() - end - else - vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(obj) - vim.schedule(function() - -- 1. Error Handling - if obj.code ~= 0 then - local msg = obj.code == 127 and "'pio' not found" or (obj.stderr or 'Unknown Error') - vim.notify('PIO Metadata Error: ' .. msg, vim.log.levels.WARN) - - -- Retry Logic - if attempts > 0 then - vim.defer_fn(function() - get_metadata(attempts - 1, env) - end, 500) - end - return - end - - -- 2. JSON Decoding - local ok, raw_data = pcall(vim.json.decode, obj.stdout or '') - local _, data = next(raw_data or {}) - - if not ok or not data then - vim.notify('PIO: Failed to parse metadata JSON', vim.log.levels.WARN) - return - end - - -- 3. Update Global Metadata (Resetting with defaults) - local meta = _G.metadata - local norm = function(p) - return misc.normalizePath(p) or '' - end - local quote_map = function(list, prefix) - local res = {} - for _, v in ipairs(list or {}) do - table.insert(res, string.format('%q', (prefix or '') .. (prefix and norm(v) or v))) - end - return res - end - - -- Overwrite/Refresh Meta safely - meta.cc_path = norm(data.cc_path) - meta.cc_compiler = meta.cc_path - meta.cxx_path = norm(data.cxx_path) - meta.gdb_path = norm(data.gdb_path) - - meta.cc_flags = quote_map(data.cc_flags) - meta.cxx_flags = quote_map(data.cxx_flags) - meta.defines = quote_map(data.defines) - - -- 4. Process Includes - local inc = data.includes or {} - meta.includes_build = quote_map(inc.build, '-I') - meta.includes_toolchain = quote_map(inc.toolchain, '-isystem') - meta.includes_compatlib = quote_map(inc.compatlib, '-isystem') - - -- 5. Finalize - pcall(M.get_sysroot_triplet, meta.cc_compiler) - - if callback then - vim.notify('PIO: Metadata sync successful', vim.log.levels.INFO) - callback() - end - end) - end) - end -end From ca0807dfb4969c60566b126fe222695045ac04d4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 09:35:24 +0300 Subject: [PATCH 0991/1406] update --- lua/platformio/pio_setup.lua | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 0fe32da0..09ed1b80 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -478,8 +478,7 @@ function M.init() -- INFO: create clangd required files ----------------------------------------------------------------------------------------- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') - boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') + -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) boilerplate.core_dir = _G.metadata.core_dir boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) From 42ab7077269908fa51d26f0e3ea9791617b19b8f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 09:44:50 +0300 Subject: [PATCH 0992/1406] update --- lua/platformio/pio_setup.lua | 4 ++-- lua/platformio/utils/pio.lua | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 09ed1b80..c61be1e7 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -285,7 +285,7 @@ function M.run_compiledb() if obj.code == 0 then M.pio_refresh(function() local dbFix = require('platformio.utils.pio').compile_commandsFix - dbFix() + -- dbFix() vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) -- pio_generate_db() -- M.run_compiledb() @@ -369,7 +369,7 @@ function M.start_watchers() -- STEP 2: Cache Path (idedata.json exists and checksum changed) M.pio_refresh(function() local dbFix = require('platformio.utils.pio').compile_commandsFix - dbFix() + -- dbFix() vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) end) end diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index c6bea134..93b6ad99 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -175,10 +175,10 @@ function M.handlePioinit(result) pio_refresh(function() vim.misc.gitignore_lsp_configs('compile_commands.json') -- _G.metadata.dbTrigger = true - local ok, _ = pcall(M.compile_commandsFix) - if not ok then - print('Env: dbTrigger, fail to call dbFix') - end + -- local ok, _ = pcall(M.compile_commandsFix) + -- if not ok then + -- print('Env: dbTrigger, fail to call dbFix') + -- end end) end) elseif result == 'FAIL' then From 65a419f47faa5cd5a390d9e100c09e67fa711845 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 16:49:16 +0300 Subject: [PATCH 0993/1406] update --- mini_nvimPlatformio.lua | 53 +++++++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 20 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 463f9d81..c5f75fd9 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -205,6 +205,7 @@ local plugins = { require('lualine').setup({ options = { globalstatus = true, -- Single statusline for all windows + extensios = { 'neo-treee' }, }, -- This replaces the visual part of bufferline tabline = { @@ -257,29 +258,41 @@ local plugins = { -- config = true, -- config = true is shorthand for config = function() require('bufferline').setup() end }, + { - 'nvim-tree/nvim-tree.lua', - -- version = '*', - lazy = false, - dependencies = 'nvim-tree/nvim-web-devicons', - config = function() - require('nvim-tree').setup({ - filesystem_watchers = { - ignore_dirs = { - '/.cache', -- Ignores clangd's heavy index folder - '/.pio', -- Ignores pio heavy index folder - '/node_modules', -- Good practice for performance - '/.git', - }, - }, - -- Optional: If you also want to hide it from the tree view entirely - -- filters = { - -- custom = { '^\\.cache$', '^\\.pio$' }, - -- }, - }) - end, + 'nvim-neo-tree/neo-tree.nvim', + branch = 'v3.x', + dependencies = { + 'nvim-lua/plenary.nvim', + 'MunifTanjim/nui.nvim', + 'nvim-tree/nvim-web-devicons', -- optional, but recommended + }, + lazy = false, -- neo-tree will lazily load itself }, + -- { + -- 'nvim-tree/nvim-tree.lua', + -- -- version = '*', + -- lazy = false, + -- dependencies = 'nvim-tree/nvim-web-devicons', + -- config = function() + -- require('nvim-tree').setup({ + -- filesystem_watchers = { + -- ignore_dirs = { + -- '/.cache', -- Ignores clangd's heavy index folder + -- '/.pio', -- Ignores pio heavy index folder + -- '/node_modules', -- Good practice for performance + -- '/.git', + -- }, + -- }, + -- -- Optional: If you also want to hide it from the tree view entirely + -- -- filters = { + -- -- custom = { '^\\.cache$', '^\\.pio$' }, + -- -- }, + -- }) + -- end, + -- }, + { 'batoaqaa/nvim-platformio.lua', cond = function() From 99fa30fd6adc95ac71343214202c552cea2ca023 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 17:16:09 +0300 Subject: [PATCH 0994/1406] update --- mini_nvimPlatformio.lua | 49 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index c5f75fd9..3e6e2406 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -464,6 +464,15 @@ if tok then -- local telescope = require('telescope') -- print("here" .. vim.inspect(pioConfig)) telescope.setup({ + extensions = { + ['ui-select'] = { + require('telescope.themes').get_dropdown({ + -- Customizing the dialog appearance + width = 0.6, + previewer = false, + }), + }, + }, defaults = { mappings = { i = { @@ -488,6 +497,46 @@ if tok then pcall(require('telescope').load_extension, 'fzf') pcall(require('telescope').load_extension, 'ui-select') + local function run_project_wizard() + local project_config = {} + + -- Step 1: Select IDE + vim.ui.select({ 'Neovim', 'VS Code', 'IntelliJ' }, { prompt = 'Select IDE' }, function(ide) + if not ide then + return + end + project_config.ide = ide + + -- Step 2: Select Board + vim.ui.select({ 'ESP32', 'Arduino Uno', 'Raspberry Pi' }, { prompt = 'Select Board' }, function(board) + if not board then + return + end + project_config.board = board + + -- Step 3: Select Framework + vim.ui.select({ 'ESP-IDF', 'Arduino Core', 'MicroPython' }, { prompt = 'Select Framework' }, function(fw) + if not fw then + return + end + project_config.framework = fw + + -- Step 4: Final Selection + vim.ui.select({ 'true', 'false' }, { prompt = 'Include Sample Code?' }, function(sample) + project_config.sample = sample == 'true' + + -- Final Output/Action + print( + string.format('Setup: %s on %s using %s (Sample: %s)', project_config.ide, project_config.board, project_config.framework, project_config.sample) + ) + end) + end) + end) + end) + end + + vim.keymap.set('n', 'pw', run_project_wizard, { desc = 'Run Project Wizard' }) + -- See `:help telescope.builtin` local builtin = require('telescope.builtin') vim.keymap.set('n', 'sh', builtin.help_tags, { desc = 'Search [H]elp' }) From 1a298aec6c039410bba8d3d21c1f1a1176f7ff39 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 17:44:03 +0300 Subject: [PATCH 0995/1406] update --- lua/platformio/pioinit2.lua | 160 ++++++++++++++++++++++++++++++++++++ plugin/platformio.lua | 13 +++ 2 files changed, 173 insertions(+) create mode 100644 lua/platformio/pioinit2.lua diff --git a/lua/platformio/pioinit2.lua b/lua/platformio/pioinit2.lua new file mode 100644 index 00000000..66af0990 --- /dev/null +++ b/lua/platformio/pioinit2.lua @@ -0,0 +1,160 @@ +local pickers = require('telescope.pickers') +local finders = require('telescope.finders') +local actions = require('telescope.actions') +local action_state = require('telescope.actions.state') +local previewers = require('telescope.previewers') +local telescope_conf = require('telescope.config').values + +local wizard_data = {} + +-- Final Step: Command Construction & Execution +local function finalize_setup() + local pio = require('platformio.utils.pio') + + -- 1. Determine IDE flag: --ide vim enables LSP support for Neovim + local ide_flag = wizard_data.use_ide and ' --ide vim' or '' + + -- 2. Determine Sample flag: --sample-code generates boilerplate + local sample_flag = wizard_data.sample == 'true' and ' --sample-code' or '' + + -- 3. Construct the full init command + local init_cmd = string.format('pio project init --board %s %s -O "framework=%s"%s', wizard_data.board_id, ide_flag, wizard_data.framework, sample_flag) + + print('Executing: ' .. init_cmd) + + pio.run_sequence({ + cmnds = { + init_cmd, + 'pio run -t compiledb', -- Essential to generate compile_commands.json for LSP + }, + cb = pio.handlePioinit, + }) +end + +-- --- PICKERS (In Order of Execution) --- + +-- STEP 4: Sample (True/False) +local function pick_sample() + pickers + .new({}, { + prompt_title = 'Include Sample Code?', + finder = finders.new_table({ results = { 'true', 'false' } }), + sorter = telescope_conf.generic_sorter({}), + attach_mappings = function(prompt_bufnr) + actions.select_default:replace(function() + local selection = action_state.get_selected_entry() + actions.close(prompt_bufnr) + wizard_data.sample = selection[1] -- Capture result + finalize_setup() + end) + return true + end, + }) + :find() +end + +-- STEP 3: Framework (From Board Data) +local function pick_framework(board_details) + pickers + .new({}, { + prompt_title = 'Select Framework (' .. board_details.id .. ')', + finder = finders.new_table({ results = board_details['frameworks'] }), + sorter = telescope_conf.generic_sorter({}), + attach_mappings = function(prompt_bufnr) + actions.select_default:replace(function() + local selection = action_state.get_selected_entry() + actions.close(prompt_bufnr) + wizard_data.framework = selection[1] + pick_sample() -- Next step + end) + return true + end, + }) + :find() +end + +-- STEP 2: Board (with Buffer Previewer) +local function pick_board(json_data) + pickers + .new({}, { + prompt_title = 'Select Board', + finder = finders.new_table({ + results = json_data, + entry_maker = function(entry) + return { + value = entry, + display = entry.name or entry.id, + ordinal = (entry.name or '') .. ' ' .. (entry.id or ''), + } + end, + }), + previewer = previewers.new_buffer_previewer({ + title = 'Board Details', + define_preview = function(self, entry) + local content = vim.split(vim.inspect(entry.value), '\n') + vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, content) + vim.api.nvim_set_option_value('filetype', 'lua', { buf = self.state.bufnr }) + end, + }), + sorter = telescope_conf.generic_sorter({}), + attach_mappings = function(prompt_bufnr) + actions.select_default:replace(function() + local selection = action_state.get_selected_entry() + actions.close(prompt_bufnr) + wizard_data.board_id = selection.value.id + pick_framework(selection.value) -- Next step + end) + return true + end, + }) + :find() +end + +-- STEP 1: IDE (True/False) +local function start_pio_wizard(json_data) + pickers + .new({}, { + prompt_title = 'Setup for Neovim IDE?', + finder = finders.new_table({ results = { 'true', 'false' } }), + sorter = telescope_conf.generic_sorter({}), + attach_mappings = function(prompt_bufnr) + actions.select_default:replace(function() + local selection = action_state.get_selected_entry() + actions.close(prompt_bufnr) + wizard_data.use_ide = (selection[1] == 'true') + pick_board(json_data) -- Next step + end) + return true + end, + }) + :find() +end + +local function launch_pio_project_wizard() + print('Fetching board data from PlatformIO...') + + -- 1. Get board data from PIO CLI in JSON format + -- The '--json-output' flag ensures we get structured data + local handle = io.popen('pio boards --json-output') + if not handle then + return + end + + local result = handle:read('*a') + handle:close() + + -- 2. Decode the JSON string into a Lua table + local ok, json_data = pcall(vim.json.decode, result) + if not ok or not json_data then + print('Error: Could not parse PlatformIO board data.') + return + end + + -- 3. Start the wizard we built previously + start_pio_wizard(json_data) +end + +-- Export the function so it's accessible via require() +return { + launch = launch_pio_project_wizard, +} diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 9fbdc8a2..b9dfc649 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -31,6 +31,19 @@ vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) -- end -- end, { ['repeat'] = -1 }) +-- In ~/.config/nvim/init.lua +local pio_wiz = require('platformio.pioinit2') + +-- Create a keybinding to trigger the wizard +vim.keymap.set('n', 'pi', function() + pio_wiz.launch() +end, { desc = 'Run PIO Project Wizard' }) + +-- Alternatively, create a user command +vim.api.nvim_create_user_command('PioWizard', function() + pio_wiz.launch() +end, {}) + -- Pioinit vim.api.nvim_create_user_command('Pioinit', function() require('platformio.pioinit').pioinit() From e67db14c2915793815f53b4feb7ffc21ce89450e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 17:57:18 +0300 Subject: [PATCH 0996/1406] update --- lua/platformio/pioinit2.lua | 26 ++++-- pioinit2.lua | 160 ++++++++++++++++++++++++++++++++++++ plugin/platformio.lua | 4 +- 3 files changed, 181 insertions(+), 9 deletions(-) create mode 100644 pioinit2.lua diff --git a/lua/platformio/pioinit2.lua b/lua/platformio/pioinit2.lua index 66af0990..eff3bfee 100644 --- a/lua/platformio/pioinit2.lua +++ b/lua/platformio/pioinit2.lua @@ -33,18 +33,28 @@ end -- --- PICKERS (In Order of Execution) --- +local function dialog_opts(title, width) + return require('telescope.themes').get_dropdown({ + prompt_title = title, + layout_config = { + width = width or 0.4, -- Adjust width (0.4 = 40% of screen) + height = 0.2, -- Small height for few choices + }, + previewer = false, -- Hide preview for simple choices + }) +end -- STEP 4: Sample (True/False) local function pick_sample() + local opts = dialog_opts('Include Sample Code?', 0.3) pickers - .new({}, { - prompt_title = 'Include Sample Code?', + .new(opts, { finder = finders.new_table({ results = { 'true', 'false' } }), - sorter = telescope_conf.generic_sorter({}), + sorter = telescope_conf.generic_sorter(opts), attach_mappings = function(prompt_bufnr) actions.select_default:replace(function() local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) - wizard_data.sample = selection[1] -- Capture result + wizard_data.sample = selection[1] finalize_setup() end) return true @@ -112,17 +122,17 @@ end -- STEP 1: IDE (True/False) local function start_pio_wizard(json_data) + local opts = dialog_opts('Initialize for Neovim?', 0.3) pickers - .new({}, { - prompt_title = 'Setup for Neovim IDE?', + .new(opts, { finder = finders.new_table({ results = { 'true', 'false' } }), - sorter = telescope_conf.generic_sorter({}), + sorter = telescope_conf.generic_sorter(opts), attach_mappings = function(prompt_bufnr) actions.select_default:replace(function() local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) wizard_data.use_ide = (selection[1] == 'true') - pick_board(json_data) -- Next step + pick_board(json_data) end) return true end, diff --git a/pioinit2.lua b/pioinit2.lua new file mode 100644 index 00000000..66af0990 --- /dev/null +++ b/pioinit2.lua @@ -0,0 +1,160 @@ +local pickers = require('telescope.pickers') +local finders = require('telescope.finders') +local actions = require('telescope.actions') +local action_state = require('telescope.actions.state') +local previewers = require('telescope.previewers') +local telescope_conf = require('telescope.config').values + +local wizard_data = {} + +-- Final Step: Command Construction & Execution +local function finalize_setup() + local pio = require('platformio.utils.pio') + + -- 1. Determine IDE flag: --ide vim enables LSP support for Neovim + local ide_flag = wizard_data.use_ide and ' --ide vim' or '' + + -- 2. Determine Sample flag: --sample-code generates boilerplate + local sample_flag = wizard_data.sample == 'true' and ' --sample-code' or '' + + -- 3. Construct the full init command + local init_cmd = string.format('pio project init --board %s %s -O "framework=%s"%s', wizard_data.board_id, ide_flag, wizard_data.framework, sample_flag) + + print('Executing: ' .. init_cmd) + + pio.run_sequence({ + cmnds = { + init_cmd, + 'pio run -t compiledb', -- Essential to generate compile_commands.json for LSP + }, + cb = pio.handlePioinit, + }) +end + +-- --- PICKERS (In Order of Execution) --- + +-- STEP 4: Sample (True/False) +local function pick_sample() + pickers + .new({}, { + prompt_title = 'Include Sample Code?', + finder = finders.new_table({ results = { 'true', 'false' } }), + sorter = telescope_conf.generic_sorter({}), + attach_mappings = function(prompt_bufnr) + actions.select_default:replace(function() + local selection = action_state.get_selected_entry() + actions.close(prompt_bufnr) + wizard_data.sample = selection[1] -- Capture result + finalize_setup() + end) + return true + end, + }) + :find() +end + +-- STEP 3: Framework (From Board Data) +local function pick_framework(board_details) + pickers + .new({}, { + prompt_title = 'Select Framework (' .. board_details.id .. ')', + finder = finders.new_table({ results = board_details['frameworks'] }), + sorter = telescope_conf.generic_sorter({}), + attach_mappings = function(prompt_bufnr) + actions.select_default:replace(function() + local selection = action_state.get_selected_entry() + actions.close(prompt_bufnr) + wizard_data.framework = selection[1] + pick_sample() -- Next step + end) + return true + end, + }) + :find() +end + +-- STEP 2: Board (with Buffer Previewer) +local function pick_board(json_data) + pickers + .new({}, { + prompt_title = 'Select Board', + finder = finders.new_table({ + results = json_data, + entry_maker = function(entry) + return { + value = entry, + display = entry.name or entry.id, + ordinal = (entry.name or '') .. ' ' .. (entry.id or ''), + } + end, + }), + previewer = previewers.new_buffer_previewer({ + title = 'Board Details', + define_preview = function(self, entry) + local content = vim.split(vim.inspect(entry.value), '\n') + vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, content) + vim.api.nvim_set_option_value('filetype', 'lua', { buf = self.state.bufnr }) + end, + }), + sorter = telescope_conf.generic_sorter({}), + attach_mappings = function(prompt_bufnr) + actions.select_default:replace(function() + local selection = action_state.get_selected_entry() + actions.close(prompt_bufnr) + wizard_data.board_id = selection.value.id + pick_framework(selection.value) -- Next step + end) + return true + end, + }) + :find() +end + +-- STEP 1: IDE (True/False) +local function start_pio_wizard(json_data) + pickers + .new({}, { + prompt_title = 'Setup for Neovim IDE?', + finder = finders.new_table({ results = { 'true', 'false' } }), + sorter = telescope_conf.generic_sorter({}), + attach_mappings = function(prompt_bufnr) + actions.select_default:replace(function() + local selection = action_state.get_selected_entry() + actions.close(prompt_bufnr) + wizard_data.use_ide = (selection[1] == 'true') + pick_board(json_data) -- Next step + end) + return true + end, + }) + :find() +end + +local function launch_pio_project_wizard() + print('Fetching board data from PlatformIO...') + + -- 1. Get board data from PIO CLI in JSON format + -- The '--json-output' flag ensures we get structured data + local handle = io.popen('pio boards --json-output') + if not handle then + return + end + + local result = handle:read('*a') + handle:close() + + -- 2. Decode the JSON string into a Lua table + local ok, json_data = pcall(vim.json.decode, result) + if not ok or not json_data then + print('Error: Could not parse PlatformIO board data.') + return + end + + -- 3. Start the wizard we built previously + start_pio_wizard(json_data) +end + +-- Export the function so it's accessible via require() +return { + launch = launch_pio_project_wizard, +} diff --git a/plugin/platformio.lua b/plugin/platformio.lua index b9dfc649..3e80fa37 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -31,7 +31,8 @@ vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) -- end -- end, { ['repeat'] = -1 }) --- In ~/.config/nvim/init.lua +---------------------------------------------------------------- +-- Pioinit2 local pio_wiz = require('platformio.pioinit2') -- Create a keybinding to trigger the wizard @@ -43,6 +44,7 @@ end, { desc = 'Run PIO Project Wizard' }) vim.api.nvim_create_user_command('PioWizard', function() pio_wiz.launch() end, {}) +---------------------------------------------------------------- -- Pioinit vim.api.nvim_create_user_command('Pioinit', function() From 92270a1481af4e987d169f02c9b03b8af9bd6ae0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 18:02:05 +0300 Subject: [PATCH 0997/1406] update --- lua/platformio/pioinit2.lua | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/lua/platformio/pioinit2.lua b/lua/platformio/pioinit2.lua index eff3bfee..243a6b6f 100644 --- a/lua/platformio/pioinit2.lua +++ b/lua/platformio/pioinit2.lua @@ -64,18 +64,32 @@ local function pick_sample() end -- STEP 3: Framework (From Board Data) + +-- STEP 3: Framework Selection (Small Dialog) local function pick_framework(board_details) + -- Use dropdown theme to keep the window small and centered + local opts = require('telescope.themes').get_dropdown({ + prompt_title = 'Select Framework (' .. board_details.id .. ')', + layout_config = { + width = 0.4, -- 40% of screen width + height = 0.25, -- Small height for few choices + }, + previewer = false, -- No preview needed for framework names + }) + pickers - .new({}, { - prompt_title = 'Select Framework (' .. board_details.id .. ')', - finder = finders.new_table({ results = board_details['frameworks'] }), - sorter = telescope_conf.generic_sorter({}), + .new(opts, { + finder = finders.new_table({ + results = board_details['frameworks'], + }), + sorter = telescope_conf.generic_sorter(opts), attach_mappings = function(prompt_bufnr) actions.select_default:replace(function() local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) + -- selection is a simple string in this case wizard_data.framework = selection[1] - pick_sample() -- Next step + pick_sample() end) return true end, From 734c0eb7ac30d9887a0a5856afccf5c0e422e51e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 18:09:34 +0300 Subject: [PATCH 0998/1406] update --- lua/platformio/pioinit2.lua | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/lua/platformio/pioinit2.lua b/lua/platformio/pioinit2.lua index 243a6b6f..eb5302c7 100644 --- a/lua/platformio/pioinit2.lua +++ b/lua/platformio/pioinit2.lua @@ -11,22 +11,21 @@ local wizard_data = {} local function finalize_setup() local pio = require('platformio.utils.pio') - -- 1. Determine IDE flag: --ide vim enables LSP support for Neovim - local ide_flag = wizard_data.use_ide and ' --ide vim' or '' - - -- 2. Determine Sample flag: --sample-code generates boilerplate + -- 1. Flags (We'll default IDE to atom or similar if not using vim specifically) local sample_flag = wizard_data.sample == 'true' and ' --sample-code' or '' - -- 3. Construct the full init command - local init_cmd = string.format('pio project init --board %s %s -O "framework=%s"%s', wizard_data.board_id, ide_flag, wizard_data.framework, sample_flag) + local init_cmd = string.format('pio project init --board %s -O "framework=%s"%s', wizard_data.board_id, wizard_data.framework, sample_flag) + + -- 2. Build command list based on Selection + local commands = { init_cmd } + if wizard_data.use_compiledb then + table.insert(commands, 'pio run -t compiledb') + end - print('Executing: ' .. init_cmd) + print('Running ' .. #commands .. ' commands...') pio.run_sequence({ - cmnds = { - init_cmd, - 'pio run -t compiledb', -- Essential to generate compile_commands.json for LSP - }, + cmnds = commands, cb = pio.handlePioinit, }) end @@ -136,7 +135,12 @@ end -- STEP 1: IDE (True/False) local function start_pio_wizard(json_data) - local opts = dialog_opts('Initialize for Neovim?', 0.3) + local opts = require('telescope.themes').get_dropdown({ + prompt_title = 'Generate Compilation Database (LSP)?', + layout_config = { width = 0.4, height = 0.2 }, + previewer = false, + }) + pickers .new(opts, { finder = finders.new_table({ results = { 'true', 'false' } }), @@ -145,7 +149,8 @@ local function start_pio_wizard(json_data) actions.select_default:replace(function() local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) - wizard_data.use_ide = (selection[1] == 'true') + -- Save the boolean for the final step + wizard_data.use_compiledb = (selection[1] == 'true') pick_board(json_data) end) return true From f5a65a64917e324f4f29ba34c4b451093446c5be Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 18:56:59 +0300 Subject: [PATCH 0999/1406] update --- lua/platformio/pioinit2.lua | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/lua/platformio/pioinit2.lua b/lua/platformio/pioinit2.lua index eb5302c7..952fc3e3 100644 --- a/lua/platformio/pioinit2.lua +++ b/lua/platformio/pioinit2.lua @@ -11,27 +11,26 @@ local wizard_data = {} local function finalize_setup() local pio = require('platformio.utils.pio') - -- 1. Flags (We'll default IDE to atom or similar if not using vim specifically) + -- 1. Construct the basic init command local sample_flag = wizard_data.sample == 'true' and ' --sample-code' or '' - local init_cmd = string.format('pio project init --board %s -O "framework=%s"%s', wizard_data.board_id, wizard_data.framework, sample_flag) - -- 2. Build command list based on Selection + -- 2. Determine commands and callback local commands = { init_cmd } + local final_cb = pio.handlePioinit -- Default for 1 command + if wizard_data.use_compiledb then table.insert(commands, 'pio run -t compiledb') + final_cb = pio.handlePioinitDb -- Switch to Db handler for 2 commands end - print('Running ' .. #commands .. ' commands...') - + -- 3. Execute pio.run_sequence({ cmnds = commands, - cb = pio.handlePioinit, + cb = final_cb, }) end --- --- PICKERS (In Order of Execution) --- - local function dialog_opts(title, width) return require('telescope.themes').get_dropdown({ prompt_title = title, @@ -42,6 +41,9 @@ local function dialog_opts(title, width) previewer = false, -- Hide preview for simple choices }) end + +--- PICKERS (In Order of Execution) --- + -- STEP 4: Sample (True/False) local function pick_sample() local opts = dialog_opts('Include Sample Code?', 0.3) @@ -62,8 +64,6 @@ local function pick_sample() :find() end --- STEP 3: Framework (From Board Data) - -- STEP 3: Framework Selection (Small Dialog) local function pick_framework(board_details) -- Use dropdown theme to keep the window small and centered From 6b77dbbd38566fc256be9879144393fbd496954f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 19:22:25 +0300 Subject: [PATCH 1000/1406] update --- lua/platformio/utils/pio.lua | 39 ++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 93b6ad99..b968aa52 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -146,7 +146,7 @@ end ------------------------------------------------------ -- Handle after pioinit execution local commandPassed = 0 -function M.handlePioinit(result) +function M.handlePioinitDb(result) if result == 'INIT' then -- initialize commandPassed = 0 _G.metadata.isBusy = true @@ -159,7 +159,6 @@ function M.handlePioinit(result) vim.schedule(function() vim.notify('Pioinit: Done ..', vim.log.levels.INFO) local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') boilerplate_gen([[.clangd]], _G.metadata.core_dir) end) -- elseif commandPassed == 2 then -- if you sned more than 2 commands you need this @@ -188,6 +187,42 @@ function M.handlePioinit(result) end end +------------------------------------------------------ +-- Handle after pioinit execution +function M.handlePioinit(result) + if result == 'INIT' then -- initialize + commandPassed = 0 + _G.metadata.isBusy = true + local full_cmd = table.remove(M.queue, 1) + term.stdout_callback = M.stdoutcallback + term.ToggleTerminal(full_cmd, 'float') + elseif result == 'DONE' then -- result of the last command + vim.schedule(function() + vim.notify('compiledb: Done ..', vim.log.levels.INFO) + M.queue = {} + term.stdout_callback = nil + vim.schedule(function() + vim.notify('Pioinit: Done ..', vim.log.levels.INFO) + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen([[.clangd]], _G.metadata.core_dir) + local pio_refresh = require('platformio.pio_setup').pio_refresh + pio_refresh(function() + vim.misc.gitignore_lsp_configs('compile_commands.json') + -- _G.metadata.dbTrigger = true + -- local ok, _ = pcall(M.compile_commandsFix) + -- if not ok then + -- print('Env: dbTrigger, fail to call dbFix') + -- end + end) + end) + end) + elseif result == 'FAIL' then + M.queue = {} + term.stdout_callback = nil + _G.metadata.isBusy = false + end +end + ------------------------------------------------------ -- Handle after piolib execution function M.handlePiolib(result) From f27db6fd67139e1d76b812ead1702bbaa6d53c7a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 19:42:42 +0300 Subject: [PATCH 1001/1406] update --- lua/platformio/utils/pio.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index b968aa52..b7d47c5b 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -129,7 +129,8 @@ M.run_sequence = function(tasks) M.queue = {} callBack = tasks.cb -- 1. Save the callback in a local variable local commands = tasks.cmnds - + print(#commands) + local done = ' && echo _CMMNDS_":"DONE' local pass = ' && echo _CMMNDS_":"PASS' local fail = ' || echo _CMMNDS_":"FAIL' From 43400f4091da9f3e04261d38a009a8d539ace813 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 19:53:09 +0300 Subject: [PATCH 1002/1406] update --- lua/platformio/utils/pio.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index b7d47c5b..aefaa26b 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -149,6 +149,7 @@ end local commandPassed = 0 function M.handlePioinitDb(result) if result == 'INIT' then -- initialize + print('db') commandPassed = 0 _G.metadata.isBusy = true local full_cmd = table.remove(M.queue, 1) @@ -192,6 +193,7 @@ end -- Handle after pioinit execution function M.handlePioinit(result) if result == 'INIT' then -- initialize + print('init') commandPassed = 0 _G.metadata.isBusy = true local full_cmd = table.remove(M.queue, 1) From d1932daaedb807cf70ba7863fc027b01b031e902 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 20:26:07 +0300 Subject: [PATCH 1003/1406] update --- lua/platformio/pioinit2.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pioinit2.lua b/lua/platformio/pioinit2.lua index 952fc3e3..452e3958 100644 --- a/lua/platformio/pioinit2.lua +++ b/lua/platformio/pioinit2.lua @@ -13,7 +13,7 @@ local function finalize_setup() -- 1. Construct the basic init command local sample_flag = wizard_data.sample == 'true' and ' --sample-code' or '' - local init_cmd = string.format('pio project init --board %s -O "framework=%s"%s', wizard_data.board_id, wizard_data.framework, sample_flag) + local init_cmd = string.format('pio project init --ide vim --board %s -O "framework=%s"%s', wizard_data.board_id, wizard_data.framework, sample_flag) -- 2. Determine commands and callback local commands = { init_cmd } From b0400798526e6fac071075ad04e77864150eae6c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 20:57:33 +0300 Subject: [PATCH 1004/1406] update --- mini_nvimPlatformio.lua | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 3e6e2406..d19dc204 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -146,8 +146,10 @@ end, { desc = '[D]elete Buffer' }) -- keymap('n', '[B', 'BufferLineMovePrev', { desc = 'Move buffer prev' }) -- keymap('n', ']B', 'BufferLineMoveNext', { desc = 'Move buffer next' }) -keymap('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) -keymap('n', '\\', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) +keymap('n', 'e', 'NeoTreeToggle', { desc = 'NvimTreeToggle' }) +keymap('n', '\\', 'NeoTreeToggle', { desc = 'NvimTreeToggle' }) +-- keymap('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) +-- keymap('n', '\\', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) -- Keybinds to make split navigation easier. -- Use CTRL+ to switch between windows From 4a60bf412f192405d2d74174cb8e4d36a0217369 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 21:03:26 +0300 Subject: [PATCH 1005/1406] update --- mini_nvimPlatformio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index d19dc204..9a2581a9 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -146,8 +146,8 @@ end, { desc = '[D]elete Buffer' }) -- keymap('n', '[B', 'BufferLineMovePrev', { desc = 'Move buffer prev' }) -- keymap('n', ']B', 'BufferLineMoveNext', { desc = 'Move buffer next' }) -keymap('n', 'e', 'NeoTreeToggle', { desc = 'NvimTreeToggle' }) -keymap('n', '\\', 'NeoTreeToggle', { desc = 'NvimTreeToggle' }) +keymap('n', 'e', 'NeoTree', { desc = 'NvimTreeToggle' }) +keymap('n', '\\', 'NeoTree', { desc = 'NvimTreeToggle' }) -- keymap('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) -- keymap('n', '\\', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) From 72e94eaac51ebb6f33722e0db21981797676151b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 21:04:37 +0300 Subject: [PATCH 1006/1406] update --- mini_nvimPlatformio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 9a2581a9..80bfffbc 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -146,8 +146,8 @@ end, { desc = '[D]elete Buffer' }) -- keymap('n', '[B', 'BufferLineMovePrev', { desc = 'Move buffer prev' }) -- keymap('n', ']B', 'BufferLineMoveNext', { desc = 'Move buffer next' }) -keymap('n', 'e', 'NeoTree', { desc = 'NvimTreeToggle' }) -keymap('n', '\\', 'NeoTree', { desc = 'NvimTreeToggle' }) +keymap('n', 'e', 'Neotree', { desc = 'NvimTreeToggle' }) +keymap('n', '\\', 'Neotree', { desc = 'NvimTreeToggle' }) -- keymap('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) -- keymap('n', '\\', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) From c8bd42f0f0406334e961542cefe269a0b1250e1f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 21:16:02 +0300 Subject: [PATCH 1007/1406] update --- mini_nvimPlatformio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 80bfffbc..d1406af6 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -146,8 +146,8 @@ end, { desc = '[D]elete Buffer' }) -- keymap('n', '[B', 'BufferLineMovePrev', { desc = 'Move buffer prev' }) -- keymap('n', ']B', 'BufferLineMoveNext', { desc = 'Move buffer next' }) -keymap('n', 'e', 'Neotree', { desc = 'NvimTreeToggle' }) -keymap('n', '\\', 'Neotree', { desc = 'NvimTreeToggle' }) +keymap('n', 'e', 'Neotree toggle', { desc = 'NeoTreeToggle' }) +keymap('n', '\\', 'Neotree toggle', { desc = 'NeoTreeToggle' }) -- keymap('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) -- keymap('n', '\\', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) From 62d0a3f019cd5c6a5cf7f7c1e169d4c86839ea47 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 21:25:50 +0300 Subject: [PATCH 1008/1406] update --- lua/platformio/utils/pio.lua | 3 --- mini_nvimPlatformio.lua | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index aefaa26b..6964370f 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -129,7 +129,6 @@ M.run_sequence = function(tasks) M.queue = {} callBack = tasks.cb -- 1. Save the callback in a local variable local commands = tasks.cmnds - print(#commands) local done = ' && echo _CMMNDS_":"DONE' local pass = ' && echo _CMMNDS_":"PASS' @@ -149,7 +148,6 @@ end local commandPassed = 0 function M.handlePioinitDb(result) if result == 'INIT' then -- initialize - print('db') commandPassed = 0 _G.metadata.isBusy = true local full_cmd = table.remove(M.queue, 1) @@ -193,7 +191,6 @@ end -- Handle after pioinit execution function M.handlePioinit(result) if result == 'INIT' then -- initialize - print('init') commandPassed = 0 _G.metadata.isBusy = true local full_cmd = table.remove(M.queue, 1) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index d1406af6..22accaa1 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -146,7 +146,7 @@ end, { desc = '[D]elete Buffer' }) -- keymap('n', '[B', 'BufferLineMovePrev', { desc = 'Move buffer prev' }) -- keymap('n', ']B', 'BufferLineMoveNext', { desc = 'Move buffer next' }) -keymap('n', 'e', 'Neotree toggle', { desc = 'NeoTreeToggle' }) +keymap('n', 'e', 'Neotree document_symbols', { desc = 'NeoTreeToggle' }) keymap('n', '\\', 'Neotree toggle', { desc = 'NeoTreeToggle' }) -- keymap('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) -- keymap('n', '\\', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) From c021ed51068841751a1eb1458cc47590d0c791b2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 21:32:42 +0300 Subject: [PATCH 1009/1406] update --- mini_nvimPlatformio.lua | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 22accaa1..99ce79cb 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -270,6 +270,14 @@ local plugins = { 'nvim-tree/nvim-web-devicons', -- optional, but recommended }, lazy = false, -- neo-tree will lazily load itself + opts = { + sources = { + 'filesystem', + 'buffers', + 'git_status', + 'document_symbols', -- Add this line + }, + }, }, -- { From 614e0769da8d3ed631ea1619506bd57df23f331f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 21:40:13 +0300 Subject: [PATCH 1010/1406] update --- lua/platformio/lsp/clangd.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lsp/clangd.lua index a6a1e763..874ffa70 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lsp/clangd.lua @@ -115,7 +115,8 @@ function _G.get_clangd_config() -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) - q_driver = '**' --_G.metadata.query_driver .. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" + -- q_driver = '**' --_G.metadata.query_driver .. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" + q_driver = _G.metadata.query_driver --.. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" end end From d576a2d88edcf295cb8b36b8394d4173c9bfb30c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 25 Apr 2026 21:50:03 +0300 Subject: [PATCH 1011/1406] update --- mini_nvimPlatformio.lua | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 99ce79cb..33838c47 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -271,12 +271,16 @@ local plugins = { }, lazy = false, -- neo-tree will lazily load itself opts = { + use_libuv_file_watcher = true, sources = { 'filesystem', 'buffers', 'git_status', 'document_symbols', -- Add this line }, + filters = { + custom = { '^\\.cache$', '^\\.pio$' }, + }, }, }, From 6ec173aaee9a17892065d9bac7681986912619ea Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 12:59:24 +0300 Subject: [PATCH 1012/1406] update --- .luarc.json | 9 +++++ lua/platformio/boilerplate.lua | 70 ---------------------------------- lua/platformio/init.lua | 2 + lua/platformio/metadata.lua | 48 +++-------------------- lua/platformio/pio_setup.lua | 48 ++++++++++------------- lua/platformio/utils/misc.lua | 6 +++ lua/platformio/utils/pio.lua | 1 + mini_nvimPlatformio.lua | 39 ++++++++++++++++--- plugin/platformio.lua | 59 +++++++++++++++++----------- 9 files changed, 116 insertions(+), 166 deletions(-) create mode 100644 .luarc.json diff --git a/.luarc.json b/.luarc.json new file mode 100644 index 00000000..54965bab --- /dev/null +++ b/.luarc.json @@ -0,0 +1,9 @@ +{ + "workspace": { + "library": ["$VIMRUNTIME/lua", "${3rd}/luv/library", "./lua"], + "checkThirdParty": false + }, + "diagnostics": { + "globals": ["vim"] + } +} diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 0b8b444e..d82851cf 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -49,13 +49,6 @@ extra_scripts = lib_ldf_mode = chain ;Library dependencies Finder ldf -;build_flags = -; -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0 -; -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include/c++/14.2.0/riscv32-esp-elf -; -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include -; -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/lib/gcc/riscv32-esp-elf/14.2.0/include-fixed -; -isystemC:/Users/tom/.platformio/packages/toolchain-riscv32-esp/riscv32-esp-elf/include -; -D COMPILATIONDB_INCLUDE_TOOLCHAIN ]], content = function(self) -- local pio = require('platformio.utils.pio') @@ -117,34 +110,6 @@ boilerplate['.clangd_config'] = { } ]], } --- INFO: .clangd_cmd -boilerplate['.clangd_cmd'] = { - rewrite = true, - read = false, - template = [[ -clangd ---all-scopes-completion ---background-index ---clang-tidy ---compile_args_from=filesystem ---compile-commands-dir=. ---enable-config ---completion-parse=always ---completion-style=detailed ---header-insertion=iwyu ---fallback-style=llvm --j=12 ---log=verbose ---offset-encoding=utf-8 ---pch-storage=memory ---pretty ---ranking-model=decision_forest ---query-driver=%s -]], - content = function(self) - return string.format(self.template, _G.metadata.query_driver or '**') - end, -} -- CompileFlags: -- Add: -- - "-xc++" @@ -250,41 +215,6 @@ Diagnostics: -- end, } --- INFO: .stylua.toml -boilerplate['.stylua.toml'] = { - rewrite = false, - read = false, - content = [[ -syntax = "All" -column_width = 132 -line_endings = "Unix" -indent_type = "Spaces" -indent_width = 2 -quote_style = "AutoPreferSingle" -call_parentheses = "Always" -collapse_simple_statement = "Never" -space_after_function_names = "Never" - -[sort_requires] -enabled = false -]], -} - --- INFO: generate_compileDB.py -boilerplate['generate_compileDB.py'] = { - rewrite = false, - read = false, - content = [[ -import subprocess -from SCons.Script import COMMAND_LINE_TARGETS - -# Only run if we are NOT already generating the compilation database -if "compiledb" not in COMMAND_LINE_TARGETS: - print("Regenerating compile_commands.json...") - subprocess.run(["pio", "run", "-t", "compiledb"]) -]], -} - -- INFO: .clang-format boilerplate['.clang-format'] = { rewrite = false, diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index 8d0aa865..b98b7c68 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -188,4 +188,6 @@ function M.setup(user_config) end) end +vim.notify('nvim-platformio.lua started', vim.log.levels.INFO) + return M diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 64b02da1..a194a4f7 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -1,28 +1,5 @@ local M = {} -local pio = require('platformio.utils.pio') -local frames = { '⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏' } -local frame_idx = 1 - -function M.get_pio_status() - local meta = _G.metadata - if not meta then - return '' - end - - -- Accessing meta.active_env triggers __index automatically in Lua - local active = meta.active_env or '' - if active == '' then - return '' - end - - if M.is_busy then - local icon = frames[frame_idx] - frame_idx = (frame_idx % #frames) + 1 - return string.format(' [ %s %s ] ', icon, active) - end - return string.format(' [ %s ] ', active) -end ------------------------------------------------------------------------------------------------------- local last_saved_hash = '' local config_path = vim.fs.joinpath(vim.uv.cwd(), '.project_config.json') @@ -53,7 +30,7 @@ local _pio_metadata = { sysroot = '', fallbackFlags = {}, dbTrigger = false, - last_checksum = '', -- Used to track changes + last_projectChecksum = '', -- Used to track changes } -- 2. The Reactive Proxy Wrapper -- Any write to _G.metadata.key = val triggers this logic @@ -86,6 +63,7 @@ _G.metadata = setmetatable({}, { -- vim.notify('Env: LspRestart', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) -- end -- end) + elseif key == 'last_projectChecksum' then elseif key == 'active_env' then -- Force global statusline so it doesn't get pushed around by Trouble or splits vim.o.laststatus = 3 @@ -94,6 +72,9 @@ _G.metadata = setmetatable({}, { end, }) +-- -- Add this temporary line in a file where you are coding: +-- ---@type platformio.utils.misc +-- local misc = vim.misc --INFO: -- 3. Save Logic (Uses sha256 for stability) function M.save_project_config(quiet) @@ -112,7 +93,7 @@ function M.save_project_config(quiet) -- file:write(pio.jsonFormat(json_data)) if current_hash ~= last_saved_hash then -- local status = vim.fn.writefile({ json_data }, config_path) - local status, _ = vim.misc.writeFile({ json_data }, config_path) + local status, _ = vim.misc.writeFile(json_data, config_path, {}) if status == 0 then last_saved_hash = current_hash if not quiet then @@ -127,23 +108,6 @@ end --INFO: -- 4. Load Logic (Populates proxy safely) function M.load_project_config() - -- if vim.fn.filereadable(config_path) == 1 then - -- local file = io.open(config_path, 'r') - -- if file then - -- local content = file:read('*a') - -- file:close() - -- local ok, decoded = pcall(vim.json.decode, content) - -- if ok and type(decoded) == 'table' then - -- -- We update _pio_metadata directly to avoid triggering - -- -- 50+ notifications/restarts during the initial load loop - -- for k, v in pairs(decoded) do - -- _pio_metadata[k] = v - -- end - -- last_saved_hash = vim.fn.sha256(content) - -- return - -- end - -- end - -- end if vim.fn.filereadable(config_path) == 1 then local _, json_data = vim.misc.readFile(config_path) if json_data then diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index c61be1e7..f0b73f7b 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -110,7 +110,7 @@ function M.pio_refresh(callback) meta.includes_build = quote_map(inc.build, '-I') meta.includes_toolchain = quote_map(inc.toolchain, '-isystem') meta.includes_compatlib = quote_map(inc.compatlib, '-isystem') - meta.last_checksum = checksum + meta.last_projectChecksum = checksum pcall(M.get_sysroot_triplet, meta.cc_compiler) if callback then callback() end @@ -122,7 +122,7 @@ function M.pio_refresh(callback) --------------------------------------------------------- local _, current_checksum = vim.misc.readFile(checksum_path) if current_checksum and current_checksum ~= '' then - if current_checksum == meta.last_checksum then return end -- Already updated + if current_checksum == meta.last_projectChecksum then return end -- Already updated -- STEP 2: Cache Path (idedata.json exists and checksum changed) local _, content = vim.misc.readFile(idedata_path) @@ -345,8 +345,8 @@ function M.start_watchers() local targets = { { -- watcher for platformio.ini - path = vim.misc.joinPath(project_root, 'platformio.ini'), current_ini_hash = '', + path = vim.misc.joinPath(project_root, 'platformio.ini'), cb = function(self) local new_hash = get_hash(self.path) or '' if new_hash and new_hash ~= self.current_ini_hash then @@ -357,10 +357,10 @@ function M.start_watchers() end, }, { -- watcher for ./.pio/build/projct.checksum - checksum_path = vim.misc.joinPath(project_root, '.pio/build', 'project.checksum'), idedata_path = vim.misc.joinPath(project_root, '.pio/build', active_env, 'idedata.json'), + path = vim.misc.joinPath(project_root, '.pio/build', 'project.checksum'), --checksum_path cb = function(self) - local _, current_checksum = vim.misc.readFile(self.checksum_path) + local _, current_checksum = vim.misc.readFile(self.path) if current_checksum and current_checksum ~= '' then if current_checksum == _G.metadata.last_checksum then return @@ -474,19 +474,6 @@ function M.init() local metadata = require('platformio.metadata') metadata.load_project_config() - ---------------------------------------------------------------------------------------- - -- INFO: create clangd required files - ----------------------------------------------------------------------------------------- - boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') - -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) - boilerplate.core_dir = _G.metadata.core_dir - boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) - boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) - boilerplate_gen([[.stylua.toml]], vim.g.platformioRootDir) - boilerplate_gen([[generate_compileDB.py]], vim.g.platformioRootDir) - --------------------------------------------------------------------------------- - require('platformio.lsp.clangd') if config.lspClangd.attach.enabled then require('platformio.lsp.attach') @@ -498,15 +485,22 @@ function M.init() -- If the file already exists, do an initial sync if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then - M.run_compiledb() -- Smart: Auto-update DB if config changes - -- M.pio_refresh(function() - -- -- vim.schedule(function() - -- -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - -- -- pio_generate_db() - -- -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) - -- -- lsp_restart('clangd') - -- -- end) - -- end) + ---------------------------------------------------------------------------------------- + -- INFO: create clangd required files + ----------------------------------------------------------------------------------------- + boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') + -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) + boilerplate.core_dir = _G.metadata.core_dir + boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) + boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) + --------------------------------------------------------------------------------- + -- M.run_compiledb() -- Smart: Auto-update DB if config changes + M.pio_refresh(function() + -- vim.schedule(function() + -- lsp_restart('clangd') + -- end) + end) end end end diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index fb9f3b52..2544b1b4 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -1,3 +1,5 @@ +--@class lua.platformio.utils.misc +-- File: lua/platformio/wizard.lua local M = {} M.is_windows = jit.os == 'Windows' @@ -154,6 +156,7 @@ end -- local content = readFile("compile_commands.json") -- if content then local data = vim.json.decode(content) end -- stylua: ignore +---@param path string function M.readFile(path) local uv = vim.uv or vim.loop -- Support older and newer Neovim versions @@ -187,6 +190,9 @@ end -- local ok, err = writeFiile(path, json) -- if ok then print("Write complete!") end -- stylua: ignore +---@param path string +---@param data string +---@param opts table function M.writeFile(path, data, opts) local uv = vim.uv or vim.loop opts = opts or {} diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 6964370f..71fb7cd6 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -1,3 +1,4 @@ +---@class platformio.utils.pio local M = {} -- to fix require loop, this value is set in plugin/platformio diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 33838c47..12a29732 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -312,13 +312,10 @@ local plugins = { cond = function() -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.fn.getcwd() or nil local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.uv.cwd() or nil - if platformioRootDir and vim.fs.find('.pio', { path = platformioRootDir, type = 'directory' })[1] then + -- if platformioRootDir and vim.fs.find('.pio', { path = platformioRootDir, type = 'directory' })[1] then + if platformioRootDir then -- if platformio.ini file and .pio folder exist in cwd, enable plugin to install plugin (if not istalled) and load it. vim.g.platformioRootDir = platformioRootDir - elseif (vim.uv or vim.loop).fs_stat(vim.env.XDG_DATA_HOME .. '/lazy/nvim-platformio.lua') == nil then - -- if nvim-platformio not installed, enable plugin to install it first time - -- vim.g.platformioRootDir = vim.fn.getcwd() - vim.g.platformioRootDir = vim.uv.cwd() else -- if nvim-platformio.lua installed but disabled, create Pioinit command vim.api.nvim_create_user_command('Pioinit', function() --available only if no platformio.ini and .pio in cwd vim.api.nvim_create_autocmd('User', { @@ -337,9 +334,41 @@ local plugins = { vim.g.platformioRootDir = vim.uv.cwd() require('lazy').restore({ plguins = { 'nvim-platformio.lua' }, show = false }) end, {}) + vim.g.platformioRootDir = nil end return vim.g.platformioRootDir ~= nil end, + -- cond = function() + -- -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.fn.getcwd() or nil + -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.uv.cwd() or nil + -- if platformioRootDir and vim.fs.find('.pio', { path = platformioRootDir, type = 'directory' })[1] then + -- -- if platformio.ini file and .pio folder exist in cwd, enable plugin to install plugin (if not istalled) and load it. + -- vim.g.platformioRootDir = platformioRootDir + -- elseif (vim.uv or vim.loop).fs_stat(vim.env.XDG_DATA_HOME .. '/lazy/nvim-platformio.lua') == nil then + -- -- if nvim-platformio not installed, enable plugin to install it first time + -- -- vim.g.platformioRootDir = vim.fn.getcwd() + -- vim.g.platformioRootDir = vim.uv.cwd() + -- else -- if nvim-platformio.lua installed but disabled, create Pioinit command + -- vim.api.nvim_create_user_command('Pioinit', function() --available only if no platformio.ini and .pio in cwd + -- vim.api.nvim_create_autocmd('User', { + -- pattern = { 'LazyRestore', 'LazyLoad' }, + -- once = true, + -- callback = function(args) + -- if args.match == 'LazyRestore' then + -- require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) + -- elseif args.match == 'LazyLoad' then + -- vim.notify('PlatformIO loaded', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- vim.cmd('Pioinit') + -- end + -- end, + -- }) + -- -- vim.g.platformioRootDir = vim.fn.getcwd() + -- vim.g.platformioRootDir = vim.uv.cwd() + -- require('lazy').restore({ plguins = { 'nvim-platformio.lua' }, show = false }) + -- end, {}) + -- end + -- return vim.g.platformioRootDir ~= nil + -- end, dependencies = { { 'akinsho/toggleterm.nvim' }, { 'nvim-telescope/telescope.nvim' }, diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 3e80fa37..6da9e0da 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -6,32 +6,51 @@ -- +: At least one argument. -- -1: Zero or one argument (like ?, explicitly). --- - Only requires the module the FIRST time you actually try to use vim.pf +---------------------------------------------------------------- +-- lazy-loading technique using a Lua metatable. +-- It essentially "teaches" Neovim how to find a custom module only when you actually try to use it -- setmetatable(vim, { -- __index = function(t, k) +-- -- Lazy load the misc module if requested -- if k == 'misc' then -- t.misc = require('platformio.utils.misc') -- return t.misc -- end +-- +-- -- Alias vim.pio to the pio module for convenience +-- if k == 'pio' then +-- t.pio = require('platformio.utils.pio') +-- return t.pio +-- end -- end, -- }) -vim.misc = require('platformio.utils.misc') -local piolsserial = require('platformio.piolsserial') -local pio = require('platformio.utils.pio') --- Statusline: Using luaeval for best cross-platform stability -vim.o.laststatus = 3 -vim.o.statusline = '%f %m %r %= %#PioStatus#%{luaeval("require(\'platformio.metadata\').get_pio_status()")} %y %p%% %l:%c' -vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#7aa2f7', bold = true }) +---@class vim +---@field pio platformio.utils.pio +---@field misc platformio.utils.misc --- Simple timer to animate the spinner if M.is_busy --- vim.fn.timer_start(100, function() --- if meta.is_busy then --- vim.cmd('redrawstatus') --- end --- end, { ['repeat'] = -1 }) +setmetatable(vim, { + __index = function(t, k) + if k == 'misc' then + local m = require('platformio.utils.misc') + rawset(t, k, m) -- Physically add 'misc' to 'vim' + return m + end + if k == 'pio' then + local p = require('platformio.utils.pio') + rawset(t, k, p) -- Physically add 'pio' to 'vim' + return p + end + end, +}) +-- vim.misc = require('platformio.utils.misc') +-- vim.pio = require('platformio.utils.pio') + +-- INFO: fix paths in compile_commands.json +vim.api.nvim_create_user_command('PioFixPaths', function() + vim.pio.compile_commandsFix() +end, {}) ----------------------------------------------------------------- -- Pioinit2 local pio_wiz = require('platformio.pioinit2') @@ -44,7 +63,9 @@ end, { desc = 'Run PIO Project Wizard' }) vim.api.nvim_create_user_command('PioWizard', function() pio_wiz.launch() end, {}) ----------------------------------------------------------------- + +------------------------------------------------------ +local piolsserial = require('platformio.piolsserial') -- Pioinit vim.api.nvim_create_user_command('Pioinit', function() @@ -130,12 +151,6 @@ end, {}) ------------------------------------------------------ --- INFO: fix paths in compile_commands.json -vim.api.nvim_create_user_command('PioFixPaths', function() - pio.compile_commandsFix() -end, {}) ------------------------------------------------------- - -- require('telescope').load_extension('ui-select') -- INFO: List ToggleTerminals vim.api.nvim_create_user_command('PioTermList', function() From a37a43b4b2f9edd4ce4ec6ba877b1193ed1162af Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 13:03:42 +0300 Subject: [PATCH 1013/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index f0b73f7b..d1e8a7f8 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -492,7 +492,7 @@ function M.init() -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) boilerplate.core_dir = _G.metadata.core_dir - boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) + -- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) --------------------------------------------------------------------------------- -- M.run_compiledb() -- Smart: Auto-update DB if config changes From 43f7a6b99ba2179823c4c0e9e57c7d6dd9780994 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 13:09:37 +0300 Subject: [PATCH 1014/1406] update --- mini_nvimPlatformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 12a29732..349a1a16 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -313,6 +313,7 @@ local plugins = { -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.fn.getcwd() or nil local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.uv.cwd() or nil -- if platformioRootDir and vim.fs.find('.pio', { path = platformioRootDir, type = 'directory' })[1] then + vim.g.platformioRootDir = nil if platformioRootDir then -- if platformio.ini file and .pio folder exist in cwd, enable plugin to install plugin (if not istalled) and load it. vim.g.platformioRootDir = platformioRootDir @@ -334,7 +335,6 @@ local plugins = { vim.g.platformioRootDir = vim.uv.cwd() require('lazy').restore({ plguins = { 'nvim-platformio.lua' }, show = false }) end, {}) - vim.g.platformioRootDir = nil end return vim.g.platformioRootDir ~= nil end, From 060a7ed8718949e833d1666033b2b2474760f1af Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 13:16:04 +0300 Subject: [PATCH 1015/1406] update --- mini_nvimPlatformio.lua | 67 +++++++++++++++++++++++++---------------- 1 file changed, 41 insertions(+), 26 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 349a1a16..5918aefb 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -310,37 +310,52 @@ local plugins = { { 'batoaqaa/nvim-platformio.lua', cond = function() - -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.fn.getcwd() or nil - local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.uv.cwd() or nil - -- if platformioRootDir and vim.fs.find('.pio', { path = platformioRootDir, type = 'directory' })[1] then - vim.g.platformioRootDir = nil - if platformioRootDir then - -- if platformio.ini file and .pio folder exist in cwd, enable plugin to install plugin (if not istalled) and load it. - vim.g.platformioRootDir = platformioRootDir - else -- if nvim-platformio.lua installed but disabled, create Pioinit command - vim.api.nvim_create_user_command('Pioinit', function() --available only if no platformio.ini and .pio in cwd - vim.api.nvim_create_autocmd('User', { - pattern = { 'LazyRestore', 'LazyLoad' }, - once = true, - callback = function(args) - if args.match == 'LazyRestore' then - require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) - elseif args.match == 'LazyLoad' then - vim.notify('PlatformIO loaded', vim.log.levels.INFO, { title = 'PlatformIO' }) - vim.cmd('Pioinit') - end - end, - }) - -- vim.g.platformioRootDir = vim.fn.getcwd() - vim.g.platformioRootDir = vim.uv.cwd() - require('lazy').restore({ plguins = { 'nvim-platformio.lua' }, show = false }) - end, {}) + -- Check if platformio.ini exists in the current directory + local pio_exists = vim.fn.filereadable('platformio.ini') == 1 + if pio_exists then + return true end - return vim.g.platformioRootDir ~= nil + + -- If not found, create the :Pioinit command to force load the plugin + vim.api.nvim_create_user_command('Pioinit', function() + require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) + vim.notify('nvim-platformio.lua forced activation') + end, { desc = 'Force activate PlatformIO plugin' }) + + return false end, -- cond = function() -- -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.fn.getcwd() or nil -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.uv.cwd() or nil + -- -- if platformioRootDir and vim.fs.find('.pio', { path = platformioRootDir, type = 'directory' })[1] then + -- vim.g.platformioRootDir = nil + -- if platformioRootDir then + -- -- if platformio.ini file and .pio folder exist in cwd, enable plugin to install plugin (if not istalled) and load it. + -- vim.g.platformioRootDir = platformioRootDir + -- else -- if nvim-platformio.lua installed but disabled, create Pioinit command + -- vim.api.nvim_create_user_command('Pioinit', function() --available only if no platformio.ini and .pio in cwd + -- vim.api.nvim_create_autocmd('User', { + -- pattern = { 'LazyRestore', 'LazyLoad' }, + -- once = true, + -- callback = function(args) + -- if args.match == 'LazyRestore' then + -- require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) + -- elseif args.match == 'LazyLoad' then + -- vim.notify('PlatformIO loaded', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- vim.cmd('Pioinit') + -- end + -- end, + -- }) + -- -- vim.g.platformioRootDir = vim.fn.getcwd() + -- vim.g.platformioRootDir = vim.uv.cwd() + -- require('lazy').restore({ plguins = { 'nvim-platformio.lua' }, show = false }) + -- end, {}) + -- end + -- return vim.g.platformioRootDir ~= nil + -- end, + -- cond = function() + -- -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.fn.getcwd() or nil + -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.uv.cwd() or nil -- if platformioRootDir and vim.fs.find('.pio', { path = platformioRootDir, type = 'directory' })[1] then -- -- if platformio.ini file and .pio folder exist in cwd, enable plugin to install plugin (if not istalled) and load it. -- vim.g.platformioRootDir = platformioRootDir From c20c36e46e863a285135b1720a5ee07cc2641318 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 13:19:20 +0300 Subject: [PATCH 1016/1406] update --- mini_nvimPlatformio.lua | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 5918aefb..c58bcf40 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -316,13 +316,27 @@ local plugins = { return true end - -- If not found, create the :Pioinit command to force load the plugin + -- Create command to load AND open the plugin menu vim.api.nvim_create_user_command('Pioinit', function() + -- 1. Force lazy.nvim to load the plugin require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) - vim.notify('nvim-platformio.lua forced activation') - end, { desc = 'Force activate PlatformIO plugin' }) + + -- 2. Issue the main command to the plugin (opens the Telescope menu) + -- Use pcall to ensure it doesn't error if setup takes a millisecond to register + vim.schedule(function() + vim.cmd('Pio') + vim.notify('PlatformIO Activated and Menu Opened') + end) + end, { desc = 'Force load and open PlatformIO' }) return false + -- If not found, create the :Pioinit command to force load the plugin + -- vim.api.nvim_create_user_command('Pioinit', function() + -- require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) + -- vim.notify('nvim-platformio.lua forced activation') + -- end, { desc = 'Force activate PlatformIO plugin' }) + -- + -- return false end, -- cond = function() -- -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.fn.getcwd() or nil From 221f78217bcd09f3a4eb62cb217094a9365fe930 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 13:29:41 +0300 Subject: [PATCH 1017/1406] update --- mini_nvimPlatformio.lua | 59 ++++++++++++++++++++++++++--------------- 1 file changed, 37 insertions(+), 22 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index c58bcf40..3ae2616a 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -309,36 +309,51 @@ local plugins = { { 'batoaqaa/nvim-platformio.lua', - cond = function() - -- Check if platformio.ini exists in the current directory - local pio_exists = vim.fn.filereadable('platformio.ini') == 1 - if pio_exists then - return true + + init = function() + -- 1. Automatic check: Load if file exists + if vim.fn.filereadable('platformio.ini') == 1 then + require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) end - -- Create command to load AND open the plugin menu + -- 2. Manual Force: Create a command that overrides the check vim.api.nvim_create_user_command('Pioinit', function() - -- 1. Force lazy.nvim to load the plugin require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) - - -- 2. Issue the main command to the plugin (opens the Telescope menu) - -- Use pcall to ensure it doesn't error if setup takes a millisecond to register vim.schedule(function() - vim.cmd('Pio') - vim.notify('PlatformIO Activated and Menu Opened') + vim.cmd('Pio') -- Trigger the plugin's internal menu end) - end, { desc = 'Force load and open PlatformIO' }) - - return false - -- If not found, create the :Pioinit command to force load the plugin - -- vim.api.nvim_create_user_command('Pioinit', function() - -- require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) - -- vim.notify('nvim-platformio.lua forced activation') - -- end, { desc = 'Force activate PlatformIO plugin' }) - -- - -- return false + end, { desc = 'Force activate PlatformIO' }) end, -- cond = function() + -- -- Check if platformio.ini exists in the current directory + -- local pio_exists = vim.fn.filereadable('platformio.ini') == 1 + -- if pio_exists then + -- return true + -- end + -- + -- -- Create command to load AND open the plugin menu + -- vim.api.nvim_create_user_command('Pioinit', function() + -- -- 1. Force lazy.nvim to load the plugin + -- require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) + -- + -- -- 2. Issue the main command to the plugin (opens the Telescope menu) + -- -- Use pcall to ensure it doesn't error if setup takes a millisecond to register + -- vim.schedule(function() + -- vim.cmd('Pio') + -- vim.notify('PlatformIO Activated and Menu Opened') + -- end) + -- end, { desc = 'Force load and open PlatformIO' }) + -- + -- return false + -- -- If not found, create the :Pioinit command to force load the plugin + -- -- vim.api.nvim_create_user_command('Pioinit', function() + -- -- require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) + -- -- vim.notify('nvim-platformio.lua forced activation') + -- -- end, { desc = 'Force activate PlatformIO plugin' }) + -- -- + -- -- return false + -- end, + -- cond = function() -- -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.fn.getcwd() or nil -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.uv.cwd() or nil -- -- if platformioRootDir and vim.fs.find('.pio', { path = platformioRootDir, type = 'directory' })[1] then From c2254278b9945e97834557512bc27b33f1d0f0d0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 13:36:20 +0300 Subject: [PATCH 1018/1406] update --- mini_nvimPlatformio.lua | 3 +++ 1 file changed, 3 insertions(+) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 3ae2616a..d28e6304 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -314,6 +314,9 @@ local plugins = { -- 1. Automatic check: Load if file exists if vim.fn.filereadable('platformio.ini') == 1 then require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) + vim.g.platformioRootDir = vim.uv.cwd() + else + vim.g.platformioRootDir = nil end -- 2. Manual Force: Create a command that overrides the check From a558d5b8d7e4d8644c5cabc0cd0074faeab5bbca Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 13:41:00 +0300 Subject: [PATCH 1019/1406] update --- lua/platformio/init.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index b98b7c68..3f109c48 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -155,7 +155,7 @@ local function validateMenu(menu) end function M.setup(user_config) - if next(user_config) ~= nil then + if vim.g.platformioRootDir and (next(user_config) ~= nil) then if user_config.lspClangd then vim.validate('lspClangd', user_config.lspClangd, 'table', true) vim.validate('lspClangdEnabled', user_config.lspClangd.enabled, 'boolean', true) From 19513a4128a5b8a0d4f1b6e6fea0e15ca59fd79b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 13:50:37 +0300 Subject: [PATCH 1020/1406] update --- mini_nvimPlatformio.lua | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index d28e6304..80279d87 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -278,8 +278,16 @@ local plugins = { 'git_status', 'document_symbols', -- Add this line }, - filters = { - custom = { '^\\.cache$', '^\\.pio$' }, + filtered_items = { + visible = false, -- Change to true if you want to see them dimmed + hide_dotfiles = true, + hide_gitignored = true, + hide_by_name = { '^\\.cache$', '^\\.pio$' }, + never_show = { -- This is the strongest setting to ignore the folder + '.cache', + '.git', + 'node_modules', + }, }, }, }, From 71470f3779f3d4be8564b6909233b881af9794b5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 14:02:27 +0300 Subject: [PATCH 1021/1406] update --- mini_nvimPlatformio.lua | 66 ++++++++++++++++++++++++++++++----------- 1 file changed, 48 insertions(+), 18 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 80279d87..8ca7af62 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -335,6 +335,36 @@ local plugins = { end) end, { desc = 'Force activate PlatformIO' }) end, + config = function() + -- -- 3. Setup happens ONLY when the plugin is loaded + -- require("platformio").setup({ + -- lspClangd = { + -- enabled = true, + -- attach = { + -- enabled = true, + -- keymaps = true, + -- }, + -- }, + -- }) + local pioConfig = { + lspClangd = { + -- enabled = false, + enabled = true, + attach = { + enabled = true, + keymaps = true, + }, + }, + -- menu_key = "\\", -- replace this menu key to your convenience + -- menu_name = "PlatformIO", -- replace this menu name to your convenience + -- debug = false, + } + local pok, platformio = pcall(require, 'platformio') + if pok then + -- print("here" .. vim.inspect(pioConfig)) + platformio.setup(pioConfig) + end + end, -- cond = function() -- -- Check if platformio.ini exists in the current directory -- local pio_exists = vim.fn.filereadable('platformio.ini') == 1 @@ -659,21 +689,21 @@ if tok then end -- Keymap to open the buffer list vim.keymap.set('n', 'fb', 'Telescope buffers', { desc = 'Find Buffers' }) -local pioConfig = { - lspClangd = { - -- enabled = false, - enabled = true, - attach = { - enabled = true, - keymaps = true, - }, - }, - -- menu_key = "\\", -- replace this menu key to your convenience - -- menu_name = "PlatformIO", -- replace this menu name to your convenience - -- debug = false, -} -local pok, platformio = pcall(require, 'platformio') -if pok then - -- print("here" .. vim.inspect(pioConfig)) - platformio.setup(pioConfig) -end +-- local pioConfig = { +-- lspClangd = { +-- -- enabled = false, +-- enabled = true, +-- attach = { +-- enabled = true, +-- keymaps = true, +-- }, +-- }, +-- -- menu_key = "\\", -- replace this menu key to your convenience +-- -- menu_name = "PlatformIO", -- replace this menu name to your convenience +-- -- debug = false, +-- } +-- local pok, platformio = pcall(require, 'platformio') +-- if pok then +-- -- print("here" .. vim.inspect(pioConfig)) +-- platformio.setup(pioConfig) +-- end From 499e83287c8fffcb26fe6bd10f5e20332aa7bd1d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 14:06:03 +0300 Subject: [PATCH 1022/1406] update --- mini_nvimPlatformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 8ca7af62..7c1aebcf 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -282,7 +282,7 @@ local plugins = { visible = false, -- Change to true if you want to see them dimmed hide_dotfiles = true, hide_gitignored = true, - hide_by_name = { '^\\.cache$', '^\\.pio$' }, + hide_by_name = { '.cache', '.pio' }, never_show = { -- This is the strongest setting to ignore the folder '.cache', '.git', From 568111579b731414227e3602480a8d9635fe1f8e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 14:07:28 +0300 Subject: [PATCH 1023/1406] update --- mini_nvimPlatformio.lua | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 7c1aebcf..a20e4991 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -278,17 +278,17 @@ local plugins = { 'git_status', 'document_symbols', -- Add this line }, - filtered_items = { - visible = false, -- Change to true if you want to see them dimmed - hide_dotfiles = true, - hide_gitignored = true, - hide_by_name = { '.cache', '.pio' }, - never_show = { -- This is the strongest setting to ignore the folder - '.cache', - '.git', - 'node_modules', - }, - }, + -- filtered_items = { + -- visible = false, -- Change to true if you want to see them dimmed + -- hide_dotfiles = true, + -- hide_gitignored = true, + -- hide_by_name = { '.cache', '.pio' }, + -- never_show = { -- This is the strongest setting to ignore the folder + -- '.cache', + -- '.git', + -- 'node_modules', + -- }, + -- }, }, }, From 7b2787576e95398f1c1f73117c8d69d8333f16ac Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 14:16:52 +0300 Subject: [PATCH 1024/1406] update --- mini_nvimPlatformio.lua | 118 ++++++++++++++++++++++++++++++++-------- 1 file changed, 95 insertions(+), 23 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index a20e4991..ba266760 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -263,33 +263,105 @@ local plugins = { { 'nvim-neo-tree/neo-tree.nvim', - branch = 'v3.x', - dependencies = { - 'nvim-lua/plenary.nvim', - 'MunifTanjim/nui.nvim', - 'nvim-tree/nvim-web-devicons', -- optional, but recommended + cmd = 'Neotree', + keys = { + { + '\\', + function() + require('neo-tree.command').execute({ toggle = true, dir = vim.uv.cwd() }) + end, + desc = 'Explorer NeoTree (cwd)', + }, + { 'e', 'fe', desc = 'Explorer NeoTree (Root Dir)', remap = true }, + { 'E', 'fE', desc = 'Explorer NeoTree (cwd)', remap = true }, + { + 'ge', + function() + require('neo-tree.command').execute({ source = 'git_status', toggle = true }) + end, + desc = 'Git Explorer', + }, + { + 'be', + function() + require('neo-tree.command').execute({ source = 'buffers', toggle = true }) + end, + desc = 'Buffer Explorer', + }, }, - lazy = false, -- neo-tree will lazily load itself opts = { - use_libuv_file_watcher = true, - sources = { - 'filesystem', - 'buffers', - 'git_status', - 'document_symbols', -- Add this line + sources = { 'filesystem', 'buffers', 'git_status' }, + open_files_do_not_replace_types = { 'terminal', 'Trouble', 'trouble', 'qf', 'Outline' }, + filesystem = { + bind_to_cwd = false, + follow_current_file = { enabled = true }, + use_libuv_file_watcher = true, + }, + window = { + mappings = { + ['l'] = 'open', + ['h'] = 'close_node', + [''] = 'none', + ['Y'] = { + function(state) + local node = state.tree:get_node() + local path = node:get_id() + vim.fn.setreg('+', path, 'c') + end, + desc = 'Copy Path to Clipboard', + }, + ['O'] = { + function(state) + require('lazy.util').open(state.tree:get_node().path, { system = true }) + end, + desc = 'Open with System Application', + }, + ['P'] = { 'toggle_preview', config = { use_float = false } }, + }, + }, + default_component_configs = { + indent = { + with_expanders = true, -- if nil and file nesting is enabled, will enable expanders + expander_collapsed = '', + expander_expanded = '', + expander_highlight = 'NeoTreeExpander', + }, + git_status = { + symbols = { + unstaged = '󰄱', + staged = '󰱒', + }, + }, }, - -- filtered_items = { - -- visible = false, -- Change to true if you want to see them dimmed - -- hide_dotfiles = true, - -- hide_gitignored = true, - -- hide_by_name = { '.cache', '.pio' }, - -- never_show = { -- This is the strongest setting to ignore the folder - -- '.cache', - -- '.git', - -- 'node_modules', - -- }, - -- }, }, + -- 'nvim-neo-tree/neo-tree.nvim', + -- branch = 'v3.x', + -- dependencies = { + -- 'nvim-lua/plenary.nvim', + -- 'MunifTanjim/nui.nvim', + -- 'nvim-tree/nvim-web-devicons', -- optional, but recommended + -- }, + -- lazy = false, -- neo-tree will lazily load itself + -- opts = { + -- use_libuv_file_watcher = true, + -- sources = { + -- 'filesystem', + -- 'buffers', + -- 'git_status', + -- 'document_symbols', -- Add this line + -- }, + -- -- filtered_items = { + -- -- visible = false, -- Change to true if you want to see them dimmed + -- -- hide_dotfiles = true, + -- -- hide_gitignored = true, + -- -- hide_by_name = { '.cache', '.pio' }, + -- -- never_show = { -- This is the strongest setting to ignore the folder + -- -- '.cache', + -- -- '.git', + -- -- 'node_modules', + -- -- }, + -- -- }, + -- }, }, -- { From db61a079c2c660efe4395986b5d20c4a111534ac Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 14:30:52 +0300 Subject: [PATCH 1025/1406] update --- lua/platformio/{lsp => lspConfig}/attach.lua | 2 +- lua/platformio/{lsp => lspConfig}/clangd.lua | 2 +- lua/platformio/{lsp => lspConfig}/keymaps.lua | 0 lua/platformio/{lsp => lspConfig}/tools.lua | 0 lua/platformio/metadata.lua | 2 +- lua/platformio/pioCommands.lua | 2 +- lua/platformio/pio_setup.lua | 6 +++--- lua/platformio/utils/pio.lua | 2 +- lua/platformio/utils/pio2.lua | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) rename lua/platformio/{lsp => lspConfig}/attach.lua (96%) rename lua/platformio/{lsp => lspConfig}/clangd.lua (96%) rename lua/platformio/{lsp => lspConfig}/keymaps.lua (100%) rename lua/platformio/{lsp => lspConfig}/tools.lua (100%) diff --git a/lua/platformio/lsp/attach.lua b/lua/platformio/lspConfig/attach.lua similarity index 96% rename from lua/platformio/lsp/attach.lua rename to lua/platformio/lspConfig/attach.lua index 9b4d4c51..3d3bfe5d 100644 --- a/lua/platformio/lsp/attach.lua +++ b/lua/platformio/lspConfig/attach.lua @@ -91,7 +91,7 @@ vim.api.nvim_create_autocmd('LspAttach', { ------------------------------------------------------------------ local config = require('platformio').config if config.lspClangd.attach.keymaps then - local lspkeymaps = require('platformio.lsp.keymaps') + local lspkeymaps = require('platformio.lspConfig.keymaps') lspkeymaps.lspKeymaps(client, bufnr) end end diff --git a/lua/platformio/lsp/clangd.lua b/lua/platformio/lspConfig/clangd.lua similarity index 96% rename from lua/platformio/lsp/clangd.lua rename to lua/platformio/lspConfig/clangd.lua index 874ffa70..4f2ff715 100644 --- a/lua/platformio/lsp/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -267,5 +267,5 @@ local pyrefly = { vim.lsp.config('pyrefly', pyrefly) -- restart lsp --- require('platformio.lsp.tools').lsp_restart('clangd') +-- require('platformio.lspConfig.tools').lsp_restart('clangd') ---------------------------------------------------------------------------------- diff --git a/lua/platformio/lsp/keymaps.lua b/lua/platformio/lspConfig/keymaps.lua similarity index 100% rename from lua/platformio/lsp/keymaps.lua rename to lua/platformio/lspConfig/keymaps.lua diff --git a/lua/platformio/lsp/tools.lua b/lua/platformio/lspConfig/tools.lua similarity index 100% rename from lua/platformio/lsp/tools.lua rename to lua/platformio/lspConfig/tools.lua diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index a194a4f7..b23aecf0 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -58,7 +58,7 @@ _G.metadata = setmetatable({}, { -- -- dbFix() -- _pio_metadata.dbTrigger = false -- else - -- local LspRestart = require('platformio.lsp.tools').lsp_restart + -- local LspRestart = require('platformio.lspConfigConfig.tools').lsp_restart -- LspRestart('clangd') -- vim.notify('Env: LspRestart', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) -- end diff --git a/lua/platformio/pioCommands.lua b/lua/platformio/pioCommands.lua index 61d939b6..a24a5036 100644 --- a/lua/platformio/pioCommands.lua +++ b/lua/platformio/pioCommands.lua @@ -5,7 +5,7 @@ local ToggleTerminal = require('platformio.utils.term').ToggleTerminal -- stylua: ignore function M.piolsp() - require('platformio.lsp.tools').lsp_restart('clangd') + require('platformio.lspConfig.tools').lsp_restart('clangd') end function M.piocmd(cmd_table, direction) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index d1e8a7f8..ab916e8e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,6 +1,6 @@ M = {} --- local lsp_restart = require('platformio.lsp.tools').lsp_restart +-- local lsp_restart = require('platformio.lspConfig.tools').lsp_restart local boilerplate = require('platformio.boilerplate') local boilerplate_gen = boilerplate.boilerplate_gen @@ -474,9 +474,9 @@ function M.init() local metadata = require('platformio.metadata') metadata.load_project_config() - require('platformio.lsp.clangd') + require('platformio.lspConfig.clangd') if config.lspClangd.attach.enabled then - require('platformio.lsp.attach') + require('platformio.lspConfig.attach') end -- Always start the watcher so it can catch a future 'pio init' diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 71fb7cd6..33ede1ab 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -10,7 +10,7 @@ M.is_processing = false M.queue = {} local term = require('platformio.utils.term') -local lsp_restart = require('platformio.lsp.tools').lsp_restart +local lsp_restart = require('platformio.lspConfig.tools').lsp_restart -- INFO: -- ============================================================================= diff --git a/lua/platformio/utils/pio2.lua b/lua/platformio/utils/pio2.lua index 45cbf30b..81af31aa 100644 --- a/lua/platformio/utils/pio2.lua +++ b/lua/platformio/utils/pio2.lua @@ -3,7 +3,7 @@ local M = {} M.selected_framework = '' local misc = require('platformio.utils.misc') -local lsp_restart = require('platformio.lsp.tools').lsp_restart +local lsp_restart = require('platformio.lspConfig.tools').lsp_restart local term = require('platformio.utils.term') -- term.on_stdout_handler = nil From 0069b5e95bf89e1f03b72b5f1a1fc43daa08f429 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 14:49:33 +0300 Subject: [PATCH 1026/1406] update --- lua/platformio/lspConfig/clangd.lua | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 4f2ff715..51f4e18a 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -74,7 +74,9 @@ if mok then }) end -local capabilities = vim.lsp.protocol.make_client_capabilities({ +local capabilities = vim.lsp.protocol.make_client_capabilities() + +capabilities.textDocument.foldingRange = { textDocument = { -- Folding capabilities for nvim-ufo foldingRange = { @@ -82,7 +84,7 @@ local capabilities = vim.lsp.protocol.make_client_capabilities({ lineFoldingOnly = true, }, }, -}) +} local bok, blink = pcall(require, 'blink.cmp') if bok then capabilities = blink.get_lsp_capabilities(capabilities) From 96840e2a81753b90f6731621fc7e90b98e74a64e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 14:59:41 +0300 Subject: [PATCH 1027/1406] update --- mini_nvimPlatformio.lua | 135 ++++++++++++++++++++++++---------------- 1 file changed, 82 insertions(+), 53 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index ba266760..f7fc1eb5 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -389,54 +389,103 @@ local plugins = { { 'batoaqaa/nvim-platformio.lua', + dependencies = { + { 'akinsho/toggleterm.nvim' }, + { 'nvim-telescope/telescope.nvim' }, + -- { + -- 'nvim-telescope/telescope.nvim', + -- tag = '0.1.8', + -- dependencies = { 'nvim-lua/plenary.nvim' }, + -- }, + { 'nvim-telescope/telescope-ui-select.nvim' }, + { 'nvim-lua/plenary.nvim' }, + { 'folke/which-key.nvim' }, + { + 'mason-org/mason-lspconfig.nvim', + dependencies = { + { 'mason-org/mason.nvim' }, + { 'folke/trouble.nvim' }, + { 'j-hui/fidget.nvim' }, -- status bottom right + }, + }, + }, + -- This is the "magic" line. + -- If it returns false, the plugin won't load on startup. + cond = function() + return vim.fn.filereadable('platformio.ini') == 1 + end, - init = function() - -- 1. Automatic check: Load if file exists - if vim.fn.filereadable('platformio.ini') == 1 then - require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) - vim.g.platformioRootDir = vim.uv.cwd() - else - vim.g.platformioRootDir = nil - end + -- This allows you to MANUALLY load it via :Pioinit even if platformio.ini is missing + -- Lazy.nvim allows 'cmd' to override 'cond' in most versions + cmd = { 'Pio', 'Pioinit' }, - -- 2. Manual Force: Create a command that overrides the check + init = function() + -- Create the manual force command vim.api.nvim_create_user_command('Pioinit', function() + -- We bypass the cond by explicitly loading require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) vim.schedule(function() - vim.cmd('Pio') -- Trigger the plugin's internal menu + vim.cmd('Pio') end) end, { desc = 'Force activate PlatformIO' }) end, + config = function() - -- -- 3. Setup happens ONLY when the plugin is loaded - -- require("platformio").setup({ - -- lspClangd = { - -- enabled = true, - -- attach = { - -- enabled = true, - -- keymaps = true, - -- }, - -- }, - -- }) local pioConfig = { lspClangd = { - -- enabled = false, enabled = true, - attach = { - enabled = true, - keymaps = true, - }, + attach = { enabled = true, keymaps = true }, }, - -- menu_key = "\\", -- replace this menu key to your convenience - -- menu_name = "PlatformIO", -- replace this menu name to your convenience - -- debug = false, } - local pok, platformio = pcall(require, 'platformio') - if pok then - -- print("here" .. vim.inspect(pioConfig)) - platformio.setup(pioConfig) - end + require('platformio').setup(pioConfig) end, + -- init = function() + -- -- 1. Automatic check: Load if file exists + -- if vim.fn.filereadable('platformio.ini') == 1 then + -- require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) + -- vim.g.platformioRootDir = vim.uv.cwd() + -- else + -- vim.g.platformioRootDir = nil + -- end + -- + -- -- 2. Manual Force: Create a command that overrides the check + -- vim.api.nvim_create_user_command('Pioinit', function() + -- require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) + -- vim.schedule(function() + -- vim.cmd('Pio') -- Trigger the plugin's internal menu + -- end) + -- end, { desc = 'Force activate PlatformIO' }) + -- end, + -- config = function() + -- -- -- 3. Setup happens ONLY when the plugin is loaded + -- -- require("platformio").setup({ + -- -- lspClangd = { + -- -- enabled = true, + -- -- attach = { + -- -- enabled = true, + -- -- keymaps = true, + -- -- }, + -- -- }, + -- -- }) + -- local pioConfig = { + -- lspClangd = { + -- -- enabled = false, + -- enabled = true, + -- attach = { + -- enabled = true, + -- keymaps = true, + -- }, + -- }, + -- -- menu_key = "\\", -- replace this menu key to your convenience + -- -- menu_name = "PlatformIO", -- replace this menu name to your convenience + -- -- debug = false, + -- } + -- local pok, platformio = pcall(require, 'platformio') + -- if pok then + -- -- print("here" .. vim.inspect(pioConfig)) + -- platformio.setup(pioConfig) + -- end + -- end, -- cond = function() -- -- Check if platformio.ini exists in the current directory -- local pio_exists = vim.fn.filereadable('platformio.ini') == 1 @@ -526,26 +575,6 @@ local plugins = { -- end -- return vim.g.platformioRootDir ~= nil -- end, - dependencies = { - { 'akinsho/toggleterm.nvim' }, - { 'nvim-telescope/telescope.nvim' }, - -- { - -- 'nvim-telescope/telescope.nvim', - -- tag = '0.1.8', - -- dependencies = { 'nvim-lua/plenary.nvim' }, - -- }, - { 'nvim-telescope/telescope-ui-select.nvim' }, - { 'nvim-lua/plenary.nvim' }, - { 'folke/which-key.nvim' }, - { - 'mason-org/mason-lspconfig.nvim', - dependencies = { - { 'mason-org/mason.nvim' }, - { 'folke/trouble.nvim' }, - { 'j-hui/fidget.nvim' }, -- status bottom right - }, - }, - }, }, } ---------------------------------------------------------------------------------------- From 4b749dbbe9b471908a514580602a6f9bc66a15cc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 15:03:25 +0300 Subject: [PATCH 1028/1406] update --- mini_nvimPlatformio.lua | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index f7fc1eb5..6eea4a9d 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -409,35 +409,35 @@ local plugins = { }, }, }, - -- This is the "magic" line. - -- If it returns false, the plugin won't load on startup. - cond = function() - return vim.fn.filereadable('platformio.ini') == 1 - end, - -- This allows you to MANUALLY load it via :Pioinit even if platformio.ini is missing - -- Lazy.nvim allows 'cmd' to override 'cond' in most versions + lazy = true, + + -- 2. Define commands that should trigger the load cmd = { 'Pio', 'Pioinit' }, init = function() - -- Create the manual force command + -- 3. Automatic Check: Runs on startup + if vim.fn.filereadable('platformio.ini') == 1 then + require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) + end + + -- 4. Manual Force: This command is now always registered vim.api.nvim_create_user_command('Pioinit', function() - -- We bypass the cond by explicitly loading require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) vim.schedule(function() - vim.cmd('Pio') + vim.cmd('Pio') -- Automatically opens the menu after force-loading end) end, { desc = 'Force activate PlatformIO' }) end, config = function() - local pioConfig = { + -- 5. Standard plugin configuration + require('platformio').setup({ lspClangd = { enabled = true, attach = { enabled = true, keymaps = true }, }, - } - require('platformio').setup(pioConfig) + }) end, -- init = function() -- -- 1. Automatic check: Load if file exists From 91ed6b1cd844266437f59ef5923d00e6a8af382d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 15:08:25 +0300 Subject: [PATCH 1029/1406] update --- mini_nvimPlatformio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 6eea4a9d..39ab1971 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -413,7 +413,7 @@ local plugins = { lazy = true, -- 2. Define commands that should trigger the load - cmd = { 'Pio', 'Pioinit' }, + cmd = { 'Pioinit' }, init = function() -- 3. Automatic Check: Runs on startup @@ -425,7 +425,7 @@ local plugins = { vim.api.nvim_create_user_command('Pioinit', function() require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) vim.schedule(function() - vim.cmd('Pio') -- Automatically opens the menu after force-loading + vim.cmd('Pioinit') -- Automatically opens the menu after force-loading end) end, { desc = 'Force activate PlatformIO' }) end, From bc6ecd72da16866b1687904f15a67790bca6601b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 15:20:23 +0300 Subject: [PATCH 1030/1406] update --- mini_nvimPlatformio.lua | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 39ab1971..ac9e8378 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -423,10 +423,19 @@ local plugins = { -- 4. Manual Force: This command is now always registered vim.api.nvim_create_user_command('Pioinit', function() + vim.api.nvim_create_autocmd('User', { + pattern = { 'LazyLoad' }, + once = true, + callback = function(args) + if args.match == 'LazyLoad' then + vim.notify('PlatformIO loaded', vim.log.levels.INFO, { title = 'PlatformIO' }) + vim.cmd('Pioinit') + end + end, + }) + vim.g.platformioRootDir = vim.uv.cwd() require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) - vim.schedule(function() - vim.cmd('Pioinit') -- Automatically opens the menu after force-loading - end) + -- end) end, { desc = 'Force activate PlatformIO' }) end, From 8c90055d2fc2135f3694d03a80e9584461ffa086 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 15:23:34 +0300 Subject: [PATCH 1031/1406] update --- mini_nvimPlatformio.lua | 202 ++++++---------------------------------- 1 file changed, 29 insertions(+), 173 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index ac9e8378..25c7671c 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -409,181 +409,37 @@ local plugins = { }, }, }, - - lazy = true, - - -- 2. Define commands that should trigger the load - cmd = { 'Pioinit' }, - - init = function() - -- 3. Automatic Check: Runs on startup - if vim.fn.filereadable('platformio.ini') == 1 then - require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) - end - - -- 4. Manual Force: This command is now always registered - vim.api.nvim_create_user_command('Pioinit', function() - vim.api.nvim_create_autocmd('User', { - pattern = { 'LazyLoad' }, - once = true, - callback = function(args) - if args.match == 'LazyLoad' then - vim.notify('PlatformIO loaded', vim.log.levels.INFO, { title = 'PlatformIO' }) - vim.cmd('Pioinit') - end - end, - }) + cond = function() + -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.fn.getcwd() or nil + local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.uv.cwd() or nil + if platformioRootDir and vim.fs.find('.pio', { path = platformioRootDir, type = 'directory' })[1] then + -- if platformio.ini file and .pio folder exist in cwd, enable plugin to install plugin (if not istalled) and load it. + vim.g.platformioRootDir = platformioRootDir + elseif (vim.uv or vim.loop).fs_stat(vim.env.XDG_DATA_HOME .. '/lazy/nvim-platformio.lua') == nil then + -- if nvim-platformio not installed, enable plugin to install it first time + -- vim.g.platformioRootDir = vim.fn.getcwd() vim.g.platformioRootDir = vim.uv.cwd() - require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) - -- end) - end, { desc = 'Force activate PlatformIO' }) - end, - - config = function() - -- 5. Standard plugin configuration - require('platformio').setup({ - lspClangd = { - enabled = true, - attach = { enabled = true, keymaps = true }, - }, - }) + else -- if nvim-platformio.lua installed but disabled, create Pioinit command + vim.api.nvim_create_user_command('Pioinit', function() --available only if no platformio.ini and .pio in cwd + vim.api.nvim_create_autocmd('User', { + pattern = { 'LazyRestore', 'LazyLoad' }, + once = true, + callback = function(args) + if args.match == 'LazyRestore' then + require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) + elseif args.match == 'LazyLoad' then + vim.notify('PlatformIO loaded', vim.log.levels.INFO, { title = 'PlatformIO' }) + vim.cmd('Pioinit') + end + end, + }) + -- vim.g.platformioRootDir = vim.fn.getcwd() + vim.g.platformioRootDir = vim.uv.cwd() + require('lazy').restore({ plguins = { 'nvim-platformio.lua' }, show = false }) + end, {}) + end + return vim.g.platformioRootDir ~= nil end, - -- init = function() - -- -- 1. Automatic check: Load if file exists - -- if vim.fn.filereadable('platformio.ini') == 1 then - -- require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) - -- vim.g.platformioRootDir = vim.uv.cwd() - -- else - -- vim.g.platformioRootDir = nil - -- end - -- - -- -- 2. Manual Force: Create a command that overrides the check - -- vim.api.nvim_create_user_command('Pioinit', function() - -- require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) - -- vim.schedule(function() - -- vim.cmd('Pio') -- Trigger the plugin's internal menu - -- end) - -- end, { desc = 'Force activate PlatformIO' }) - -- end, - -- config = function() - -- -- -- 3. Setup happens ONLY when the plugin is loaded - -- -- require("platformio").setup({ - -- -- lspClangd = { - -- -- enabled = true, - -- -- attach = { - -- -- enabled = true, - -- -- keymaps = true, - -- -- }, - -- -- }, - -- -- }) - -- local pioConfig = { - -- lspClangd = { - -- -- enabled = false, - -- enabled = true, - -- attach = { - -- enabled = true, - -- keymaps = true, - -- }, - -- }, - -- -- menu_key = "\\", -- replace this menu key to your convenience - -- -- menu_name = "PlatformIO", -- replace this menu name to your convenience - -- -- debug = false, - -- } - -- local pok, platformio = pcall(require, 'platformio') - -- if pok then - -- -- print("here" .. vim.inspect(pioConfig)) - -- platformio.setup(pioConfig) - -- end - -- end, - -- cond = function() - -- -- Check if platformio.ini exists in the current directory - -- local pio_exists = vim.fn.filereadable('platformio.ini') == 1 - -- if pio_exists then - -- return true - -- end - -- - -- -- Create command to load AND open the plugin menu - -- vim.api.nvim_create_user_command('Pioinit', function() - -- -- 1. Force lazy.nvim to load the plugin - -- require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) - -- - -- -- 2. Issue the main command to the plugin (opens the Telescope menu) - -- -- Use pcall to ensure it doesn't error if setup takes a millisecond to register - -- vim.schedule(function() - -- vim.cmd('Pio') - -- vim.notify('PlatformIO Activated and Menu Opened') - -- end) - -- end, { desc = 'Force load and open PlatformIO' }) - -- - -- return false - -- -- If not found, create the :Pioinit command to force load the plugin - -- -- vim.api.nvim_create_user_command('Pioinit', function() - -- -- require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) - -- -- vim.notify('nvim-platformio.lua forced activation') - -- -- end, { desc = 'Force activate PlatformIO plugin' }) - -- -- - -- -- return false - -- end, - -- cond = function() - -- -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.fn.getcwd() or nil - -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.uv.cwd() or nil - -- -- if platformioRootDir and vim.fs.find('.pio', { path = platformioRootDir, type = 'directory' })[1] then - -- vim.g.platformioRootDir = nil - -- if platformioRootDir then - -- -- if platformio.ini file and .pio folder exist in cwd, enable plugin to install plugin (if not istalled) and load it. - -- vim.g.platformioRootDir = platformioRootDir - -- else -- if nvim-platformio.lua installed but disabled, create Pioinit command - -- vim.api.nvim_create_user_command('Pioinit', function() --available only if no platformio.ini and .pio in cwd - -- vim.api.nvim_create_autocmd('User', { - -- pattern = { 'LazyRestore', 'LazyLoad' }, - -- once = true, - -- callback = function(args) - -- if args.match == 'LazyRestore' then - -- require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) - -- elseif args.match == 'LazyLoad' then - -- vim.notify('PlatformIO loaded', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- vim.cmd('Pioinit') - -- end - -- end, - -- }) - -- -- vim.g.platformioRootDir = vim.fn.getcwd() - -- vim.g.platformioRootDir = vim.uv.cwd() - -- require('lazy').restore({ plguins = { 'nvim-platformio.lua' }, show = false }) - -- end, {}) - -- end - -- return vim.g.platformioRootDir ~= nil - -- end, - -- cond = function() - -- -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.fn.getcwd() or nil - -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.uv.cwd() or nil - -- if platformioRootDir and vim.fs.find('.pio', { path = platformioRootDir, type = 'directory' })[1] then - -- -- if platformio.ini file and .pio folder exist in cwd, enable plugin to install plugin (if not istalled) and load it. - -- vim.g.platformioRootDir = platformioRootDir - -- elseif (vim.uv or vim.loop).fs_stat(vim.env.XDG_DATA_HOME .. '/lazy/nvim-platformio.lua') == nil then - -- -- if nvim-platformio not installed, enable plugin to install it first time - -- -- vim.g.platformioRootDir = vim.fn.getcwd() - -- vim.g.platformioRootDir = vim.uv.cwd() - -- else -- if nvim-platformio.lua installed but disabled, create Pioinit command - -- vim.api.nvim_create_user_command('Pioinit', function() --available only if no platformio.ini and .pio in cwd - -- vim.api.nvim_create_autocmd('User', { - -- pattern = { 'LazyRestore', 'LazyLoad' }, - -- once = true, - -- callback = function(args) - -- if args.match == 'LazyRestore' then - -- require('lazy').load({ plugins = { 'nvim-platformio.lua' } }) - -- elseif args.match == 'LazyLoad' then - -- vim.notify('PlatformIO loaded', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- vim.cmd('Pioinit') - -- end - -- end, - -- }) - -- -- vim.g.platformioRootDir = vim.fn.getcwd() - -- vim.g.platformioRootDir = vim.uv.cwd() - -- require('lazy').restore({ plguins = { 'nvim-platformio.lua' }, show = false }) - -- end, {}) - -- end - -- return vim.g.platformioRootDir ~= nil - -- end, }, } ---------------------------------------------------------------------------------------- From fc59a3ee638d7af247fb278c1d9265484b28d99d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 15:50:57 +0300 Subject: [PATCH 1032/1406] update --- mini_nvimPlatformio.lua | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 25c7671c..79fc2b95 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -433,8 +433,7 @@ local plugins = { end end, }) - -- vim.g.platformioRootDir = vim.fn.getcwd() - vim.g.platformioRootDir = vim.uv.cwd() + -- vim.g.platformioRootDir = vim.uv.cwd() require('lazy').restore({ plguins = { 'nvim-platformio.lua' }, show = false }) end, {}) end From 9ad751c4a0cf0d7d0f37fbe90aeb3fc95f295c85 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 15:56:46 +0300 Subject: [PATCH 1033/1406] update --- mini_nvimPlatformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 79fc2b95..0ee59cb2 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -193,7 +193,7 @@ local plugins = { opts = { keymap = { preset = 'default' }, -- 'default', 'super-tab', or 'enter' sources = { - default = { 'lsp', 'path', 'snippets', 'buffer' }, + default = { 'path', 'snippets', 'buffer' }, }, }, }, From c1e1ac75c87c24818ee323223cebaeaaa381b736 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 15:59:31 +0300 Subject: [PATCH 1034/1406] update --- mini_nvimPlatformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 0ee59cb2..e64b08f4 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -266,7 +266,7 @@ local plugins = { cmd = 'Neotree', keys = { { - '\\', + '\\', function() require('neo-tree.command').execute({ toggle = true, dir = vim.uv.cwd() }) end, From b25693da84f2429550d2cb3ce4719d28e2cf3b65 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 16:03:36 +0300 Subject: [PATCH 1035/1406] update --- mini_nvimPlatformio.lua | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index e64b08f4..06ea534d 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -263,7 +263,9 @@ local plugins = { { 'nvim-neo-tree/neo-tree.nvim', - cmd = 'Neotree', + -- cmd = 'Neotree', + lazy = false, + dependencies = 'nvim-tree/nvim-web-devicons', keys = { { '\\', From c3e0b913b80f6a1d24a7ad38658115ab2c5f67b1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 16:08:56 +0300 Subject: [PATCH 1036/1406] update --- mini_nvimPlatformio.lua | 188 +++++++++++++++++++++------------------- 1 file changed, 97 insertions(+), 91 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 06ea534d..fab1779c 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -262,108 +262,114 @@ local plugins = { }, { + -- 'nvim-neo-tree/neo-tree.nvim', + -- -- cmd = 'Neotree', + -- lazy = false, + -- dependencies = 'nvim-tree/nvim-web-devicons', + -- keys = { + -- { + -- '\\', + -- function() + -- require('neo-tree.command').execute({ toggle = true, dir = vim.uv.cwd() }) + -- end, + -- desc = 'Explorer NeoTree (cwd)', + -- }, + -- { 'e', 'fe', desc = 'Explorer NeoTree (Root Dir)', remap = true }, + -- { 'E', 'fE', desc = 'Explorer NeoTree (cwd)', remap = true }, + -- { + -- 'ge', + -- function() + -- require('neo-tree.command').execute({ source = 'git_status', toggle = true }) + -- end, + -- desc = 'Git Explorer', + -- }, + -- { + -- 'be', + -- function() + -- require('neo-tree.command').execute({ source = 'buffers', toggle = true }) + -- end, + -- desc = 'Buffer Explorer', + -- }, + -- }, + -- opts = { + -- sources = { 'filesystem', 'buffers', 'git_status' }, + -- open_files_do_not_replace_types = { 'terminal', 'Trouble', 'trouble', 'qf', 'Outline' }, + -- filesystem = { + -- bind_to_cwd = false, + -- follow_current_file = { enabled = true }, + -- use_libuv_file_watcher = true, + -- }, + -- window = { + -- mappings = { + -- ['l'] = 'open', + -- ['h'] = 'close_node', + -- [''] = 'none', + -- ['Y'] = { + -- function(state) + -- local node = state.tree:get_node() + -- local path = node:get_id() + -- vim.fn.setreg('+', path, 'c') + -- end, + -- desc = 'Copy Path to Clipboard', + -- }, + -- ['O'] = { + -- function(state) + -- require('lazy.util').open(state.tree:get_node().path, { system = true }) + -- end, + -- desc = 'Open with System Application', + -- }, + -- ['P'] = { 'toggle_preview', config = { use_float = false } }, + -- }, + -- }, + -- default_component_configs = { + -- indent = { + -- with_expanders = true, -- if nil and file nesting is enabled, will enable expanders + -- expander_collapsed = '', + -- expander_expanded = '', + -- expander_highlight = 'NeoTreeExpander', + -- }, + -- git_status = { + -- symbols = { + -- unstaged = '󰄱', + -- staged = '󰱒', + -- }, + -- }, + -- }, + -- }, 'nvim-neo-tree/neo-tree.nvim', - -- cmd = 'Neotree', - lazy = false, - dependencies = 'nvim-tree/nvim-web-devicons', - keys = { - { - '\\', - function() - require('neo-tree.command').execute({ toggle = true, dir = vim.uv.cwd() }) - end, - desc = 'Explorer NeoTree (cwd)', - }, - { 'e', 'fe', desc = 'Explorer NeoTree (Root Dir)', remap = true }, - { 'E', 'fE', desc = 'Explorer NeoTree (cwd)', remap = true }, - { - 'ge', - function() - require('neo-tree.command').execute({ source = 'git_status', toggle = true }) - end, - desc = 'Git Explorer', - }, - { - 'be', - function() - require('neo-tree.command').execute({ source = 'buffers', toggle = true }) - end, - desc = 'Buffer Explorer', - }, + branch = 'v3.x', + dependencies = { + 'nvim-lua/plenary.nvim', + 'MunifTanjim/nui.nvim', + 'nvim-tree/nvim-web-devicons', -- optional, but recommended }, + lazy = false, -- neo-tree will lazily load itself opts = { - sources = { 'filesystem', 'buffers', 'git_status' }, + -- use_libuv_file_watcher = true, open_files_do_not_replace_types = { 'terminal', 'Trouble', 'trouble', 'qf', 'Outline' }, filesystem = { bind_to_cwd = false, follow_current_file = { enabled = true }, use_libuv_file_watcher = true, }, - window = { - mappings = { - ['l'] = 'open', - ['h'] = 'close_node', - [''] = 'none', - ['Y'] = { - function(state) - local node = state.tree:get_node() - local path = node:get_id() - vim.fn.setreg('+', path, 'c') - end, - desc = 'Copy Path to Clipboard', - }, - ['O'] = { - function(state) - require('lazy.util').open(state.tree:get_node().path, { system = true }) - end, - desc = 'Open with System Application', - }, - ['P'] = { 'toggle_preview', config = { use_float = false } }, - }, - }, - default_component_configs = { - indent = { - with_expanders = true, -- if nil and file nesting is enabled, will enable expanders - expander_collapsed = '', - expander_expanded = '', - expander_highlight = 'NeoTreeExpander', - }, - git_status = { - symbols = { - unstaged = '󰄱', - staged = '󰱒', - }, - }, + sources = { + 'filesystem', + 'buffers', + 'git_status', + 'document_symbols', -- Add this line }, + -- filtered_items = { + -- visible = false, -- Change to true if you want to see them dimmed + -- hide_dotfiles = true, + -- hide_gitignored = true, + -- hide_by_name = { '.cache', '.pio' }, + -- never_show = { -- This is the strongest setting to ignore the folder + -- '.cache', + -- '.git', + -- 'node_modules', + -- }, + -- }, }, - -- 'nvim-neo-tree/neo-tree.nvim', - -- branch = 'v3.x', - -- dependencies = { - -- 'nvim-lua/plenary.nvim', - -- 'MunifTanjim/nui.nvim', - -- 'nvim-tree/nvim-web-devicons', -- optional, but recommended - -- }, - -- lazy = false, -- neo-tree will lazily load itself - -- opts = { - -- use_libuv_file_watcher = true, - -- sources = { - -- 'filesystem', - -- 'buffers', - -- 'git_status', - -- 'document_symbols', -- Add this line - -- }, - -- -- filtered_items = { - -- -- visible = false, -- Change to true if you want to see them dimmed - -- -- hide_dotfiles = true, - -- -- hide_gitignored = true, - -- -- hide_by_name = { '.cache', '.pio' }, - -- -- never_show = { -- This is the strongest setting to ignore the folder - -- -- '.cache', - -- -- '.git', - -- -- 'node_modules', - -- -- }, - -- -- }, - -- }, }, -- { From 93c7398ab614f04eeaa6b2de6461e1a150e53f70 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 16:27:41 +0300 Subject: [PATCH 1037/1406] update --- mini_nvimPlatformio.lua | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index fab1779c..be589ab8 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -662,21 +662,21 @@ if tok then end -- Keymap to open the buffer list vim.keymap.set('n', 'fb', 'Telescope buffers', { desc = 'Find Buffers' }) --- local pioConfig = { --- lspClangd = { --- -- enabled = false, --- enabled = true, --- attach = { --- enabled = true, --- keymaps = true, --- }, --- }, --- -- menu_key = "\\", -- replace this menu key to your convenience --- -- menu_name = "PlatformIO", -- replace this menu name to your convenience --- -- debug = false, --- } --- local pok, platformio = pcall(require, 'platformio') --- if pok then --- -- print("here" .. vim.inspect(pioConfig)) --- platformio.setup(pioConfig) --- end +local pioConfig = { + lspClangd = { + -- enabled = false, + enabled = true, + attach = { + enabled = true, + keymaps = true, + }, + }, + -- menu_key = "\\", -- replace this menu key to your convenience + -- menu_name = "PlatformIO", -- replace this menu name to your convenience + -- debug = false, +} +local pok, platformio = pcall(require, 'platformio') +if pok then + -- print("here" .. vim.inspect(pioConfig)) + platformio.setup(pioConfig) +end From 57749cccbdb4c62727398085bd90545fb1adebb1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 16:32:19 +0300 Subject: [PATCH 1038/1406] update --- mini_nvimPlatformio.lua | 112 ++++++++++++++++++++-------------------- 1 file changed, 56 insertions(+), 56 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index be589ab8..ce0daeec 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -336,64 +336,64 @@ local plugins = { -- }, -- }, -- }, - 'nvim-neo-tree/neo-tree.nvim', - branch = 'v3.x', - dependencies = { - 'nvim-lua/plenary.nvim', - 'MunifTanjim/nui.nvim', - 'nvim-tree/nvim-web-devicons', -- optional, but recommended - }, - lazy = false, -- neo-tree will lazily load itself - opts = { - -- use_libuv_file_watcher = true, - open_files_do_not_replace_types = { 'terminal', 'Trouble', 'trouble', 'qf', 'Outline' }, - filesystem = { - bind_to_cwd = false, - follow_current_file = { enabled = true }, - use_libuv_file_watcher = true, - }, - sources = { - 'filesystem', - 'buffers', - 'git_status', - 'document_symbols', -- Add this line - }, - -- filtered_items = { - -- visible = false, -- Change to true if you want to see them dimmed - -- hide_dotfiles = true, - -- hide_gitignored = true, - -- hide_by_name = { '.cache', '.pio' }, - -- never_show = { -- This is the strongest setting to ignore the folder - -- '.cache', - -- '.git', - -- 'node_modules', - -- }, - -- }, - }, + -- 'nvim-neo-tree/neo-tree.nvim', + -- branch = 'v3.x', + -- dependencies = { + -- 'nvim-lua/plenary.nvim', + -- 'MunifTanjim/nui.nvim', + -- 'nvim-tree/nvim-web-devicons', -- optional, but recommended + -- }, + -- lazy = false, -- neo-tree will lazily load itself + -- opts = { + -- -- use_libuv_file_watcher = true, + -- open_files_do_not_replace_types = { 'terminal', 'Trouble', 'trouble', 'qf', 'Outline' }, + -- filesystem = { + -- bind_to_cwd = false, + -- follow_current_file = { enabled = true }, + -- use_libuv_file_watcher = true, + -- }, + -- sources = { + -- 'filesystem', + -- 'buffers', + -- 'git_status', + -- 'document_symbols', -- Add this line + -- }, + -- filtered_items = { + -- visible = false, -- Change to true if you want to see them dimmed + -- hide_dotfiles = true, + -- hide_gitignored = true, + -- hide_by_name = { '.cache', '.pio' }, + -- never_show = { -- This is the strongest setting to ignore the folder + -- '.cache', + -- '.git', + -- 'node_modules', + -- }, + -- }, + -- }, }, - -- { - -- 'nvim-tree/nvim-tree.lua', - -- -- version = '*', - -- lazy = false, - -- dependencies = 'nvim-tree/nvim-web-devicons', - -- config = function() - -- require('nvim-tree').setup({ - -- filesystem_watchers = { - -- ignore_dirs = { - -- '/.cache', -- Ignores clangd's heavy index folder - -- '/.pio', -- Ignores pio heavy index folder - -- '/node_modules', -- Good practice for performance - -- '/.git', - -- }, - -- }, - -- -- Optional: If you also want to hide it from the tree view entirely - -- -- filters = { - -- -- custom = { '^\\.cache$', '^\\.pio$' }, - -- -- }, - -- }) - -- end, - -- }, + { + 'nvim-tree/nvim-tree.lua', + -- version = '*', + lazy = false, + dependencies = 'nvim-tree/nvim-web-devicons', + config = function() + require('nvim-tree').setup({ + filesystem_watchers = { + ignore_dirs = { + '/.cache', -- Ignores clangd's heavy index folder + '/.pio', -- Ignores pio heavy index folder + '/node_modules', -- Good practice for performance + '/.git', + }, + }, + -- Optional: If you also want to hide it from the tree view entirely + -- filters = { + -- custom = { '^\\.cache$', '^\\.pio$' }, + -- }, + }) + end, + }, { 'batoaqaa/nvim-platformio.lua', From bcc0ddfb5ae16bdb032eb8e217951cb1de0e48e3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 16:33:50 +0300 Subject: [PATCH 1039/1406] update --- mini_nvimPlatformio.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index ce0daeec..ad76200a 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -146,10 +146,10 @@ end, { desc = '[D]elete Buffer' }) -- keymap('n', '[B', 'BufferLineMovePrev', { desc = 'Move buffer prev' }) -- keymap('n', ']B', 'BufferLineMoveNext', { desc = 'Move buffer next' }) -keymap('n', 'e', 'Neotree document_symbols', { desc = 'NeoTreeToggle' }) -keymap('n', '\\', 'Neotree toggle', { desc = 'NeoTreeToggle' }) --- keymap('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) --- keymap('n', '\\', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) +-- keymap('n', 'e', 'Neotree document_symbols', { desc = 'NeoTreeToggle' }) +-- keymap('n', '\\', 'Neotree toggle', { desc = 'NeoTreeToggle' }) +keymap('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) +keymap('n', '\\', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) -- Keybinds to make split navigation easier. -- Use CTRL+ to switch between windows From 93dcc6f0df6e59b916d78f8ef2569706057fbe10 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 16:50:15 +0300 Subject: [PATCH 1040/1406] update --- mini_nvimPlatformio.lua | 172 +++++++++------------------------------- 1 file changed, 36 insertions(+), 136 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index ad76200a..d49c4a17 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -146,10 +146,10 @@ end, { desc = '[D]elete Buffer' }) -- keymap('n', '[B', 'BufferLineMovePrev', { desc = 'Move buffer prev' }) -- keymap('n', ']B', 'BufferLineMoveNext', { desc = 'Move buffer next' }) --- keymap('n', 'e', 'Neotree document_symbols', { desc = 'NeoTreeToggle' }) --- keymap('n', '\\', 'Neotree toggle', { desc = 'NeoTreeToggle' }) -keymap('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) -keymap('n', '\\', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) +keymap('n', 'e', 'Neotree document_symbols', { desc = 'NeoTreeToggle' }) +keymap('n', '\\', 'Neotree toggle', { desc = 'NeoTreeToggle' }) +-- keymap('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) +-- keymap('n', '\\', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) -- Keybinds to make split navigation easier. -- Use CTRL+ to switch between windows @@ -262,138 +262,37 @@ local plugins = { }, { - -- 'nvim-neo-tree/neo-tree.nvim', - -- -- cmd = 'Neotree', - -- lazy = false, - -- dependencies = 'nvim-tree/nvim-web-devicons', - -- keys = { - -- { - -- '\\', - -- function() - -- require('neo-tree.command').execute({ toggle = true, dir = vim.uv.cwd() }) - -- end, - -- desc = 'Explorer NeoTree (cwd)', - -- }, - -- { 'e', 'fe', desc = 'Explorer NeoTree (Root Dir)', remap = true }, - -- { 'E', 'fE', desc = 'Explorer NeoTree (cwd)', remap = true }, - -- { - -- 'ge', - -- function() - -- require('neo-tree.command').execute({ source = 'git_status', toggle = true }) - -- end, - -- desc = 'Git Explorer', - -- }, - -- { - -- 'be', - -- function() - -- require('neo-tree.command').execute({ source = 'buffers', toggle = true }) - -- end, - -- desc = 'Buffer Explorer', - -- }, - -- }, - -- opts = { - -- sources = { 'filesystem', 'buffers', 'git_status' }, - -- open_files_do_not_replace_types = { 'terminal', 'Trouble', 'trouble', 'qf', 'Outline' }, - -- filesystem = { - -- bind_to_cwd = false, - -- follow_current_file = { enabled = true }, - -- use_libuv_file_watcher = true, - -- }, - -- window = { - -- mappings = { - -- ['l'] = 'open', - -- ['h'] = 'close_node', - -- [''] = 'none', - -- ['Y'] = { - -- function(state) - -- local node = state.tree:get_node() - -- local path = node:get_id() - -- vim.fn.setreg('+', path, 'c') - -- end, - -- desc = 'Copy Path to Clipboard', - -- }, - -- ['O'] = { - -- function(state) - -- require('lazy.util').open(state.tree:get_node().path, { system = true }) - -- end, - -- desc = 'Open with System Application', - -- }, - -- ['P'] = { 'toggle_preview', config = { use_float = false } }, - -- }, - -- }, - -- default_component_configs = { - -- indent = { - -- with_expanders = true, -- if nil and file nesting is enabled, will enable expanders - -- expander_collapsed = '', - -- expander_expanded = '', - -- expander_highlight = 'NeoTreeExpander', - -- }, - -- git_status = { - -- symbols = { - -- unstaged = '󰄱', - -- staged = '󰱒', - -- }, - -- }, - -- }, - -- }, - -- 'nvim-neo-tree/neo-tree.nvim', - -- branch = 'v3.x', - -- dependencies = { - -- 'nvim-lua/plenary.nvim', - -- 'MunifTanjim/nui.nvim', - -- 'nvim-tree/nvim-web-devicons', -- optional, but recommended - -- }, - -- lazy = false, -- neo-tree will lazily load itself - -- opts = { - -- -- use_libuv_file_watcher = true, - -- open_files_do_not_replace_types = { 'terminal', 'Trouble', 'trouble', 'qf', 'Outline' }, - -- filesystem = { - -- bind_to_cwd = false, - -- follow_current_file = { enabled = true }, - -- use_libuv_file_watcher = true, - -- }, - -- sources = { - -- 'filesystem', - -- 'buffers', - -- 'git_status', - -- 'document_symbols', -- Add this line - -- }, - -- filtered_items = { - -- visible = false, -- Change to true if you want to see them dimmed - -- hide_dotfiles = true, - -- hide_gitignored = true, - -- hide_by_name = { '.cache', '.pio' }, - -- never_show = { -- This is the strongest setting to ignore the folder - -- '.cache', - -- '.git', - -- 'node_modules', - -- }, - -- }, - -- }, - }, - - { - 'nvim-tree/nvim-tree.lua', - -- version = '*', - lazy = false, - dependencies = 'nvim-tree/nvim-web-devicons', - config = function() - require('nvim-tree').setup({ - filesystem_watchers = { - ignore_dirs = { - '/.cache', -- Ignores clangd's heavy index folder - '/.pio', -- Ignores pio heavy index folder - '/node_modules', -- Good practice for performance - '/.git', - }, - }, - -- Optional: If you also want to hide it from the tree view entirely - -- filters = { - -- custom = { '^\\.cache$', '^\\.pio$' }, - -- }, - }) - end, + 'nvim-neo-tree/neo-tree.nvim', + branch = 'v3.x', + dependencies = { + 'nvim-lua/plenary.nvim', + 'MunifTanjim/nui.nvim', + 'nvim-tree/nvim-web-devicons', -- optional, but recommended + }, + lazy = false, -- neo-tree will lazily load itself }, + -- { + -- 'nvim-tree/nvim-tree.lua', + -- -- version = '*', + -- lazy = false, + -- dependencies = 'nvim-tree/nvim-web-devicons', + -- config = function() + -- require('nvim-tree').setup({ + -- filesystem_watchers = { + -- ignore_dirs = { + -- '/.cache', -- Ignores clangd's heavy index folder + -- '/.pio', -- Ignores pio heavy index folder + -- '/node_modules', -- Good practice for performance + -- '/.git', + -- }, + -- }, + -- -- Optional: If you also want to hide it from the tree view entirely + -- -- filters = { + -- -- custom = { '^\\.cache$', '^\\.pio$' }, + -- -- }, + -- }) + -- end, + -- }, { 'batoaqaa/nvim-platformio.lua', @@ -441,7 +340,7 @@ local plugins = { end end, }) - -- vim.g.platformioRootDir = vim.uv.cwd() + vim.g.platformioRootDir = vim.uv.cwd() require('lazy').restore({ plguins = { 'nvim-platformio.lua' }, show = false }) end, {}) end @@ -662,6 +561,7 @@ if tok then end -- Keymap to open the buffer list vim.keymap.set('n', 'fb', 'Telescope buffers', { desc = 'Find Buffers' }) + local pioConfig = { lspClangd = { -- enabled = false, From fbbd980d29e8e817d73276b6df736bcadc0d14bf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 17:13:09 +0300 Subject: [PATCH 1041/1406] update --- mini_nvimPlatformio.lua | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index d49c4a17..03d87d69 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -169,6 +169,23 @@ vim.env.XDG_STATE_HOME = tmp .. '/state' local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' +local data_path = vim.env.XDG_DATA_HOME +local plugins = { + nui = data_path .. 'nui.nvim', + plenary = data_path .. 'plenary.nvim', + neotree = data_path .. 'neo-tree.nvim', + pio = data_path .. 'nvim-platformio.lua', + telescope = data_path .. 'telescope.nvim', + toggleterm = data_path .. 'toggleterm.nvim', +} + +-- 2. Add ALL to runtimepath immediately +for _, path in pairs(plugins) do + if vim.fn.isdirectory(path) == 1 then + vim.opt.rtp:append(path) + end +end + if not (vim.uv or vim.loop).fs_stat(lazypath) then vim.fn.system({ 'git', From 5ad2469cf30eb969ff97db08b460fa389f25167a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 17:15:42 +0300 Subject: [PATCH 1042/1406] update --- mini_nvimPlatformio.lua | 48 ++++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 03d87d69..72efed20 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -377,33 +377,33 @@ require('lazy').setup(plugins, { ---------------------------------------------------------------------------------------- -- stylua: ignore -if vim.fn.has('nvim-0.11') == 1 then - -- Create an augroup to manage the autocmd - local json_format_group = vim.api.nvim_create_augroup('JsonFormat', { clear = true }) - vim.api.nvim_create_autocmd('BufWritePre', { - group = json_format_group, - pattern = '*.json', - -- This runs 'python -m json.tool' on the current buffer content - -- It updates the buffer in-place before the file is written to disk - callback = function() vim.cmd('%!python -m json.tool') end, - }) -elseif vim.fn.has('nvim-0.12') == 1 then -end +-- if vim.fn.has('nvim-0.11') == 1 then +-- -- Create an augroup to manage the autocmd +-- local json_format_group = vim.api.nvim_create_augroup('JsonFormat', { clear = true }) +-- vim.api.nvim_create_autocmd('BufWritePre', { +-- group = json_format_group, +-- pattern = '*.json', +-- -- This runs 'python -m json.tool' on the current buffer content +-- -- It updates the buffer in-place before the file is written to disk +-- callback = function() vim.cmd('%!python -m json.tool') end, +-- }) +-- elseif vim.fn.has('nvim-0.12') == 1 then +-- end ---------------------------------------------------------------------------------------- -- INFO: autocommand to Update lazy.nvim plugins in the background -vim.api.nvim_create_autocmd('User', { - pattern = 'LazyVimStarted', -- Triggers after the UI enters and startup time is calculated - desc = 'Update lazy.nvim plugins in the background', - callback = function() - require('lazy').sync({ - wait = false, -- Makes the operation asynchronous - show = false, -- Prevents the Lazy UI from automatically opening - }) - -- You can add a notification here if you like - -- vim.notify("Lazy plugins sync started in background", vim.log.levels.INFO) - end, -}) +-- vim.api.nvim_create_autocmd('User', { +-- pattern = 'LazyVimStarted', -- Triggers after the UI enters and startup time is calculated +-- desc = 'Update lazy.nvim plugins in the background', +-- callback = function() +-- require('lazy').sync({ +-- wait = false, -- Makes the operation asynchronous +-- show = false, -- Prevents the Lazy UI from automatically opening +-- }) +-- -- You can add a notification here if you like +-- -- vim.notify("Lazy plugins sync started in background", vim.log.levels.INFO) +-- end, +-- }) ---------------------------------------------------------------------------------------- -- INFO: set up python nvim venv (virtual environment 'nenv'), activaten. From bf9ad09b308204ecc60446c650091a68b25bdfc2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 17:24:47 +0300 Subject: [PATCH 1043/1406] update --- mini_nvimPlatformio.lua | 80 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 78 insertions(+), 2 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 72efed20..c8942088 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -369,11 +369,87 @@ local plugins = { ---------------------------------------------------------------------------------------- -- INFO: Install/config plugins +-- require('lazy').setup(plugins, { +-- install = { +-- missing = true, +-- }, +-- }) + require('lazy').setup(plugins, { - install = { - missing = true, + rocks = { enabled = false }, + git = { log = { '--since=3 days ago' } }, + ui = { + custom_keys = { false }, + defaults = { + lazy = true, + }, + -- a number <1 is a percentage., >1 is a fixed size + size = { width = 0.8, height = 0.8 }, + wrap = true, -- wrap the lines in the ui + -- The border to use for the UI window. Accepts same border values as |nvim_open_win()|. + border = 'none', + -- The backdrop opacity. 0 is fully opaque, 100 is fully transparent. + backdrop = 60, + title = nil, ---@type string only works when border is not "none" + title_pos = 'center', ---@type "center" | "left" | "right" + -- Show pills on top of the Lazy window + pills = true, ---@type boolean + icons = vim.g.have_nerd_font and {} or { + cmd = ' ', + config = '🛠', + debug = '● ', + event = '📅', + favorite = ' ', + ft = ' ', + init = '⚙', + import = ' ', + keys = ' ', + lazy = '󰒲 ', + loaded = '●', + not_loaded = '○', + plugin = ' ', + runtime = '💻', + require = '󰢱 ', + source = '📄', + start = ' ', + task = '✔ ', + list = { + '●', + '➜', + '★', + '‒', + }, + }, + }, + -- install = { colorscheme = { 'catppuccin' } }, + performance = { + rtp = { + disabled_plugins = { + 'gzip', + 'netrwPlugin', + 'tarPlugin', + 'tohtml', + 'tutor', + 'zipPlugin', + 'rplugin', + 'editorconfig', + 'matchparen', + 'matchit', + }, + }, + }, + checker = { enabled = false }, + change_detection = { + enabled = true, + notify = false, }, }) + + + + + + ---------------------------------------------------------------------------------------- -- stylua: ignore From 5fa93dc784a66af3653dc064dcce34b538a0d3a8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 17:30:15 +0300 Subject: [PATCH 1044/1406] update --- mini_nvimPlatformio.lua | 206 ++++++++++++++++++++-------------------- 1 file changed, 103 insertions(+), 103 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index c8942088..f4fa92b5 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -550,110 +550,110 @@ end ---------------------------------------------------------------------------------------- -- INFO: configure nvim-platformio and load ----------------------------------------------------------------------------------------- -local tok, telescope = pcall(require, 'telescope') -if tok then - -- 1. Import the actions module (This is the missing part!) - local actions = require('telescope.actions') - -- local telescope = require('telescope') - -- print("here" .. vim.inspect(pioConfig)) - telescope.setup({ - extensions = { - ['ui-select'] = { - require('telescope.themes').get_dropdown({ - -- Customizing the dialog appearance - width = 0.6, - previewer = false, - }), - }, - }, - defaults = { - mappings = { - i = { - [''] = actions.delete_buffer, -- Delete buffer in insert mode - }, - n = { - ['dd'] = actions.delete_buffer, -- Delete buffer in normal mode - }, - }, - }, - pickers = { - buffers = { - show_all_buffers = true, - sort_lastused = true, - theme = 'dropdown', -- Compact look - previewer = false, -- Disable preview for a faster feel - }, - }, - }) - - -- Enable Telescope extensions if they are installed - pcall(require('telescope').load_extension, 'fzf') - pcall(require('telescope').load_extension, 'ui-select') - - local function run_project_wizard() - local project_config = {} - - -- Step 1: Select IDE - vim.ui.select({ 'Neovim', 'VS Code', 'IntelliJ' }, { prompt = 'Select IDE' }, function(ide) - if not ide then - return - end - project_config.ide = ide - - -- Step 2: Select Board - vim.ui.select({ 'ESP32', 'Arduino Uno', 'Raspberry Pi' }, { prompt = 'Select Board' }, function(board) - if not board then - return - end - project_config.board = board - - -- Step 3: Select Framework - vim.ui.select({ 'ESP-IDF', 'Arduino Core', 'MicroPython' }, { prompt = 'Select Framework' }, function(fw) - if not fw then - return - end - project_config.framework = fw - - -- Step 4: Final Selection - vim.ui.select({ 'true', 'false' }, { prompt = 'Include Sample Code?' }, function(sample) - project_config.sample = sample == 'true' - - -- Final Output/Action - print( - string.format('Setup: %s on %s using %s (Sample: %s)', project_config.ide, project_config.board, project_config.framework, project_config.sample) - ) - end) - end) - end) - end) - end - - vim.keymap.set('n', 'pw', run_project_wizard, { desc = 'Run Project Wizard' }) - - -- See `:help telescope.builtin` - local builtin = require('telescope.builtin') - vim.keymap.set('n', 'sh', builtin.help_tags, { desc = 'Search [H]elp' }) - vim.keymap.set('n', 'sk', builtin.keymaps, { desc = 'Search [K]eymaps' }) - vim.keymap.set('n', 'sf', builtin.find_files, { desc = 'Search [F]iles' }) - vim.keymap.set('n', 'ss', builtin.builtin, { desc = 'Search [S]elect Telescope' }) - vim.keymap.set('n', 'sw', builtin.grep_string, { desc = 'Search current [W]ord' }) - vim.keymap.set('n', 'sg', builtin.live_grep, { desc = 'Search by [G]rep' }) - vim.keymap.set('n', 'sd', builtin.diagnostics, { desc = 'Search [D]iagnostics' }) - vim.keymap.set('n', 'sr', builtin.resume, { desc = 'Search [R]esume' }) - vim.keymap.set('n', 's.', builtin.oldfiles, { desc = 'Search Recent Files ("." for repeat)' }) - vim.keymap.set('n', '', builtin.buffers, { desc = '[ ] Find existing buffers' }) - - -- Slightly advanced example of overriding default behavior and theme - vim.keymap.set('n', '/', function() - -- You can pass additional configuration to Telescope to change the theme, layout, etc. - builtin.current_buffer_fuzzy_find(require('telescope.themes').get_dropdown({ - winblend = 10, - previewer = false, - })) - end, { desc = '[/] Fuzzily search in current buffer' }) -end +-- local tok, telescope = pcall(require, 'telescope') +-- if tok then +-- -- 1. Import the actions module (This is the missing part!) +-- local actions = require('telescope.actions') +-- -- local telescope = require('telescope') +-- -- print("here" .. vim.inspect(pioConfig)) +-- telescope.setup({ +-- extensions = { +-- ['ui-select'] = { +-- require('telescope.themes').get_dropdown({ +-- -- Customizing the dialog appearance +-- width = 0.6, +-- previewer = false, +-- }), +-- }, +-- }, +-- defaults = { +-- mappings = { +-- i = { +-- [''] = actions.delete_buffer, -- Delete buffer in insert mode +-- }, +-- n = { +-- ['dd'] = actions.delete_buffer, -- Delete buffer in normal mode +-- }, +-- }, +-- }, +-- pickers = { +-- buffers = { +-- show_all_buffers = true, +-- sort_lastused = true, +-- theme = 'dropdown', -- Compact look +-- previewer = false, -- Disable preview for a faster feel +-- }, +-- }, +-- }) +-- +-- -- Enable Telescope extensions if they are installed +-- pcall(require('telescope').load_extension, 'fzf') +-- pcall(require('telescope').load_extension, 'ui-select') +-- +-- local function run_project_wizard() +-- local project_config = {} +-- +-- -- Step 1: Select IDE +-- vim.ui.select({ 'Neovim', 'VS Code', 'IntelliJ' }, { prompt = 'Select IDE' }, function(ide) +-- if not ide then +-- return +-- end +-- project_config.ide = ide +-- +-- -- Step 2: Select Board +-- vim.ui.select({ 'ESP32', 'Arduino Uno', 'Raspberry Pi' }, { prompt = 'Select Board' }, function(board) +-- if not board then +-- return +-- end +-- project_config.board = board +-- +-- -- Step 3: Select Framework +-- vim.ui.select({ 'ESP-IDF', 'Arduino Core', 'MicroPython' }, { prompt = 'Select Framework' }, function(fw) +-- if not fw then +-- return +-- end +-- project_config.framework = fw +-- +-- -- Step 4: Final Selection +-- vim.ui.select({ 'true', 'false' }, { prompt = 'Include Sample Code?' }, function(sample) +-- project_config.sample = sample == 'true' +-- +-- -- Final Output/Action +-- print( +-- string.format('Setup: %s on %s using %s (Sample: %s)', project_config.ide, project_config.board, project_config.framework, project_config.sample) +-- ) +-- end) +-- end) +-- end) +-- end) +-- end +-- +-- vim.keymap.set('n', 'pw', run_project_wizard, { desc = 'Run Project Wizard' }) +-- +-- -- See `:help telescope.builtin` +-- local builtin = require('telescope.builtin') +-- vim.keymap.set('n', 'sh', builtin.help_tags, { desc = 'Search [H]elp' }) +-- vim.keymap.set('n', 'sk', builtin.keymaps, { desc = 'Search [K]eymaps' }) +-- vim.keymap.set('n', 'sf', builtin.find_files, { desc = 'Search [F]iles' }) +-- vim.keymap.set('n', 'ss', builtin.builtin, { desc = 'Search [S]elect Telescope' }) +-- vim.keymap.set('n', 'sw', builtin.grep_string, { desc = 'Search current [W]ord' }) +-- vim.keymap.set('n', 'sg', builtin.live_grep, { desc = 'Search by [G]rep' }) +-- vim.keymap.set('n', 'sd', builtin.diagnostics, { desc = 'Search [D]iagnostics' }) +-- vim.keymap.set('n', 'sr', builtin.resume, { desc = 'Search [R]esume' }) +-- vim.keymap.set('n', 's.', builtin.oldfiles, { desc = 'Search Recent Files ("." for repeat)' }) +-- vim.keymap.set('n', '', builtin.buffers, { desc = '[ ] Find existing buffers' }) +-- +-- -- Slightly advanced example of overriding default behavior and theme +-- vim.keymap.set('n', '/', function() +-- -- You can pass additional configuration to Telescope to change the theme, layout, etc. +-- builtin.current_buffer_fuzzy_find(require('telescope.themes').get_dropdown({ +-- winblend = 10, +-- previewer = false, +-- })) +-- end, { desc = '[/] Fuzzily search in current buffer' }) +-- end -- Keymap to open the buffer list -vim.keymap.set('n', 'fb', 'Telescope buffers', { desc = 'Find Buffers' }) +-- vim.keymap.set('n', 'fb', 'Telescope buffers', { desc = 'Find Buffers' }) local pioConfig = { lspClangd = { From 401b4b70846091d521b4f8efe3461e1a5e02aa86 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 17:33:18 +0300 Subject: [PATCH 1045/1406] update --- mini_nvimPlatformio.lua | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index f4fa92b5..a6599d6d 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -654,7 +654,17 @@ end -- end -- Keymap to open the buffer list -- vim.keymap.set('n', 'fb', 'Telescope buffers', { desc = 'Find Buffers' }) - +require('plenary') +require('nui.utils') + +-- 4. Setup Neo-tree with Watcher Exclusions +require('neo-tree').setup({ + filesystem = { + filtered_items = { + never_show = { '.cache', '.git' }, -- Prevents file-watcher loops + }, + }, +}) local pioConfig = { lspClangd = { -- enabled = false, From 443247acee3de739e49cf9127ffcb14cc89a35d8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 17:38:24 +0300 Subject: [PATCH 1046/1406] update --- mini_nvimPlatformio.lua | 96 ++++++++++++++++++++--------------------- 1 file changed, 48 insertions(+), 48 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index a6599d6d..7decad93 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -169,33 +169,33 @@ vim.env.XDG_STATE_HOME = tmp .. '/state' local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' -local data_path = vim.env.XDG_DATA_HOME -local plugins = { - nui = data_path .. 'nui.nvim', - plenary = data_path .. 'plenary.nvim', - neotree = data_path .. 'neo-tree.nvim', - pio = data_path .. 'nvim-platformio.lua', - telescope = data_path .. 'telescope.nvim', - toggleterm = data_path .. 'toggleterm.nvim', -} - --- 2. Add ALL to runtimepath immediately -for _, path in pairs(plugins) do - if vim.fn.isdirectory(path) == 1 then - vim.opt.rtp:append(path) - end -end - -if not (vim.uv or vim.loop).fs_stat(lazypath) then - vim.fn.system({ - 'git', - 'clone', - '--filter=blob:none', - 'https://github.com/folke/lazy.nvim.git', - '--branch=stable', - lazypath, - }) -end +-- local data_path = vim.env.XDG_DATA_HOME +-- local plugins = { +-- nui = data_path .. 'nui.nvim', +-- plenary = data_path .. 'plenary.nvim', +-- neotree = data_path .. 'neo-tree.nvim', +-- pio = data_path .. 'nvim-platformio.lua', +-- telescope = data_path .. 'telescope.nvim', +-- toggleterm = data_path .. 'toggleterm.nvim', +-- } +-- +-- -- 2. Add ALL to runtimepath immediately +-- for _, path in pairs(plugins) do +-- if vim.fn.isdirectory(path) == 1 then +-- vim.opt.rtp:append(path) +-- end +-- end +-- +-- if not (vim.uv or vim.loop).fs_stat(lazypath) then +-- vim.fn.system({ +-- 'git', +-- 'clone', +-- '--filter=blob:none', +-- 'https://github.com/folke/lazy.nvim.git', +-- '--branch=stable', +-- lazypath, +-- }) +-- end vim.opt.rtp:prepend(lazypath) @@ -278,16 +278,16 @@ local plugins = { -- config = true is shorthand for config = function() require('bufferline').setup() end }, - { - 'nvim-neo-tree/neo-tree.nvim', - branch = 'v3.x', - dependencies = { - 'nvim-lua/plenary.nvim', - 'MunifTanjim/nui.nvim', - 'nvim-tree/nvim-web-devicons', -- optional, but recommended - }, - lazy = false, -- neo-tree will lazily load itself - }, + -- { + -- 'nvim-neo-tree/neo-tree.nvim', + -- branch = 'v3.x', + -- dependencies = { + -- 'nvim-lua/plenary.nvim', + -- 'MunifTanjim/nui.nvim', + -- 'nvim-tree/nvim-web-devicons', -- optional, but recommended + -- }, + -- lazy = false, -- neo-tree will lazily load itself + -- }, -- { -- 'nvim-tree/nvim-tree.lua', -- -- version = '*', @@ -654,17 +654,17 @@ end -- end -- Keymap to open the buffer list -- vim.keymap.set('n', 'fb', 'Telescope buffers', { desc = 'Find Buffers' }) -require('plenary') -require('nui.utils') - --- 4. Setup Neo-tree with Watcher Exclusions -require('neo-tree').setup({ - filesystem = { - filtered_items = { - never_show = { '.cache', '.git' }, -- Prevents file-watcher loops - }, - }, -}) +-- require('plenary') +-- require('nui.utils') +-- +-- -- 4. Setup Neo-tree with Watcher Exclusions +-- require('neo-tree').setup({ +-- filesystem = { +-- filtered_items = { +-- never_show = { '.cache', '.git' }, -- Prevents file-watcher loops +-- }, +-- }, +-- }) local pioConfig = { lspClangd = { -- enabled = false, From 767df301ffb73f3f4a58ee1f9451e780b49996aa Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 17:39:58 +0300 Subject: [PATCH 1047/1406] update --- mini_nvimPlatformio.lua | 144 ++++++++++++++++++++-------------------- 1 file changed, 72 insertions(+), 72 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 7decad93..336f088f 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -369,82 +369,82 @@ local plugins = { ---------------------------------------------------------------------------------------- -- INFO: Install/config plugins --- require('lazy').setup(plugins, { --- install = { --- missing = true, --- }, --- }) - require('lazy').setup(plugins, { - rocks = { enabled = false }, - git = { log = { '--since=3 days ago' } }, - ui = { - custom_keys = { false }, - defaults = { - lazy = true, - }, - -- a number <1 is a percentage., >1 is a fixed size - size = { width = 0.8, height = 0.8 }, - wrap = true, -- wrap the lines in the ui - -- The border to use for the UI window. Accepts same border values as |nvim_open_win()|. - border = 'none', - -- The backdrop opacity. 0 is fully opaque, 100 is fully transparent. - backdrop = 60, - title = nil, ---@type string only works when border is not "none" - title_pos = 'center', ---@type "center" | "left" | "right" - -- Show pills on top of the Lazy window - pills = true, ---@type boolean - icons = vim.g.have_nerd_font and {} or { - cmd = ' ', - config = '🛠', - debug = '● ', - event = '📅', - favorite = ' ', - ft = ' ', - init = '⚙', - import = ' ', - keys = ' ', - lazy = '󰒲 ', - loaded = '●', - not_loaded = '○', - plugin = ' ', - runtime = '💻', - require = '󰢱 ', - source = '📄', - start = ' ', - task = '✔ ', - list = { - '●', - '➜', - '★', - '‒', - }, - }, - }, - -- install = { colorscheme = { 'catppuccin' } }, - performance = { - rtp = { - disabled_plugins = { - 'gzip', - 'netrwPlugin', - 'tarPlugin', - 'tohtml', - 'tutor', - 'zipPlugin', - 'rplugin', - 'editorconfig', - 'matchparen', - 'matchit', - }, - }, - }, - checker = { enabled = false }, - change_detection = { - enabled = true, - notify = false, + install = { + missing = true, }, }) +-- require('lazy').setup(plugins, { +-- rocks = { enabled = false }, +-- git = { log = { '--since=3 days ago' } }, +-- ui = { +-- custom_keys = { false }, +-- defaults = { +-- lazy = true, +-- }, +-- -- a number <1 is a percentage., >1 is a fixed size +-- size = { width = 0.8, height = 0.8 }, +-- wrap = true, -- wrap the lines in the ui +-- -- The border to use for the UI window. Accepts same border values as |nvim_open_win()|. +-- border = 'none', +-- -- The backdrop opacity. 0 is fully opaque, 100 is fully transparent. +-- backdrop = 60, +-- title = nil, ---@type string only works when border is not "none" +-- title_pos = 'center', ---@type "center" | "left" | "right" +-- -- Show pills on top of the Lazy window +-- pills = true, ---@type boolean +-- icons = vim.g.have_nerd_font and {} or { +-- cmd = ' ', +-- config = '🛠', +-- debug = '● ', +-- event = '📅', +-- favorite = ' ', +-- ft = ' ', +-- init = '⚙', +-- import = ' ', +-- keys = ' ', +-- lazy = '󰒲 ', +-- loaded = '●', +-- not_loaded = '○', +-- plugin = ' ', +-- runtime = '💻', +-- require = '󰢱 ', +-- source = '📄', +-- start = ' ', +-- task = '✔ ', +-- list = { +-- '●', +-- '➜', +-- '★', +-- '‒', +-- }, +-- }, +-- }, +-- -- install = { colorscheme = { 'catppuccin' } }, +-- performance = { +-- rtp = { +-- disabled_plugins = { +-- 'gzip', +-- 'netrwPlugin', +-- 'tarPlugin', +-- 'tohtml', +-- 'tutor', +-- 'zipPlugin', +-- 'rplugin', +-- 'editorconfig', +-- 'matchparen', +-- 'matchit', +-- }, +-- }, +-- }, +-- checker = { enabled = false }, +-- change_detection = { +-- enabled = true, +-- notify = false, +-- }, +-- }) + From b5e34bd1412c9aac0df6dd69dcfd90b12cce76e2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 17:43:39 +0300 Subject: [PATCH 1048/1406] update --- mini_nvimPlatformio.lua | 448 +++++++++++++++------------------------- 1 file changed, 172 insertions(+), 276 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 336f088f..3e6e2406 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -146,10 +146,8 @@ end, { desc = '[D]elete Buffer' }) -- keymap('n', '[B', 'BufferLineMovePrev', { desc = 'Move buffer prev' }) -- keymap('n', ']B', 'BufferLineMoveNext', { desc = 'Move buffer next' }) -keymap('n', 'e', 'Neotree document_symbols', { desc = 'NeoTreeToggle' }) -keymap('n', '\\', 'Neotree toggle', { desc = 'NeoTreeToggle' }) --- keymap('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) --- keymap('n', '\\', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) +keymap('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) +keymap('n', '\\', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) -- Keybinds to make split navigation easier. -- Use CTRL+ to switch between windows @@ -169,33 +167,16 @@ vim.env.XDG_STATE_HOME = tmp .. '/state' local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' --- local data_path = vim.env.XDG_DATA_HOME --- local plugins = { --- nui = data_path .. 'nui.nvim', --- plenary = data_path .. 'plenary.nvim', --- neotree = data_path .. 'neo-tree.nvim', --- pio = data_path .. 'nvim-platformio.lua', --- telescope = data_path .. 'telescope.nvim', --- toggleterm = data_path .. 'toggleterm.nvim', --- } --- --- -- 2. Add ALL to runtimepath immediately --- for _, path in pairs(plugins) do --- if vim.fn.isdirectory(path) == 1 then --- vim.opt.rtp:append(path) --- end --- end --- --- if not (vim.uv or vim.loop).fs_stat(lazypath) then --- vim.fn.system({ --- 'git', --- 'clone', --- '--filter=blob:none', --- 'https://github.com/folke/lazy.nvim.git', --- '--branch=stable', --- lazypath, --- }) --- end +if not (vim.uv or vim.loop).fs_stat(lazypath) then + vim.fn.system({ + 'git', + 'clone', + '--filter=blob:none', + 'https://github.com/folke/lazy.nvim.git', + '--branch=stable', + lazypath, + }) +end vim.opt.rtp:prepend(lazypath) @@ -210,7 +191,7 @@ local plugins = { opts = { keymap = { preset = 'default' }, -- 'default', 'super-tab', or 'enter' sources = { - default = { 'path', 'snippets', 'buffer' }, + default = { 'lsp', 'path', 'snippets', 'buffer' }, }, }, }, @@ -278,16 +259,17 @@ local plugins = { -- config = true is shorthand for config = function() require('bufferline').setup() end }, - -- { - -- 'nvim-neo-tree/neo-tree.nvim', - -- branch = 'v3.x', - -- dependencies = { - -- 'nvim-lua/plenary.nvim', - -- 'MunifTanjim/nui.nvim', - -- 'nvim-tree/nvim-web-devicons', -- optional, but recommended - -- }, - -- lazy = false, -- neo-tree will lazily load itself - -- }, + { + 'nvim-neo-tree/neo-tree.nvim', + branch = 'v3.x', + dependencies = { + 'nvim-lua/plenary.nvim', + 'MunifTanjim/nui.nvim', + 'nvim-tree/nvim-web-devicons', -- optional, but recommended + }, + lazy = false, -- neo-tree will lazily load itself + }, + -- { -- 'nvim-tree/nvim-tree.lua', -- -- version = '*', @@ -313,26 +295,6 @@ local plugins = { { 'batoaqaa/nvim-platformio.lua', - dependencies = { - { 'akinsho/toggleterm.nvim' }, - { 'nvim-telescope/telescope.nvim' }, - -- { - -- 'nvim-telescope/telescope.nvim', - -- tag = '0.1.8', - -- dependencies = { 'nvim-lua/plenary.nvim' }, - -- }, - { 'nvim-telescope/telescope-ui-select.nvim' }, - { 'nvim-lua/plenary.nvim' }, - { 'folke/which-key.nvim' }, - { - 'mason-org/mason-lspconfig.nvim', - dependencies = { - { 'mason-org/mason.nvim' }, - { 'folke/trouble.nvim' }, - { 'j-hui/fidget.nvim' }, -- status bottom right - }, - }, - }, cond = function() -- local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.fn.getcwd() or nil local platformioRootDir = (vim.fn.filereadable('platformio.ini') == 1) and vim.uv.cwd() or nil @@ -357,12 +319,33 @@ local plugins = { end end, }) + -- vim.g.platformioRootDir = vim.fn.getcwd() vim.g.platformioRootDir = vim.uv.cwd() require('lazy').restore({ plguins = { 'nvim-platformio.lua' }, show = false }) end, {}) end return vim.g.platformioRootDir ~= nil end, + dependencies = { + { 'akinsho/toggleterm.nvim' }, + { 'nvim-telescope/telescope.nvim' }, + -- { + -- 'nvim-telescope/telescope.nvim', + -- tag = '0.1.8', + -- dependencies = { 'nvim-lua/plenary.nvim' }, + -- }, + { 'nvim-telescope/telescope-ui-select.nvim' }, + { 'nvim-lua/plenary.nvim' }, + { 'folke/which-key.nvim' }, + { + 'mason-org/mason-lspconfig.nvim', + dependencies = { + { 'mason-org/mason.nvim' }, + { 'folke/trouble.nvim' }, + { 'j-hui/fidget.nvim' }, -- status bottom right + }, + }, + }, }, } ---------------------------------------------------------------------------------------- @@ -374,112 +357,36 @@ require('lazy').setup(plugins, { missing = true, }, }) - --- require('lazy').setup(plugins, { --- rocks = { enabled = false }, --- git = { log = { '--since=3 days ago' } }, --- ui = { --- custom_keys = { false }, --- defaults = { --- lazy = true, --- }, --- -- a number <1 is a percentage., >1 is a fixed size --- size = { width = 0.8, height = 0.8 }, --- wrap = true, -- wrap the lines in the ui --- -- The border to use for the UI window. Accepts same border values as |nvim_open_win()|. --- border = 'none', --- -- The backdrop opacity. 0 is fully opaque, 100 is fully transparent. --- backdrop = 60, --- title = nil, ---@type string only works when border is not "none" --- title_pos = 'center', ---@type "center" | "left" | "right" --- -- Show pills on top of the Lazy window --- pills = true, ---@type boolean --- icons = vim.g.have_nerd_font and {} or { --- cmd = ' ', --- config = '🛠', --- debug = '● ', --- event = '📅', --- favorite = ' ', --- ft = ' ', --- init = '⚙', --- import = ' ', --- keys = ' ', --- lazy = '󰒲 ', --- loaded = '●', --- not_loaded = '○', --- plugin = ' ', --- runtime = '💻', --- require = '󰢱 ', --- source = '📄', --- start = ' ', --- task = '✔ ', --- list = { --- '●', --- '➜', --- '★', --- '‒', --- }, --- }, --- }, --- -- install = { colorscheme = { 'catppuccin' } }, --- performance = { --- rtp = { --- disabled_plugins = { --- 'gzip', --- 'netrwPlugin', --- 'tarPlugin', --- 'tohtml', --- 'tutor', --- 'zipPlugin', --- 'rplugin', --- 'editorconfig', --- 'matchparen', --- 'matchit', --- }, --- }, --- }, --- checker = { enabled = false }, --- change_detection = { --- enabled = true, --- notify = false, --- }, --- }) - - - - - - ---------------------------------------------------------------------------------------- -- stylua: ignore --- if vim.fn.has('nvim-0.11') == 1 then --- -- Create an augroup to manage the autocmd --- local json_format_group = vim.api.nvim_create_augroup('JsonFormat', { clear = true }) --- vim.api.nvim_create_autocmd('BufWritePre', { --- group = json_format_group, --- pattern = '*.json', --- -- This runs 'python -m json.tool' on the current buffer content --- -- It updates the buffer in-place before the file is written to disk --- callback = function() vim.cmd('%!python -m json.tool') end, --- }) --- elseif vim.fn.has('nvim-0.12') == 1 then --- end +if vim.fn.has('nvim-0.11') == 1 then + -- Create an augroup to manage the autocmd + local json_format_group = vim.api.nvim_create_augroup('JsonFormat', { clear = true }) + vim.api.nvim_create_autocmd('BufWritePre', { + group = json_format_group, + pattern = '*.json', + -- This runs 'python -m json.tool' on the current buffer content + -- It updates the buffer in-place before the file is written to disk + callback = function() vim.cmd('%!python -m json.tool') end, + }) +elseif vim.fn.has('nvim-0.12') == 1 then +end ---------------------------------------------------------------------------------------- -- INFO: autocommand to Update lazy.nvim plugins in the background --- vim.api.nvim_create_autocmd('User', { --- pattern = 'LazyVimStarted', -- Triggers after the UI enters and startup time is calculated --- desc = 'Update lazy.nvim plugins in the background', --- callback = function() --- require('lazy').sync({ --- wait = false, -- Makes the operation asynchronous --- show = false, -- Prevents the Lazy UI from automatically opening --- }) --- -- You can add a notification here if you like --- -- vim.notify("Lazy plugins sync started in background", vim.log.levels.INFO) --- end, --- }) +vim.api.nvim_create_autocmd('User', { + pattern = 'LazyVimStarted', -- Triggers after the UI enters and startup time is calculated + desc = 'Update lazy.nvim plugins in the background', + callback = function() + require('lazy').sync({ + wait = false, -- Makes the operation asynchronous + show = false, -- Prevents the Lazy UI from automatically opening + }) + -- You can add a notification here if you like + -- vim.notify("Lazy plugins sync started in background", vim.log.levels.INFO) + end, +}) ---------------------------------------------------------------------------------------- -- INFO: set up python nvim venv (virtual environment 'nenv'), activaten. @@ -550,121 +457,110 @@ end ---------------------------------------------------------------------------------------- -- INFO: configure nvim-platformio and load ----------------------------------------------------------------------------------------- --- local tok, telescope = pcall(require, 'telescope') --- if tok then --- -- 1. Import the actions module (This is the missing part!) --- local actions = require('telescope.actions') --- -- local telescope = require('telescope') --- -- print("here" .. vim.inspect(pioConfig)) --- telescope.setup({ --- extensions = { --- ['ui-select'] = { --- require('telescope.themes').get_dropdown({ --- -- Customizing the dialog appearance --- width = 0.6, --- previewer = false, --- }), --- }, --- }, --- defaults = { --- mappings = { --- i = { --- [''] = actions.delete_buffer, -- Delete buffer in insert mode --- }, --- n = { --- ['dd'] = actions.delete_buffer, -- Delete buffer in normal mode --- }, --- }, --- }, --- pickers = { --- buffers = { --- show_all_buffers = true, --- sort_lastused = true, --- theme = 'dropdown', -- Compact look --- previewer = false, -- Disable preview for a faster feel --- }, --- }, --- }) --- --- -- Enable Telescope extensions if they are installed --- pcall(require('telescope').load_extension, 'fzf') --- pcall(require('telescope').load_extension, 'ui-select') --- --- local function run_project_wizard() --- local project_config = {} --- --- -- Step 1: Select IDE --- vim.ui.select({ 'Neovim', 'VS Code', 'IntelliJ' }, { prompt = 'Select IDE' }, function(ide) --- if not ide then --- return --- end --- project_config.ide = ide --- --- -- Step 2: Select Board --- vim.ui.select({ 'ESP32', 'Arduino Uno', 'Raspberry Pi' }, { prompt = 'Select Board' }, function(board) --- if not board then --- return --- end --- project_config.board = board --- --- -- Step 3: Select Framework --- vim.ui.select({ 'ESP-IDF', 'Arduino Core', 'MicroPython' }, { prompt = 'Select Framework' }, function(fw) --- if not fw then --- return --- end --- project_config.framework = fw --- --- -- Step 4: Final Selection --- vim.ui.select({ 'true', 'false' }, { prompt = 'Include Sample Code?' }, function(sample) --- project_config.sample = sample == 'true' --- --- -- Final Output/Action --- print( --- string.format('Setup: %s on %s using %s (Sample: %s)', project_config.ide, project_config.board, project_config.framework, project_config.sample) --- ) --- end) --- end) --- end) --- end) --- end --- --- vim.keymap.set('n', 'pw', run_project_wizard, { desc = 'Run Project Wizard' }) --- --- -- See `:help telescope.builtin` --- local builtin = require('telescope.builtin') --- vim.keymap.set('n', 'sh', builtin.help_tags, { desc = 'Search [H]elp' }) --- vim.keymap.set('n', 'sk', builtin.keymaps, { desc = 'Search [K]eymaps' }) --- vim.keymap.set('n', 'sf', builtin.find_files, { desc = 'Search [F]iles' }) --- vim.keymap.set('n', 'ss', builtin.builtin, { desc = 'Search [S]elect Telescope' }) --- vim.keymap.set('n', 'sw', builtin.grep_string, { desc = 'Search current [W]ord' }) --- vim.keymap.set('n', 'sg', builtin.live_grep, { desc = 'Search by [G]rep' }) --- vim.keymap.set('n', 'sd', builtin.diagnostics, { desc = 'Search [D]iagnostics' }) --- vim.keymap.set('n', 'sr', builtin.resume, { desc = 'Search [R]esume' }) --- vim.keymap.set('n', 's.', builtin.oldfiles, { desc = 'Search Recent Files ("." for repeat)' }) --- vim.keymap.set('n', '', builtin.buffers, { desc = '[ ] Find existing buffers' }) --- --- -- Slightly advanced example of overriding default behavior and theme --- vim.keymap.set('n', '/', function() --- -- You can pass additional configuration to Telescope to change the theme, layout, etc. --- builtin.current_buffer_fuzzy_find(require('telescope.themes').get_dropdown({ --- winblend = 10, --- previewer = false, --- })) --- end, { desc = '[/] Fuzzily search in current buffer' }) --- end +local tok, telescope = pcall(require, 'telescope') +if tok then + -- 1. Import the actions module (This is the missing part!) + local actions = require('telescope.actions') + -- local telescope = require('telescope') + -- print("here" .. vim.inspect(pioConfig)) + telescope.setup({ + extensions = { + ['ui-select'] = { + require('telescope.themes').get_dropdown({ + -- Customizing the dialog appearance + width = 0.6, + previewer = false, + }), + }, + }, + defaults = { + mappings = { + i = { + [''] = actions.delete_buffer, -- Delete buffer in insert mode + }, + n = { + ['dd'] = actions.delete_buffer, -- Delete buffer in normal mode + }, + }, + }, + pickers = { + buffers = { + show_all_buffers = true, + sort_lastused = true, + theme = 'dropdown', -- Compact look + previewer = false, -- Disable preview for a faster feel + }, + }, + }) + + -- Enable Telescope extensions if they are installed + pcall(require('telescope').load_extension, 'fzf') + pcall(require('telescope').load_extension, 'ui-select') + + local function run_project_wizard() + local project_config = {} + + -- Step 1: Select IDE + vim.ui.select({ 'Neovim', 'VS Code', 'IntelliJ' }, { prompt = 'Select IDE' }, function(ide) + if not ide then + return + end + project_config.ide = ide + + -- Step 2: Select Board + vim.ui.select({ 'ESP32', 'Arduino Uno', 'Raspberry Pi' }, { prompt = 'Select Board' }, function(board) + if not board then + return + end + project_config.board = board + + -- Step 3: Select Framework + vim.ui.select({ 'ESP-IDF', 'Arduino Core', 'MicroPython' }, { prompt = 'Select Framework' }, function(fw) + if not fw then + return + end + project_config.framework = fw + + -- Step 4: Final Selection + vim.ui.select({ 'true', 'false' }, { prompt = 'Include Sample Code?' }, function(sample) + project_config.sample = sample == 'true' + + -- Final Output/Action + print( + string.format('Setup: %s on %s using %s (Sample: %s)', project_config.ide, project_config.board, project_config.framework, project_config.sample) + ) + end) + end) + end) + end) + end + + vim.keymap.set('n', 'pw', run_project_wizard, { desc = 'Run Project Wizard' }) + + -- See `:help telescope.builtin` + local builtin = require('telescope.builtin') + vim.keymap.set('n', 'sh', builtin.help_tags, { desc = 'Search [H]elp' }) + vim.keymap.set('n', 'sk', builtin.keymaps, { desc = 'Search [K]eymaps' }) + vim.keymap.set('n', 'sf', builtin.find_files, { desc = 'Search [F]iles' }) + vim.keymap.set('n', 'ss', builtin.builtin, { desc = 'Search [S]elect Telescope' }) + vim.keymap.set('n', 'sw', builtin.grep_string, { desc = 'Search current [W]ord' }) + vim.keymap.set('n', 'sg', builtin.live_grep, { desc = 'Search by [G]rep' }) + vim.keymap.set('n', 'sd', builtin.diagnostics, { desc = 'Search [D]iagnostics' }) + vim.keymap.set('n', 'sr', builtin.resume, { desc = 'Search [R]esume' }) + vim.keymap.set('n', 's.', builtin.oldfiles, { desc = 'Search Recent Files ("." for repeat)' }) + vim.keymap.set('n', '', builtin.buffers, { desc = '[ ] Find existing buffers' }) + + -- Slightly advanced example of overriding default behavior and theme + vim.keymap.set('n', '/', function() + -- You can pass additional configuration to Telescope to change the theme, layout, etc. + builtin.current_buffer_fuzzy_find(require('telescope.themes').get_dropdown({ + winblend = 10, + previewer = false, + })) + end, { desc = '[/] Fuzzily search in current buffer' }) +end -- Keymap to open the buffer list --- vim.keymap.set('n', 'fb', 'Telescope buffers', { desc = 'Find Buffers' }) --- require('plenary') --- require('nui.utils') --- --- -- 4. Setup Neo-tree with Watcher Exclusions --- require('neo-tree').setup({ --- filesystem = { --- filtered_items = { --- never_show = { '.cache', '.git' }, -- Prevents file-watcher loops --- }, --- }, --- }) +vim.keymap.set('n', 'fb', 'Telescope buffers', { desc = 'Find Buffers' }) local pioConfig = { lspClangd = { -- enabled = false, From 1e9b0cf0b5ecfc4f3313796bb2a861761758ef6e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 17:47:13 +0300 Subject: [PATCH 1049/1406] update --- mini_nvimPlatformio.lua | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 3e6e2406..99ce79cb 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -146,8 +146,10 @@ end, { desc = '[D]elete Buffer' }) -- keymap('n', '[B', 'BufferLineMovePrev', { desc = 'Move buffer prev' }) -- keymap('n', ']B', 'BufferLineMoveNext', { desc = 'Move buffer next' }) -keymap('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) -keymap('n', '\\', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) +keymap('n', 'e', 'Neotree document_symbols', { desc = 'NeoTreeToggle' }) +keymap('n', '\\', 'Neotree toggle', { desc = 'NeoTreeToggle' }) +-- keymap('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) +-- keymap('n', '\\', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) -- Keybinds to make split navigation easier. -- Use CTRL+ to switch between windows @@ -268,6 +270,14 @@ local plugins = { 'nvim-tree/nvim-web-devicons', -- optional, but recommended }, lazy = false, -- neo-tree will lazily load itself + opts = { + sources = { + 'filesystem', + 'buffers', + 'git_status', + 'document_symbols', -- Add this line + }, + }, }, -- { From 95cc0a26a6420b823a4a21e22ed0e6cff7afee64 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 17:51:55 +0300 Subject: [PATCH 1050/1406] update --- lua/platformio/utils/misc.lua | 4 ++-- plugin/platformio.lua | 40 +++++++++++++++++------------------ 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 2544b1b4..065fc4b9 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -1,5 +1,5 @@ ---@class lua.platformio.utils.misc --- File: lua/platformio/wizard.lua +---@class platformio.utils.misc + local M = {} M.is_windows = jit.os == 'Windows' diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 6da9e0da..710e57b2 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -25,26 +25,26 @@ -- end, -- }) ----@class vim ----@field pio platformio.utils.pio ----@field misc platformio.utils.misc - -setmetatable(vim, { - __index = function(t, k) - if k == 'misc' then - local m = require('platformio.utils.misc') - rawset(t, k, m) -- Physically add 'misc' to 'vim' - return m - end - if k == 'pio' then - local p = require('platformio.utils.pio') - rawset(t, k, p) -- Physically add 'pio' to 'vim' - return p - end - end, -}) --- vim.misc = require('platformio.utils.misc') --- vim.pio = require('platformio.utils.pio') +--@class vim +--@field pio platformio.utils.pio +--@field misc platformio.utils.misc + +-- setmetatable(vim, { +-- __index = function(t, k) +-- if k == 'misc' then +-- local m = require('platformio.utils.misc') +-- rawset(t, k, m) -- Physically add 'misc' to 'vim' +-- return m +-- end +-- if k == 'pio' then +-- local p = require('platformio.utils.pio') +-- rawset(t, k, p) -- Physically add 'pio' to 'vim' +-- return p +-- end +-- end, +-- }) +vim.misc = require('platformio.utils.misc') +vim.pio = require('platformio.utils.pio') -- INFO: fix paths in compile_commands.json vim.api.nvim_create_user_command('PioFixPaths', function() From 91b4d16e8283081cc1dbf1ec4b694d925869f65d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 18:15:15 +0300 Subject: [PATCH 1051/1406] update --- mini_nvimPlatformio.lua | 67 +++++++++++++++++++++++++++++++++-------- 1 file changed, 55 insertions(+), 12 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 99ce79cb..5acc770e 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -161,20 +161,56 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) ---------------------------------------------------------------------------------------- -- INFO: Set mini lazy config -- pick a temp root -local tmp = vim.loop.os_tmpdir() .. '/nvim-temp' -vim.env.XDG_CONFIG_HOME = vim.fn.expand('~/.miniConfig') -vim.env.XDG_DATA_HOME = tmp .. '/data' -vim.env.XDG_CACHE_HOME = tmp .. '/cache' -vim.env.XDG_STATE_HOME = tmp .. '/state' +-- local tmp = vim.loop.os_tmpdir() .. '/nvim-temp' +-- vim.env.XDG_CONFIG_HOME = vim.fn.expand('~/.miniConfig') +-- vim.env.XDG_DATA_HOME = tmp .. '/data' +-- vim.env.XDG_CACHE_HOME = tmp .. '/cache' +-- vim.env.XDG_STATE_HOME = tmp .. '/state' +-- +-- local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' +-- +-- if not (vim.uv or vim.loop).fs_stat(lazypath) then +-- vim.fn.system({ +-- 'git', +-- 'clone', +-- '--filter=blob:none', +-- 'https://github.com/folke/lazy.nvim.git', +-- '--branch=stable', +-- lazypath, +-- }) +-- end + +-- 1. Setup Cross-Platform Redirected Paths +local home = os.getenv('USERPROFILE') or os.getenv('HOME') +local tmp_root = home .. '/tmp/nvim-tmp' +local data_dir = tmp_root .. '/data' +local config_dir = tmp_root .. '/config' +local cache_dir = tmp_root .. '/cache' +local state_dir = tmp_root .. '/state' + +-- Create directories (handles Windows/Linux) +for _, dir in ipairs({ data_dir, config_dir, cache_dir, state_dir }) do + if vim.fn.isdirectory(dir) == 0 then + vim.fn.mkdir(dir, 'p') + end +end -local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' +-- Override stdpath so lazy.nvim knows where to stay +vim.fn.stdpath = (function(orig) + return function(what) + local redirected = { data = data_dir, config = config_dir, cache = cache_dir, state = state_dir } + return redirected[what] or orig(what) + end +end)(vim.fn.stdpath) -if not (vim.uv or vim.loop).fs_stat(lazypath) then +-- 2. Bootstrap lazy.nvim +local lazypath = data_dir .. '/lazy/lazy.nvim' +if not vim.uv.fs_stat(lazypath) then vim.fn.system({ 'git', 'clone', '--filter=blob:none', - 'https://github.com/folke/lazy.nvim.git', + 'https://github.com', '--branch=stable', lazypath, }) @@ -362,11 +398,18 @@ local plugins = { ---------------------------------------------------------------------------------------- -- INFO: Install/config plugins -require('lazy').setup(plugins, { - install = { - missing = true, - }, +-- require('lazy').setup(plugins, { +-- install = { +-- missing = true, +-- }, +-- }) + +require('lazy').setup({ + root = data_dir .. '/lazy', + spec = { plugins }, }) + + ---------------------------------------------------------------------------------------- -- stylua: ignore From d75331fdd2f460fd105652cba8375fe6f95080a7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 18:18:02 +0300 Subject: [PATCH 1052/1406] update --- mini_nvimPlatformio.lua | 3 +++ 1 file changed, 3 insertions(+) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 5acc770e..55a123e4 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -404,6 +404,9 @@ local plugins = { -- }, -- }) +vim.opt.rtp:prepend(lazypath) +package.path = package.path .. ';' .. lazypath .. '/lua/?.lua' +package.path = package.path .. ';' .. lazypath .. '/lua/?/init.lua' require('lazy').setup({ root = data_dir .. '/lazy', spec = { plugins }, From bd492498f86d12963e2477b1aae4ad63015e403a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 20:39:07 +0300 Subject: [PATCH 1053/1406] update --- mini_nvimPlatformio.lua | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 55a123e4..83317586 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -407,12 +407,13 @@ local plugins = { vim.opt.rtp:prepend(lazypath) package.path = package.path .. ';' .. lazypath .. '/lua/?.lua' package.path = package.path .. ';' .. lazypath .. '/lua/?/init.lua' -require('lazy').setup({ - root = data_dir .. '/lazy', - spec = { plugins }, +require('lazy').setup(plugins, { + root = data_dir .. '/lazy', -- Ensure plugins install in tmp + install = { + missing = true, + }, }) - ---------------------------------------------------------------------------------------- -- stylua: ignore From e5f6be09b93f2bdcac84fa17199a4c00ebaa2573 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 20:41:43 +0300 Subject: [PATCH 1054/1406] update --- mini_nvimPlatformio.lua | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 83317586..1b94fba2 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -218,6 +218,8 @@ end vim.opt.rtp:prepend(lazypath) +package.path = package.path .. ';' .. lazypath .. '/lua/?.lua' +package.path = package.path .. ';' .. lazypath .. '/lua/?/init.lua' ---------------------------------------------------------------------------------------- -- INFO: define plugins table local plugins = { @@ -404,9 +406,6 @@ local plugins = { -- }, -- }) -vim.opt.rtp:prepend(lazypath) -package.path = package.path .. ';' .. lazypath .. '/lua/?.lua' -package.path = package.path .. ';' .. lazypath .. '/lua/?/init.lua' require('lazy').setup(plugins, { root = data_dir .. '/lazy', -- Ensure plugins install in tmp install = { From 6b793c88eeb917a32e6f28171f40c70f55bf059f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 20:46:46 +0300 Subject: [PATCH 1055/1406] update --- mini_nvimPlatformio.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 1b94fba2..733bb4e1 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -182,7 +182,8 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- 1. Setup Cross-Platform Redirected Paths local home = os.getenv('USERPROFILE') or os.getenv('HOME') -local tmp_root = home .. '/tmp/nvim-tmp' +-- local tmp_root = home .. '/tmp/nvim-tmp' +local tmp_root = (home .. [[/tmp/nvim-tmp]]):gsub('[\\]+', '/') local data_dir = tmp_root .. '/data' local config_dir = tmp_root .. '/config' local cache_dir = tmp_root .. '/cache' From acad870873e0a92433c59e03484b85c06c466c10 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 21:18:31 +0300 Subject: [PATCH 1056/1406] update --- mini_nvimPlatformio.lua | 36 ++++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 733bb4e1..d28ec3fa 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -188,9 +188,10 @@ local data_dir = tmp_root .. '/data' local config_dir = tmp_root .. '/config' local cache_dir = tmp_root .. '/cache' local state_dir = tmp_root .. '/state' +local lazypath = data_dir .. '/lazy/lazy.nvim' -- Create directories (handles Windows/Linux) -for _, dir in ipairs({ data_dir, config_dir, cache_dir, state_dir }) do +for _, dir in ipairs({ data_dir, config_dir, cache_dir, state_dir, lazypath }) do if vim.fn.isdirectory(dir) == 0 then vim.fn.mkdir(dir, 'p') end @@ -204,10 +205,9 @@ vim.fn.stdpath = (function(orig) end end)(vim.fn.stdpath) --- 2. Bootstrap lazy.nvim -local lazypath = data_dir .. '/lazy/lazy.nvim' -if not vim.uv.fs_stat(lazypath) then - vim.fn.system({ +if not (vim.uv or vim.loop).fs_stat(lazypath) then + print('Downloading lazy.nvim... please wait.') + local output = vim.fn.system({ 'git', 'clone', '--filter=blob:none', @@ -215,12 +215,32 @@ if not vim.uv.fs_stat(lazypath) then '--branch=stable', lazypath, }) + if vim.v.shell_error ~= 0 then + print('FATAL: Git clone failed!') + print(output) + return + end end +vim.opt.rtp:prepend(lazypath) +local lua_src = lazypath .. [[/lua]] +package.path = package.path .. ';' .. lua_src .. [[/?.lua;]] .. lua_src .. [[/?/init.lua]] +-- 2. Bootstrap lazy.nvim +-- if not vim.uv.fs_stat(lazypath) then +-- vim.fn.system({ +-- 'git', +-- 'clone', +-- '--filter=blob:none', +-- 'https://github.com', +-- '--branch=stable', +-- lazypath, +-- }) +-- end + vim.opt.rtp:prepend(lazypath) -package.path = package.path .. ';' .. lazypath .. '/lua/?.lua' -package.path = package.path .. ';' .. lazypath .. '/lua/?/init.lua' +-- package.path = package.path .. ';' .. lazypath .. '/lua/?.lua' +-- package.path = package.path .. ';' .. lazypath .. '/lua/?/init.lua' ---------------------------------------------------------------------------------------- -- INFO: define plugins table local plugins = { @@ -408,7 +428,7 @@ local plugins = { -- }) require('lazy').setup(plugins, { - root = data_dir .. '/lazy', -- Ensure plugins install in tmp + root = data_dir .. [[/lazy]], -- Ensure plugins install in tmp install = { missing = true, }, From 65e7f6e9976a49e053ed00c0b6b3f42e83090ba9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 21:30:17 +0300 Subject: [PATCH 1057/1406] update --- mini_nvimPlatformio.lua | 63 ++++++++++++++++++++++++----------------- 1 file changed, 37 insertions(+), 26 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index d28ec3fa..0b769182 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -183,7 +183,7 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- 1. Setup Cross-Platform Redirected Paths local home = os.getenv('USERPROFILE') or os.getenv('HOME') -- local tmp_root = home .. '/tmp/nvim-tmp' -local tmp_root = (home .. [[/tmp/nvim-tmp]]):gsub('[\\]+', '/') +local tmp_root = (home .. [[/tmp/nvim-temp]]):gsub('[\\/]+', '/') local data_dir = tmp_root .. '/data' local config_dir = tmp_root .. '/config' local cache_dir = tmp_root .. '/cache' @@ -191,35 +191,48 @@ local state_dir = tmp_root .. '/state' local lazypath = data_dir .. '/lazy/lazy.nvim' -- Create directories (handles Windows/Linux) -for _, dir in ipairs({ data_dir, config_dir, cache_dir, state_dir, lazypath }) do +for _, dir in ipairs({ data_dir, config_dir, cache_dir, state_dir }) do if vim.fn.isdirectory(dir) == 0 then vim.fn.mkdir(dir, 'p') end end +if vim.fn.isdirectory(lazypath) == 0 then + print('Folder missing. Creating and downloading lazy.nvim...') + vim.fn.mkdir(lazypath, 'p') + local cmd = 'git clone --filter=blob:none https://github.com --branch=stable "' .. lazypath .. '"' + vim.fn.system(cmd) +end + -- Override stdpath so lazy.nvim knows where to stay -vim.fn.stdpath = (function(orig) - return function(what) - local redirected = { data = data_dir, config = config_dir, cache = cache_dir, state = state_dir } - return redirected[what] or orig(what) - end -end)(vim.fn.stdpath) - -if not (vim.uv or vim.loop).fs_stat(lazypath) then - print('Downloading lazy.nvim... please wait.') - local output = vim.fn.system({ - 'git', - 'clone', - '--filter=blob:none', - 'https://github.com', - '--branch=stable', - lazypath, - }) - if vim.v.shell_error ~= 0 then - print('FATAL: Git clone failed!') - print(output) - return - end +-- vim.fn.stdpath = (function(orig) +-- return function(what) +-- local redirected = { data = data_dir, config = config_dir, cache = cache_dir, state = state_dir } +-- return redirected[what] or orig(what) +-- end +-- end)(vim.fn.stdpath) +-- +-- if not (vim.uv or vim.loop).fs_stat(lazypath) then +-- print('Downloading lazy.nvim... please wait.') +-- local output = vim.fn.system({ +-- 'git', +-- 'clone', +-- '--filter=blob:none', +-- 'https://github.com', +-- '--branch=stable', +-- lazypath, +-- }) +-- if vim.v.shell_error ~= 0 then +-- print('FATAL: Git clone failed!') +-- print(output) +-- return +-- end +-- end +local checker = io.open(lazypath .. [[\lua\lazy\init.lua]], 'r') +if checker then + checker:close() +else + error('FATAL: lazy.nvim was not downloaded correctly to ' .. lazypath) end vim.opt.rtp:prepend(lazypath) @@ -237,8 +250,6 @@ package.path = package.path .. ';' .. lua_src .. [[/?.lua;]] .. lua_src .. [[/?/ -- }) -- end -vim.opt.rtp:prepend(lazypath) - -- package.path = package.path .. ';' .. lazypath .. '/lua/?.lua' -- package.path = package.path .. ';' .. lazypath .. '/lua/?/init.lua' ---------------------------------------------------------------------------------------- From c46fc0264e32fd0458b2762e48735be974cc925d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 21:31:54 +0300 Subject: [PATCH 1058/1406] update --- mini_nvimPlatformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 0b769182..63ef4ef1 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -228,7 +228,7 @@ end -- return -- end -- end -local checker = io.open(lazypath .. [[\lua\lazy\init.lua]], 'r') +local checker = io.open(lazypath .. [[/lua/lazy/init.lua]], 'r') if checker then checker:close() else From df412affaaf4e7e91775bc87158392d6fd438dcb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 21:41:48 +0300 Subject: [PATCH 1059/1406] update --- mini_nvimPlatformio.lua | 67 ++++++++--------------------------------- 1 file changed, 13 insertions(+), 54 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 63ef4ef1..e2500f07 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -180,78 +180,37 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- }) -- end --- 1. Setup Cross-Platform Redirected Paths local home = os.getenv('USERPROFILE') or os.getenv('HOME') --- local tmp_root = home .. '/tmp/nvim-tmp' -local tmp_root = (home .. [[/tmp/nvim-temp]]):gsub('[\\/]+', '/') +local tmp_root = home:gsub('\\', '/') .. '/tmp/nvim-temp' local data_dir = tmp_root .. '/data' -local config_dir = tmp_root .. '/config' -local cache_dir = tmp_root .. '/cache' -local state_dir = tmp_root .. '/state' local lazypath = data_dir .. '/lazy/lazy.nvim' --- Create directories (handles Windows/Linux) -for _, dir in ipairs({ data_dir, config_dir, cache_dir, state_dir }) do - if vim.fn.isdirectory(dir) == 0 then - vim.fn.mkdir(dir, 'p') - end +-- 1. Create parents, but NOT the lazypath itself (Git needs to create it) +if vim.fn.isdirectory(data_dir .. '/lazy') == 0 then + vim.fn.mkdir(data_dir .. '/lazy', 'p') end +-- 2. Correct Git Clone URL and logic if vim.fn.isdirectory(lazypath) == 0 then - print('Folder missing. Creating and downloading lazy.nvim...') - vim.fn.mkdir(lazypath, 'p') - local cmd = 'git clone --filter=blob:none https://github.com --branch=stable "' .. lazypath .. '"' + print('Downloading lazy.nvim...') + -- Correct URL: https://github.com + local cmd = string.format('git clone --filter=blob:none https://github.com --branch=stable "%s"', lazypath) vim.fn.system(cmd) end --- Override stdpath so lazy.nvim knows where to stay --- vim.fn.stdpath = (function(orig) --- return function(what) --- local redirected = { data = data_dir, config = config_dir, cache = cache_dir, state = state_dir } --- return redirected[what] or orig(what) --- end --- end)(vim.fn.stdpath) --- --- if not (vim.uv or vim.loop).fs_stat(lazypath) then --- print('Downloading lazy.nvim... please wait.') --- local output = vim.fn.system({ --- 'git', --- 'clone', --- '--filter=blob:none', --- 'https://github.com', --- '--branch=stable', --- lazypath, --- }) --- if vim.v.shell_error ~= 0 then --- print('FATAL: Git clone failed!') --- print(output) --- return --- end --- end -local checker = io.open(lazypath .. [[/lua/lazy/init.lua]], 'r') +-- 3. Verify +local checker = io.open(lazypath .. '/lua/lazy/init.lua', 'r') if checker then checker:close() else + -- If this hits, check if 'git' is in your PATH error('FATAL: lazy.nvim was not downloaded correctly to ' .. lazypath) end +-- 4. Environment Setup vim.opt.rtp:prepend(lazypath) -local lua_src = lazypath .. [[/lua]] -package.path = package.path .. ';' .. lua_src .. [[/?.lua;]] .. lua_src .. [[/?/init.lua]] --- 2. Bootstrap lazy.nvim --- if not vim.uv.fs_stat(lazypath) then --- vim.fn.system({ --- 'git', --- 'clone', --- '--filter=blob:none', --- 'https://github.com', --- '--branch=stable', --- lazypath, --- }) --- end +package.path = package.path .. ';' .. lazypath .. '/lua/?.lua;' .. lazypath .. '/lua/?/init.lua' --- package.path = package.path .. ';' .. lazypath .. '/lua/?.lua' --- package.path = package.path .. ';' .. lazypath .. '/lua/?/init.lua' ---------------------------------------------------------------------------------------- -- INFO: define plugins table local plugins = { From 14309c00e1845f818ae839d16b5c710062cab70a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 21:46:32 +0300 Subject: [PATCH 1060/1406] update --- mini_nvimPlatformio.lua | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index e2500f07..193a3fb9 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -185,28 +185,39 @@ local tmp_root = home:gsub('\\', '/') .. '/tmp/nvim-temp' local data_dir = tmp_root .. '/data' local lazypath = data_dir .. '/lazy/lazy.nvim' --- 1. Create parents, but NOT the lazypath itself (Git needs to create it) +-- 1. Ensure the parent directory exists if vim.fn.isdirectory(data_dir .. '/lazy') == 0 then vim.fn.mkdir(data_dir .. '/lazy', 'p') end --- 2. Correct Git Clone URL and logic +-- 2. Improved Git Clone with Error Reporting if vim.fn.isdirectory(lazypath) == 0 then - print('Downloading lazy.nvim...') - -- Correct URL: https://github.com - local cmd = string.format('git clone --filter=blob:none https://github.com --branch=stable "%s"', lazypath) - vim.fn.system(cmd) + print('Attempting to download lazy.nvim...') + + -- The full URL is mandatory + local repo = 'https://github.com' + local cmd = string.format('git clone --filter=blob:none %s --branch=stable "%s"', repo, lazypath) + + local output = vim.fn.system(cmd) + + -- Check if git actually worked + if vim.v.shell_error ~= 0 then + print('GIT ERROR DETECTED:') + print(output) -- This will tell you if 'git' is not found or access is denied + error("Could not clone lazy.nvim. Please ensure 'git' is installed and accessible.") + end end --- 3. Verify +-- 3. Verify the specific file needed for require('lazy') local checker = io.open(lazypath .. '/lua/lazy/init.lua', 'r') if checker then checker:close() else - -- If this hits, check if 'git' is in your PATH - error('FATAL: lazy.nvim was not downloaded correctly to ' .. lazypath) + error('FATAL: Folder exists but /lua/lazy/init.lua is missing at ' .. lazypath) end +-- ... rest of your setup ... + -- 4. Environment Setup vim.opt.rtp:prepend(lazypath) package.path = package.path .. ';' .. lazypath .. '/lua/?.lua;' .. lazypath .. '/lua/?/init.lua' From ab40e28aa161141dd186affe6879a0f3c31f9db9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 21:58:49 +0300 Subject: [PATCH 1061/1406] update --- mini_nvimPlatformio.lua | 39 ++++++++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 193a3fb9..b4da443a 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -185,37 +185,50 @@ local tmp_root = home:gsub('\\', '/') .. '/tmp/nvim-temp' local data_dir = tmp_root .. '/data' local lazypath = data_dir .. '/lazy/lazy.nvim' --- 1. Ensure the parent directory exists +-- 1. Ensure parent exists if vim.fn.isdirectory(data_dir .. '/lazy') == 0 then vim.fn.mkdir(data_dir .. '/lazy', 'p') end --- 2. Improved Git Clone with Error Reporting +-- 2. Improved Git Clone with the CORRECT URL if vim.fn.isdirectory(lazypath) == 0 then print('Attempting to download lazy.nvim...') - -- The full URL is mandatory - local repo = 'https://github.com' - local cmd = string.format('git clone --filter=blob:none %s --branch=stable "%s"', repo, lazypath) - - local output = vim.fn.system(cmd) + -- MANDATORY: The URL must point to the specific repository + -- local repo = 'https://github.com' + -- local cmd = string.format('git clone --filter=blob:none %s --branch=stable "%s"', repo, lazypath) + + -- local output = vim.fn.system(cmd) + -- if not (vim.uv or vim.loop).fs_stat(lazypath) then + local output = vim.fn.system({ + 'git', + 'clone', + '--filter=blob:none', + 'https://github.com/folke/lazy.nvim.git', + '--branch=stable', + lazypath, + }) + -- end - -- Check if git actually worked if vim.v.shell_error ~= 0 then print('GIT ERROR DETECTED:') - print(output) -- This will tell you if 'git' is not found or access is denied - error("Could not clone lazy.nvim. Please ensure 'git' is installed and accessible.") + print(output) + -- Delete the failed folder so it can retry next time + vim.fn.delete(lazypath, 'rf') + error('Could not clone lazy.nvim. Check the URL above.') end end --- 3. Verify the specific file needed for require('lazy') +-- 3. Verify and Load local checker = io.open(lazypath .. '/lua/lazy/init.lua', 'r') if checker then checker:close() + vim.opt.rtp:prepend(lazypath) + package.path = package.path .. ';' .. lazypath .. '/lua/?.lua;' .. lazypath .. '/lua/?/init.lua' else - error('FATAL: Folder exists but /lua/lazy/init.lua is missing at ' .. lazypath) + vim.fn.delete(lazypath, 'rf') + error('FATAL: Downloaded folder is corrupted. Retrying next launch.') end - -- ... rest of your setup ... -- 4. Environment Setup From 8e62737e1df5249df192b45fa78527c922b95f80 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 22:01:33 +0300 Subject: [PATCH 1062/1406] update --- mini_nvimPlatformio.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index b4da443a..6d0526d0 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -183,6 +183,7 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) local home = os.getenv('USERPROFILE') or os.getenv('HOME') local tmp_root = home:gsub('\\', '/') .. '/tmp/nvim-temp' local data_dir = tmp_root .. '/data' +vim.env.XDG_DATA_HOME = data_dir local lazypath = data_dir .. '/lazy/lazy.nvim' -- 1. Ensure parent exists From 021a3e28b93d085e133cbdd3f60663cf43b1154e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 22:04:05 +0300 Subject: [PATCH 1063/1406] update --- mini_nvimPlatformio.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 6d0526d0..b7ce140b 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -184,6 +184,7 @@ local home = os.getenv('USERPROFILE') or os.getenv('HOME') local tmp_root = home:gsub('\\', '/') .. '/tmp/nvim-temp' local data_dir = tmp_root .. '/data' vim.env.XDG_DATA_HOME = data_dir +print(vim.env.XDG_DATA_HOME) local lazypath = data_dir .. '/lazy/lazy.nvim' -- 1. Ensure parent exists From 72a4be8ff8f1c3e3110ddf0699000610ffa006f5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 22:16:45 +0300 Subject: [PATCH 1064/1406] update --- mini_nvimPlatformio.lua | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index b7ce140b..08f5fbbb 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -180,9 +180,44 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- }) -- end -local home = os.getenv('USERPROFILE') or os.getenv('HOME') -local tmp_root = home:gsub('\\', '/') .. '/tmp/nvim-temp' +-- 1. Setup Redirected Paths +local tmp_root = vim.fn.expand('~/tmp/nvim-tmp'):gsub('\\', '/') local data_dir = tmp_root .. '/data' +local config_dir = tmp_root .. '/config' +local cache_dir = tmp_root .. '/cache' +local state_dir = tmp_root .. '/state' +local nvim_data = data_dir .. '/nvim-data' + +-- Create directories if they don't exist +for _, dir in ipairs({ data_dir, config_dir, cache_dir, state_dir, nvim_data }) do + if vim.fn.isdirectory(dir) == 0 then + vim.fn.mkdir(dir, 'p') + end +end + +-- Override Neovim's internal paths +vim.opt.packpath = { data_dir .. '/site' } +vim.fn.stdpath = (function(orig) + return function(what) + if what == 'data' then + return data_dir + end + if what == 'config' then + return config_dir + end + if what == 'cache' then + return cache_dir + end + if what == 'state' then + return state_dir + end + return orig(what) + end +end)(vim.fn.stdpath) + +-- local home = os.getenv('USERPROFILE') or os.getenv('HOME') +-- local tmp_root = home:gsub('\\', '/') .. '/tmp/nvim-temp' +-- local data_dir = tmp_root .. '/data' vim.env.XDG_DATA_HOME = data_dir print(vim.env.XDG_DATA_HOME) local lazypath = data_dir .. '/lazy/lazy.nvim' From 999cbf18880237d436ecc01e6cb6c5fe6debc988 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 22:44:08 +0300 Subject: [PATCH 1065/1406] update --- mini_nvimPlatformio.lua | 150 +++++++++++++++++++--------------------- 1 file changed, 71 insertions(+), 79 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 08f5fbbb..8fd9e812 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -180,64 +180,21 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- }) -- end --- 1. Setup Redirected Paths -local tmp_root = vim.fn.expand('~/tmp/nvim-tmp'):gsub('\\', '/') -local data_dir = tmp_root .. '/data' -local config_dir = tmp_root .. '/config' -local cache_dir = tmp_root .. '/cache' -local state_dir = tmp_root .. '/state' -local nvim_data = data_dir .. '/nvim-data' - --- Create directories if they don't exist -for _, dir in ipairs({ data_dir, config_dir, cache_dir, state_dir, nvim_data }) do - if vim.fn.isdirectory(dir) == 0 then - vim.fn.mkdir(dir, 'p') - end -end --- Override Neovim's internal paths -vim.opt.packpath = { data_dir .. '/site' } -vim.fn.stdpath = (function(orig) - return function(what) - if what == 'data' then - return data_dir - end - if what == 'config' then - return config_dir - end - if what == 'cache' then - return cache_dir - end - if what == 'state' then - return state_dir - end - return orig(what) - end -end)(vim.fn.stdpath) - --- local home = os.getenv('USERPROFILE') or os.getenv('HOME') --- local tmp_root = home:gsub('\\', '/') .. '/tmp/nvim-temp' --- local data_dir = tmp_root .. '/data' -vim.env.XDG_DATA_HOME = data_dir -print(vim.env.XDG_DATA_HOME) -local lazypath = data_dir .. '/lazy/lazy.nvim' - --- 1. Ensure parent exists -if vim.fn.isdirectory(data_dir .. '/lazy') == 0 then - vim.fn.mkdir(data_dir .. '/lazy', 'p') -end +local home = os.getenv('USERPROFILE') or os.getenv('HOME') +local tmp_root = home:gsub('\\', '/') .. '/tmp/nvim-temp' --- 2. Improved Git Clone with the CORRECT URL -if vim.fn.isdirectory(lazypath) == 0 then - print('Attempting to download lazy.nvim...') +-- Set environment variables so Neovim and plugins use the tmp folder automatically +vim.env.XDG_CONFIG_HOME = tmp_root .. '/config' +vim.env.XDG_DATA_HOME = tmp_root .. '/data' +vim.env.XDG_CACHE_HOME = tmp_root .. '/cache' +vim.env.XDG_STATE_HOME = tmp_root .. '/state' - -- MANDATORY: The URL must point to the specific repository - -- local repo = 'https://github.com' - -- local cmd = string.format('git clone --filter=blob:none %s --branch=stable "%s"', repo, lazypath) - - -- local output = vim.fn.system(cmd) - -- if not (vim.uv or vim.loop).fs_stat(lazypath) then - local output = vim.fn.system({ +local lazypath = vim.fn.stdpath("data") .. '/lazy/lazy.nvim' +if not (vim.uv or vim.loop).fs_stat(lazypath) then +-- if vim.fn.isdirectory(lazypath) == 0 then + print('Attempting to download lazy.nvim...') + vim.fn.system({ 'git', 'clone', '--filter=blob:none', @@ -245,18 +202,8 @@ if vim.fn.isdirectory(lazypath) == 0 then '--branch=stable', lazypath, }) - -- end - - if vim.v.shell_error ~= 0 then - print('GIT ERROR DETECTED:') - print(output) - -- Delete the failed folder so it can retry next time - vim.fn.delete(lazypath, 'rf') - error('Could not clone lazy.nvim. Check the URL above.') - end end --- 3. Verify and Load local checker = io.open(lazypath .. '/lua/lazy/init.lua', 'r') if checker then checker:close() @@ -266,9 +213,7 @@ else vim.fn.delete(lazypath, 'rf') error('FATAL: Downloaded folder is corrupted. Retrying next launch.') end --- ... rest of your setup ... --- 4. Environment Setup vim.opt.rtp:prepend(lazypath) package.path = package.path .. ';' .. lazypath .. '/lua/?.lua;' .. lazypath .. '/lua/?/init.lua' @@ -351,25 +296,66 @@ local plugins = { -- config = true is shorthand for config = function() require('bufferline').setup() end }, - { + -- { + -- 'nvim-neo-tree/neo-tree.nvim', + -- branch = 'v3.x', + -- dependencies = { + -- 'nvim-lua/plenary.nvim', + -- 'MunifTanjim/nui.nvim', + -- 'nvim-tree/nvim-web-devicons', -- optional, but recommended + -- }, + -- lazy = false, -- neo-tree will lazily load itself + -- opts = { + -- sources = { + -- 'filesystem', + -- 'buffers', + -- 'git_status', + -- 'document_symbols', -- Add this line + -- }, + -- }, + -- }, + + { 'nvim-neo-tree/neo-tree.nvim', branch = 'v3.x', dependencies = { 'nvim-lua/plenary.nvim', + 'nvim-tree/nvim-web-devicons', 'MunifTanjim/nui.nvim', - 'nvim-tree/nvim-web-devicons', -- optional, but recommended }, - lazy = false, -- neo-tree will lazily load itself opts = { - sources = { - 'filesystem', - 'buffers', - 'git_status', - 'document_symbols', -- Add this line + filesystem = { + filtered_items = { + never_show = { '.cache', '.git' }, + }, }, }, }, +} + +-- 4. Setup lazy.nvim +require('lazy').setup(plugins, { + root = vim.fn.stdpath("data") .. '/lazy', + install = { missing = true }, + ui = { border = 'rounded' }, +}) + +-- 5. Basic Minimal UI Settings +vim.opt.termguicolors = true +vim.opt.number = true +vim.opt.mouse = 'a' + +print("Minimal environment loaded in: " .. tmp_root) + +Use code with caution. +Why this is the correct "Complete" version: + XDG Variables: By setting XDG_DATA_HOME, you don't need to manually mkdir the nvim-data folder for Neo-tree; Neovim handles it. + Correct Git URL: It points to folke/lazy.nvim.git so the download actually works. + Package Path: It fixes the module 'lazy' not found error on Windows. + Conditional Loading: The PlatformIO plugin remains lazy/disabled until it sees the config file or you run :Pioinit. + +Does this version successfully download all plugins without any "module not found" or "log file" errors? -- { -- 'nvim-tree/nvim-tree.lua', -- -- version = '*', @@ -459,12 +445,18 @@ local plugins = { -- }) require('lazy').setup(plugins, { - root = data_dir .. [[/lazy]], -- Ensure plugins install in tmp - install = { - missing = true, - }, + root = vim.fn.stdpath("data") .. '/lazy', + install = { missing = true }, + ui = { border = 'rounded' }, }) +-- require('lazy').setup(plugins, { +-- root = data_dir .. [[/lazy]], -- Ensure plugins install in tmp +-- install = { +-- missing = true, +-- }, +-- }) + ---------------------------------------------------------------------------------------- -- stylua: ignore From b1c3fbcdbae7563acff769be858612064f26be11 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 22:53:47 +0300 Subject: [PATCH 1066/1406] update --- mini_nvimPlatformio.lua | 49 ++++++++++++++--------------------------- 1 file changed, 17 insertions(+), 32 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 8fd9e812..90cd2051 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -180,20 +180,20 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- }) -- end - local home = os.getenv('USERPROFILE') or os.getenv('HOME') local tmp_root = home:gsub('\\', '/') .. '/tmp/nvim-temp' -- Set environment variables so Neovim and plugins use the tmp folder automatically vim.env.XDG_CONFIG_HOME = tmp_root .. '/config' -vim.env.XDG_DATA_HOME = tmp_root .. '/data' -vim.env.XDG_CACHE_HOME = tmp_root .. '/cache' -vim.env.XDG_STATE_HOME = tmp_root .. '/state' +vim.env.XDG_DATA_HOME = tmp_root .. '/data' +vim.env.XDG_CACHE_HOME = tmp_root .. '/cache' +vim.env.XDG_STATE_HOME = tmp_root .. '/state' -local lazypath = vim.fn.stdpath("data") .. '/lazy/lazy.nvim' +local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' if not (vim.uv or vim.loop).fs_stat(lazypath) then --- if vim.fn.isdirectory(lazypath) == 0 then + -- if vim.fn.isdirectory(lazypath) == 0 then print('Attempting to download lazy.nvim...') + vim.fn.system({ 'git', 'clone', @@ -315,7 +315,7 @@ local plugins = { -- }, -- }, - { + { 'nvim-neo-tree/neo-tree.nvim', branch = 'v3.x', dependencies = { @@ -331,31 +331,16 @@ local plugins = { }, }, }, -} - --- 4. Setup lazy.nvim -require('lazy').setup(plugins, { - root = vim.fn.stdpath("data") .. '/lazy', - install = { missing = true }, - ui = { border = 'rounded' }, -}) - --- 5. Basic Minimal UI Settings -vim.opt.termguicolors = true -vim.opt.number = true -vim.opt.mouse = 'a' - -print("Minimal environment loaded in: " .. tmp_root) - -Use code with caution. -Why this is the correct "Complete" version: - - XDG Variables: By setting XDG_DATA_HOME, you don't need to manually mkdir the nvim-data folder for Neo-tree; Neovim handles it. - Correct Git URL: It points to folke/lazy.nvim.git so the download actually works. - Package Path: It fixes the module 'lazy' not found error on Windows. - Conditional Loading: The PlatformIO plugin remains lazy/disabled until it sees the config file or you run :Pioinit. -Does this version successfully download all plugins without any "module not found" or "log file" errors? + -- Use code with caution. + -- Why this is the correct "Complete" version: + -- + -- XDG Variables: By setting XDG_DATA_HOME, you don't need to manually mkdir the nvim-data folder for Neo-tree; Neovim handles it. + -- Correct Git URL: It points to folke/lazy.nvim.git so the download actually works. + -- Package Path: It fixes the module 'lazy' not found error on Windows. + -- Conditional Loading: The PlatformIO plugin remains lazy/disabled until it sees the config file or you run :Pioinit. + -- + -- Does this version successfully download all plugins without any "module not found" or "log file" errors? -- { -- 'nvim-tree/nvim-tree.lua', -- -- version = '*', @@ -445,7 +430,7 @@ Does this version successfully download all plugins without any "module not foun -- }) require('lazy').setup(plugins, { - root = vim.fn.stdpath("data") .. '/lazy', + root = vim.fn.stdpath('data') .. '/lazy', install = { missing = true }, ui = { border = 'rounded' }, }) From 633395d92443899ffcac57204ee48607c9912889 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 23:29:05 +0300 Subject: [PATCH 1067/1406] update --- mini_nvimPlatformio.lua | 132 +++------------------------------------- 1 file changed, 8 insertions(+), 124 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 90cd2051..f3ee8acd 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -161,39 +161,17 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) ---------------------------------------------------------------------------------------- -- INFO: Set mini lazy config -- pick a temp root --- local tmp = vim.loop.os_tmpdir() .. '/nvim-temp' --- vim.env.XDG_CONFIG_HOME = vim.fn.expand('~/.miniConfig') --- vim.env.XDG_DATA_HOME = tmp .. '/data' --- vim.env.XDG_CACHE_HOME = tmp .. '/cache' --- vim.env.XDG_STATE_HOME = tmp .. '/state' --- --- local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' --- --- if not (vim.uv or vim.loop).fs_stat(lazypath) then --- vim.fn.system({ --- 'git', --- 'clone', --- '--filter=blob:none', --- 'https://github.com/folke/lazy.nvim.git', --- '--branch=stable', --- lazypath, --- }) --- end - -local home = os.getenv('USERPROFILE') or os.getenv('HOME') -local tmp_root = home:gsub('\\', '/') .. '/tmp/nvim-temp' - --- Set environment variables so Neovim and plugins use the tmp folder automatically +local tmp_root = vim.loop.os_tmpdir():gsub('\\', '/') .. '/nvim-temp' vim.env.XDG_CONFIG_HOME = tmp_root .. '/config' vim.env.XDG_DATA_HOME = tmp_root .. '/data' vim.env.XDG_CACHE_HOME = tmp_root .. '/cache' vim.env.XDG_STATE_HOME = tmp_root .. '/state' -local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' +print(tmp_root) +local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' +-- local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' if not (vim.uv or vim.loop).fs_stat(lazypath) then - -- if vim.fn.isdirectory(lazypath) == 0 then print('Attempting to download lazy.nvim...') - vim.fn.system({ 'git', 'clone', @@ -221,6 +199,7 @@ package.path = package.path .. ';' .. lazypath .. '/lua/?.lua;' .. lazypath .. ' -- INFO: define plugins table local plugins = { { 'windwp/nvim-autopairs', event = 'InsertEnter', config = true }, + { 'Saghen/blink.cmp', dependencies = { 'rafamadriz/friendly-snippets' }, @@ -266,55 +245,6 @@ local plugins = { }, }, - { - -- 'akinsho/bufferline.nvim', - -- dependencies = 'nvim-tree/nvim-web-devicons', - -- config = function() - -- require('bufferline').setup({ - -- options = { - -- mode = 'buffers', -- set to "tabs" to only show standard vim tabs - -- separator_style = 'thin', -- options: "slant" | "slope" | "thick" | "thin" - -- always_show_bufferline = true, - -- show_buffer_close_icons = true, - -- show_close_icon = true, - -- color_icons = true, - -- - -- -- Add this if you use NvimTree or Neo-tree to prevent overlap - -- offsets = { - -- { - -- filetype = 'NvimTree', - -- text = 'File Explorer', - -- text_align = 'left', - -- separator = true, - -- }, - -- }, - -- }, - -- }) - -- require('bufferline').setup({}) - -- end, - -- config = true, - -- config = true is shorthand for config = function() require('bufferline').setup() end - }, - - -- { - -- 'nvim-neo-tree/neo-tree.nvim', - -- branch = 'v3.x', - -- dependencies = { - -- 'nvim-lua/plenary.nvim', - -- 'MunifTanjim/nui.nvim', - -- 'nvim-tree/nvim-web-devicons', -- optional, but recommended - -- }, - -- lazy = false, -- neo-tree will lazily load itself - -- opts = { - -- sources = { - -- 'filesystem', - -- 'buffers', - -- 'git_status', - -- 'document_symbols', -- Add this line - -- }, - -- }, - -- }, - { 'nvim-neo-tree/neo-tree.nvim', branch = 'v3.x', @@ -332,38 +262,6 @@ local plugins = { }, }, - -- Use code with caution. - -- Why this is the correct "Complete" version: - -- - -- XDG Variables: By setting XDG_DATA_HOME, you don't need to manually mkdir the nvim-data folder for Neo-tree; Neovim handles it. - -- Correct Git URL: It points to folke/lazy.nvim.git so the download actually works. - -- Package Path: It fixes the module 'lazy' not found error on Windows. - -- Conditional Loading: The PlatformIO plugin remains lazy/disabled until it sees the config file or you run :Pioinit. - -- - -- Does this version successfully download all plugins without any "module not found" or "log file" errors? - -- { - -- 'nvim-tree/nvim-tree.lua', - -- -- version = '*', - -- lazy = false, - -- dependencies = 'nvim-tree/nvim-web-devicons', - -- config = function() - -- require('nvim-tree').setup({ - -- filesystem_watchers = { - -- ignore_dirs = { - -- '/.cache', -- Ignores clangd's heavy index folder - -- '/.pio', -- Ignores pio heavy index folder - -- '/node_modules', -- Good practice for performance - -- '/.git', - -- }, - -- }, - -- -- Optional: If you also want to hide it from the tree view entirely - -- -- filters = { - -- -- custom = { '^\\.cache$', '^\\.pio$' }, - -- -- }, - -- }) - -- end, - -- }, - { 'batoaqaa/nvim-platformio.lua', cond = function() @@ -423,30 +321,15 @@ local plugins = { ---------------------------------------------------------------------------------------- -- INFO: Install/config plugins --- require('lazy').setup(plugins, { --- install = { --- missing = true, --- }, --- }) - require('lazy').setup(plugins, { root = vim.fn.stdpath('data') .. '/lazy', install = { missing = true }, ui = { border = 'rounded' }, }) --- require('lazy').setup(plugins, { --- root = data_dir .. [[/lazy]], -- Ensure plugins install in tmp --- install = { --- missing = true, --- }, --- }) - ---------------------------------------------------------------------------------------- - -- stylua: ignore if vim.fn.has('nvim-0.11') == 1 then - -- Create an augroup to manage the autocmd local json_format_group = vim.api.nvim_create_augroup('JsonFormat', { clear = true }) vim.api.nvim_create_autocmd('BufWritePre', { group = json_format_group, @@ -643,9 +526,10 @@ if tok then previewer = false, })) end, { desc = '[/] Fuzzily search in current buffer' }) + -- Keymap to open the buffer list + vim.keymap.set('n', 'fb', 'Telescope buffers', { desc = 'Find Buffers' }) end --- Keymap to open the buffer list -vim.keymap.set('n', 'fb', 'Telescope buffers', { desc = 'Find Buffers' }) + local pioConfig = { lspClangd = { -- enabled = false, From 7a80ca42be70b35f1cb7810e3dfafd541e88ffef Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 23:36:02 +0300 Subject: [PATCH 1068/1406] update --- lua/platformio/pioinit2.lua | 43 ++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pioinit2.lua b/lua/platformio/pioinit2.lua index 452e3958..ed9c9300 100644 --- a/lua/platformio/pioinit2.lua +++ b/lua/platformio/pioinit2.lua @@ -97,10 +97,52 @@ local function pick_framework(board_details) end -- STEP 2: Board (with Buffer Previewer) +-- local function pick_board(json_data) +-- pickers +-- .new({}, { +-- prompt_title = 'Select Board', +-- finder = finders.new_table({ +-- results = json_data, +-- entry_maker = function(entry) +-- return { +-- value = entry, +-- display = entry.name or entry.id, +-- ordinal = (entry.name or '') .. ' ' .. (entry.id or ''), +-- } +-- end, +-- }), +-- previewer = previewers.new_buffer_previewer({ +-- title = 'Board Details', +-- define_preview = function(self, entry) +-- local content = vim.split(vim.inspect(entry.value), '\n') +-- vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, content) +-- vim.api.nvim_set_option_value('filetype', 'lua', { buf = self.state.bufnr }) +-- end, +-- }), +-- sorter = telescope_conf.generic_sorter({}), +-- attach_mappings = function(prompt_bufnr) +-- actions.select_default:replace(function() +-- local selection = action_state.get_selected_entry() +-- actions.close(prompt_bufnr) +-- wizard_data.board_id = selection.value.id +-- pick_framework(selection.value) -- Next step +-- end) +-- return true +-- end, +-- }) +-- :find() +-- end + local function pick_board(json_data) pickers .new({}, { prompt_title = 'Select Board', + -- Define the layout behavior + layout_strategy = 'horizontal', + layout_config = { + width = 0.9, -- Overall width of the Telescope window (90% of screen) + preview_width = 0.75, -- 75% of the window goes to "Board Details", leaving 25% for results + }, finder = finders.new_table({ results = json_data, entry_maker = function(entry) @@ -132,7 +174,6 @@ local function pick_board(json_data) }) :find() end - -- STEP 1: IDE (True/False) local function start_pio_wizard(json_data) local opts = require('telescope.themes').get_dropdown({ From 181d3f4c74b6fbfdc5a52616292ae974f059b09c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 23:38:41 +0300 Subject: [PATCH 1069/1406] update --- lua/platformio/pioinit2.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pioinit2.lua b/lua/platformio/pioinit2.lua index ed9c9300..678f1b4b 100644 --- a/lua/platformio/pioinit2.lua +++ b/lua/platformio/pioinit2.lua @@ -141,7 +141,7 @@ local function pick_board(json_data) layout_strategy = 'horizontal', layout_config = { width = 0.9, -- Overall width of the Telescope window (90% of screen) - preview_width = 0.75, -- 75% of the window goes to "Board Details", leaving 25% for results + preview_width = 0.65, -- 65% of the window goes to "Board Details", leaving 25% for results }, finder = finders.new_table({ results = json_data, @@ -174,6 +174,7 @@ local function pick_board(json_data) }) :find() end + -- STEP 1: IDE (True/False) local function start_pio_wizard(json_data) local opts = require('telescope.themes').get_dropdown({ From 949275bf073ffc129244a707eaee9b125c7e0f44 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 23:44:28 +0300 Subject: [PATCH 1070/1406] update --- mini_nvimPlatformio.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index f3ee8acd..30a85a38 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -255,6 +255,8 @@ local plugins = { }, opts = { filesystem = { + hijack_netrw_behavior = 'open_default', + use_libuv_file_watcher = false, -- This will use the OS level file watchers to detect changes filtered_items = { never_show = { '.cache', '.git' }, }, From 13521e0ce65df7cbe6574032764940a85b847826 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 23:47:01 +0300 Subject: [PATCH 1071/1406] update --- mini_nvimPlatformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 30a85a38..19491c9e 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -256,7 +256,7 @@ local plugins = { opts = { filesystem = { hijack_netrw_behavior = 'open_default', - use_libuv_file_watcher = false, -- This will use the OS level file watchers to detect changes + use_libuv_file_watcher = true, -- This will use the OS level file watchers to detect changes filtered_items = { never_show = { '.cache', '.git' }, }, From 0847629e797fbef41bf38dd67e72299b4c81be9f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 23:53:46 +0300 Subject: [PATCH 1072/1406] update --- mini_nvimPlatformio.lua | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 19491c9e..a8bcf5a1 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -255,12 +255,26 @@ local plugins = { }, opts = { filesystem = { - hijack_netrw_behavior = 'open_default', - use_libuv_file_watcher = true, -- This will use the OS level file watchers to detect changes + use_libuv_file_watcher = true, filtered_items = { - never_show = { '.cache', '.git' }, + hide_dotfiles = false, + hide_gitignored = true, + never_show = { -- Add any massive folders here + '.cache', + '.git', + 'node_modules', + 'build', + 'target', + }, }, }, + -- filesystem = { + -- hijack_netrw_behavior = 'open_default', + -- use_libuv_file_watcher = true, -- This will use the OS level file watchers to detect changes + -- filtered_items = { + -- never_show = { '.cache', '.git', '.pio' }, + -- }, + -- }, }, }, From 12215ef34b2a1574a006ae709e996489f481a444 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 26 Apr 2026 23:58:38 +0300 Subject: [PATCH 1073/1406] update --- lua/platformio/pioinit2.lua | 36 ------------------------------------ lua/platformio/piolib.lua | 4 ++++ 2 files changed, 4 insertions(+), 36 deletions(-) diff --git a/lua/platformio/pioinit2.lua b/lua/platformio/pioinit2.lua index 678f1b4b..d08f07a8 100644 --- a/lua/platformio/pioinit2.lua +++ b/lua/platformio/pioinit2.lua @@ -97,42 +97,6 @@ local function pick_framework(board_details) end -- STEP 2: Board (with Buffer Previewer) --- local function pick_board(json_data) --- pickers --- .new({}, { --- prompt_title = 'Select Board', --- finder = finders.new_table({ --- results = json_data, --- entry_maker = function(entry) --- return { --- value = entry, --- display = entry.name or entry.id, --- ordinal = (entry.name or '') .. ' ' .. (entry.id or ''), --- } --- end, --- }), --- previewer = previewers.new_buffer_previewer({ --- title = 'Board Details', --- define_preview = function(self, entry) --- local content = vim.split(vim.inspect(entry.value), '\n') --- vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, content) --- vim.api.nvim_set_option_value('filetype', 'lua', { buf = self.state.bufnr }) --- end, --- }), --- sorter = telescope_conf.generic_sorter({}), --- attach_mappings = function(prompt_bufnr) --- actions.select_default:replace(function() --- local selection = action_state.get_selected_entry() --- actions.close(prompt_bufnr) --- wizard_data.board_id = selection.value.id --- pick_framework(selection.value) -- Next step --- end) --- return true --- end, --- }) --- :find() --- end - local function pick_board(json_data) pickers .new({}, { diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 735679fc..8cb3845e 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -48,6 +48,10 @@ local function pick_library(json_data) local opts = {} pickers.new(opts, { prompt_title = 'Libraries', + layout_config = { + width = 0.9, -- Overall width of the Telescope window (90% of screen) + preview_width = 0.60, -- 65% of the window goes to "Board Details", leaving 25% for results + }, finder = finders.new_table({ results = json_data['items'], entry_maker = opts.entry_maker or libentry_maker(opts), From 8a46c7422c47f23293278d0cd0cba1c5ae4a516a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 00:07:22 +0300 Subject: [PATCH 1074/1406] update --- lua/platformio/piolib.lua | 99 ++++++++++++++++++++++++++++++++++----- mini_nvimPlatformio.lua | 1 - 2 files changed, 86 insertions(+), 14 deletions(-) diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 8cb3845e..09c2e679 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -44,25 +44,98 @@ local libentry_maker = function(opts) end -- stylua: ignore +-- local function pick_library(json_data) +-- local opts = {} +-- pickers.new(opts, { +-- prompt_title = 'Libraries', +-- layout_config = { +-- width = 0.9, -- Overall width of the Telescope window (90% of screen) +-- preview_width = 0.60, -- 65% of the window goes to "Board Details", leaving 25% for results +-- }, +-- finder = finders.new_table({ +-- results = json_data['items'], +-- entry_maker = opts.entry_maker or libentry_maker(opts), +-- }), +-- attach_mappings = function(prompt_bufnr, _) +-- actions.select_default:replace(function() +-- actions.close(prompt_bufnr) +-- local selection = action_state.get_selected_entry() +-- local pkg_name = selection['value']['owner'] .. '/' .. selection['value']['name'] +-- -- local command = 'pio pkg install --library "' .. pkg_name .. '"' +-- -- command = command .. ' && pio run -t compiledb' +-- +-- local pio = require('platformio.utils.pio') +-- pio.run_sequence({ +-- { +-- cmnds = {'pio pkg install --library "' .. pkg_name .. '"'}, +-- cb = function () vim.notify('Piolib: Done', vim.log.levels.INFO) end +-- }, +-- }) +-- end) +-- return true +-- end, +-- +-- previewer = previewers.new_buffer_previewer({ +-- title = 'Package Info', +-- define_preview = function(self, entry, _) +-- local json = misc.strsplit(vim.inspect(entry['value']['data']), '\n') +-- local bufnr = self.state.bufnr +-- vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) +-- vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function +-- vim.defer_fn(function() +-- local win = self.state.winid +-- vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) +-- vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) +-- vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) +-- end, 0) +-- end, +-- }), +-- sorter = conf.generic_sorter(opts), +-- }):find() +-- end + local function pick_library(json_data) local opts = {} + + -- 1. Create a displayer for exactly 2 columns + local displayer = entry_display.create({ + separator = " │ ", + items = { + { width = 25 }, -- Column 1: Owner (fixed width) + { remaining = true }, -- Column 2: Library Name + }, + }) + + -- 2. Define the display logic for each row + local make_display = function(entry) + return displayer({ + { entry.value.owner or "unknown", "TelescopeResultsVariable" }, + entry.value.name or "unnamed", + }) + end + pickers.new(opts, { prompt_title = 'Libraries', layout_config = { - width = 0.9, -- Overall width of the Telescope window (90% of screen) - preview_width = 0.60, -- 65% of the window goes to "Board Details", leaving 25% for results + width = 0.9, -- Overall width (90%) + preview_width = 0.60, -- Wider preview (60%) }, finder = finders.new_table({ results = json_data['items'], - entry_maker = opts.entry_maker or libentry_maker(opts), + entry_maker = function(entry) + return { + value = entry, + display = make_display, + -- Ordinal is used for searching/filtering + ordinal = (entry.owner or '') .. ' ' .. (entry.name or ''), + } + end, }), attach_mappings = function(prompt_bufnr, _) actions.select_default:replace(function() actions.close(prompt_bufnr) local selection = action_state.get_selected_entry() local pkg_name = selection['value']['owner'] .. '/' .. selection['value']['name'] - -- local command = 'pio pkg install --library "' .. pkg_name .. '"' - -- command = command .. ' && pio run -t compiledb' local pio = require('platformio.utils.pio') pio.run_sequence({ @@ -78,16 +151,16 @@ local function pick_library(json_data) previewer = previewers.new_buffer_previewer({ title = 'Package Info', define_preview = function(self, entry, _) - local json = misc.strsplit(vim.inspect(entry['value']['data']), '\n') + local json = misc.strsplit(vim.inspect(entry['value']['data'] or entry['value']), '\n') local bufnr = self.state.bufnr + local win = self.state.winid + vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) - vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function - vim.defer_fn(function() - local win = self.state.winid - vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) - vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) - vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) - end, 0) + vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) + + -- Apply wrapping to make the wide preview readable + vim.api.nvim_set_option_value('wrap', true, { win = win }) + vim.api.nvim_set_option_value('linebreak', true, { win = win }) end, }), sorter = conf.generic_sorter(opts), diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index a8bcf5a1..233e0937 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -167,7 +167,6 @@ vim.env.XDG_DATA_HOME = tmp_root .. '/data' vim.env.XDG_CACHE_HOME = tmp_root .. '/cache' vim.env.XDG_STATE_HOME = tmp_root .. '/state' -print(tmp_root) local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' -- local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' if not (vim.uv or vim.loop).fs_stat(lazypath) then From 2412e8ad7d6e8f1439fd7e6792290c15f13a87f0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 00:16:12 +0300 Subject: [PATCH 1075/1406] update --- lua/platformio/piolib.lua | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 09c2e679..6bb91574 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -120,17 +120,33 @@ local function pick_library(json_data) width = 0.9, -- Overall width (90%) preview_width = 0.60, -- Wider preview (60%) }, + finder = finders.new_table({ results = json_data['items'], entry_maker = function(entry) + -- Safe string conversion to prevent "concatenate table" errors + local owner = type(entry.owner) == "string" and entry.owner or tostring(entry.owner or "") + local name = type(entry.name) == "string" and entry.name or tostring(entry.name or "") + return { value = entry, display = make_display, - -- Ordinal is used for searching/filtering - ordinal = (entry.owner or '') .. ' ' .. (entry.name or ''), + ordinal = owner .. ' ' .. name, } end, }), + + -- finder = finders.new_table({ + -- results = json_data['items'], + -- entry_maker = function(entry) + -- return { + -- value = entry, + -- display = make_display, + -- -- Ordinal is used for searching/filtering + -- ordinal = (entry.owner or '') .. ' ' .. (entry.name or ''), + -- } + -- end, + -- }), attach_mappings = function(prompt_bufnr, _) actions.select_default:replace(function() actions.close(prompt_bufnr) From b4237b644cc86d17f61418c5bd3f84e67018381a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 00:19:08 +0300 Subject: [PATCH 1076/1406] update --- lua/platformio/piolib.lua | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 6bb91574..e8f3f9cb 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -147,17 +147,41 @@ local function pick_library(json_data) -- } -- end, -- }), + -- attach_mappings = function(prompt_bufnr, _) + -- actions.select_default:replace(function() + -- actions.close(prompt_bufnr) + -- local selection = action_state.get_selected_entry() + -- local pkg_name = selection['value']['owner'] .. '/' .. selection['value']['name'] + -- + -- local pio = require('platformio.utils.pio') + -- pio.run_sequence({ + -- { + -- cmnds = {'pio pkg install --library "' .. pkg_name .. '"'}, + -- cb = function () vim.notify('Piolib: Done', vim.log.levels.INFO) end + -- }, + -- }) + -- end) + -- return true + -- end, + attach_mappings = function(prompt_bufnr, _) actions.select_default:replace(function() - actions.close(prompt_bufnr) local selection = action_state.get_selected_entry() - local pkg_name = selection['value']['owner'] .. '/' .. selection['value']['name'] + actions.close(prompt_bufnr) + + -- SAFE EXTRACTION: + -- Check if owner is a table (like {name = "xxx", ...}) or just a string + local owner = selection.value.owner + local owner_name = type(owner) == "table" and (owner.name or owner.username) or tostring(owner) + local lib_name = tostring(selection.value.name) + + local pkg_name = owner_name .. '/' .. lib_name local pio = require('platformio.utils.pio') pio.run_sequence({ { cmnds = {'pio pkg install --library "' .. pkg_name .. '"'}, - cb = function () vim.notify('Piolib: Done', vim.log.levels.INFO) end + cb = function () vim.notify('Piolib: Done installing ' .. pkg_name, vim.log.levels.INFO) end }, }) end) From 4b23c675f346de2872c67cd752fe26945337cb63 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 00:22:36 +0300 Subject: [PATCH 1077/1406] update --- lua/platformio/piolib.lua | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index e8f3f9cb..65607436 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -168,20 +168,19 @@ local function pick_library(json_data) actions.select_default:replace(function() local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) - - -- SAFE EXTRACTION: - -- Check if owner is a table (like {name = "xxx", ...}) or just a string + + -- Fix the table concatenation first local owner = selection.value.owner local owner_name = type(owner) == "table" and (owner.name or owner.username) or tostring(owner) local lib_name = tostring(selection.value.name) - local pkg_name = owner_name .. '/' .. lib_name local pio = require('platformio.utils.pio') pio.run_sequence({ { - cmnds = {'pio pkg install --library "' .. pkg_name .. '"'}, - cb = function () vim.notify('Piolib: Done installing ' .. pkg_name, vim.log.levels.INFO) end + -- CHANGE 'cmnds' to 'cmds' + cmds = {'pio pkg install --library "' .. pkg_name .. '"'}, + cb = function () vim.notify('Piolib: Done', vim.log.levels.INFO) end }, }) end) From 0d9af0d025f9504b282fe4a7becf6c2da3ccf521 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 00:25:58 +0300 Subject: [PATCH 1078/1406] update --- lua/platformio/piolib.lua | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 65607436..90f60966 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -168,25 +168,28 @@ local function pick_library(json_data) actions.select_default:replace(function() local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) - - -- Fix the table concatenation first + + -- 1. Safe string extraction for pkg_name local owner = selection.value.owner local owner_name = type(owner) == "table" and (owner.name or owner.username) or tostring(owner) local lib_name = tostring(selection.value.name) local pkg_name = owner_name .. '/' .. lib_name + -- 2. Execute with the correct key 'cmd' local pio = require('platformio.utils.pio') pio.run_sequence({ { - -- CHANGE 'cmnds' to 'cmds' - cmds = {'pio pkg install --library "' .. pkg_name .. '"'}, - cb = function () vim.notify('Piolib: Done', vim.log.levels.INFO) end + -- Use 'cmd' (singular), not 'cmds' or 'cmnds' + cmd = {'pio pkg install --library "' .. pkg_name .. '"'}, + cb = function () + vim.notify('Piolib: Done installing ' .. pkg_name, vim.log.levels.INFO) + end }, }) end) return true end, - + -- previewer = previewers.new_buffer_previewer({ title = 'Package Info', define_preview = function(self, entry, _) From 498250c1993f30095e62b10482e1a2d60989e3bc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 00:31:37 +0300 Subject: [PATCH 1079/1406] update --- lua/platformio/piolib.lua | 6 +++--- lua/platformio/utils/pio.lua | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 90f60966..3ba39ac8 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -180,9 +180,9 @@ local function pick_library(json_data) pio.run_sequence({ { -- Use 'cmd' (singular), not 'cmds' or 'cmnds' - cmd = {'pio pkg install --library "' .. pkg_name .. '"'}, - cb = function () - vim.notify('Piolib: Done installing ' .. pkg_name, vim.log.levels.INFO) + cmnds = {'pio pkg install --library "' .. pkg_name .. '"'}, + cb = function () + vim.notify('Piolib: Done installing ' .. pkg_name, vim.log.levels.INFO) end }, }) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 33ede1ab..8cb0e111 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -130,7 +130,7 @@ M.run_sequence = function(tasks) M.queue = {} callBack = tasks.cb -- 1. Save the callback in a local variable local commands = tasks.cmnds - + local done = ' && echo _CMMNDS_":"DONE' local pass = ' && echo _CMMNDS_":"PASS' local fail = ' || echo _CMMNDS_":"FAIL' From 0fad8fc05bb256fb311e7df35121f25aae73e456 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 00:35:54 +0300 Subject: [PATCH 1080/1406] update --- lua/platformio/piolib.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 3ba39ac8..0888a994 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -180,7 +180,7 @@ local function pick_library(json_data) pio.run_sequence({ { -- Use 'cmd' (singular), not 'cmds' or 'cmnds' - cmnds = {'pio pkg install --library "' .. pkg_name .. '"'}, + cmnds = {'pio pkg install --library "' .. pkg_name .. '"',}, cb = function () vim.notify('Piolib: Done installing ' .. pkg_name, vim.log.levels.INFO) end From 078a9964aebcafe73f6e2cca8a8cd36ca5eacbf4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 04:11:39 +0300 Subject: [PATCH 1081/1406] update --- lua/platformio/piolib.lua | 2 -- 1 file changed, 2 deletions(-) diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 0888a994..9ad4a9c2 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -178,13 +178,11 @@ local function pick_library(json_data) -- 2. Execute with the correct key 'cmd' local pio = require('platformio.utils.pio') pio.run_sequence({ - { -- Use 'cmd' (singular), not 'cmds' or 'cmnds' cmnds = {'pio pkg install --library "' .. pkg_name .. '"',}, cb = function () vim.notify('Piolib: Done installing ' .. pkg_name, vim.log.levels.INFO) end - }, }) end) return true From 983ec4a2c1e250faf7a04c629980024e4561d07f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 04:46:39 +0300 Subject: [PATCH 1082/1406] update --- lua/platformio/piolib.lua | 55 ++++++--------------------------------- 1 file changed, 8 insertions(+), 47 deletions(-) diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 9ad4a9c2..8e7bd7de 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -121,72 +121,33 @@ local function pick_library(json_data) preview_width = 0.60, -- Wider preview (60%) }, + finder = finders.new_table({ results = json_data['items'], entry_maker = function(entry) - -- Safe string conversion to prevent "concatenate table" errors - local owner = type(entry.owner) == "string" and entry.owner or tostring(entry.owner or "") - local name = type(entry.name) == "string" and entry.name or tostring(entry.name or "") - return { value = entry, display = make_display, - ordinal = owner .. ' ' .. name, + -- Ordinal is used for searching/filtering + ordinal = (entry.owner or '') .. ' ' .. (entry.name or ''), } end, }), - - -- finder = finders.new_table({ - -- results = json_data['items'], - -- entry_maker = function(entry) - -- return { - -- value = entry, - -- display = make_display, - -- -- Ordinal is used for searching/filtering - -- ordinal = (entry.owner or '') .. ' ' .. (entry.name or ''), - -- } - -- end, - -- }), - -- attach_mappings = function(prompt_bufnr, _) - -- actions.select_default:replace(function() - -- actions.close(prompt_bufnr) - -- local selection = action_state.get_selected_entry() - -- local pkg_name = selection['value']['owner'] .. '/' .. selection['value']['name'] - -- - -- local pio = require('platformio.utils.pio') - -- pio.run_sequence({ - -- { - -- cmnds = {'pio pkg install --library "' .. pkg_name .. '"'}, - -- cb = function () vim.notify('Piolib: Done', vim.log.levels.INFO) end - -- }, - -- }) - -- end) - -- return true - -- end, - attach_mappings = function(prompt_bufnr, _) actions.select_default:replace(function() - local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) + local selection = action_state.get_selected_entry() + local pkg_name = selection['value']['owner'] .. '/' .. selection['value']['name'] - -- 1. Safe string extraction for pkg_name - local owner = selection.value.owner - local owner_name = type(owner) == "table" and (owner.name or owner.username) or tostring(owner) - local lib_name = tostring(selection.value.name) - local pkg_name = owner_name .. '/' .. lib_name - - -- 2. Execute with the correct key 'cmd' local pio = require('platformio.utils.pio') pio.run_sequence({ - -- Use 'cmd' (singular), not 'cmds' or 'cmnds' - cmnds = {'pio pkg install --library "' .. pkg_name .. '"',}, - cb = function () - vim.notify('Piolib: Done installing ' .. pkg_name, vim.log.levels.INFO) - end + cmnds = {'pio pkg install --library "' .. pkg_name .. '"'}, + cb = function () vim.notify('Piolib: Done', vim.log.levels.INFO) end }) end) return true end, + -- previewer = previewers.new_buffer_previewer({ title = 'Package Info', From 9f6fd1a5d48ca2bfd4113af2339b4cfe57f318ab Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 04:51:54 +0300 Subject: [PATCH 1083/1406] update --- lua/platformio/piolib.lua | 178 +++++++++++++++++++------------------- 1 file changed, 89 insertions(+), 89 deletions(-) diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 8e7bd7de..e1bd1945 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -44,130 +44,130 @@ local libentry_maker = function(opts) end -- stylua: ignore --- local function pick_library(json_data) --- local opts = {} --- pickers.new(opts, { --- prompt_title = 'Libraries', --- layout_config = { --- width = 0.9, -- Overall width of the Telescope window (90% of screen) --- preview_width = 0.60, -- 65% of the window goes to "Board Details", leaving 25% for results --- }, --- finder = finders.new_table({ --- results = json_data['items'], --- entry_maker = opts.entry_maker or libentry_maker(opts), --- }), --- attach_mappings = function(prompt_bufnr, _) --- actions.select_default:replace(function() --- actions.close(prompt_bufnr) --- local selection = action_state.get_selected_entry() --- local pkg_name = selection['value']['owner'] .. '/' .. selection['value']['name'] --- -- local command = 'pio pkg install --library "' .. pkg_name .. '"' --- -- command = command .. ' && pio run -t compiledb' --- --- local pio = require('platformio.utils.pio') --- pio.run_sequence({ --- { --- cmnds = {'pio pkg install --library "' .. pkg_name .. '"'}, --- cb = function () vim.notify('Piolib: Done', vim.log.levels.INFO) end --- }, --- }) --- end) --- return true --- end, --- --- previewer = previewers.new_buffer_previewer({ --- title = 'Package Info', --- define_preview = function(self, entry, _) --- local json = misc.strsplit(vim.inspect(entry['value']['data']), '\n') --- local bufnr = self.state.bufnr --- vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) --- vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function --- vim.defer_fn(function() --- local win = self.state.winid --- vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) --- vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) --- vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) --- end, 0) --- end, --- }), --- sorter = conf.generic_sorter(opts), --- }):find() --- end - local function pick_library(json_data) local opts = {} - - -- 1. Create a displayer for exactly 2 columns - local displayer = entry_display.create({ - separator = " │ ", - items = { - { width = 25 }, -- Column 1: Owner (fixed width) - { remaining = true }, -- Column 2: Library Name - }, - }) - - -- 2. Define the display logic for each row - local make_display = function(entry) - return displayer({ - { entry.value.owner or "unknown", "TelescopeResultsVariable" }, - entry.value.name or "unnamed", - }) - end - pickers.new(opts, { prompt_title = 'Libraries', layout_config = { - width = 0.9, -- Overall width (90%) - preview_width = 0.60, -- Wider preview (60%) + width = 0.9, -- Overall width of the Telescope window (90% of screen) + preview_width = 0.60, -- 65% of the window goes to "Board Details", leaving 25% for results }, - - finder = finders.new_table({ results = json_data['items'], - entry_maker = function(entry) - return { - value = entry, - display = make_display, - -- Ordinal is used for searching/filtering - ordinal = (entry.owner or '') .. ' ' .. (entry.name or ''), - } - end, + entry_maker = opts.entry_maker or libentry_maker(opts), }), attach_mappings = function(prompt_bufnr, _) actions.select_default:replace(function() actions.close(prompt_bufnr) local selection = action_state.get_selected_entry() local pkg_name = selection['value']['owner'] .. '/' .. selection['value']['name'] + -- local command = 'pio pkg install --library "' .. pkg_name .. '"' + -- command = command .. ' && pio run -t compiledb' local pio = require('platformio.utils.pio') pio.run_sequence({ + { cmnds = {'pio pkg install --library "' .. pkg_name .. '"'}, cb = function () vim.notify('Piolib: Done', vim.log.levels.INFO) end + }, }) end) return true end, - -- previewer = previewers.new_buffer_previewer({ title = 'Package Info', define_preview = function(self, entry, _) - local json = misc.strsplit(vim.inspect(entry['value']['data'] or entry['value']), '\n') + local json = misc.strsplit(vim.inspect(entry['value']['data']), '\n') local bufnr = self.state.bufnr - local win = self.state.winid - vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) - vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) - - -- Apply wrapping to make the wide preview readable - vim.api.nvim_set_option_value('wrap', true, { win = win }) - vim.api.nvim_set_option_value('linebreak', true, { win = win }) + vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function + vim.defer_fn(function() + local win = self.state.winid + vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) + vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) + vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) + end, 0) end, }), sorter = conf.generic_sorter(opts), }):find() end +-- local function pick_library(json_data) +-- local opts = {} +-- +-- -- 1. Create a displayer for exactly 2 columns +-- local displayer = entry_display.create({ +-- separator = " │ ", +-- items = { +-- { width = 25 }, -- Column 1: Owner (fixed width) +-- { remaining = true }, -- Column 2: Library Name +-- }, +-- }) +-- +-- -- 2. Define the display logic for each row +-- local make_display = function(entry) +-- return displayer({ +-- { entry.value.owner or "unknown", "TelescopeResultsVariable" }, +-- entry.value.name or "unnamed", +-- }) +-- end +-- +-- pickers.new(opts, { +-- prompt_title = 'Libraries', +-- layout_config = { +-- width = 0.9, -- Overall width (90%) +-- preview_width = 0.60, -- Wider preview (60%) +-- }, +-- +-- +-- finder = finders.new_table({ +-- results = json_data['items'], +-- entry_maker = function(entry) +-- return { +-- value = entry, +-- display = make_display, +-- -- Ordinal is used for searching/filtering +-- ordinal = (entry.owner or '') .. ' ' .. (entry.name or ''), +-- } +-- end, +-- }), +-- attach_mappings = function(prompt_bufnr, _) +-- actions.select_default:replace(function() +-- actions.close(prompt_bufnr) +-- local selection = action_state.get_selected_entry() +-- local pkg_name = selection['value']['owner'] .. '/' .. selection['value']['name'] +-- +-- local pio = require('platformio.utils.pio') +-- pio.run_sequence({ +-- cmnds = {'pio pkg install --library "' .. pkg_name .. '"'}, +-- cb = function () vim.notify('Piolib: Done', vim.log.levels.INFO) end +-- }) +-- end) +-- return true +-- end, +-- +-- -- +-- previewer = previewers.new_buffer_previewer({ +-- title = 'Package Info', +-- define_preview = function(self, entry, _) +-- local json = misc.strsplit(vim.inspect(entry['value']['data'] or entry['value']), '\n') +-- local bufnr = self.state.bufnr +-- local win = self.state.winid +-- +-- vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) +-- vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) +-- +-- -- Apply wrapping to make the wide preview readable +-- vim.api.nvim_set_option_value('wrap', true, { win = win }) +-- vim.api.nvim_set_option_value('linebreak', true, { win = win }) +-- end, +-- }), +-- sorter = conf.generic_sorter(opts), +-- }):find() +-- end + function M.piolib(lib_arg_list) if not misc.pio_install_check() then return From 8acb6e113d311702f04389914695b5a80c95b325 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 05:05:57 +0300 Subject: [PATCH 1084/1406] update --- lua/platformio/piolib.lua | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index e1bd1945..5dc8cd12 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -15,8 +15,8 @@ local libentry_maker = function(opts) local displayer = entry_display.create({ separator = '▏', items = { - { width = 20 }, - { width = 20 }, + { width = 50 }, + { width = 50 }, { remaining = true }, }, }) @@ -66,10 +66,9 @@ local function pick_library(json_data) local pio = require('platformio.utils.pio') pio.run_sequence({ - { cmnds = {'pio pkg install --library "' .. pkg_name .. '"'}, - cb = function () vim.notify('Piolib: Done', vim.log.levels.INFO) end - }, + cb = pio.handlePiolib + --function () vim.notify('Piolib: Done', vim.log.levels.INFO) end }) end) return true From 8b5aaf8c9f23202fd790762eb8a695c37a7f49d9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 05:23:02 +0300 Subject: [PATCH 1085/1406] update --- lua/platformio/piolib.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 5dc8cd12..46ce0ef3 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -66,7 +66,7 @@ local function pick_library(json_data) local pio = require('platformio.utils.pio') pio.run_sequence({ - cmnds = {'pio pkg install --library "' .. pkg_name .. '"'}, + cmnds = {'pio pkg install --library "' .. pkg_name .. '" --no-save'}, cb = pio.handlePiolib --function () vim.notify('Piolib: Done', vim.log.levels.INFO) end }) From efa6046199bd02bc7abc0d006da84b592a026ef0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 05:39:02 +0300 Subject: [PATCH 1086/1406] update --- lua/platformio/boilerplate.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index d82851cf..8dfc6744 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -31,6 +31,7 @@ boilerplate['platformio.ini'] = { core_dir = %s platforms_dir = ${platformio.core_dir}/platforms packages_dir = ${platformio.core_dir}/packages +libdeps_dir = ./external_libs default_envs = ;default_envs = uno, nodemcu From 505d0e6bb3e4d6b610b9f2b3874d83d35c412201 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 05:43:18 +0300 Subject: [PATCH 1087/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index ab916e8e..a182bdc3 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -492,7 +492,6 @@ function M.init() -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) boilerplate.core_dir = _G.metadata.core_dir - -- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) --------------------------------------------------------------------------------- -- M.run_compiledb() -- Smart: Auto-update DB if config changes @@ -500,6 +499,7 @@ function M.init() -- vim.schedule(function() -- lsp_restart('clangd') -- end) + boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) end) end end From df268c84f8535d0f40ff68003ae583c65b05d07c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 05:48:14 +0300 Subject: [PATCH 1088/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index a182bdc3..81b3b5d6 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -493,13 +493,13 @@ function M.init() -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) boilerplate.core_dir = _G.metadata.core_dir boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) + boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) --------------------------------------------------------------------------------- -- M.run_compiledb() -- Smart: Auto-update DB if config changes M.pio_refresh(function() -- vim.schedule(function() -- lsp_restart('clangd') -- end) - boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) end) end end From 28da8953e5e9843120169fab6afa8cc9bd112279 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 06:27:47 +0300 Subject: [PATCH 1089/1406] update --- lua/platformio/pio_setup.lua | 2 +- lua/platformio/utils/pio.lua | 73 +++++++++++++++--------------------- 2 files changed, 31 insertions(+), 44 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 81b3b5d6..dd27a572 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -483,6 +483,7 @@ function M.init() -- M.start_pio_watcher() M.start_watchers() + -- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) -- If the file already exists, do an initial sync if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then ---------------------------------------------------------------------------------------- @@ -493,7 +494,6 @@ function M.init() -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) boilerplate.core_dir = _G.metadata.core_dir boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) - boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) --------------------------------------------------------------------------------- -- M.run_compiledb() -- Smart: Auto-update DB if config changes M.pio_refresh(function() diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 8cb0e111..e0c52c4a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -123,12 +123,12 @@ function M.stdoutcallback(_, _, data) if #pio_buffer > 5000 then pio_buffer = pio_buffer:sub(-2500) end end +local commandPassed = 0 ------------------------------------------------------ -- INFO: commands sequencer -- stylua: ignore M.run_sequence = function(tasks) M.queue = {} - callBack = tasks.cb -- 1. Save the callback in a local variable local commands = tasks.cmnds local done = ' && echo _CMMNDS_":"DONE' @@ -141,19 +141,23 @@ M.run_sequence = function(tasks) else full_cmd = cmd .. pass .. fail end table.insert(M.queue, full_cmd) end + + + callBack = tasks.cb -- 1. Save the callback in a local variable + commandPassed = 0 + _G.metadata.isBusy = true + + term.stdout_callback = M.stdoutcallback vim.schedule(function() if callBack then callBack('INIT') end end) end ------------------------------------------------------ -- Handle after pioinit execution -local commandPassed = 0 function M.handlePioinitDb(result) - if result == 'INIT' then -- initialize - commandPassed = 0 - _G.metadata.isBusy = true - local full_cmd = table.remove(M.queue, 1) - term.stdout_callback = M.stdoutcallback - term.ToggleTerminal(full_cmd, 'float') + if result == 'INIT' then + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) + term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'PASS' then commandPassed = commandPassed + 1 if commandPassed == 1 then @@ -164,8 +168,7 @@ function M.handlePioinitDb(result) end) -- elseif commandPassed == 2 then -- if you sned more than 2 commands you need this end - local full_cmd = table.remove(M.queue, 1) - term.ToggleTerminal(full_cmd, 'float') + term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'DONE' then -- result of the last command vim.schedule(function() vim.notify('compiledb: Done ..', vim.log.levels.INFO) @@ -174,6 +177,7 @@ function M.handlePioinitDb(result) local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() vim.misc.gitignore_lsp_configs('compile_commands.json') + lsp_restart('clangd') -- _G.metadata.dbTrigger = true -- local ok, _ = pcall(M.compile_commandsFix) -- if not ok then @@ -191,56 +195,39 @@ end ------------------------------------------------------ -- Handle after pioinit execution function M.handlePioinit(result) - if result == 'INIT' then -- initialize - commandPassed = 0 - _G.metadata.isBusy = true - local full_cmd = table.remove(M.queue, 1) - term.stdout_callback = M.stdoutcallback - term.ToggleTerminal(full_cmd, 'float') + if result == 'INIT' then + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) + term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'DONE' then -- result of the last command vim.schedule(function() - vim.notify('compiledb: Done ..', vim.log.levels.INFO) - M.queue = {} - term.stdout_callback = nil - vim.schedule(function() - vim.notify('Pioinit: Done ..', vim.log.levels.INFO) + vim.notify('Pioinit: Done ..', vim.log.levels.INFO) + local pio_refresh = require('platformio.pio_setup').pio_refresh + pio_refresh(function() + vim.misc.gitignore_lsp_configs('compile_commands.json') local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], _G.metadata.core_dir) - local pio_refresh = require('platformio.pio_setup').pio_refresh - pio_refresh(function() - vim.misc.gitignore_lsp_configs('compile_commands.json') - -- _G.metadata.dbTrigger = true - -- local ok, _ = pcall(M.compile_commandsFix) - -- if not ok then - -- print('Env: dbTrigger, fail to call dbFix') - -- end - end) end) end) elseif result == 'FAIL' then - M.queue = {} - term.stdout_callback = nil - _G.metadata.isBusy = false end + M.queue = {} + term.stdout_callback = nil + _G.metadata.isBusy = false end ------------------------------------------------------ -- Handle after piolib execution function M.handlePiolib(result) - if result == 'INIT' then -- initialize - commandPassed = 0 - _G.metadata.isBusy = true - local full_cmd = table.remove(M.queue, 1) - term.stdout_callback = M.stdoutcallback - term.ToggleTerminal(full_cmd, 'float') - -- elseif result == 'PASS' then + if result == 'INIT' then + term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'DONE' then -- result of the only and the last command vim.notify('Piolib: Success', vim.log.levels.INFO) elseif result == 'FAIL' then - M.queue = {} - term.stdout_callback = nil - _G.metadata.isBusy = false end + M.queue = {} + term.stdout_callback = nil + _G.metadata.isBusy = false end return M From 61f3c20085c31f08417d27893007b25de5b2f0e5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 06:30:22 +0300 Subject: [PATCH 1090/1406] update --- lua/platformio/piolib.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 46ce0ef3..5dc8cd12 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -66,7 +66,7 @@ local function pick_library(json_data) local pio = require('platformio.utils.pio') pio.run_sequence({ - cmnds = {'pio pkg install --library "' .. pkg_name .. '" --no-save'}, + cmnds = {'pio pkg install --library "' .. pkg_name .. '"'}, cb = pio.handlePiolib --function () vim.notify('Piolib: Done', vim.log.levels.INFO) end }) From e485c3a5338217eb61c86c10c3127010687001f9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 06:52:52 +0300 Subject: [PATCH 1091/1406] update --- lua/platformio/boilerplate.lua | 2 ++ lua/platformio/utils/pio.lua | 24 ++++++++++++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 8dfc6744..9df21dbe 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -1,5 +1,7 @@ M = {} + M.core_dir = '' + local uv = vim.loop local boilerplate = {} diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index e0c52c4a..4f1f8081 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -155,8 +155,18 @@ end -- Handle after pioinit execution function M.handlePioinitDb(result) if result == 'INIT' then - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + local boilerplate = require('platformio.boilerplate') + local boilerplate_gen = boilerplate.boilerplate_gen + + boilerplate.core_dir = _G.metadata.core_dir boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) + + boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) + + boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) + -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') + term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'PASS' then commandPassed = commandPassed + 1 @@ -196,8 +206,18 @@ end -- Handle after pioinit execution function M.handlePioinit(result) if result == 'INIT' then - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + local boilerplate = require('platformio.boilerplate') + local boilerplate_gen = boilerplate.boilerplate_gen + + boilerplate.core_dir = _G.metadata.core_dir boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) + + boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) + + boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) + -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') + term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'DONE' then -- result of the last command vim.schedule(function() From 296de6c1d7ef23f2dc387d023900ec2c64d0fbde Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 07:13:40 +0300 Subject: [PATCH 1092/1406] update --- lua/platformio/utils/pio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 4f1f8081..a59ce6cb 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -159,7 +159,7 @@ function M.handlePioinitDb(result) local boilerplate_gen = boilerplate.boilerplate_gen boilerplate.core_dir = _G.metadata.core_dir - boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) + -- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) @@ -210,7 +210,7 @@ function M.handlePioinit(result) local boilerplate_gen = boilerplate.boilerplate_gen boilerplate.core_dir = _G.metadata.core_dir - boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) + -- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) From ac619916f59d09028fe48a99fa615bfe3c2a3713 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 07:36:02 +0300 Subject: [PATCH 1093/1406] update --- lua/platformio/boilerplate.lua | 28 +++++++++++++++------------- lua/platformio/utils/misc.lua | 8 ++++---- 2 files changed, 19 insertions(+), 17 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 9df21dbe..8d376d9c 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -480,24 +480,26 @@ function M.boilerplate_gen(framework, src_path, filename) if vim.uv.fs_stat(file_path) then if not entry.rewrite then if entry.read then - local fr = io.open(file_path, 'r') - if fr then return (fr:read('*a')) end + local ok, content = vim.misc.readFile(file_path) + if ok then return content end + -- local fr = io.open(file_path, 'r') + -- if fr then return (fr:read('*a')) end end return '' end end - - if vim.fn.isdirectory(src_path) == 0 then vim.fn.mkdir(src_path, 'p') end - - local fd = assert(uv.fs_open(file_path, 'w', 420)) - if not fd then - print('failed to create file: ' .. file_path) - return '' - end - + -- if vim.fn.isdirectory(src_path) == 0 then vim.fn.mkdir(src_path, 'p') end + -- + -- local fd = assert(uv.fs_open(file_path, 'w', 420)) + -- if not fd then + -- print('failed to create file: ' .. file_path) + -- return '' + -- end + -- local template = type(entry.content) == 'function' and entry:content() or entry.content - uv.fs_write(fd, template, 0) - uv.fs_close(fd) + -- uv.fs_write(fd, template, 0) + -- uv.fs_close(fd) + vim.misc.writeFile(file_path, template, {}) if entry.read then return template diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 065fc4b9..9ef3ed6d 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -202,7 +202,7 @@ function M.writeFile(path, data, opts) -- 1. Check if file exists and handle overwrite flag local stat = uv.fs_stat(path) if stat and opts.overwrite == false then - return nil, 'writeFile: File already exists and overwrite is disabled' + return false, 'writeFile: File already exists and overwrite is disabled' end -- 2. Ensure folder exists (mkdir -p logic) @@ -219,7 +219,7 @@ function M.writeFile(path, data, opts) -- 'w' truncates existing, 'wx' fails if exists (extra safety) local flags = opts.overwrite == false and 'wx' or 'w' local fd, err = uv.fs_open(path, flags, 438) - if not fd then return nil, 'writeFile: Open error: ' .. (err or 'unknown') end + if not fd then return false, 'writeFile: Open error: ' .. (err or 'unknown') end -- 4. Write data local _, write_err = uv.fs_write(fd, data, 0) @@ -227,9 +227,9 @@ function M.writeFile(path, data, opts) -- 5. ALWAYS close uv.fs_close(fd) - if write_err then return nil, 'writeFile: Write error: ' .. write_err end + if write_err then return false, 'writeFile: Write error: ' .. write_err end - return true + return true, 'writeFile: complete' end ------------------------------------------------------ --[[ From 1c7e2ef0ee918ed8cdd2e85660caa08e369fd9f9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 07:52:04 +0300 Subject: [PATCH 1094/1406] update --- lua/platformio/metadata.lua | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index b23aecf0..cad2bd16 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -46,6 +46,10 @@ _G.metadata = setmetatable({}, { vim.schedule(function() -- M.save_project_config(true) if key == 'toolchain_root' then + local binPath = value .. '/bin' + local sep = (vim.fn.has('win32') == 1 and ';' or ':') + vim.env.PATH = binPath .. sep .. vim.env.PATH + vim.notify('Env: ' .. binPath .. ' added to path', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) -- vim.notify('Env: ' .. value, vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) -- pcall(function() -- if _pio_metadata.dbTrigger then From 1969d5b2c43fc4e260bd7eb56436145ec9ed2b54 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 08:15:25 +0300 Subject: [PATCH 1095/1406] update --- lua/platformio/lspConfig/clangd.lua | 4 ++-- lua/platformio/pio_setup.lua | 4 +--- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 51f4e18a..078d8068 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -118,14 +118,14 @@ function _G.get_clangd_config() -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) -- q_driver = '**' --_G.metadata.query_driver .. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" - q_driver = _G.metadata.query_driver --.. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" + q_driver = _G.metadata.query_driver .. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" end end -- 3. Format your template string local table_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) -- local formatted_str = string.format(table_config, q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) - local formatted_str = string.format(table_config, q_driver, '', vim.misc.normalizePath(new_root_dir)) + local formatted_str = string.format(table_config or '', q_driver, '', vim.misc.normalizePath(new_root_dir)) -- 4. Load the config table local cok, clangd_config = pcall(function() return load('return ' .. formatted_str)() end) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index dd27a572..f4942946 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -59,10 +59,9 @@ end function M.pio_refresh(callback) vim.notify('PIO: Config sync ...', vim.log.levels.INFO) - -- stylua: ignore -- INFO:------------------------------------------------- -- get pio project metadata info - --------------------------------------------------------- + -- stylua: ignore local function get_metadata(attempts, env) local meta = _G.metadata local active_env = env or meta.active_env @@ -78,7 +77,6 @@ function M.pio_refresh(callback) --------------------------------------------------------- -- INTERNAL PROCESSOR: Applies parsed data to _G.metadata - --------------------------------------------------------- local function apply_metadata(data, checksum) if not data then return false end From 1544165beb253e86c508fa661161615284827cf0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 13:10:43 +0300 Subject: [PATCH 1096/1406] update --- lua/platformio/pioinit2.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/pioinit2.lua b/lua/platformio/pioinit2.lua index d08f07a8..92e6f72a 100644 --- a/lua/platformio/pioinit2.lua +++ b/lua/platformio/pioinit2.lua @@ -70,7 +70,7 @@ local function pick_framework(board_details) local opts = require('telescope.themes').get_dropdown({ prompt_title = 'Select Framework (' .. board_details.id .. ')', layout_config = { - width = 0.4, -- 40% of screen width + width = 0.25, -- 40% of screen width height = 0.25, -- Small height for few choices }, previewer = false, -- No preview needed for framework names @@ -105,7 +105,7 @@ local function pick_board(json_data) layout_strategy = 'horizontal', layout_config = { width = 0.9, -- Overall width of the Telescope window (90% of screen) - preview_width = 0.65, -- 65% of the window goes to "Board Details", leaving 25% for results + preview_width = 0.70, -- 65% of the window goes to "Board Details", leaving 25% for results }, finder = finders.new_table({ results = json_data, @@ -143,7 +143,7 @@ end local function start_pio_wizard(json_data) local opts = require('telescope.themes').get_dropdown({ prompt_title = 'Generate Compilation Database (LSP)?', - layout_config = { width = 0.4, height = 0.2 }, + layout_config = { width = 0.2, height = 0.2 }, previewer = false, }) From e76d0036638275135347a3ba0fc0796dde74195a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 13:44:48 +0300 Subject: [PATCH 1097/1406] update --- lua/platformio/boilerplate.lua | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 8d376d9c..966f4a9b 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -81,7 +81,7 @@ boilerplate['.clangd_config'] = { "--completion-style=detailed", "--header-insertion=iwyu", "--fallback-style=llvm", - "--log=verbose", + "--log=error", "--pch-storage=memory", "--pretty", "--ranking-model=decision_forest", @@ -170,12 +170,14 @@ boilerplate['.clangd_config'] = { boilerplate['.clangd'] = { rewrite = false, read = false, + -- - "-std=c++17" + -- - "-std=gnu++17" -- template = [[ content = [[ CompileFlags: Add: - "-xc++" - - "-std=gnu++17" + - "-std=c++17" Remove: - "-fno-fat-lto-objects" - "-fno%%-fat%%-lto%%-objects" From d7f3c83bfc757891a2677cbd249bb0890b768786 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 14:01:06 +0300 Subject: [PATCH 1098/1406] update --- lua/platformio/pioinit2.lua | 403 +++++++++++++++++++++++++----------- 1 file changed, 283 insertions(+), 120 deletions(-) diff --git a/lua/platformio/pioinit2.lua b/lua/platformio/pioinit2.lua index 92e6f72a..0e2e6b30 100644 --- a/lua/platformio/pioinit2.lua +++ b/lua/platformio/pioinit2.lua @@ -4,125 +4,120 @@ local actions = require('telescope.actions') local action_state = require('telescope.actions.state') local previewers = require('telescope.previewers') local telescope_conf = require('telescope.config').values +local themes = require('telescope.themes') local wizard_data = {} --- Final Step: Command Construction & Execution +-- Visual Notifications +local function notify(msg, level) + vim.notify('PIO Wizard: ' .. msg, level or vim.log.levels.INFO) +end + +-- Reusable Small Menu for Yes/No and Frameworks +local function small_menu(title, results, callback) + pickers + .new( + themes.get_dropdown({ + prompt_title = title, + layout_config = { width = 0.3, height = 0.25 }, + previewer = false, + }), + { + finder = finders.new_table({ results = results }), + sorter = telescope_conf.generic_sorter({}), + attach_mappings = function(prompt_bufnr) + actions.select_default:replace(function() + local selection = action_state.get_selected_entry() + actions.close(prompt_bufnr) + if selection then + callback(selection[1]) + end + end) + return true + end, + } + ) + :find() +end + +-- FINAL STEP: Construction & Sequence Execution local function finalize_setup() local pio = require('platformio.utils.pio') - -- 1. Construct the basic init command - local sample_flag = wizard_data.sample == 'true' and ' --sample-code' or '' + local sample_flag = wizard_data.sample == 'Yes' and ' --sample-code' or '' local init_cmd = string.format('pio project init --ide vim --board %s -O "framework=%s"%s', wizard_data.board_id, wizard_data.framework, sample_flag) - -- 2. Determine commands and callback local commands = { init_cmd } - local final_cb = pio.handlePioinit -- Default for 1 command + local final_cb = pio.handlePioinit - if wizard_data.use_compiledb then + if wizard_data.use_compiledb == 'Yes' then table.insert(commands, 'pio run -t compiledb') - final_cb = pio.handlePioinitDb -- Switch to Db handler for 2 commands + final_cb = pio.handlePioinitDb end - -- 3. Execute - pio.run_sequence({ - cmnds = commands, - cb = final_cb, - }) + notify('Starting project setup for ' .. wizard_data.board_id .. '...') + pio.run_sequence({ cmnds = commands, cb = final_cb }) end -local function dialog_opts(title, width) - return require('telescope.themes').get_dropdown({ - prompt_title = title, - layout_config = { - width = width or 0.4, -- Adjust width (0.4 = 40% of screen) - height = 0.2, -- Small height for few choices - }, - previewer = false, -- Hide preview for simple choices - }) -end +--- SEQUENTIAL STEPS --- ---- PICKERS (In Order of Execution) --- +-- Step 4: CompileDB +local function pick_compiledb() + small_menu('Generate Compilation Database (LSP)?', { 'Yes', 'No' }, function(choice) + wizard_data.use_compiledb = choice + finalize_setup() + end) +end --- STEP 4: Sample (True/False) +-- Step 3: Sample Code local function pick_sample() - local opts = dialog_opts('Include Sample Code?', 0.3) - pickers - .new(opts, { - finder = finders.new_table({ results = { 'true', 'false' } }), - sorter = telescope_conf.generic_sorter(opts), - attach_mappings = function(prompt_bufnr) - actions.select_default:replace(function() - local selection = action_state.get_selected_entry() - actions.close(prompt_bufnr) - wizard_data.sample = selection[1] - finalize_setup() - end) - return true - end, - }) - :find() + small_menu('Include Sample Code?', { 'Yes', 'No' }, function(choice) + wizard_data.sample = choice + pick_compiledb() + end) end --- STEP 3: Framework Selection (Small Dialog) +-- Step 2: Framework local function pick_framework(board_details) - -- Use dropdown theme to keep the window small and centered - local opts = require('telescope.themes').get_dropdown({ - prompt_title = 'Select Framework (' .. board_details.id .. ')', - layout_config = { - width = 0.25, -- 40% of screen width - height = 0.25, -- Small height for few choices - }, - previewer = false, -- No preview needed for framework names - }) - - pickers - .new(opts, { - finder = finders.new_table({ - results = board_details['frameworks'], - }), - sorter = telescope_conf.generic_sorter(opts), - attach_mappings = function(prompt_bufnr) - actions.select_default:replace(function() - local selection = action_state.get_selected_entry() - actions.close(prompt_bufnr) - -- selection is a simple string in this case - wizard_data.framework = selection[1] - pick_sample() - end) - return true - end, - }) - :find() + small_menu('Select Framework', board_details.frameworks, function(choice) + wizard_data.framework = choice + pick_sample() + end) end --- STEP 2: Board (with Buffer Previewer) +-- Step 1: Board (Entry Point) local function pick_board(json_data) pickers .new({}, { - prompt_title = 'Select Board', - -- Define the layout behavior + prompt_title = 'Select PlatformIO Board', layout_strategy = 'horizontal', - layout_config = { - width = 0.9, -- Overall width of the Telescope window (90% of screen) - preview_width = 0.70, -- 65% of the window goes to "Board Details", leaving 25% for results - }, + layout_config = { width = 0.9, preview_width = 0.6 }, finder = finders.new_table({ results = json_data, entry_maker = function(entry) return { value = entry, - display = entry.name or entry.id, - ordinal = (entry.name or '') .. ' ' .. (entry.id or ''), + display = string.format('%-25s | %s', entry.id, entry.name), + ordinal = entry.id .. ' ' .. entry.name, } end, }), previewer = previewers.new_buffer_previewer({ - title = 'Board Details', + title = 'Board Specs', define_preview = function(self, entry) - local content = vim.split(vim.inspect(entry.value), '\n') - vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, content) - vim.api.nvim_set_option_value('filetype', 'lua', { buf = self.state.bufnr }) + local val = entry.value + local lines = { + '# ' .. (val.name or val.id), + '', + '**Micro:** ' .. (val.mcu or 'N/A'), + '**Vendor:** ' .. (val.vendor or 'N/A'), + '**Clock:** ' .. (val.fcpu or 0) / 1000000 .. ' MHz', + '**RAM:** ' .. (val.ram or 0) / 1024 .. ' KB', + '', + '**Frameworks:** ' .. table.concat(val.frameworks, ', '), + } + vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, lines) + vim.api.nvim_set_option_value('filetype', 'markdown', { buf = self.state.bufnr }) end, }), sorter = telescope_conf.generic_sorter({}), @@ -130,34 +125,10 @@ local function pick_board(json_data) actions.select_default:replace(function() local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) - wizard_data.board_id = selection.value.id - pick_framework(selection.value) -- Next step - end) - return true - end, - }) - :find() -end - --- STEP 1: IDE (True/False) -local function start_pio_wizard(json_data) - local opts = require('telescope.themes').get_dropdown({ - prompt_title = 'Generate Compilation Database (LSP)?', - layout_config = { width = 0.2, height = 0.2 }, - previewer = false, - }) - - pickers - .new(opts, { - finder = finders.new_table({ results = { 'true', 'false' } }), - sorter = telescope_conf.generic_sorter(opts), - attach_mappings = function(prompt_bufnr) - actions.select_default:replace(function() - local selection = action_state.get_selected_entry() - actions.close(prompt_bufnr) - -- Save the boolean for the final step - wizard_data.use_compiledb = (selection[1] == 'true') - pick_board(json_data) + if selection then + wizard_data.board_id = selection.value.id + pick_framework(selection.value) + end end) return true end, @@ -165,31 +136,223 @@ local function start_pio_wizard(json_data) :find() end +-- Entry point local function launch_pio_project_wizard() - print('Fetching board data from PlatformIO...') + wizard_data = {} -- Reset state + notify('Fetching board database...') - -- 1. Get board data from PIO CLI in JSON format - -- The '--json-output' flag ensures we get structured data local handle = io.popen('pio boards --json-output') if not handle then return end - local result = handle:read('*a') handle:close() - -- 2. Decode the JSON string into a Lua table local ok, json_data = pcall(vim.json.decode, result) - if not ok or not json_data then - print('Error: Could not parse PlatformIO board data.') + if not ok or type(json_data) ~= 'table' then + notify('Failed to parse board data.', vim.log.levels.ERROR) return end - -- 3. Start the wizard we built previously - start_pio_wizard(json_data) + pick_board(json_data) end --- Export the function so it's accessible via require() return { launch = launch_pio_project_wizard, } + +-- local pickers = require('telescope.pickers') +-- local finders = require('telescope.finders') +-- local actions = require('telescope.actions') +-- local action_state = require('telescope.actions.state') +-- local previewers = require('telescope.previewers') +-- local telescope_conf = require('telescope.config').values +-- +-- local wizard_data = {} +-- +-- -- Final Step: Command Construction & Execution +-- local function finalize_setup() +-- local pio = require('platformio.utils.pio') +-- +-- -- 1. Construct the basic init command +-- local sample_flag = wizard_data.sample == 'true' and ' --sample-code' or '' +-- local init_cmd = string.format('pio project init --ide vim --board %s -O "framework=%s"%s', wizard_data.board_id, wizard_data.framework, sample_flag) +-- +-- -- 2. Determine commands and callback +-- local commands = { init_cmd } +-- local final_cb = pio.handlePioinit -- Default for 1 command +-- +-- if wizard_data.use_compiledb then +-- table.insert(commands, 'pio run -t compiledb') +-- final_cb = pio.handlePioinitDb -- Switch to Db handler for 2 commands +-- end +-- +-- -- 3. Execute +-- pio.run_sequence({ +-- cmnds = commands, +-- cb = final_cb, +-- }) +-- end +-- +-- local function dialog_opts(title, width) +-- return require('telescope.themes').get_dropdown({ +-- prompt_title = title, +-- layout_config = { +-- width = width or 0.4, -- Adjust width (0.4 = 40% of screen) +-- height = 0.2, -- Small height for few choices +-- }, +-- previewer = false, -- Hide preview for simple choices +-- }) +-- end +-- +-- --- PICKERS (In Order of Execution) --- +-- +-- -- STEP 4: Sample (True/False) +-- local function pick_sample() +-- local opts = dialog_opts('Include Sample Code?', 0.3) +-- pickers +-- .new(opts, { +-- finder = finders.new_table({ results = { 'true', 'false' } }), +-- sorter = telescope_conf.generic_sorter(opts), +-- attach_mappings = function(prompt_bufnr) +-- actions.select_default:replace(function() +-- local selection = action_state.get_selected_entry() +-- actions.close(prompt_bufnr) +-- wizard_data.sample = selection[1] +-- finalize_setup() +-- end) +-- return true +-- end, +-- }) +-- :find() +-- end +-- +-- -- STEP 3: Framework Selection (Small Dialog) +-- local function pick_framework(board_details) +-- -- Use dropdown theme to keep the window small and centered +-- local opts = require('telescope.themes').get_dropdown({ +-- prompt_title = 'Select Framework (' .. board_details.id .. ')', +-- layout_config = { +-- width = 0.25, -- 40% of screen width +-- height = 0.25, -- Small height for few choices +-- }, +-- previewer = false, -- No preview needed for framework names +-- }) +-- +-- pickers +-- .new(opts, { +-- finder = finders.new_table({ +-- results = board_details['frameworks'], +-- }), +-- sorter = telescope_conf.generic_sorter(opts), +-- attach_mappings = function(prompt_bufnr) +-- actions.select_default:replace(function() +-- local selection = action_state.get_selected_entry() +-- actions.close(prompt_bufnr) +-- -- selection is a simple string in this case +-- wizard_data.framework = selection[1] +-- pick_sample() +-- end) +-- return true +-- end, +-- }) +-- :find() +-- end +-- +-- -- STEP 2: Board (with Buffer Previewer) +-- local function pick_board(json_data) +-- pickers +-- .new({}, { +-- prompt_title = 'Select Board', +-- -- Define the layout behavior +-- layout_strategy = 'horizontal', +-- layout_config = { +-- width = 0.9, -- Overall width of the Telescope window (90% of screen) +-- preview_width = 0.70, -- 65% of the window goes to "Board Details", leaving 25% for results +-- }, +-- finder = finders.new_table({ +-- results = json_data, +-- entry_maker = function(entry) +-- return { +-- value = entry, +-- display = entry.name or entry.id, +-- ordinal = (entry.name or '') .. ' ' .. (entry.id or ''), +-- } +-- end, +-- }), +-- previewer = previewers.new_buffer_previewer({ +-- title = 'Board Details', +-- define_preview = function(self, entry) +-- local content = vim.split(vim.inspect(entry.value), '\n') +-- vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, content) +-- vim.api.nvim_set_option_value('filetype', 'lua', { buf = self.state.bufnr }) +-- end, +-- }), +-- sorter = telescope_conf.generic_sorter({}), +-- attach_mappings = function(prompt_bufnr) +-- actions.select_default:replace(function() +-- local selection = action_state.get_selected_entry() +-- actions.close(prompt_bufnr) +-- wizard_data.board_id = selection.value.id +-- pick_framework(selection.value) -- Next step +-- end) +-- return true +-- end, +-- }) +-- :find() +-- end +-- +-- -- STEP 1: IDE (True/False) +-- local function start_pio_wizard(json_data) +-- local opts = require('telescope.themes').get_dropdown({ +-- prompt_title = 'Generate Compilation Database (LSP)?', +-- layout_config = { width = 0.2, height = 0.2 }, +-- previewer = false, +-- }) +-- +-- pickers +-- .new(opts, { +-- finder = finders.new_table({ results = { 'true', 'false' } }), +-- sorter = telescope_conf.generic_sorter(opts), +-- attach_mappings = function(prompt_bufnr) +-- actions.select_default:replace(function() +-- local selection = action_state.get_selected_entry() +-- actions.close(prompt_bufnr) +-- -- Save the boolean for the final step +-- wizard_data.use_compiledb = (selection[1] == 'true') +-- pick_board(json_data) +-- end) +-- return true +-- end, +-- }) +-- :find() +-- end +-- +-- local function launch_pio_project_wizard() +-- print('Fetching board data from PlatformIO...') +-- +-- -- 1. Get board data from PIO CLI in JSON format +-- -- The '--json-output' flag ensures we get structured data +-- local handle = io.popen('pio boards --json-output') +-- if not handle then +-- return +-- end +-- +-- local result = handle:read('*a') +-- handle:close() +-- +-- -- 2. Decode the JSON string into a Lua table +-- local ok, json_data = pcall(vim.json.decode, result) +-- if not ok or not json_data then +-- print('Error: Could not parse PlatformIO board data.') +-- return +-- end +-- +-- -- 3. Start the wizard we built previously +-- start_pio_wizard(json_data) +-- end +-- +-- -- Export the function so it's accessible via require() +-- return { +-- launch = launch_pio_project_wizard, +-- } From 2d66a3acffb47ce91cf0ab7905dc5a504ac09668 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 14:09:03 +0300 Subject: [PATCH 1099/1406] update --- lua/platformio/pioinit2.lua | 84 +++++++++++++++++++++++++++++++++---- 1 file changed, 77 insertions(+), 7 deletions(-) diff --git a/lua/platformio/pioinit2.lua b/lua/platformio/pioinit2.lua index 0e2e6b30..943e914e 100644 --- a/lua/platformio/pioinit2.lua +++ b/lua/platformio/pioinit2.lua @@ -91,7 +91,10 @@ local function pick_board(json_data) .new({}, { prompt_title = 'Select PlatformIO Board', layout_strategy = 'horizontal', - layout_config = { width = 0.9, preview_width = 0.6 }, + layout_config = { + width = 0.9, + preview_width = 0.6, + }, finder = finders.new_table({ results = json_data, entry_maker = function(entry) @@ -103,19 +106,36 @@ local function pick_board(json_data) end, }), previewer = previewers.new_buffer_previewer({ - title = 'Board Specs', + title = 'Full Board Specifications', define_preview = function(self, entry) local val = entry.value + + -- Logic for human-readable sizes + local ram = val.ram and (val.ram / 1024 .. ' KB') or 'Unknown' + local flash = val.rom and (val.rom / 1024 .. ' KB') or 'Unknown' + local mhz = val.fcpu and (val.fcpu / 1000000 .. ' MHz') or 'Unknown' + local lines = { '# ' .. (val.name or val.id), '', - '**Micro:** ' .. (val.mcu or 'N/A'), - '**Vendor:** ' .. (val.vendor or 'N/A'), - '**Clock:** ' .. (val.fcpu or 0) / 1000000 .. ' MHz', - '**RAM:** ' .. (val.ram or 0) / 1024 .. ' KB', + '**Basic Info**', + '---', + '**Board ID:** ' .. val.id, + '**Vendor:** ' .. (val.vendor or 'Generic'), + '**Platform:** ' .. (val.platform or 'N/A'), + '', + '**Hardware Specs**', + '---', + '**MCU:** ' .. (val.mcu or 'N/A'), + '**CPU Speed:** ' .. mhz, + '**Flash (ROM):** ' .. flash, + '**RAM:** ' .. ram, '', - '**Frameworks:** ' .. table.concat(val.frameworks, ', '), + '**Available Frameworks**', + '---', + '- ' .. table.concat(val.frameworks, '\n- '), } + vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, lines) vim.api.nvim_set_option_value('filetype', 'markdown', { buf = self.state.bufnr }) end, @@ -136,6 +156,56 @@ local function pick_board(json_data) :find() end +-- local function pick_board(json_data) +-- pickers +-- .new({}, { +-- prompt_title = 'Select PlatformIO Board', +-- layout_strategy = 'horizontal', +-- layout_config = { width = 0.9, preview_width = 0.6 }, +-- finder = finders.new_table({ +-- results = json_data, +-- entry_maker = function(entry) +-- return { +-- value = entry, +-- display = string.format('%-25s | %s', entry.id, entry.name), +-- ordinal = entry.id .. ' ' .. entry.name, +-- } +-- end, +-- }), +-- previewer = previewers.new_buffer_previewer({ +-- title = 'Board Specs', +-- define_preview = function(self, entry) +-- local val = entry.value +-- local lines = { +-- '# ' .. (val.name or val.id), +-- '', +-- '**Micro:** ' .. (val.mcu or 'N/A'), +-- '**Vendor:** ' .. (val.vendor or 'N/A'), +-- '**Clock:** ' .. (val.fcpu or 0) / 1000000 .. ' MHz', +-- '**RAM:** ' .. (val.ram or 0) / 1024 .. ' KB', +-- '', +-- '**Frameworks:** ' .. table.concat(val.frameworks, ', '), +-- } +-- vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, lines) +-- vim.api.nvim_set_option_value('filetype', 'markdown', { buf = self.state.bufnr }) +-- end, +-- }), +-- sorter = telescope_conf.generic_sorter({}), +-- attach_mappings = function(prompt_bufnr) +-- actions.select_default:replace(function() +-- local selection = action_state.get_selected_entry() +-- actions.close(prompt_bufnr) +-- if selection then +-- wizard_data.board_id = selection.value.id +-- pick_framework(selection.value) +-- end +-- end) +-- return true +-- end, +-- }) +-- :find() +-- end + -- Entry point local function launch_pio_project_wizard() wizard_data = {} -- Reset state From 00692158c0ee7d192cfafe52c5365557bc3f7647 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 14:11:30 +0300 Subject: [PATCH 1100/1406] update --- lua/platformio/pioinit2.lua | 26 ++++++++++++++++---------- mini_nvimPlatformio.lua | 2 +- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/lua/platformio/pioinit2.lua b/lua/platformio/pioinit2.lua index 943e914e..a5b68227 100644 --- a/lua/platformio/pioinit2.lua +++ b/lua/platformio/pioinit2.lua @@ -91,10 +91,7 @@ local function pick_board(json_data) .new({}, { prompt_title = 'Select PlatformIO Board', layout_strategy = 'horizontal', - layout_config = { - width = 0.9, - preview_width = 0.6, - }, + layout_config = { width = 0.9, preview_width = 0.6 }, finder = finders.new_table({ results = json_data, entry_maker = function(entry) @@ -106,15 +103,16 @@ local function pick_board(json_data) end, }), previewer = previewers.new_buffer_previewer({ - title = 'Full Board Specifications', + title = 'Board Specifications', define_preview = function(self, entry) local val = entry.value - -- Logic for human-readable sizes - local ram = val.ram and (val.ram / 1024 .. ' KB') or 'Unknown' - local flash = val.rom and (val.rom / 1024 .. ' KB') or 'Unknown' - local mhz = val.fcpu and (val.fcpu / 1000000 .. ' MHz') or 'Unknown' + -- Safe conversion for hardware specs + local ram = val.ram and (math.floor(val.ram / 1024) .. ' KB') or 'Unknown' + local flash = val.rom and (math.floor(val.rom / 1024) .. ' KB') or 'Unknown' + local mhz = val.fcpu and (math.floor(val.fcpu / 1000000) .. ' MHz') or 'Unknown' + -- Build base lines local lines = { '# ' .. (val.name or val.id), '', @@ -133,9 +131,17 @@ local function pick_board(json_data) '', '**Available Frameworks**', '---', - '- ' .. table.concat(val.frameworks, '\n- '), } + -- Correctly append frameworks as separate lines to avoid the newline error + if val.frameworks and #val.frameworks > 0 then + for _, fw in ipairs(val.frameworks) do + table.insert(lines, '- ' .. fw) + end + else + table.insert(lines, '*No frameworks listed*') + end + vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, lines) vim.api.nvim_set_option_value('filetype', 'markdown', { buf = self.state.bufnr }) end, diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 233e0937..21fce98e 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -170,7 +170,7 @@ vim.env.XDG_STATE_HOME = tmp_root .. '/state' local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' -- local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' if not (vim.uv or vim.loop).fs_stat(lazypath) then - print('Attempting to download lazy.nvim...') + print('Attempting to download lazy.nvim ...') vim.fn.system({ 'git', 'clone', From 1c0e16a01ba629e002a0cca6b5ad50e157079c67 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 14:21:22 +0300 Subject: [PATCH 1101/1406] update --- lua/platformio/pioinit2.lua | 135 ++++++++++++++++++++++++------------ 1 file changed, 91 insertions(+), 44 deletions(-) diff --git a/lua/platformio/pioinit2.lua b/lua/platformio/pioinit2.lua index a5b68227..eec9c30a 100644 --- a/lua/platformio/pioinit2.lua +++ b/lua/platformio/pioinit2.lua @@ -86,64 +86,33 @@ local function pick_framework(board_details) end -- Step 1: Board (Entry Point) + local function pick_board(json_data) pickers .new({}, { - prompt_title = 'Select PlatformIO Board', + prompt_title = 'Select Board', + -- Define the layout behavior layout_strategy = 'horizontal', - layout_config = { width = 0.9, preview_width = 0.6 }, + layout_config = { + width = 0.9, -- Overall width of the Telescope window (90% of screen) + preview_width = 0.70, -- 65% of the window goes to "Board Details", leaving 25% for results + }, finder = finders.new_table({ results = json_data, entry_maker = function(entry) return { value = entry, - display = string.format('%-25s | %s', entry.id, entry.name), - ordinal = entry.id .. ' ' .. entry.name, + display = entry.name or entry.id, + ordinal = (entry.name or '') .. ' ' .. (entry.id or ''), } end, }), previewer = previewers.new_buffer_previewer({ - title = 'Board Specifications', + title = 'Board Details', define_preview = function(self, entry) - local val = entry.value - - -- Safe conversion for hardware specs - local ram = val.ram and (math.floor(val.ram / 1024) .. ' KB') or 'Unknown' - local flash = val.rom and (math.floor(val.rom / 1024) .. ' KB') or 'Unknown' - local mhz = val.fcpu and (math.floor(val.fcpu / 1000000) .. ' MHz') or 'Unknown' - - -- Build base lines - local lines = { - '# ' .. (val.name or val.id), - '', - '**Basic Info**', - '---', - '**Board ID:** ' .. val.id, - '**Vendor:** ' .. (val.vendor or 'Generic'), - '**Platform:** ' .. (val.platform or 'N/A'), - '', - '**Hardware Specs**', - '---', - '**MCU:** ' .. (val.mcu or 'N/A'), - '**CPU Speed:** ' .. mhz, - '**Flash (ROM):** ' .. flash, - '**RAM:** ' .. ram, - '', - '**Available Frameworks**', - '---', - } - - -- Correctly append frameworks as separate lines to avoid the newline error - if val.frameworks and #val.frameworks > 0 then - for _, fw in ipairs(val.frameworks) do - table.insert(lines, '- ' .. fw) - end - else - table.insert(lines, '*No frameworks listed*') - end - - vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, lines) - vim.api.nvim_set_option_value('filetype', 'markdown', { buf = self.state.bufnr }) + local content = vim.split(vim.inspect(entry.value), '\n') + vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, content) + vim.api.nvim_set_option_value('filetype', 'lua', { buf = self.state.bufnr }) end, }), sorter = telescope_conf.generic_sorter({}), @@ -151,6 +120,8 @@ local function pick_board(json_data) actions.select_default:replace(function() local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) + -- wizard_data.board_id = selection.value.id + -- pick_framework(selection.value) -- Next step if selection then wizard_data.board_id = selection.value.id pick_framework(selection.value) @@ -162,6 +133,82 @@ local function pick_board(json_data) :find() end +-- local function pick_board(json_data) +-- pickers +-- .new({}, { +-- prompt_title = 'Select PlatformIO Board', +-- layout_strategy = 'horizontal', +-- layout_config = { width = 0.9, preview_width = 0.6 }, +-- finder = finders.new_table({ +-- results = json_data, +-- entry_maker = function(entry) +-- return { +-- value = entry, +-- display = string.format('%-25s | %s', entry.id, entry.name), +-- ordinal = entry.id .. ' ' .. entry.name, +-- } +-- end, +-- }), +-- previewer = previewers.new_buffer_previewer({ +-- title = 'Board Specifications', +-- define_preview = function(self, entry) +-- local val = entry.value +-- +-- -- Safe conversion for hardware specs +-- local ram = val.ram and (math.floor(val.ram / 1024) .. ' KB') or 'Unknown' +-- local flash = val.rom and (math.floor(val.rom / 1024) .. ' KB') or 'Unknown' +-- local mhz = val.fcpu and (math.floor(val.fcpu / 1000000) .. ' MHz') or 'Unknown' +-- +-- -- Build base lines +-- local lines = { +-- '# ' .. (val.name or val.id), +-- '', +-- '**Basic Info**', +-- '---', +-- '**Board ID:** ' .. val.id, +-- '**Vendor:** ' .. (val.vendor or 'Generic'), +-- '**Platform:** ' .. (val.platform or 'N/A'), +-- '', +-- '**Hardware Specs**', +-- '---', +-- '**MCU:** ' .. (val.mcu or 'N/A'), +-- '**CPU Speed:** ' .. mhz, +-- '**Flash (ROM):** ' .. flash, +-- '**RAM:** ' .. ram, +-- '', +-- '**Available Frameworks**', +-- '---', +-- } +-- +-- -- Correctly append frameworks as separate lines to avoid the newline error +-- if val.frameworks and #val.frameworks > 0 then +-- for _, fw in ipairs(val.frameworks) do +-- table.insert(lines, '- ' .. fw) +-- end +-- else +-- table.insert(lines, '*No frameworks listed*') +-- end +-- +-- vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, lines) +-- vim.api.nvim_set_option_value('filetype', 'markdown', { buf = self.state.bufnr }) +-- end, +-- }), +-- sorter = telescope_conf.generic_sorter({}), +-- attach_mappings = function(prompt_bufnr) +-- actions.select_default:replace(function() +-- local selection = action_state.get_selected_entry() +-- actions.close(prompt_bufnr) +-- if selection then +-- wizard_data.board_id = selection.value.id +-- pick_framework(selection.value) +-- end +-- end) +-- return true +-- end, +-- }) +-- :find() +-- end + -- local function pick_board(json_data) -- pickers -- .new({}, { From 5d61cc81214d0ba97319406f53aa33dd5ce43e26 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 14:29:55 +0300 Subject: [PATCH 1102/1406] update --- lua/platformio/lspConfig/clangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 078d8068..a18a7728 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -118,7 +118,7 @@ function _G.get_clangd_config() -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) -- q_driver = '**' --_G.metadata.query_driver .. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" - q_driver = _G.metadata.query_driver .. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" + q_driver = _G.metadata.query_driver --.. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" end end From 8fe50c5f373ca34d4907385df4f99a60ea0a15f6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 14:51:33 +0300 Subject: [PATCH 1103/1406] update --- mini_nvimPlatformio.lua | 87 ++++++++++++++++++++++++++++++----------- 1 file changed, 64 insertions(+), 23 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 21fce98e..acd02dd1 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -158,41 +158,82 @@ keymap('n', '', '', { desc = 'Move focus to the right window' }) keymap('n', '', '', { desc = 'Move focus to the lower window' }) keymap('n', '', '', { desc = 'Move focus to the upper window' }) +---------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------- -- INFO: Set mini lazy config +---------------------------------------------------------------------------------------- -- pick a temp root -local tmp_root = vim.loop.os_tmpdir():gsub('\\', '/') .. '/nvim-temp' -vim.env.XDG_CONFIG_HOME = tmp_root .. '/config' -vim.env.XDG_DATA_HOME = tmp_root .. '/data' -vim.env.XDG_CACHE_HOME = tmp_root .. '/cache' -vim.env.XDG_STATE_HOME = tmp_root .. '/state' - -local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' --- local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' -if not (vim.uv or vim.loop).fs_stat(lazypath) then - print('Attempting to download lazy.nvim ...') +-- 1. CROSS-PLATFORM ENVIRONMENT ISOLATION +-- This acts like the "bash" or "powershell" setup inside Lua +local app_name = 'nvim-minimal' +local is_windows = vim.loop.os_uname().sysname == 'Windows_NT' +local home = is_windows and vim.env.USERPROFILE or vim.env.HOME +local separator = is_windows and '\\' or '/' + +-- Set names for isolation +vim.env.NVIM_APPNAME = app_name + +-- Manually set XDG paths to force isolation on both OS types +if is_windows then + local localappdata = vim.env.LOCALAPPDATA + vim.env.XDG_CONFIG_HOME = localappdata .. separator .. app_name + vim.env.XDG_DATA_HOME = localappdata .. separator .. app_name .. '-data' + vim.env.XDG_STATE_HOME = localappdata .. separator .. app_name .. '-data' .. separator .. 'state' + vim.env.XDG_CACHE_HOME = localappdata .. separator .. app_name .. '-data' .. separator .. 'cache' +else + vim.env.XDG_CONFIG_HOME = home .. '/.config/' .. app_name + vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name + vim.env.XDG_STATE_HOME = home .. '/.local/state/' .. app_name + vim.env.XDG_CACHE_HOME = home .. '/.cache/' .. app_name +end + +-- 2. CORE SETTINGS + +-- 3. BOOTSTRAP PLUGIN MANAGER (Lazy.nvim) +local lazypath = vim.fn.stdpath('data') .. separator .. 'lazy' .. separator .. 'lazy.nvim' +if not vim.loop.fs_stat(lazypath) then vim.fn.system({ 'git', 'clone', '--filter=blob:none', - 'https://github.com/folke/lazy.nvim.git', + 'https://github.com', '--branch=stable', lazypath, }) end - -local checker = io.open(lazypath .. '/lua/lazy/init.lua', 'r') -if checker then - checker:close() - vim.opt.rtp:prepend(lazypath) - package.path = package.path .. ';' .. lazypath .. '/lua/?.lua;' .. lazypath .. '/lua/?/init.lua' -else - vim.fn.delete(lazypath, 'rf') - error('FATAL: Downloaded folder is corrupted. Retrying next launch.') -end - vim.opt.rtp:prepend(lazypath) -package.path = package.path .. ';' .. lazypath .. '/lua/?.lua;' .. lazypath .. '/lua/?/init.lua' +-- local tmp_root = vim.loop.os_tmpdir():gsub('\\', '/') .. '/nvim-temp' +-- vim.env.XDG_CONFIG_HOME = tmp_root .. '/config' +-- vim.env.XDG_DATA_HOME = tmp_root .. '/data' +-- vim.env.XDG_CACHE_HOME = tmp_root .. '/cache' +-- vim.env.XDG_STATE_HOME = tmp_root .. '/state' +-- +-- local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' +-- -- local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' +-- if not (vim.uv or vim.loop).fs_stat(lazypath) then +-- print('Attempting to download lazy.nvim ...') +-- vim.fn.system({ +-- 'git', +-- 'clone', +-- '--filter=blob:none', +-- 'https://github.com/folke/lazy.nvim.git', +-- '--branch=stable', +-- lazypath, +-- }) +-- end +-- +-- local checker = io.open(lazypath .. '/lua/lazy/init.lua', 'r') +-- if checker then +-- checker:close() +-- vim.opt.rtp:prepend(lazypath) +-- package.path = package.path .. ';' .. lazypath .. '/lua/?.lua;' .. lazypath .. '/lua/?/init.lua' +-- else +-- vim.fn.delete(lazypath, 'rf') +-- error('FATAL: Downloaded folder is corrupted. Retrying next launch.') +-- end +-- +-- vim.opt.rtp:prepend(lazypath) +-- package.path = package.path .. ';' .. lazypath .. '/lua/?.lua;' .. lazypath .. '/lua/?/init.lua' ---------------------------------------------------------------------------------------- -- INFO: define plugins table From ec4662d2011d55e3190bd097d5c717de2141e658 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 14:54:40 +0300 Subject: [PATCH 1104/1406] update --- mini_nvimPlatformio.lua | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index acd02dd1..486437a5 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -190,17 +190,32 @@ end -- 2. CORE SETTINGS -- 3. BOOTSTRAP PLUGIN MANAGER (Lazy.nvim) -local lazypath = vim.fn.stdpath('data') .. separator .. 'lazy' .. separator .. 'lazy.nvim' -if not vim.loop.fs_stat(lazypath) then +local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' +-- local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' +if not (vim.uv or vim.loop).fs_stat(lazypath) then + print('Attempting to download lazy.nvim ...') vim.fn.system({ 'git', 'clone', '--filter=blob:none', - 'https://github.com', + 'https://github.com/folke/lazy.nvim.git', '--branch=stable', lazypath, }) end + +-- local lazypath = vim.fn.stdpath('data') .. separator .. 'lazy' .. separator .. 'lazy.nvim' +-- if not vim.loop.fs_stat(lazypath) then +-- vim.fn.system({ +-- 'git', +-- 'clone', +-- '--filter=blob:none', +-- 'https://github.com', +-- '--branch=stable', +-- lazypath, +-- }) +-- end +-- vim.opt.rtp:prepend(lazypath) -- local tmp_root = vim.loop.os_tmpdir():gsub('\\', '/') .. '/nvim-temp' -- vim.env.XDG_CONFIG_HOME = tmp_root .. '/config' From 6f13f13bfc6e10988401d261765c620af40ea193 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 15:00:17 +0300 Subject: [PATCH 1105/1406] update --- mini_nvimPlatformio.lua | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 486437a5..950c3a48 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -167,8 +167,9 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- This acts like the "bash" or "powershell" setup inside Lua local app_name = 'nvim-minimal' local is_windows = vim.loop.os_uname().sysname == 'Windows_NT' -local home = is_windows and vim.env.USERPROFILE or vim.env.HOME -local separator = is_windows and '\\' or '/' +local home = vim.loop.os_tmpdir():gsub('\\', '/') .. '/nvim-temp' +-- local home = is_windows and vim.env.USERPROFILE or vim.env.HOME +local separator = is_windows and '/' or '/' -- Set names for isolation vim.env.NVIM_APPNAME = app_name @@ -217,6 +218,8 @@ end -- end -- vim.opt.rtp:prepend(lazypath) +------------------------------------------------------------------------------------ + -- local tmp_root = vim.loop.os_tmpdir():gsub('\\', '/') .. '/nvim-temp' -- vim.env.XDG_CONFIG_HOME = tmp_root .. '/config' -- vim.env.XDG_DATA_HOME = tmp_root .. '/data' From cc20b96ac6a6273a6bbd11f81dd39a76b96054a4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 15:05:56 +0300 Subject: [PATCH 1106/1406] update --- mini_nvimPlatformio.lua | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 950c3a48..4308ee86 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -167,7 +167,7 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- This acts like the "bash" or "powershell" setup inside Lua local app_name = 'nvim-minimal' local is_windows = vim.loop.os_uname().sysname == 'Windows_NT' -local home = vim.loop.os_tmpdir():gsub('\\', '/') .. '/nvim-temp' +local home = vim.loop.os_tmpdir():gsub('\\', '/') -- local home = is_windows and vim.env.USERPROFILE or vim.env.HOME local separator = is_windows and '/' or '/' @@ -176,11 +176,10 @@ vim.env.NVIM_APPNAME = app_name -- Manually set XDG paths to force isolation on both OS types if is_windows then - local localappdata = vim.env.LOCALAPPDATA - vim.env.XDG_CONFIG_HOME = localappdata .. separator .. app_name - vim.env.XDG_DATA_HOME = localappdata .. separator .. app_name .. '-data' - vim.env.XDG_STATE_HOME = localappdata .. separator .. app_name .. '-data' .. separator .. 'state' - vim.env.XDG_CACHE_HOME = localappdata .. separator .. app_name .. '-data' .. separator .. 'cache' + vim.env.XDG_CONFIG_HOME = home .. separator .. app_name + vim.env.XDG_DATA_HOME = home .. separator .. app_name .. '-data' + vim.env.XDG_STATE_HOME = home .. separator .. app_name .. '-data' .. separator .. 'state' + vim.env.XDG_CACHE_HOME = home .. separator .. app_name .. '-data' .. separator .. 'cache' else vim.env.XDG_CONFIG_HOME = home .. '/.config/' .. app_name vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name From 2ed4997312d9ec755eebc2cfbbe3d40d7e8a2d83 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 17:05:24 +0300 Subject: [PATCH 1107/1406] update --- mini_nvimPlatformio.lua | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 4308ee86..54b72f05 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -167,19 +167,19 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- This acts like the "bash" or "powershell" setup inside Lua local app_name = 'nvim-minimal' local is_windows = vim.loop.os_uname().sysname == 'Windows_NT' -local home = vim.loop.os_tmpdir():gsub('\\', '/') --- local home = is_windows and vim.env.USERPROFILE or vim.env.HOME -local separator = is_windows and '/' or '/' +-- local home = vim.loop.os_tmpdir():gsub('\\', '/') +local home = is_windows and vim.env.USERPROFILE or vim.env.HOME +local sep = is_windows and '/' or '/' -- Set names for isolation vim.env.NVIM_APPNAME = app_name -- Manually set XDG paths to force isolation on both OS types if is_windows then - vim.env.XDG_CONFIG_HOME = home .. separator .. app_name - vim.env.XDG_DATA_HOME = home .. separator .. app_name .. '-data' - vim.env.XDG_STATE_HOME = home .. separator .. app_name .. '-data' .. separator .. 'state' - vim.env.XDG_CACHE_HOME = home .. separator .. app_name .. '-data' .. separator .. 'cache' + vim.env.XDG_CONFIG_HOME = home .. sep .. app_name + vim.env.XDG_DATA_HOME = home .. sep .. app_name .. '-data' + vim.env.XDG_STATE_HOME = home .. sep .. app_name .. '-data' .. sep .. 'state' + vim.env.XDG_CACHE_HOME = home .. sep .. app_name .. '-data' .. sep .. 'cache' else vim.env.XDG_CONFIG_HOME = home .. '/.config/' .. app_name vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name From 753731d44b99f20522f2e671fa3d322c1ff68196 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 17:12:20 +0300 Subject: [PATCH 1108/1406] update --- mini_nvimPlatformio.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 54b72f05..cbc0937e 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -165,7 +165,7 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- pick a temp root -- 1. CROSS-PLATFORM ENVIRONMENT ISOLATION -- This acts like the "bash" or "powershell" setup inside Lua -local app_name = 'nvim-minimal' +local app_name = 'nvim-min-platformio' local is_windows = vim.loop.os_uname().sysname == 'Windows_NT' -- local home = vim.loop.os_tmpdir():gsub('\\', '/') local home = is_windows and vim.env.USERPROFILE or vim.env.HOME @@ -177,6 +177,7 @@ vim.env.NVIM_APPNAME = app_name -- Manually set XDG paths to force isolation on both OS types if is_windows then vim.env.XDG_CONFIG_HOME = home .. sep .. app_name + print(vim.XDG_DATA_HOME) vim.env.XDG_DATA_HOME = home .. sep .. app_name .. '-data' vim.env.XDG_STATE_HOME = home .. sep .. app_name .. '-data' .. sep .. 'state' vim.env.XDG_CACHE_HOME = home .. sep .. app_name .. '-data' .. sep .. 'cache' From 3a1d2345c43538417ebb0fc1ec3ef5ec4620cae3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 17:14:12 +0300 Subject: [PATCH 1109/1406] update --- mini_nvimPlatformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index cbc0937e..28a62ffb 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -173,7 +173,7 @@ local sep = is_windows and '/' or '/' -- Set names for isolation vim.env.NVIM_APPNAME = app_name - +print(home) -- Manually set XDG paths to force isolation on both OS types if is_windows then vim.env.XDG_CONFIG_HOME = home .. sep .. app_name From 312f38766ae2a41ca12cb29f6e3e2607334da27c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 17:21:45 +0300 Subject: [PATCH 1110/1406] update --- mini_nvimPlatformio.lua | 51 +++++++++++++++-------------------------- 1 file changed, 18 insertions(+), 33 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 28a62ffb..96e69556 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -163,38 +163,32 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- INFO: Set mini lazy config ---------------------------------------------------------------------------------------- -- pick a temp root --- 1. CROSS-PLATFORM ENVIRONMENT ISOLATION --- This acts like the "bash" or "powershell" setup inside Lua -local app_name = 'nvim-min-platformio' + +local app_name = 'nvim-mini-pio' local is_windows = vim.loop.os_uname().sysname == 'Windows_NT' --- local home = vim.loop.os_tmpdir():gsub('\\', '/') -local home = is_windows and vim.env.USERPROFILE or vim.env.HOME -local sep = is_windows and '/' or '/' --- Set names for isolation +-- 1. SET NAMES FIRST vim.env.NVIM_APPNAME = app_name -print(home) --- Manually set XDG paths to force isolation on both OS types + +-- 2. ISOLATE ENVIRONMENT if is_windows then - vim.env.XDG_CONFIG_HOME = home .. sep .. app_name - print(vim.XDG_DATA_HOME) - vim.env.XDG_DATA_HOME = home .. sep .. app_name .. '-data' - vim.env.XDG_STATE_HOME = home .. sep .. app_name .. '-data' .. sep .. 'state' - vim.env.XDG_CACHE_HOME = home .. sep .. app_name .. '-data' .. sep .. 'cache' + -- Use AppData/Local to stay clean on Windows + local base = vim.env.LOCALAPPDATA .. '/' .. app_name .. '-sandbox' + vim.env.XDG_CONFIG_HOME = base .. '/config' + vim.env.XDG_DATA_HOME = base .. '/data' + vim.env.XDG_STATE_HOME = base .. '/state' + vim.env.XDG_CACHE_HOME = base .. '/cache' else + local home = vim.env.HOME vim.env.XDG_CONFIG_HOME = home .. '/.config/' .. app_name vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name - vim.env.XDG_STATE_HOME = home .. '/.local/state/' .. app_name - vim.env.XDG_CACHE_HOME = home .. '/.cache/' .. app_name end --- 2. CORE SETTINGS +-- 3. BOOTSTRAP (Use stdpath so it ALWAYS matches Neovim's internal logic) +local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' --- 3. BOOTSTRAP PLUGIN MANAGER (Lazy.nvim) -local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' --- local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' if not (vim.uv or vim.loop).fs_stat(lazypath) then - print('Attempting to download lazy.nvim ...') + print('Installing lazy.nvim to: ' .. lazypath) vim.fn.system({ 'git', 'clone', @@ -205,19 +199,10 @@ if not (vim.uv or vim.loop).fs_stat(lazypath) then }) end --- local lazypath = vim.fn.stdpath('data') .. separator .. 'lazy' .. separator .. 'lazy.nvim' --- if not vim.loop.fs_stat(lazypath) then --- vim.fn.system({ --- 'git', --- 'clone', --- '--filter=blob:none', --- 'https://github.com', --- '--branch=stable', --- lazypath, --- }) --- end --- +-- 4. ADD TO RUNTIME PATH (Crucial: makes 'require("lazy")' work) vim.opt.rtp:prepend(lazypath) + +print('Minimal environment active at: ' .. vim.fn.stdpath('config')) ------------------------------------------------------------------------------------ -- local tmp_root = vim.loop.os_tmpdir():gsub('\\', '/') .. '/nvim-temp' From aef79329fe5c6002dc493a9ee9cd62f2a723d93b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 17:33:47 +0300 Subject: [PATCH 1111/1406] update --- mini_nvimPlatformio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 96e69556..f9900526 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -164,7 +164,7 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) ---------------------------------------------------------------------------------------- -- pick a temp root -local app_name = 'nvim-mini-pio' +local app_name = 'nvim-piomini' local is_windows = vim.loop.os_uname().sysname == 'Windows_NT' -- 1. SET NAMES FIRST @@ -173,7 +173,7 @@ vim.env.NVIM_APPNAME = app_name -- 2. ISOLATE ENVIRONMENT if is_windows then -- Use AppData/Local to stay clean on Windows - local base = vim.env.LOCALAPPDATA .. '/' .. app_name .. '-sandbox' + local base = vim.env.LOCALAPPDATA .. '/' .. app_name vim.env.XDG_CONFIG_HOME = base .. '/config' vim.env.XDG_DATA_HOME = base .. '/data' vim.env.XDG_STATE_HOME = base .. '/state' From 25aa73ee4eaa861a06e2f8a8e0de0b85ccd71fb7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 18:02:12 +0300 Subject: [PATCH 1112/1406] update --- mini_nvimPlatformio.lua | 102 ++++++++++++++++++++-------------------- 1 file changed, 51 insertions(+), 51 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index f9900526..47b7fe9a 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -164,31 +164,57 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) ---------------------------------------------------------------------------------------- -- pick a temp root -local app_name = 'nvim-piomini' -local is_windows = vim.loop.os_uname().sysname == 'Windows_NT' - --- 1. SET NAMES FIRST -vim.env.NVIM_APPNAME = app_name - --- 2. ISOLATE ENVIRONMENT -if is_windows then - -- Use AppData/Local to stay clean on Windows - local base = vim.env.LOCALAPPDATA .. '/' .. app_name - vim.env.XDG_CONFIG_HOME = base .. '/config' - vim.env.XDG_DATA_HOME = base .. '/data' - vim.env.XDG_STATE_HOME = base .. '/state' - vim.env.XDG_CACHE_HOME = base .. '/cache' -else - local home = vim.env.HOME - vim.env.XDG_CONFIG_HOME = home .. '/.config/' .. app_name - vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name -end +-- local app_name = 'nvim-piomini' +-- local is_windows = vim.loop.os_uname().sysname == 'Windows_NT' +-- +-- -- 1. SET NAMES FIRST +-- vim.env.NVIM_APPNAME = app_name +-- +-- -- 2. ISOLATE ENVIRONMENT +-- if is_windows then +-- -- Use AppData/Local to stay clean on Windows +-- local base = vim.env.LOCALAPPDATA .. '/' .. app_name +-- vim.env.XDG_CONFIG_HOME = base .. '/config' +-- vim.env.XDG_DATA_HOME = base .. '/data' +-- vim.env.XDG_STATE_HOME = base .. '/state' +-- vim.env.XDG_CACHE_HOME = base .. '/cache' +-- else +-- local home = vim.env.HOME +-- vim.env.XDG_CONFIG_HOME = home .. '/.config/' .. app_name +-- vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name +-- end +-- +-- -- 3. BOOTSTRAP (Use stdpath so it ALWAYS matches Neovim's internal logic) +-- local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' +-- +-- if not (vim.uv or vim.loop).fs_stat(lazypath) then +-- print('Installing lazy.nvim to: ' .. lazypath) +-- vim.fn.system({ +-- 'git', +-- 'clone', +-- '--filter=blob:none', +-- 'https://github.com/folke/lazy.nvim.git', +-- '--branch=stable', +-- lazypath, +-- }) +-- end +-- +-- -- 4. ADD TO RUNTIME PATH (Crucial: makes 'require("lazy")' work) +-- vim.opt.rtp:prepend(lazypath) +-- +-- print('Minimal environment active at: ' .. vim.fn.stdpath('config')) +------------------------------------------------------------------------------------ --- 3. BOOTSTRAP (Use stdpath so it ALWAYS matches Neovim's internal logic) -local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' +local tmp_root = vim.loop.os_tmpdir():gsub('\\', '/') .. '/nvim-temp' +vim.env.XDG_CONFIG_HOME = tmp_root .. '/config' +vim.env.XDG_DATA_HOME = tmp_root .. '/data' +vim.env.XDG_CACHE_HOME = tmp_root .. '/cache' +vim.env.XDG_STATE_HOME = tmp_root .. '/state' +local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' +-- local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' if not (vim.uv or vim.loop).fs_stat(lazypath) then - print('Installing lazy.nvim to: ' .. lazypath) + print('Attempting to download lazy.nvim ...') vim.fn.system({ 'git', 'clone', @@ -199,32 +225,6 @@ if not (vim.uv or vim.loop).fs_stat(lazypath) then }) end --- 4. ADD TO RUNTIME PATH (Crucial: makes 'require("lazy")' work) -vim.opt.rtp:prepend(lazypath) - -print('Minimal environment active at: ' .. vim.fn.stdpath('config')) ------------------------------------------------------------------------------------- - --- local tmp_root = vim.loop.os_tmpdir():gsub('\\', '/') .. '/nvim-temp' --- vim.env.XDG_CONFIG_HOME = tmp_root .. '/config' --- vim.env.XDG_DATA_HOME = tmp_root .. '/data' --- vim.env.XDG_CACHE_HOME = tmp_root .. '/cache' --- vim.env.XDG_STATE_HOME = tmp_root .. '/state' --- --- local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' --- -- local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' --- if not (vim.uv or vim.loop).fs_stat(lazypath) then --- print('Attempting to download lazy.nvim ...') --- vim.fn.system({ --- 'git', --- 'clone', --- '--filter=blob:none', --- 'https://github.com/folke/lazy.nvim.git', --- '--branch=stable', --- lazypath, --- }) --- end --- -- local checker = io.open(lazypath .. '/lua/lazy/init.lua', 'r') -- if checker then -- checker:close() @@ -234,9 +234,9 @@ print('Minimal environment active at: ' .. vim.fn.stdpath('config')) -- vim.fn.delete(lazypath, 'rf') -- error('FATAL: Downloaded folder is corrupted. Retrying next launch.') -- end --- --- vim.opt.rtp:prepend(lazypath) --- package.path = package.path .. ';' .. lazypath .. '/lua/?.lua;' .. lazypath .. '/lua/?/init.lua' + +vim.opt.rtp:prepend(lazypath) +print('Minimal environment active at: ' .. vim.fn.stdpath('config')) ---------------------------------------------------------------------------------------- -- INFO: define plugins table From 6ca3f800ff62c6b0fa7de48bd0f9b79faa0e18f3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 18:08:47 +0300 Subject: [PATCH 1113/1406] update --- mini_nvimPlatformio.lua | 116 ++++++++++++++++++++-------------------- 1 file changed, 58 insertions(+), 58 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 47b7fe9a..6a86c3bb 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -164,57 +164,31 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) ---------------------------------------------------------------------------------------- -- pick a temp root --- local app_name = 'nvim-piomini' --- local is_windows = vim.loop.os_uname().sysname == 'Windows_NT' --- --- -- 1. SET NAMES FIRST --- vim.env.NVIM_APPNAME = app_name --- --- -- 2. ISOLATE ENVIRONMENT --- if is_windows then --- -- Use AppData/Local to stay clean on Windows --- local base = vim.env.LOCALAPPDATA .. '/' .. app_name --- vim.env.XDG_CONFIG_HOME = base .. '/config' --- vim.env.XDG_DATA_HOME = base .. '/data' --- vim.env.XDG_STATE_HOME = base .. '/state' --- vim.env.XDG_CACHE_HOME = base .. '/cache' --- else --- local home = vim.env.HOME --- vim.env.XDG_CONFIG_HOME = home .. '/.config/' .. app_name --- vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name --- end --- --- -- 3. BOOTSTRAP (Use stdpath so it ALWAYS matches Neovim's internal logic) --- local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' --- --- if not (vim.uv or vim.loop).fs_stat(lazypath) then --- print('Installing lazy.nvim to: ' .. lazypath) --- vim.fn.system({ --- 'git', --- 'clone', --- '--filter=blob:none', --- 'https://github.com/folke/lazy.nvim.git', --- '--branch=stable', --- lazypath, --- }) --- end --- --- -- 4. ADD TO RUNTIME PATH (Crucial: makes 'require("lazy")' work) --- vim.opt.rtp:prepend(lazypath) --- --- print('Minimal environment active at: ' .. vim.fn.stdpath('config')) ------------------------------------------------------------------------------------- +local app_name = 'nvim-pio' +local is_windows = vim.loop.os_uname().sysname == 'Windows_NT' + +-- 1. SET NAMES FIRST +vim.env.NVIM_APPNAME = app_name + +-- 2. ISOLATE ENVIRONMENT +if is_windows then + -- Use AppData/Local to stay clean on Windows + local base = vim.env.LOCALAPPDATA .. '/' .. app_name + vim.env.XDG_CONFIG_HOME = base .. '/config' + vim.env.XDG_DATA_HOME = base .. '/data' + vim.env.XDG_STATE_HOME = base .. '/state' + vim.env.XDG_CACHE_HOME = base .. '/cache' +else + local home = vim.env.HOME + vim.env.XDG_CONFIG_HOME = home .. '/.config/' .. app_name + vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name +end -local tmp_root = vim.loop.os_tmpdir():gsub('\\', '/') .. '/nvim-temp' -vim.env.XDG_CONFIG_HOME = tmp_root .. '/config' -vim.env.XDG_DATA_HOME = tmp_root .. '/data' -vim.env.XDG_CACHE_HOME = tmp_root .. '/cache' -vim.env.XDG_STATE_HOME = tmp_root .. '/state' +-- 3. BOOTSTRAP (Use stdpath so it ALWAYS matches Neovim's internal logic) +local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' -local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' --- local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' if not (vim.uv or vim.loop).fs_stat(lazypath) then - print('Attempting to download lazy.nvim ...') + print('Installing lazy.nvim to: ' .. lazypath) vim.fn.system({ 'git', 'clone', @@ -225,18 +199,44 @@ if not (vim.uv or vim.loop).fs_stat(lazypath) then }) end --- local checker = io.open(lazypath .. '/lua/lazy/init.lua', 'r') --- if checker then --- checker:close() --- vim.opt.rtp:prepend(lazypath) --- package.path = package.path .. ';' .. lazypath .. '/lua/?.lua;' .. lazypath .. '/lua/?/init.lua' --- else --- vim.fn.delete(lazypath, 'rf') --- error('FATAL: Downloaded folder is corrupted. Retrying next launch.') --- end - +-- 4. ADD TO RUNTIME PATH (Crucial: makes 'require("lazy")' work) vim.opt.rtp:prepend(lazypath) + print('Minimal environment active at: ' .. vim.fn.stdpath('config')) +------------------------------------------------------------------------------------ + +-- local tmp_root = vim.loop.os_tmpdir():gsub('\\', '/') .. '/nvim-temp' +-- vim.env.XDG_CONFIG_HOME = tmp_root .. '/config' +-- vim.env.XDG_DATA_HOME = tmp_root .. '/data' +-- vim.env.XDG_CACHE_HOME = tmp_root .. '/cache' +-- vim.env.XDG_STATE_HOME = tmp_root .. '/state' +-- +-- local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' +-- -- local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' +-- if not (vim.uv or vim.loop).fs_stat(lazypath) then +-- print('Attempting to download lazy.nvim ...') +-- vim.fn.system({ +-- 'git', +-- 'clone', +-- '--filter=blob:none', +-- 'https://github.com/folke/lazy.nvim.git', +-- '--branch=stable', +-- lazypath, +-- }) +-- end +-- +-- -- local checker = io.open(lazypath .. '/lua/lazy/init.lua', 'r') +-- -- if checker then +-- -- checker:close() +-- -- vim.opt.rtp:prepend(lazypath) +-- -- package.path = package.path .. ';' .. lazypath .. '/lua/?.lua;' .. lazypath .. '/lua/?/init.lua' +-- -- else +-- -- vim.fn.delete(lazypath, 'rf') +-- -- error('FATAL: Downloaded folder is corrupted. Retrying next launch.') +-- -- end +-- +-- vim.opt.rtp:prepend(lazypath) +-- print('Minimal environment active at: ' .. vim.fn.stdpath('config')) ---------------------------------------------------------------------------------------- -- INFO: define plugins table From d350742cd980398a95f03f8f0c2201af6ad34710 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 18:17:50 +0300 Subject: [PATCH 1114/1406] update --- mini_nvimPlatformio.lua | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 6a86c3bb..cc21c6a4 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -166,23 +166,36 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) local app_name = 'nvim-pio' local is_windows = vim.loop.os_uname().sysname == 'Windows_NT' - --- 1. SET NAMES FIRST +local separator = is_windows and '\\' or '/' +-- 1. SET THE APP NAME (This is the key) vim.env.NVIM_APPNAME = app_name -- 2. ISOLATE ENVIRONMENT if is_windows then - -- Use AppData/Local to stay clean on Windows - local base = vim.env.LOCALAPPDATA .. '/' .. app_name - vim.env.XDG_CONFIG_HOME = base .. '/config' - vim.env.XDG_DATA_HOME = base .. '/data' - vim.env.XDG_STATE_HOME = base .. '/state' - vim.env.XDG_CACHE_HOME = base .. '/cache' + -- Point to a unique sandbox root + local sandbox = vim.env.USERPROFILE .. '\\AppData\\Local\\' .. app_name .. '-sandbox' + vim.env.LOCALAPPDATA = sandbox else local home = vim.env.HOME - vim.env.XDG_CONFIG_HOME = home .. '/.config/' .. app_name - vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name + vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name .. '-sandbox' end +-- +-- -- 1. SET NAMES FIRST +-- vim.env.NVIM_APPNAME = app_name +-- +-- -- 2. ISOLATE ENVIRONMENT +-- if is_windows then +-- -- Use AppData/Local to stay clean on Windows +-- local base = vim.env.LOCALAPPDATA .. '/' .. app_name +-- vim.env.XDG_CONFIG_HOME = base .. '/config' +-- vim.env.XDG_DATA_HOME = base .. '/data' +-- vim.env.XDG_STATE_HOME = base .. '/state' +-- vim.env.XDG_CACHE_HOME = base .. '/cache' +-- else +-- local home = vim.env.HOME +-- vim.env.XDG_CONFIG_HOME = home .. '/.config/' .. app_name +-- vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name +-- end -- 3. BOOTSTRAP (Use stdpath so it ALWAYS matches Neovim's internal logic) local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' From ed18cc0e346a5d785e003fdfbd8fff2fcf03efd0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 18:49:27 +0300 Subject: [PATCH 1115/1406] update --- mini_nvimPlatformio.lua | 52 ++++++++++++++++------------------------- 1 file changed, 20 insertions(+), 32 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index cc21c6a4..faedda6f 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -166,36 +166,34 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) local app_name = 'nvim-pio' local is_windows = vim.loop.os_uname().sysname == 'Windows_NT' -local separator = is_windows and '\\' or '/' +local sep = is_windows and '\\' or '/' -- 1. SET THE APP NAME (This is the key) vim.env.NVIM_APPNAME = app_name --- 2. ISOLATE ENVIRONMENT -if is_windows then - -- Point to a unique sandbox root - local sandbox = vim.env.USERPROFILE .. '\\AppData\\Local\\' .. app_name .. '-sandbox' - vim.env.LOCALAPPDATA = sandbox -else - local home = vim.env.HOME - vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name .. '-sandbox' -end --- --- -- 1. SET NAMES FIRST --- vim.env.NVIM_APPNAME = app_name --- -- -- 2. ISOLATE ENVIRONMENT -- if is_windows then --- -- Use AppData/Local to stay clean on Windows --- local base = vim.env.LOCALAPPDATA .. '/' .. app_name --- vim.env.XDG_CONFIG_HOME = base .. '/config' --- vim.env.XDG_DATA_HOME = base .. '/data' --- vim.env.XDG_STATE_HOME = base .. '/state' --- vim.env.XDG_CACHE_HOME = base .. '/cache' +-- -- Point to a unique sandbox root +-- local sandbox = vim.env.USERPROFILE .. '\\AppData\\Local\\' .. app_name .. '-sandbox' +-- vim.env.LOCALAPPDATA = sandbox -- else -- local home = vim.env.HOME --- vim.env.XDG_CONFIG_HOME = home .. '/.config/' .. app_name --- vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name +-- vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name .. '-sandbox' -- end +-- +-- +-- 2. ISOLATE ENVIRONMENT +if is_windows then + -- Use AppData/Local to stay clean on Windows + local base = vim.env.LOCALAPPDATA .. '/' .. app_name + vim.env.XDG_CONFIG_HOME = base .. '/config' + vim.env.XDG_DATA_HOME = base .. '/data' + vim.env.XDG_STATE_HOME = base .. '/state' + vim.env.XDG_CACHE_HOME = base .. '/cache' +else + local home = vim.env.HOME + vim.env.XDG_CONFIG_HOME = home .. '/.config/' .. app_name + vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name +end -- 3. BOOTSTRAP (Use stdpath so it ALWAYS matches Neovim's internal logic) local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' @@ -238,16 +236,6 @@ print('Minimal environment active at: ' .. vim.fn.stdpath('config')) -- }) -- end -- --- -- local checker = io.open(lazypath .. '/lua/lazy/init.lua', 'r') --- -- if checker then --- -- checker:close() --- -- vim.opt.rtp:prepend(lazypath) --- -- package.path = package.path .. ';' .. lazypath .. '/lua/?.lua;' .. lazypath .. '/lua/?/init.lua' --- -- else --- -- vim.fn.delete(lazypath, 'rf') --- -- error('FATAL: Downloaded folder is corrupted. Retrying next launch.') --- -- end --- -- vim.opt.rtp:prepend(lazypath) -- print('Minimal environment active at: ' .. vim.fn.stdpath('config')) From c9808475004af11e9d19fa5e3c2f3048c5207765 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 18:51:18 +0300 Subject: [PATCH 1116/1406] update --- mini_nvimPlatformio.lua | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index faedda6f..476a033a 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -170,30 +170,30 @@ local sep = is_windows and '\\' or '/' -- 1. SET THE APP NAME (This is the key) vim.env.NVIM_APPNAME = app_name --- -- 2. ISOLATE ENVIRONMENT --- if is_windows then --- -- Point to a unique sandbox root --- local sandbox = vim.env.USERPROFILE .. '\\AppData\\Local\\' .. app_name .. '-sandbox' --- vim.env.LOCALAPPDATA = sandbox --- else --- local home = vim.env.HOME --- vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name .. '-sandbox' --- end --- --- -- 2. ISOLATE ENVIRONMENT if is_windows then - -- Use AppData/Local to stay clean on Windows - local base = vim.env.LOCALAPPDATA .. '/' .. app_name - vim.env.XDG_CONFIG_HOME = base .. '/config' - vim.env.XDG_DATA_HOME = base .. '/data' - vim.env.XDG_STATE_HOME = base .. '/state' - vim.env.XDG_CACHE_HOME = base .. '/cache' + -- Point to a unique sandbox root + local sandbox = vim.env.USERPROFILE .. '\\AppData\\Local\\' .. app_name .. '-sandbox' + vim.env.LOCALAPPDATA = sandbox else local home = vim.env.HOME - vim.env.XDG_CONFIG_HOME = home .. '/.config/' .. app_name - vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name + vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name .. '-sandbox' end +-- +-- +-- 2. ISOLATE ENVIRONMENT +-- if is_windows then +-- -- Use AppData/Local to stay clean on Windows +-- local base = vim.env.LOCALAPPDATA .. '/' .. app_name +-- vim.env.XDG_CONFIG_HOME = base .. '/config' +-- vim.env.XDG_DATA_HOME = base .. '/data' +-- vim.env.XDG_STATE_HOME = base .. '/state' +-- vim.env.XDG_CACHE_HOME = base .. '/cache' +-- else +-- local home = vim.env.HOME +-- vim.env.XDG_CONFIG_HOME = home .. '/.config/' .. app_name +-- vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name +-- end -- 3. BOOTSTRAP (Use stdpath so it ALWAYS matches Neovim's internal logic) local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' From f6d89f00755857cbcba8c9315eb6366f8fd7f559 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 19:40:51 +0300 Subject: [PATCH 1117/1406] update --- mini_nvimPlatformio.lua | 62 +++++++++++++++++------------------------ 1 file changed, 26 insertions(+), 36 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 476a033a..1b80fe4c 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -162,40 +162,35 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) ---------------------------------------------------------------------------------------- -- INFO: Set mini lazy config ---------------------------------------------------------------------------------------- --- pick a temp root - -local app_name = 'nvim-pio' -local is_windows = vim.loop.os_uname().sysname == 'Windows_NT' -local sep = is_windows and '\\' or '/' --- 1. SET THE APP NAME (This is the key) -vim.env.NVIM_APPNAME = app_name - --- 2. ISOLATE ENVIRONMENT -if is_windows then - -- Point to a unique sandbox root - local sandbox = vim.env.USERPROFILE .. '\\AppData\\Local\\' .. app_name .. '-sandbox' - vim.env.LOCALAPPDATA = sandbox +local app_name = 'nvim-pio' -- pick a temp root +vim.env.NVIM_APPNAME = app_name --isolated nvim +local home = isWindows and vim.env.LOCALAPPDATA:gsub('\\', '/') or vim.env.HOME +home = home .. '/' .. app_name + +---[[ +if isWindows then + -- Use AppData/Local to stay clean on Windows + vim.env.XDG_CONFIG_HOME = home .. '/config' + vim.env.XDG_DATA_HOME = home .. '/data' + vim.env.XDG_STATE_HOME = home .. '/state' + vim.env.XDG_CACHE_HOME = home .. '/cache' else - local home = vim.env.HOME - vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name .. '-sandbox' + vim.env.XDG_CONFIG_HOME = home .. '/.config/' + vim.env.XDG_DATA_HOME = home .. '/.local/share/' + vim.env.XDG_STATE_HOME = home .. '/.local/state/' + vim.env.XDG_CACHE_HOME = home .. '/.cache/' end --- --- --- 2. ISOLATE ENVIRONMENT --- if is_windows then --- -- Use AppData/Local to stay clean on Windows --- local base = vim.env.LOCALAPPDATA .. '/' .. app_name --- vim.env.XDG_CONFIG_HOME = base .. '/config' --- vim.env.XDG_DATA_HOME = base .. '/data' --- vim.env.XDG_STATE_HOME = base .. '/state' --- vim.env.XDG_CACHE_HOME = base .. '/cache' --- else --- local home = vim.env.HOME --- vim.env.XDG_CONFIG_HOME = home .. '/.config/' .. app_name --- vim.env.XDG_DATA_HOME = home .. '/.local/share/' .. app_name --- end +--]] + +--[[ +local tmp_root = vim.loop.os_tmpdir():gsub('\\', '/') .. app_name +vim.env.XDG_CONFIG_HOME = tmp_root .. '/config' +vim.env.XDG_DATA_HOME = tmp_root .. '/data' +vim.env.XDG_CACHE_HOME = tmp_root .. '/cache' +vim.env.XDG_STATE_HOME = tmp_root .. '/state' +--]] --- 3. BOOTSTRAP (Use stdpath so it ALWAYS matches Neovim's internal logic) +-- BOOTSTRAP (Use stdpath so it ALWAYS matches Neovim's internal logic) local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' if not (vim.uv or vim.loop).fs_stat(lazypath) then @@ -216,11 +211,6 @@ vim.opt.rtp:prepend(lazypath) print('Minimal environment active at: ' .. vim.fn.stdpath('config')) ------------------------------------------------------------------------------------ --- local tmp_root = vim.loop.os_tmpdir():gsub('\\', '/') .. '/nvim-temp' --- vim.env.XDG_CONFIG_HOME = tmp_root .. '/config' --- vim.env.XDG_DATA_HOME = tmp_root .. '/data' --- vim.env.XDG_CACHE_HOME = tmp_root .. '/cache' --- vim.env.XDG_STATE_HOME = tmp_root .. '/state' -- -- local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' -- -- local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' From 447164693414c29f4058ec1774e52507ca4a3744 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 19:44:32 +0300 Subject: [PATCH 1118/1406] update --- mini_nvimPlatformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 1b80fe4c..0ca06cb9 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -163,10 +163,10 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- INFO: Set mini lazy config ---------------------------------------------------------------------------------------- local app_name = 'nvim-pio' -- pick a temp root -vim.env.NVIM_APPNAME = app_name --isolated nvim local home = isWindows and vim.env.LOCALAPPDATA:gsub('\\', '/') or vim.env.HOME home = home .. '/' .. app_name +-- vim.env.NVIM_APPNAME = app_name --isolated nvim ---[[ if isWindows then -- Use AppData/Local to stay clean on Windows From f122e5f78fbd9114aa67ce386939886589e05b25 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 19:54:08 +0300 Subject: [PATCH 1119/1406] update --- mini_nvimPlatformio.lua | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 0ca06cb9..2f6c59ca 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -165,25 +165,17 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) local app_name = 'nvim-pio' -- pick a temp root local home = isWindows and vim.env.LOCALAPPDATA:gsub('\\', '/') or vim.env.HOME home = home .. '/' .. app_name +-- local home = vim.loop.os_tmpdir():gsub('\\', '/') .. '/' .. app_name -- vim.env.NVIM_APPNAME = app_name --isolated nvim ---[[ -if isWindows then - -- Use AppData/Local to stay clean on Windows - vim.env.XDG_CONFIG_HOME = home .. '/config' - vim.env.XDG_DATA_HOME = home .. '/data' - vim.env.XDG_STATE_HOME = home .. '/state' - vim.env.XDG_CACHE_HOME = home .. '/cache' -else - vim.env.XDG_CONFIG_HOME = home .. '/.config/' - vim.env.XDG_DATA_HOME = home .. '/.local/share/' - vim.env.XDG_STATE_HOME = home .. '/.local/state/' - vim.env.XDG_CACHE_HOME = home .. '/.cache/' -end +vim.env.XDG_CONFIG_HOME = home .. isWindows and '/config/' or '/.config' +vim.env.XDG_DATA_HOME = home .. isWindows and '/data/' or '/.local/share/' +vim.env.XDG_STATE_HOME = home .. isWindows and '/state/' or '/.local/state/' +vim.env.XDG_CACHE_HOME = home .. isWindows and '/cache/' or '/.cache/' --]] --[[ -local tmp_root = vim.loop.os_tmpdir():gsub('\\', '/') .. app_name vim.env.XDG_CONFIG_HOME = tmp_root .. '/config' vim.env.XDG_DATA_HOME = tmp_root .. '/data' vim.env.XDG_CACHE_HOME = tmp_root .. '/cache' From 3f4176fe6eeac73e81d712e9becd718da6118a5e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 19:56:35 +0300 Subject: [PATCH 1120/1406] update --- mini_nvimPlatformio.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 2f6c59ca..46a3e5a3 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -169,10 +169,10 @@ home = home .. '/' .. app_name -- vim.env.NVIM_APPNAME = app_name --isolated nvim ---[[ -vim.env.XDG_CONFIG_HOME = home .. isWindows and '/config/' or '/.config' -vim.env.XDG_DATA_HOME = home .. isWindows and '/data/' or '/.local/share/' -vim.env.XDG_STATE_HOME = home .. isWindows and '/state/' or '/.local/state/' -vim.env.XDG_CACHE_HOME = home .. isWindows and '/cache/' or '/.cache/' +vim.env.XDG_CONFIG_HOME = home .. (isWindows and '/config/' or '/.config') +vim.env.XDG_DATA_HOME = home .. (isWindows and '/data/' or '/.local/share/') +vim.env.XDG_STATE_HOME = home .. (isWindows and '/state/' or '/.local/state/') +vim.env.XDG_CACHE_HOME = home .. (isWindows and '/cache/' or '/.cache/') --]] --[[ From 35734f4793168fdb3e0468004f55847220933dde Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 20:32:14 +0300 Subject: [PATCH 1121/1406] update --- mini_nvimPlatformio.lua | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 46a3e5a3..20b74da7 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -170,18 +170,11 @@ home = home .. '/' .. app_name -- vim.env.NVIM_APPNAME = app_name --isolated nvim ---[[ vim.env.XDG_CONFIG_HOME = home .. (isWindows and '/config/' or '/.config') -vim.env.XDG_DATA_HOME = home .. (isWindows and '/data/' or '/.local/share/') +vim.env.XDG_DATA_HOME = home --.. (isWindows and '/data/' or '/.local/share/') vim.env.XDG_STATE_HOME = home .. (isWindows and '/state/' or '/.local/state/') vim.env.XDG_CACHE_HOME = home .. (isWindows and '/cache/' or '/.cache/') --]] ---[[ -vim.env.XDG_CONFIG_HOME = tmp_root .. '/config' -vim.env.XDG_DATA_HOME = tmp_root .. '/data' -vim.env.XDG_CACHE_HOME = tmp_root .. '/cache' -vim.env.XDG_STATE_HOME = tmp_root .. '/state' ---]] - -- BOOTSTRAP (Use stdpath so it ALWAYS matches Neovim's internal logic) local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' @@ -197,7 +190,7 @@ if not (vim.uv or vim.loop).fs_stat(lazypath) then }) end --- 4. ADD TO RUNTIME PATH (Crucial: makes 'require("lazy")' work) +-- ADD TO RUNTIME PATH (Crucial: makes 'require("lazy")' work) vim.opt.rtp:prepend(lazypath) print('Minimal environment active at: ' .. vim.fn.stdpath('config')) From 234c98f25298c9aea3346199a16caa68d604e240 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 20:43:46 +0300 Subject: [PATCH 1122/1406] update --- mini_nvimPlatformio.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 20b74da7..1e57bac6 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -169,10 +169,10 @@ home = home .. '/' .. app_name -- vim.env.NVIM_APPNAME = app_name --isolated nvim ---[[ -vim.env.XDG_CONFIG_HOME = home .. (isWindows and '/config/' or '/.config') -vim.env.XDG_DATA_HOME = home --.. (isWindows and '/data/' or '/.local/share/') -vim.env.XDG_STATE_HOME = home .. (isWindows and '/state/' or '/.local/state/') -vim.env.XDG_CACHE_HOME = home .. (isWindows and '/cache/' or '/.cache/') +vim.env.XDG_CONFIG_HOME = home -- .. (isWindows and '/config/' or '/.config') +vim.env.XDG_DATA_HOME = home -- .. (isWindows and '/data/' or '/.local/share/') +vim.env.XDG_STATE_HOME = home -- .. (isWindows and '/state/' or '/.local/state/') +vim.env.XDG_CACHE_HOME = home -- .. (isWindows and '/cache/' or '/.cache/') --]] -- BOOTSTRAP (Use stdpath so it ALWAYS matches Neovim's internal logic) From c4a3f9581f42229e9dc1c30086aa3d57277d8a72 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 21:06:07 +0300 Subject: [PATCH 1123/1406] update --- mini_nvimPlatformio.lua | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 1e57bac6..1e23c76c 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -162,19 +162,32 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) ---------------------------------------------------------------------------------------- -- INFO: Set mini lazy config ---------------------------------------------------------------------------------------- +--[[ local app_name = 'nvim-pio' -- pick a temp root local home = isWindows and vim.env.LOCALAPPDATA:gsub('\\', '/') or vim.env.HOME home = home .. '/' .. app_name -- local home = vim.loop.os_tmpdir():gsub('\\', '/') .. '/' .. app_name -- vim.env.NVIM_APPNAME = app_name --isolated nvim ----[[ vim.env.XDG_CONFIG_HOME = home -- .. (isWindows and '/config/' or '/.config') vim.env.XDG_DATA_HOME = home -- .. (isWindows and '/data/' or '/.local/share/') vim.env.XDG_STATE_HOME = home -- .. (isWindows and '/state/' or '/.local/state/') vim.env.XDG_CACHE_HOME = home -- .. (isWindows and '/cache/' or '/.cache/') --]] +local app_name = 'nvim-pio' +local base_path = isWindows and vim.env.LOCALAPPDATA:gsub('\\', '/') or vim.env.HOME + +-- 1. THE "FLATTENER": Set NVIM_APPNAME to match your root folder name +vim.env.NVIM_APPNAME = app_name + +-- 2. Set XDG variables to the PARENT of where you want the app to live +-- Neovim will automatically append /nvim-pio to each of these +vim.env.XDG_CONFIG_HOME = base_path +vim.env.XDG_DATA_HOME = base_path +vim.env.XDG_STATE_HOME = base_path +vim.env.XDG_CACHE_HOME = base_path + -- BOOTSTRAP (Use stdpath so it ALWAYS matches Neovim's internal logic) local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' @@ -391,6 +404,30 @@ vim.api.nvim_create_autocmd('User', { end, }) +-- SELECTIVE CLEANUP ON EXIT (Keeps plugins, deletes temp files) +-- stylua: ignore +vim.api.nvim_create_autocmd('VimLeave', { + callback = function() + -- stdpath("cache") and stdpath("state") point to the isolated folders + local folders_to_clean = { + vim.fn.stdpath('cache'), + vim.fn.stdpath('state'), + } + + for _, path in ipairs(folders_to_clean) do + if vim.fn.isdirectory(path) == 1 then + local cmd = isWindows and string.format('rmdir /s /q "%s"', path:gsub('/', '\\')) or string.format('rm -rf "%s"', path) + + -- Detach so it finishes after Neovim closes + vim.fn.jobstart(cmd, { detach = true }) + end + end + + -- Optional: Also delete the .ccl file on every exit + local ccl_file = vim.fn.getcwd() .. '/.ccl' + if vim.fn.filereadable(ccl_file) == 1 then os.remove(ccl_file) end + end, +}) ---------------------------------------------------------------------------------------- -- INFO: set up python nvim venv (virtual environment 'nenv'), activaten. local platformio_core_dir, pynvim_env, pynvim_python, pynvim_lib, pynvim_bin, pynvim_activate From 9e64e9c8a2171859a1c92b73894cd3974067f039 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 21:10:48 +0300 Subject: [PATCH 1124/1406] update --- mini_nvimPlatformio.lua | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 1e23c76c..187c876f 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -162,7 +162,7 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) ---------------------------------------------------------------------------------------- -- INFO: Set mini lazy config ---------------------------------------------------------------------------------------- ---[[ +---[[ local app_name = 'nvim-pio' -- pick a temp root local home = isWindows and vim.env.LOCALAPPDATA:gsub('\\', '/') or vim.env.HOME home = home .. '/' .. app_name @@ -175,6 +175,7 @@ vim.env.XDG_STATE_HOME = home -- .. (isWindows and '/state/' or '/.local/state/' vim.env.XDG_CACHE_HOME = home -- .. (isWindows and '/cache/' or '/.cache/') --]] +--[[ local app_name = 'nvim-pio' local base_path = isWindows and vim.env.LOCALAPPDATA:gsub('\\', '/') or vim.env.HOME @@ -187,6 +188,7 @@ vim.env.XDG_CONFIG_HOME = base_path vim.env.XDG_DATA_HOME = base_path vim.env.XDG_STATE_HOME = base_path vim.env.XDG_CACHE_HOME = base_path +--]] -- BOOTSTRAP (Use stdpath so it ALWAYS matches Neovim's internal logic) local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' From 0677e8d24587aa4ad751d938a1dbd268f89aef3d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 21:12:09 +0300 Subject: [PATCH 1125/1406] update --- mini_nvimPlatformio.lua | 54 ++++++++++++++++++++++++++--------------- 1 file changed, 35 insertions(+), 19 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 187c876f..d2e1ca6d 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -406,30 +406,46 @@ vim.api.nvim_create_autocmd('User', { end, }) --- SELECTIVE CLEANUP ON EXIT (Keeps plugins, deletes temp files) --- stylua: ignore +-- AUTO-CLEANUP ON EXIT vim.api.nvim_create_autocmd('VimLeave', { callback = function() - -- stdpath("cache") and stdpath("state") point to the isolated folders - local folders_to_clean = { - vim.fn.stdpath('cache'), - vim.fn.stdpath('state'), - } - - for _, path in ipairs(folders_to_clean) do - if vim.fn.isdirectory(path) == 1 then - local cmd = isWindows and string.format('rmdir /s /q "%s"', path:gsub('/', '\\')) or string.format('rm -rf "%s"', path) - - -- Detach so it finishes after Neovim closes - vim.fn.jobstart(cmd, { detach = true }) - end - end + -- Get the root sandbox directory from our 'home' variable + local sandbox_path = home + + if vim.fn.isdirectory(sandbox_path) == 1 then + -- Use a system command to recursively delete the folder + -- Windows uses 'rmdir /s /q', Linux/macOS uses 'rm -rf' + local cmd = isWindows and string.format('rmdir /s /q "%s"', sandbox_path:gsub('/', '\\')) or string.format('rm -rf "%s"', sandbox_path) - -- Optional: Also delete the .ccl file on every exit - local ccl_file = vim.fn.getcwd() .. '/.ccl' - if vim.fn.filereadable(ccl_file) == 1 then os.remove(ccl_file) end + -- Execute the deletion in the background as we exit + vim.fn.jobstart(cmd, { detach = true }) + end end, }) +-- SELECTIVE CLEANUP ON EXIT (Keeps plugins, deletes temp files) +-- stylua: ignore +-- vim.api.nvim_create_autocmd('VimLeave', { +-- callback = function() +-- -- stdpath("cache") and stdpath("state") point to the isolated folders +-- local folders_to_clean = { +-- vim.fn.stdpath('cache'), +-- vim.fn.stdpath('state'), +-- } +-- +-- for _, path in ipairs(folders_to_clean) do +-- if vim.fn.isdirectory(path) == 1 then +-- local cmd = isWindows and string.format('rmdir /s /q "%s"', path:gsub('/', '\\')) or string.format('rm -rf "%s"', path) +-- +-- -- Detach so it finishes after Neovim closes +-- vim.fn.jobstart(cmd, { detach = true }) +-- end +-- end +-- +-- -- Optional: Also delete the .ccl file on every exit +-- local ccl_file = vim.fn.getcwd() .. '/.ccl' +-- if vim.fn.filereadable(ccl_file) == 1 then os.remove(ccl_file) end +-- end, +-- }) ---------------------------------------------------------------------------------------- -- INFO: set up python nvim venv (virtual environment 'nenv'), activaten. local platformio_core_dir, pynvim_env, pynvim_python, pynvim_lib, pynvim_bin, pynvim_activate From 4b6a1bf4e4ca8065fd2e9bd1052ebc29058cca8e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 21:21:27 +0300 Subject: [PATCH 1126/1406] update --- mini_nvimPlatformio.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index d2e1ca6d..b267619f 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -169,10 +169,10 @@ home = home .. '/' .. app_name -- local home = vim.loop.os_tmpdir():gsub('\\', '/') .. '/' .. app_name -- vim.env.NVIM_APPNAME = app_name --isolated nvim -vim.env.XDG_CONFIG_HOME = home -- .. (isWindows and '/config/' or '/.config') -vim.env.XDG_DATA_HOME = home -- .. (isWindows and '/data/' or '/.local/share/') -vim.env.XDG_STATE_HOME = home -- .. (isWindows and '/state/' or '/.local/state/') -vim.env.XDG_CACHE_HOME = home -- .. (isWindows and '/cache/' or '/.cache/') +vim.env.XDG_CONFIG_HOME = home .. (isWindows and '/config/' or '/.config') +vim.env.XDG_DATA_HOME = home .. (isWindows and '/data/' or '/.local/share/') +vim.env.XDG_STATE_HOME = home .. (isWindows and '/state/' or '/.local/state/') +vim.env.XDG_CACHE_HOME = home .. (isWindows and '/cache/' or '/.cache/') --]] --[[ From 75d35fef279eda2a811eeb1b61a68d7abca8b8a6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 21:24:05 +0300 Subject: [PATCH 1127/1406] update --- mini_nvimPlatformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index b267619f..74bf8da9 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -168,7 +168,7 @@ local home = isWindows and vim.env.LOCALAPPDATA:gsub('\\', '/') or vim.env.HOME home = home .. '/' .. app_name -- local home = vim.loop.os_tmpdir():gsub('\\', '/') .. '/' .. app_name --- vim.env.NVIM_APPNAME = app_name --isolated nvim +vim.env.NVIM_APPNAME = app_name --isolated nvim vim.env.XDG_CONFIG_HOME = home .. (isWindows and '/config/' or '/.config') vim.env.XDG_DATA_HOME = home .. (isWindows and '/data/' or '/.local/share/') vim.env.XDG_STATE_HOME = home .. (isWindows and '/state/' or '/.local/state/') From cb27d0d0e5f08e1093aebe76557e157862cf3b51 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 21:34:32 +0300 Subject: [PATCH 1128/1406] update --- mini_nvimPlatformio.lua | 58 ++++++++++++++++------------------------- 1 file changed, 22 insertions(+), 36 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 74bf8da9..c71da2ff 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -168,7 +168,7 @@ local home = isWindows and vim.env.LOCALAPPDATA:gsub('\\', '/') or vim.env.HOME home = home .. '/' .. app_name -- local home = vim.loop.os_tmpdir():gsub('\\', '/') .. '/' .. app_name -vim.env.NVIM_APPNAME = app_name --isolated nvim +-- vim.env.NVIM_APPNAME = app_name --isolated nvim vim.env.XDG_CONFIG_HOME = home .. (isWindows and '/config/' or '/.config') vim.env.XDG_DATA_HOME = home .. (isWindows and '/data/' or '/.local/share/') vim.env.XDG_STATE_HOME = home .. (isWindows and '/state/' or '/.local/state/') @@ -407,45 +407,31 @@ vim.api.nvim_create_autocmd('User', { }) -- AUTO-CLEANUP ON EXIT -vim.api.nvim_create_autocmd('VimLeave', { +-- SELECTIVE CLEANUP ON EXIT (Keeps plugins, deletes temp files) +-- stylua: ignore +-- SELECTIVE CLEANUP FOR WINDOWS +vim.api.nvim_create_autocmd("VimLeave", { callback = function() - -- Get the root sandbox directory from our 'home' variable - local sandbox_path = home - - if vim.fn.isdirectory(sandbox_path) == 1 then - -- Use a system command to recursively delete the folder - -- Windows uses 'rmdir /s /q', Linux/macOS uses 'rm -rf' - local cmd = isWindows and string.format('rmdir /s /q "%s"', sandbox_path:gsub('/', '\\')) or string.format('rm -rf "%s"', sandbox_path) - - -- Execute the deletion in the background as we exit - vim.fn.jobstart(cmd, { detach = true }) + -- On Windows, we specifically want to wipe the shada and temp files + local state_path = vim.fn.stdpath("state") + local cache_path = vim.fn.stdpath("cache") + + local targets = { + state_path .. "/shada", -- Delete history/marks + cache_path, -- Delete temp bytecode + } + + for _, path in ipairs(targets) do + if vim.fn.isdirectory(path) == 1 then + local cmd = isWindows + and string.format('rmdir /s /q "%s"', path:gsub("/", "\\")) + or string.format('rm -rf "%s"', path) + vim.fn.jobstart(cmd, { detach = true }) + end end end, }) --- SELECTIVE CLEANUP ON EXIT (Keeps plugins, deletes temp files) --- stylua: ignore --- vim.api.nvim_create_autocmd('VimLeave', { --- callback = function() --- -- stdpath("cache") and stdpath("state") point to the isolated folders --- local folders_to_clean = { --- vim.fn.stdpath('cache'), --- vim.fn.stdpath('state'), --- } --- --- for _, path in ipairs(folders_to_clean) do --- if vim.fn.isdirectory(path) == 1 then --- local cmd = isWindows and string.format('rmdir /s /q "%s"', path:gsub('/', '\\')) or string.format('rm -rf "%s"', path) --- --- -- Detach so it finishes after Neovim closes --- vim.fn.jobstart(cmd, { detach = true }) --- end --- end --- --- -- Optional: Also delete the .ccl file on every exit --- local ccl_file = vim.fn.getcwd() .. '/.ccl' --- if vim.fn.filereadable(ccl_file) == 1 then os.remove(ccl_file) end --- end, --- }) + ---------------------------------------------------------------------------------------- -- INFO: set up python nvim venv (virtual environment 'nenv'), activaten. local platformio_core_dir, pynvim_env, pynvim_python, pynvim_lib, pynvim_bin, pynvim_activate From 7e5169b18db1657f4ff17ca48e22fb7c023690cb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 21:39:29 +0300 Subject: [PATCH 1129/1406] update --- lua/platformio/boilerplate.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 966f4a9b..2cac8fa8 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -179,6 +179,7 @@ CompileFlags: - "-xc++" - "-std=c++17" Remove: + - "-Winclude-next-outside-header" - "-fno-fat-lto-objects" - "-fno%%-fat%%-lto%%-objects" - "-fno%%-canonical%%-system%%-headers" From 0b920fa6cbcbae68ddaa4cfbc7d2988c8e7f3962 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 21:54:14 +0300 Subject: [PATCH 1130/1406] update --- mini_nvimPlatformio.lua | 36 ------------------------------------ 1 file changed, 36 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index c71da2ff..c486ac16 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -175,21 +175,6 @@ vim.env.XDG_STATE_HOME = home .. (isWindows and '/state/' or '/.local/state/') vim.env.XDG_CACHE_HOME = home .. (isWindows and '/cache/' or '/.cache/') --]] ---[[ -local app_name = 'nvim-pio' -local base_path = isWindows and vim.env.LOCALAPPDATA:gsub('\\', '/') or vim.env.HOME - --- 1. THE "FLATTENER": Set NVIM_APPNAME to match your root folder name -vim.env.NVIM_APPNAME = app_name - --- 2. Set XDG variables to the PARENT of where you want the app to live --- Neovim will automatically append /nvim-pio to each of these -vim.env.XDG_CONFIG_HOME = base_path -vim.env.XDG_DATA_HOME = base_path -vim.env.XDG_STATE_HOME = base_path -vim.env.XDG_CACHE_HOME = base_path ---]] - -- BOOTSTRAP (Use stdpath so it ALWAYS matches Neovim's internal logic) local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' @@ -208,27 +193,6 @@ end -- ADD TO RUNTIME PATH (Crucial: makes 'require("lazy")' work) vim.opt.rtp:prepend(lazypath) -print('Minimal environment active at: ' .. vim.fn.stdpath('config')) ------------------------------------------------------------------------------------- - --- --- local lazypath = vim.env.XDG_DATA_HOME .. '/lazy/lazy.nvim' --- -- local lazypath = vim.fn.stdpath('data') .. '/lazy/lazy.nvim' --- if not (vim.uv or vim.loop).fs_stat(lazypath) then --- print('Attempting to download lazy.nvim ...') --- vim.fn.system({ --- 'git', --- 'clone', --- '--filter=blob:none', --- 'https://github.com/folke/lazy.nvim.git', --- '--branch=stable', --- lazypath, --- }) --- end --- --- vim.opt.rtp:prepend(lazypath) --- print('Minimal environment active at: ' .. vim.fn.stdpath('config')) - ---------------------------------------------------------------------------------------- -- INFO: define plugins table local plugins = { From 79d9ae627644e60f19105d3e2d0fec944bb63e15 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 22:04:45 +0300 Subject: [PATCH 1131/1406] update --- lua/platformio/utils/pio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index a59ce6cb..4f1f8081 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -159,7 +159,7 @@ function M.handlePioinitDb(result) local boilerplate_gen = boilerplate.boilerplate_gen boilerplate.core_dir = _G.metadata.core_dir - -- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) + boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) @@ -210,7 +210,7 @@ function M.handlePioinit(result) local boilerplate_gen = boilerplate.boilerplate_gen boilerplate.core_dir = _G.metadata.core_dir - -- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) + boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) From 9b920c8d839e2103f9f5f582fba5762c131060b0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 22:11:43 +0300 Subject: [PATCH 1132/1406] update --- mini_nvimPlatformio.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index c486ac16..27624caa 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -258,11 +258,11 @@ local plugins = { hide_dotfiles = false, hide_gitignored = true, never_show = { -- Add any massive folders here - '.cache', - '.git', + -- '.cache', + -- '.git', 'node_modules', - 'build', - 'target', + -- 'build', + -- 'target', }, }, }, From 8ec314736630c043b61f3904e1a8435921bcf5b7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 22:34:10 +0300 Subject: [PATCH 1133/1406] update --- lua/platformio/pio_setup.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index f4942946..9cdae867 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -358,6 +358,7 @@ function M.start_watchers() idedata_path = vim.misc.joinPath(project_root, '.pio/build', active_env, 'idedata.json'), path = vim.misc.joinPath(project_root, '.pio/build', 'project.checksum'), --checksum_path cb = function(self) + print(self.path) local _, current_checksum = vim.misc.readFile(self.path) if current_checksum and current_checksum ~= '' then if current_checksum == _G.metadata.last_checksum then From 3d75df758a3c77025b3fa7f2ca44ada2f560e43f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 22:54:01 +0300 Subject: [PATCH 1134/1406] update --- lua/platformio/pio_setup.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 9cdae867..6af74f8f 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -40,6 +40,7 @@ function M.get_sysroot_triplet(cc_compiler) -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) -- Only return data if the sysroot folder actually exists on disk + print('sysroot') if vim.fn.isdirectory(sysroot) == 1 then _G.metadata.triplet = triplet _G.metadata.sysroot = sysroot From ad8babf9ada09caf674f9f45981d9bcde5012584 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 23:07:30 +0300 Subject: [PATCH 1135/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 6af74f8f..8d670808 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -40,12 +40,12 @@ function M.get_sysroot_triplet(cc_compiler) -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) -- Only return data if the sysroot folder actually exists on disk - print('sysroot') if vim.fn.isdirectory(sysroot) == 1 then _G.metadata.triplet = triplet _G.metadata.sysroot = sysroot _G.metadata.toolchain_root = toolchain_root _G.metadata.query_driver = query_driver + print('sysroot') return { triplet = triplet, sysroot = sysroot, From 9697b0995d2232e39f8d16f50da9a429cfe1ce29 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 23:16:50 +0300 Subject: [PATCH 1136/1406] update --- lua/platformio/metadata.lua | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index cad2bd16..13613901 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -40,6 +40,11 @@ _G.metadata = setmetatable({}, { if _pio_metadata[key] == value then return end -- Performance check + print('Newindex attempt for: ' .. tostring(key)) -- DEBUG LINE + if _pio_metadata[key] == value then + print('Value is identical, returning...') -- DEBUG LINE + return + end _pio_metadata[key] = value -- Trigger background actions From c774c7cf02edbf82f83408885753efab783c7545 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 23:25:53 +0300 Subject: [PATCH 1137/1406] update --- lua/platformio/pio_setup.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 8d670808..7bcae92e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -43,9 +43,10 @@ function M.get_sysroot_triplet(cc_compiler) if vim.fn.isdirectory(sysroot) == 1 then _G.metadata.triplet = triplet _G.metadata.sysroot = sysroot + print(toolchain_root) + print(_G.metadata.toolchain_root) _G.metadata.toolchain_root = toolchain_root _G.metadata.query_driver = query_driver - print('sysroot') return { triplet = triplet, sysroot = sysroot, From e701d522e7a1ec28173a4cd6d0661fc1d49e5788 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Mon, 27 Apr 2026 23:31:54 +0300 Subject: [PATCH 1138/1406] update --- lua/platformio/metadata.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 13613901..4763a12a 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -125,7 +125,7 @@ function M.load_project_config() -- We update _pio_metadata directly to avoid triggering -- 50+ notifications/restarts during the initial load loop for k, v in pairs(table_data) do - _pio_metadata[k] = v + _G.metadata[k] = v end last_saved_hash = vim.fn.sha256(json_data) return From ff3373516417a70ca4701e6c2458a43a10bd25e2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 04:44:21 +0300 Subject: [PATCH 1139/1406] update --- lua/platformio/metadata.lua | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 4763a12a..c1a91413 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -38,13 +38,10 @@ _G.metadata = setmetatable({}, { __index = _pio_metadata, __newindex = function(_, key, value) if _pio_metadata[key] == value then + print('Value is identical, returning...') -- DEBUG LINE return end -- Performance check print('Newindex attempt for: ' .. tostring(key)) -- DEBUG LINE - if _pio_metadata[key] == value then - print('Value is identical, returning...') -- DEBUG LINE - return - end _pio_metadata[key] = value -- Trigger background actions From 3cfe698c5ca7f94416fda23d5ca4ea50c4ba2cd8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 05:02:08 +0300 Subject: [PATCH 1140/1406] update --- lua/platformio/pio_setup.lua | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 7bcae92e..1ca873ae 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -74,8 +74,8 @@ function M.pio_refresh(callback) -- Set up file paths local build_dir = vim.misc.joinPath(vim.uv.cwd(), '.pio', 'build') local build_env_dir = vim.misc.joinPath(build_dir, active_env) - local checksum_path = vim.misc.joinPath(build_dir, 'project.checksum') - local idedata_path = vim.misc.joinPath(build_env_dir, 'idedata.json') + local checksum_file = vim.misc.joinPath(build_dir, 'project.checksum') + local idedata_file = vim.misc.joinPath(build_env_dir, 'idedata.json') --------------------------------------------------------- -- INTERNAL PROCESSOR: Applies parsed data to _G.metadata @@ -120,12 +120,15 @@ function M.pio_refresh(callback) --------------------------------------------------------- -- STEP 1: Fast Checksum Check --------------------------------------------------------- - local _, current_checksum = vim.misc.readFile(checksum_path) + local _, current_checksum = vim.misc.readFile(checksum_file) if current_checksum and current_checksum ~= '' then - if current_checksum == meta.last_projectChecksum then return end -- Already updated + if current_checksum == meta.last_projectChecksum then + vim.notify('PIO: Metadata synced with cache', vim.log.levels.INFO) + return + end -- Already updated -- STEP 2: Cache Path (idedata.json exists and checksum changed) - local _, content = vim.misc.readFile(idedata_path) + local _, content = vim.misc.readFile(idedata_file) if content then local ok, decoded = pcall(vim.json.decode, content) if ok and apply_metadata(decoded, current_checksum) then From c7a328c23d437acb09fe350bdd887cdf37fe2a99 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 05:09:38 +0300 Subject: [PATCH 1141/1406] update --- lua/platformio/pio_setup.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 1ca873ae..58614280 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -121,6 +121,8 @@ function M.pio_refresh(callback) -- STEP 1: Fast Checksum Check --------------------------------------------------------- local _, current_checksum = vim.misc.readFile(checksum_file) + print(current_checksum) + print(_G.metadata.last_projectChecksum) if current_checksum and current_checksum ~= '' then if current_checksum == meta.last_projectChecksum then vim.notify('PIO: Metadata synced with cache', vim.log.levels.INFO) From 8f9485910bb03943fa0bd3f47af72d5bd5383af1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 05:14:08 +0300 Subject: [PATCH 1142/1406] update --- lua/platformio/pio_setup.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 58614280..ec9b1c4d 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -121,8 +121,8 @@ function M.pio_refresh(callback) -- STEP 1: Fast Checksum Check --------------------------------------------------------- local _, current_checksum = vim.misc.readFile(checksum_file) - print(current_checksum) - print(_G.metadata.last_projectChecksum) + print('check_sum1=' .. current_checksum) + print('check_sum2=' .. _G.metadata.last_projectChecksum) if current_checksum and current_checksum ~= '' then if current_checksum == meta.last_projectChecksum then vim.notify('PIO: Metadata synced with cache', vim.log.levels.INFO) From 74a4960070d47159a060fc3543865a1c4e06fa15 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 05:22:12 +0300 Subject: [PATCH 1143/1406] update --- lua/platformio/pio_setup.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index ec9b1c4d..22d7fe0c 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -134,6 +134,7 @@ function M.pio_refresh(callback) if content then local ok, decoded = pcall(vim.json.decode, content) if ok and apply_metadata(decoded, current_checksum) then + metadata.save_project_config() vim.notify('PIO: Metadata synced from cache', vim.log.levels.INFO) return end From cd121e3b8abb940cb7526b3d014876bc58b06f46 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 05:33:10 +0300 Subject: [PATCH 1144/1406] update --- lua/platformio/utils/misc.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 9ef3ed6d..fde22c64 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -196,6 +196,7 @@ end function M.writeFile(path, data, opts) local uv = vim.uv or vim.loop opts = opts or {} + if #opts == 0 then opts = {overwrite = true, mkdir = true} end -- opts.overwrite: boolean (default true) -- opts.mkdir: boolean (default true) From 472c0778b65376d013b9a70665e246791410722a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 05:37:22 +0300 Subject: [PATCH 1145/1406] update --- lua/platformio/pio_setup.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 22d7fe0c..efe8851c 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -134,6 +134,7 @@ function M.pio_refresh(callback) if content then local ok, decoded = pcall(vim.json.decode, content) if ok and apply_metadata(decoded, current_checksum) then + local metadata = require('platformio.metadata') metadata.save_project_config() vim.notify('PIO: Metadata synced from cache', vim.log.levels.INFO) return From 7736e6b78530e2b13fa9b4fd7770b7ee489322cb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 05:56:06 +0300 Subject: [PATCH 1146/1406] update --- lua/platformio/metadata.lua | 38 ++++++++++++++++++++++++++++++++----- 1 file changed, 33 insertions(+), 5 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index c1a91413..600741f8 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -2,7 +2,6 @@ local M = {} ------------------------------------------------------------------------------------------------------- local last_saved_hash = '' -local config_path = vim.fs.joinpath(vim.uv.cwd(), '.project_config.json') --INFO: -- 1. Internal State & Defaults @@ -78,6 +77,7 @@ _G.metadata = setmetatable({}, { end, }) +local config_path = vim.fs.joinpath(vim.uv.cwd(), '.project_config.json') -- -- Add this temporary line in a file where you are coding: -- ---@type platformio.utils.misc -- local misc = vim.misc @@ -88,18 +88,19 @@ function M.save_project_config(quiet) return end -- local json_data = pio.pretty_json(_pio_metadata) - local ok, json_data = pcall(vim.json.encode, _pio_metadata) + local ok, pretty_table = vim.misc.pretty_print(_pio_metadata) if not ok then - print('Error encoding JSON: ' .. json_data) + print('Error formatting metadata') return end - local pretty_json = vim.misc.pretty_print(json_data) + local _, pretty_json = pcall(vim.json.encode, pretty_table) + -- local pretty_json = vim.misc.pretty_print(json_data) local current_hash = vim.fn.sha256(pretty_json) -- file:write(pio.jsonFormat(json_data)) if current_hash ~= last_saved_hash then -- local status = vim.fn.writefile({ json_data }, config_path) - local status, _ = vim.misc.writeFile(json_data, config_path, {}) + local status, _ = vim.misc.writeFile(pretty_json, config_path, {}) if status == 0 then last_saved_hash = current_hash if not quiet then @@ -110,6 +111,33 @@ function M.save_project_config(quiet) end end end +-- function M.save_project_config(quiet) +-- if vim.fn.filereadable('platformio.ini') == 0 then +-- return +-- end +-- -- local json_data = pio.pretty_json(_pio_metadata) +-- local ok, json_data = pcall(vim.json.encode, _pio_metadata) +-- if not ok then +-- print('Error encoding JSON: ' .. json_data) +-- return +-- end +-- local pretty_json = vim.misc.pretty_print(json_data) +-- local current_hash = vim.fn.sha256(pretty_json) +-- +-- -- file:write(pio.jsonFormat(json_data)) +-- if current_hash ~= last_saved_hash then +-- -- local status = vim.fn.writefile({ json_data }, config_path) +-- local status, _ = vim.misc.writeFile(json_data, config_path, {}) +-- if status == 0 then +-- last_saved_hash = current_hash +-- if not quiet then +-- vim.notify('Config synced', vim.log.levels.INFO, { title = 'PlatformIO' }) +-- end +-- else +-- vim.notify('Could not open file for writing') +-- end +-- end +-- end --INFO: -- 4. Load Logic (Populates proxy safely) From c6da93b37e7d792fcbf2a3c521a292909ff6fbbd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 06:03:52 +0300 Subject: [PATCH 1147/1406] update --- lua/platformio/metadata.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 600741f8..c4a0ab62 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -84,9 +84,9 @@ local config_path = vim.fs.joinpath(vim.uv.cwd(), '.project_config.json') --INFO: -- 3. Save Logic (Uses sha256 for stability) function M.save_project_config(quiet) - if vim.fn.filereadable('platformio.ini') == 0 then - return - end + -- if vim.fn.filereadable('platformio.ini') == 0 then + -- return + -- end -- local json_data = pio.pretty_json(_pio_metadata) local ok, pretty_table = vim.misc.pretty_print(_pio_metadata) if not ok then From d406cb27981e2161b1f0701e942ae229f736d767 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 06:07:08 +0300 Subject: [PATCH 1148/1406] update --- lua/platformio/metadata.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index c4a0ab62..14a1239b 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -101,7 +101,7 @@ function M.save_project_config(quiet) if current_hash ~= last_saved_hash then -- local status = vim.fn.writefile({ json_data }, config_path) local status, _ = vim.misc.writeFile(pretty_json, config_path, {}) - if status == 0 then + if status then last_saved_hash = current_hash if not quiet then vim.notify('Config synced', vim.log.levels.INFO, { title = 'PlatformIO' }) From 37625f3c8d5984d044141fcb3bfc4cf531534083 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 06:23:24 +0300 Subject: [PATCH 1149/1406] update --- lua/platformio/metadata.lua | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 14a1239b..4c444e82 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -84,33 +84,31 @@ local config_path = vim.fs.joinpath(vim.uv.cwd(), '.project_config.json') --INFO: -- 3. Save Logic (Uses sha256 for stability) function M.save_project_config(quiet) - -- if vim.fn.filereadable('platformio.ini') == 0 then - -- return - -- end - -- local json_data = pio.pretty_json(_pio_metadata) - local ok, pretty_table = vim.misc.pretty_print(_pio_metadata) - if not ok then + -- 1. Generate the formatted string directly, pretty_print already returns a string! + local ok, pretty_json = pcall(vim.misc.pretty_print, _pio_metadata) + + if not ok or not pretty_json then print('Error formatting metadata') return end - local _, pretty_json = pcall(vim.json.encode, pretty_table) - -- local pretty_json = vim.misc.pretty_print(json_data) + local current_hash = vim.fn.sha256(pretty_json) - -- file:write(pio.jsonFormat(json_data)) + -- 2. Only write if the content actually changed if current_hash ~= last_saved_hash then - -- local status = vim.fn.writefile({ json_data }, config_path) - local status, _ = vim.misc.writeFile(pretty_json, config_path, {}) + local status, err = vim.misc.writeFile(pretty_json, config_path, {}) + if status then last_saved_hash = current_hash if not quiet then vim.notify('Config synced', vim.log.levels.INFO, { title = 'PlatformIO' }) end else - vim.notify('Could not open file for writing') + vim.notify('Write failed: ' .. (err or 'unknown error'), vim.log.levels.ERROR) end end end + -- function M.save_project_config(quiet) -- if vim.fn.filereadable('platformio.ini') == 0 then -- return From 28b9ac6cb50adbbefef34a23eac02a0f4c2b800e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 06:40:58 +0300 Subject: [PATCH 1150/1406] update --- lua/platformio/utils/misc.lua | 50 ++++++++++++++++++++++++++++++----- 1 file changed, 43 insertions(+), 7 deletions(-) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index fde22c64..92466ab6 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -118,34 +118,70 @@ end ------------------------------------------------------ --INFO: -- recursion 50ms --- stylua: ignore +--- stylua: ignore -- local function pretty_print(data) -- 48ms function M.pretty_print(data) -- 48ms -- Force input into a table if it's just a single string - local insert = table.insert local buffer = {} local function format_item(item, current_level) + local insert = table.insert local indent = string.rep(' ', current_level) local next_indent = string.rep(' ', current_level + 1) + if type(item) == 'table' then + -- Check if table is empty + if next(item) == nil then + insert(buffer, #item > 0 and '[]' or '{}') + return + end + local is_array = #item > 0 local opener = is_array and '[' or '{' local closer = is_array and ']' or '}' + insert(buffer, opener .. '\n') local first = true for k, v in pairs(item) do - if not first then insert(buffer, ',\n') end + if not first then + insert(buffer, ',\n') + end insert(buffer, next_indent) - if not is_array then insert(buffer, '"' .. k .. '": ') end + if not is_array then + insert(buffer, '"' .. k .. '": ') + end format_item(v, current_level + 1) first = false end insert(buffer, '\n' .. indent .. closer) elseif type(item) == 'string' then - -- Basic escaping for the string content insert(buffer, '"' .. item:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"') - else insert(buffer, tostring(item)) end + else + insert(buffer, tostring(item)) + end end + -- local function format_item(item, current_level) + -- local indent = string.rep(' ', current_level) + -- local next_indent = string.rep(' ', current_level + 1) + -- if type(item) == 'table' then + -- local is_array = #item > 0 + -- local opener = is_array and '[' or '{' + -- local closer = is_array and ']' or '}' + -- insert(buffer, opener .. '\n') + -- local first = true + -- for k, v in pairs(item) do + -- if not first then insert(buffer, ',\n') end + -- insert(buffer, next_indent) + -- if not is_array then insert(buffer, '"' .. k .. '": ') end + -- format_item(v, current_level + 1) + -- first = false + -- end + -- insert(buffer, '\n' .. indent .. closer) + -- elseif type(item) == 'string' then + -- -- Basic escaping for the string content + -- insert(buffer, '"' .. item:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"') + -- else insert(buffer, tostring(item)) end + -- end + format_item(data, 0) return table.concat(buffer) end @@ -196,7 +232,7 @@ end function M.writeFile(path, data, opts) local uv = vim.uv or vim.loop opts = opts or {} - if #opts == 0 then opts = {overwrite = true, mkdir = true} end + if next(opts) == nil then opts = {overwrite = true, mkdir = true} end -- opts.overwrite: boolean (default true) -- opts.mkdir: boolean (default true) From 518d0aa1f1c6f279e8405718115929aa07ab1396 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 07:16:54 +0300 Subject: [PATCH 1151/1406] update --- lua/platformio/metadata.lua | 2 +- lua/platformio/utils/misc.lua | 91 ++++++++++++++++++++++++++--------- 2 files changed, 70 insertions(+), 23 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 4c444e82..50174de5 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -96,7 +96,7 @@ function M.save_project_config(quiet) -- 2. Only write if the content actually changed if current_hash ~= last_saved_hash then - local status, err = vim.misc.writeFile(pretty_json, config_path, {}) + local status, err = vim.misc.writeFile(config_path, pretty_json, {}) if status then last_saved_hash = current_hash diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 92466ab6..e1e32d52 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -118,47 +118,94 @@ end ------------------------------------------------------ --INFO: -- recursion 50ms ---- stylua: ignore +-- stylua: ignore -- local function pretty_print(data) -- 48ms function M.pretty_print(data) -- 48ms -- Force input into a table if it's just a single string local buffer = {} + local function format_item(item, current_level) local insert = table.insert local indent = string.rep(' ', current_level) local next_indent = string.rep(' ', current_level + 1) if type(item) == 'table' then - -- Check if table is empty + -- 1. TRULY EMPTY CHECK if next(item) == nil then - insert(buffer, #item > 0 and '[]' or '{}') + -- In PIO metadata, most empty fields are intended to be arrays [] + -- But we use {} as a safe JSON default for generic tables. + insert(buffer, '{}') return end - local is_array = #item > 0 + -- 2. DETERMINE IF ARRAY OR OBJECT + -- A table is an array if it has a value at index 1 + local is_array = item[1] ~= nil local opener = is_array and '[' or '{' local closer = is_array and ']' or '}' insert(buffer, opener .. '\n') + + -- 3. SORT KEYS (Crucial for consistent SHA256 hashes) + local keys = {} + for k in pairs(item) do table.insert(keys, k) end + if not is_array then table.sort(keys) end + local first = true - for k, v in pairs(item) do - if not first then - insert(buffer, ',\n') - end + for _, k in ipairs(keys) do + local v = item[k] + if not first then insert(buffer, ',\n') end insert(buffer, next_indent) - if not is_array then - insert(buffer, '"' .. k .. '": ') - end + + if not is_array then insert(buffer, '"' .. tostring(k) .. '": ') end + format_item(v, current_level + 1) first = false end insert(buffer, '\n' .. indent .. closer) elseif type(item) == 'string' then - insert(buffer, '"' .. item:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"') - else - insert(buffer, tostring(item)) - end + -- Escape backslashes for Windows paths and quotes + insert(buffer, '"' .. item:gsub('[\\]+', '/'):gsub('"', '\\"') .. '"') + else insert(buffer, tostring(item)) end end + + -- local function format_item(item, current_level) + -- local insert = table.insert + -- local indent = string.rep(' ', current_level) + -- local next_indent = string.rep(' ', current_level + 1) + -- + -- if type(item) == 'table' then + -- -- Check if table is empty + -- if next(item) == nil then + -- insert(buffer, #item > 0 and '[]' or '{}') + -- return + -- end + -- + -- local is_array = #item > 0 + -- local opener = is_array and '[' or '{' + -- local closer = is_array and ']' or '}' + -- + -- insert(buffer, opener .. '\n') + -- local first = true + -- for k, v in pairs(item) do + -- if not first then + -- insert(buffer, ',\n') + -- end + -- insert(buffer, next_indent) + -- if not is_array then + -- insert(buffer, '"' .. k .. '": ') + -- end + -- format_item(v, current_level + 1) + -- first = false + -- end + -- insert(buffer, '\n' .. indent .. closer) + -- elseif type(item) == 'string' then + -- insert(buffer, '"' .. item:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"') + -- else + -- insert(buffer, tostring(item)) + -- end + -- end + -- local function format_item(item, current_level) -- local indent = string.rep(' ', current_level) -- local next_indent = string.rep(' ', current_level + 1) @@ -231,8 +278,8 @@ end ---@param opts table function M.writeFile(path, data, opts) local uv = vim.uv or vim.loop - opts = opts or {} - if next(opts) == nil then opts = {overwrite = true, mkdir = true} end + opts = opts or {overwrite = true, mkdir = true} + -- opts.overwrite: boolean (default true) -- opts.mkdir: boolean (default true) @@ -245,7 +292,8 @@ function M.writeFile(path, data, opts) -- 2. Ensure folder exists (mkdir -p logic) if opts.mkdir ~= false then local parent = vim.fn.fnamemodify(path, ':h') - if uv.fs_stat(parent) == nil then + -- if uv.fs_stat(parent) == nil then + if vim.fn.isdirectory(parent) == 0 then -- 448 is octal 0700 (user read/write/execute) -- Using vim.fn.mkdir is easier for recursive creation vim.fn.mkdir(parent, 'p') @@ -254,17 +302,16 @@ function M.writeFile(path, data, opts) -- 3. Open file for writing -- 'w' truncates existing, 'wx' fails if exists (extra safety) - local flags = opts.overwrite == false and 'wx' or 'w' - local fd, err = uv.fs_open(path, flags, 438) + local fd, err = uv.fs_open(path, 'w', 438) if not fd then return false, 'writeFile: Open error: ' .. (err or 'unknown') end -- 4. Write data - local _, write_err = uv.fs_write(fd, data, 0) + local success, write_err = uv.fs_write(fd, data, 0) -- 5. ALWAYS close uv.fs_close(fd) - if write_err then return false, 'writeFile: Write error: ' .. write_err end + if not success then return false, 'writeFile: Write error: ' .. write_err end return true, 'writeFile: complete' end From 497ae101f91a5780f366c8d91c0d29b3e002f687 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 07:19:05 +0300 Subject: [PATCH 1152/1406] update --- lua/platformio/metadata.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 50174de5..a08a859d 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -37,10 +37,10 @@ _G.metadata = setmetatable({}, { __index = _pio_metadata, __newindex = function(_, key, value) if _pio_metadata[key] == value then - print('Value is identical, returning...') -- DEBUG LINE + -- print('Value is identical, returning...') -- DEBUG LINE return end -- Performance check - print('Newindex attempt for: ' .. tostring(key)) -- DEBUG LINE + -- print('Newindex attempt for: ' .. tostring(key)) -- DEBUG LINE _pio_metadata[key] = value -- Trigger background actions From fe00eb989922ca125aed04846fca0b4fb35250e5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 12:25:18 +0300 Subject: [PATCH 1153/1406] update --- lua/platformio/pio_setup.lua | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index efe8851c..2bc38056 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -367,7 +367,6 @@ function M.start_watchers() idedata_path = vim.misc.joinPath(project_root, '.pio/build', active_env, 'idedata.json'), path = vim.misc.joinPath(project_root, '.pio/build', 'project.checksum'), --checksum_path cb = function(self) - print(self.path) local _, current_checksum = vim.misc.readFile(self.path) if current_checksum and current_checksum ~= '' then if current_checksum == _G.metadata.last_checksum then @@ -376,7 +375,7 @@ function M.start_watchers() -- STEP 2: Cache Path (idedata.json exists and checksum changed) M.pio_refresh(function() - local dbFix = require('platformio.utils.pio').compile_commandsFix + -- local dbFix = require('platformio.utils.pio').compile_commandsFix -- dbFix() vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) end) @@ -385,6 +384,10 @@ function M.start_watchers() }, } targets[1].current_ini_hash = get_hash(targets[1].path) or '' + -- targets[1].current_ini_hash = get_hash(targets[1].path) or '' + -- targets[1].path = vim.misc.joinPath(project_root, 'platformio.ini') + -- targets[2].path = vim.misc.joinPath(project_root, '.pio/build', 'project.checksum') --checksum_path + -- targets[2].idedata_path = vim.misc.joinPath(project_root, '.pio/build', active_env, 'idedata.json') for _, target in ipairs(targets) do local h = watch_file(target.path, target.cb) From 1d22504beeb4067c81b1d031a4f080b09b5b6a94 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 12:36:27 +0300 Subject: [PATCH 1154/1406] update --- lua/platformio/pio_setup.lua | 2 -- 1 file changed, 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 2bc38056..b2804e2a 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -121,8 +121,6 @@ function M.pio_refresh(callback) -- STEP 1: Fast Checksum Check --------------------------------------------------------- local _, current_checksum = vim.misc.readFile(checksum_file) - print('check_sum1=' .. current_checksum) - print('check_sum2=' .. _G.metadata.last_projectChecksum) if current_checksum and current_checksum ~= '' then if current_checksum == meta.last_projectChecksum then vim.notify('PIO: Metadata synced with cache', vim.log.levels.INFO) From 211f97c93471c7ebe17287a16eb3fca4b7a2c745 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 13:58:33 +0300 Subject: [PATCH 1155/1406] update --- lua/platformio/utils/misc.lua | 109 +++++++++++++++++++++++----------- 1 file changed, 75 insertions(+), 34 deletions(-) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index e1e32d52..791628df 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -241,28 +241,21 @@ end -- stylua: ignore ---@param path string function M.readFile(path) - local uv = vim.uv or vim.loop -- Support older and newer Neovim versions + local uv = vim.uv or vim.loop - -- 1. Open the file (r = read-only) - -- 438 is the octal for 0666 (standard permissions) - local fd, err = uv.fs_open(path, 'r', 438) - if not fd or err then return false, 'readFile: Open error: ' .. err end + -- 1. Check if file exists before opening to avoid "noisy" errors + local stat = uv.fs_stat(path) + if not stat then return false, 'File does not exist' end - -- 2. Get file stats to find out how many bytes to read - local stat, stat_err = uv.fs_fstat(fd) - if not stat or stat_err then - uv.fs_close(fd) - return false, 'readFile: Stat error: ' .. stat_err - end + -- 2. Open the file + local fd, err = uv.fs_open(path, 'r', 438) + if not fd then return false, err end - -- 3. Read the entire content - -- fd, length, offset + -- 3. Read the content (using stat.size from our check above) local content, read_err = uv.fs_read(fd, stat.size, 0) - - -- 4. ALWAYS close the file descriptor uv.fs_close(fd) - if read_err then return false, 'readFile: Read error: ' .. read_err end + if read_err then return false, read_err end return true, content end @@ -276,45 +269,93 @@ end ---@param path string ---@param data string ---@param opts table +-- function M.writeFile(path, data, opts) +-- local uv = vim.uv or vim.loop +-- +-- opts = opts or {overwrite = true, mkdir = true} +-- +-- -- 1. Check if file exists and handle overwrite flag +-- local stat = uv.fs_stat(path) +-- if stat and opts.overwrite == false then +-- return false, 'writeFile: File already exists and overwrite is disabled' +-- end +-- +-- -- 2. Ensure folder exists (mkdir -p logic) +-- if opts.mkdir ~= false then +-- local parent = vim.fn.fnamemodify(path, ':h') +-- if not stat or stat.type ~= 'directory' then +-- -- Using vim.fn.mkdir is easier for recursive creation +-- vim.fn.mkdir(parent, 'p', '0700') +-- end +-- end +-- +-- -- 3. Open file for writing +-- local fd, err = uv.fs_open(path, 'w', 438) +-- if not fd then return false, 'writeFile: Open error: ' .. (err or 'unknown') end +-- +-- -- 4. Write data +-- local success, write_err = uv.fs_write(fd, data, 0) +-- +-- -- 5. ALWAYS close +-- uv.fs_close(fd) +-- +-- if not success then return false, 'writeFile: Write error: ' .. write_err end +-- +-- return true, 'writeFile: complete' +-- end + function M.writeFile(path, data, opts) local uv = vim.uv or vim.loop - opts = opts or {overwrite = true, mkdir = true} -- opts.overwrite: boolean (default true) -- opts.mkdir: boolean (default true) + opts = opts or { overwrite = true, mkdir = true } - -- 1. Check if file exists and handle overwrite flag local stat = uv.fs_stat(path) - if stat and opts.overwrite == false then - return false, 'writeFile: File already exists and overwrite is disabled' + -- 1. Overwrite protection + if opts.overwrite == false and stat then + return false, 'writeFile: File already exists' end - -- 2. Ensure folder exists (mkdir -p logic) + -- 2. Recursive directory creation if opts.mkdir ~= false then local parent = vim.fn.fnamemodify(path, ':h') - -- if uv.fs_stat(parent) == nil then - if vim.fn.isdirectory(parent) == 0 then - -- 448 is octal 0700 (user read/write/execute) - -- Using vim.fn.mkdir is easier for recursive creation - vim.fn.mkdir(parent, 'p') + if not stat or stat.type ~= 'directory' then + vim.fn.mkdir(parent, 'p', '0700') end end - -- 3. Open file for writing - -- 'w' truncates existing, 'wx' fails if exists (extra safety) + --[[ + Octal Decimal Permission + 0700 448 Owner only (Full) + 0755 493 Owner (Full), Others (Read/Execute) + 0666 438 Everyone (Read/Write) - Not recommended for folders + 'w' truncates existing, 'wx' fails if exists (extra safety) + ]] + -- 3. Open for writing ('w' flag truncates automatically) local fd, err = uv.fs_open(path, 'w', 438) if not fd then return false, 'writeFile: Open error: ' .. (err or 'unknown') end - -- 4. Write data - local success, write_err = uv.fs_write(fd, data, 0) + -- 4. Robust Write Loop + -- Loop ensures all data is written even if it takes multiple chunks + local offset = 0 + while offset < #data do + local bytes_written, w_err = uv.fs_write(fd, data:sub(offset + 1), offset) + if w_err then + uv.fs_close(fd) + return false, 'writeFile: Write error: ' .. w_err + end + offset = offset + bytes_written + end - -- 5. ALWAYS close + -- 5. Force Sync (Crucial for your project.checksum watcher) + uv.fs_fsync(fd) uv.fs_close(fd) - if not success then return false, 'writeFile: Write error: ' .. write_err end - - return true, 'writeFile: complete' + return true, 'Success' end + + ------------------------------------------------------ --[[ Targets Windows paths, normalizes slashes, and fixes smashed PlatformIO paths. From e60ead825ebf71e4f36c4d5765063c55cbf760e3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 14:14:34 +0300 Subject: [PATCH 1156/1406] update --- lua/platformio/pio_setup.lua | 23 +++++++---------------- 1 file changed, 7 insertions(+), 16 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b2804e2a..62b760a2 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -315,32 +315,29 @@ end local uv = vim.uv or vim.loop M.watcher_handles = {} +-- stylua: ignore local function watch_file(full_path, callback) local handle = uv.new_fs_event() local parent_dir = vim.fn.fnamemodify(full_path, ':h') local target_file = vim.fn.fnamemodify(full_path, ':t') if handle then - handle:start( - parent_dir, - {}, + handle:start( parent_dir, {}, vim.schedule_wrap(function(err, filename, events) -- handle:start(parent_dir, {}, function(err, filename) -- if err then if err or filename ~= target_file or _G.metadata.isBusy or not events or not (events.change or events.renamce) then return handle:stop() - -- return end - if filename == target_file then - vim.schedule(callback) - end + if filename == target_file then vim.schedule(callback) end end) ) return handle end end +-- stylua: ignore function M.start_watchers() -- Clean up any existing watchers first to prevent duplicates M.stop_watchers() @@ -358,7 +355,6 @@ function M.start_watchers() self.current_ini_hash = new_hash M.run_compiledb() -- Smart: Auto-update DB if config changes end - -- fetch_config() end, }, { -- watcher for ./.pio/build/projct.checksum @@ -382,21 +378,16 @@ function M.start_watchers() }, } targets[1].current_ini_hash = get_hash(targets[1].path) or '' - -- targets[1].current_ini_hash = get_hash(targets[1].path) or '' - -- targets[1].path = vim.misc.joinPath(project_root, 'platformio.ini') - -- targets[2].path = vim.misc.joinPath(project_root, '.pio/build', 'project.checksum') --checksum_path - -- targets[2].idedata_path = vim.misc.joinPath(project_root, '.pio/build', active_env, 'idedata.json') for _, target in ipairs(targets) do - local h = watch_file(target.path, target.cb) + local h = watch_file(target.path, function() target.cb(target) end) table.insert(M.watcher_handles, h) end end +-- stylua: ignore function M.stop_watchers() - for _, handle in ipairs(M.watcher_handles) do - handle:stop() - end + for _, handle in ipairs(M.watcher_handles) do handle:stop() end M.watcher_handles = {} end From 76cd1ed547f07f5eba336f896a1186249d0ada0c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 14:20:12 +0300 Subject: [PATCH 1157/1406] update --- lua/platformio/metadata.lua | 2 -- lua/platformio/pio_setup.lua | 2 -- 2 files changed, 4 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index a08a859d..39c167ab 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -70,8 +70,6 @@ _G.metadata = setmetatable({}, { -- end) elseif key == 'last_projectChecksum' then elseif key == 'active_env' then - -- Force global statusline so it doesn't get pushed around by Trouble or splits - vim.o.laststatus = 3 end end) end, diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 62b760a2..4acd1c33 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -43,8 +43,6 @@ function M.get_sysroot_triplet(cc_compiler) if vim.fn.isdirectory(sysroot) == 1 then _G.metadata.triplet = triplet _G.metadata.sysroot = sysroot - print(toolchain_root) - print(_G.metadata.toolchain_root) _G.metadata.toolchain_root = toolchain_root _G.metadata.query_driver = query_driver return { From 356742bbbd737fcbc25888b6b64574cfc45a630c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 15:25:51 +0300 Subject: [PATCH 1158/1406] update --- lua/platformio/lspConfig/attach.lua | 6 +- lua/platformio/lspConfig/clangd.lua | 8 --- lua/platformio/lspConfig/tools.lua | 63 ----------------- lua/platformio/pio_setup.lua | 4 +- lua/platformio/utils/misc.lua | 106 ++++++---------------------- 5 files changed, 30 insertions(+), 157 deletions(-) diff --git a/lua/platformio/lspConfig/attach.lua b/lua/platformio/lspConfig/attach.lua index 3d3bfe5d..394e14d6 100644 --- a/lua/platformio/lspConfig/attach.lua +++ b/lua/platformio/lspConfig/attach.lua @@ -17,7 +17,7 @@ vim.api.nvim_create_autocmd('LspAttach', { end vim.api.nvim_buf_create_user_command(bufnr, 'LspClangdSwitchSourceHeader', function() local params = vim.lsp.util.make_text_document_params(bufnr) - client.request('textDocument/switchSourceHeader', params, function(err, result) + client:request('textDocument/switchSourceHeader', params, function(err, result) if err then vim.notify('Clangd Error: ' .. tostring(err), vim.log.levels.ERROR) return @@ -28,7 +28,9 @@ vim.api.nvim_create_autocmd('LspAttach', { end -- Use vim.schedule to ensure we aren't editing while the LSP is in a callback vim.schedule(function() - vim.cmd.edit(vim.uri_to_fname(result)) + local target = type(result) == 'string' and result or result.uri + local fname = vim.uri_to_fname(target) + vim.cmd.edit(vim.uri_to_fname(fname)) end) end, bufnr) end, { desc = 'Switch between source/header' }) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index a18a7728..ecb1839b 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -243,14 +243,6 @@ local yamlls = { } vim.lsp.config('yamlls', yamlls) --- local stylua = { --- cmd = { 'stylua', '--search-parent-directories', '--stdin-filepath', '$FILENAME', '-' }, --- filetypes = { 'lua' }, --- root_markers = { 'stylua.toml', '.stylua.toml', '.git' }, --- } --- vim.lsp.config('stylua', stylua) --- vim.lsp.enable('stylua') - local pyrefly = { name = 'pyrefly', cmd = { 'pyrefly', 'lsp' }, diff --git a/lua/platformio/lspConfig/tools.lua b/lua/platformio/lspConfig/tools.lua index 391b6767..bed705ea 100644 --- a/lua/platformio/lspConfig/tools.lua +++ b/lua/platformio/lspConfig/tools.lua @@ -1,75 +1,12 @@ local M = {} -- -- INFO: --- -- ============================================================================= --- -- UNIVERSAL TOOLCHAIN DETECTION --- -- ============================================================================= --- --- stylua: ignore --- function M.get_sysroot_triplet(cc_compiler) --- local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') --- --- -- Early exit if path is nil or not a directory --- if not bin_path or vim.fn.isdirectory(bin_path) == 0 then --- return nil --- end --- --- -- Normalize backslashes to forward slashes for cross-platform consistency --- bin_path = bin_path:gsub('\\', '/') --- local files = vim.fn.readdir(bin_path) --- local triplet = nil --- --- -- Loop through files to find the compiler and extract the triplet --- for _, name in ipairs(files) do --- -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ --- local match = name:match('^(.*)%-g[c%+][c%+]') --- if match then --- triplet = match --- break --- end --- end --- --- -- Return nil if no compiler was found in the bin directory --- if not triplet then --- return nil --- end --- --- -- toolchain_root is the parent of the 'bin' folder --- local toolchain_root = vim.fn.fnamemodify(bin_path, ':h') --- -- sysroot folder is expected to have the same name as the triplet --- local sysroot = toolchain_root .. '/' .. triplet --- local query_driver = bin_path .. '/' .. triplet .. '-*' --- --- -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) --- -- Only return data if the sysroot folder actually exists on disk --- if vim.fn.isdirectory(sysroot) == 1 then --- _G.metadata.triplet = triplet --- _G.metadata.sysroot = sysroot --- _G.metadata.toolchain_root = toolchain_root --- _G.metadata.query_driver = query_driver --- return { --- triplet = triplet, --- sysroot = sysroot, --- toolchain_root = toolchain_root, --- query_driver = query_driver, --- } --- end --- return nil --- end --- stylua: ignore function M.lsp_restart(name) -- vim.schedule_wrap(function() vim.notify('LSP restart.', vim.log.levels.WARN) - -- local status, data = pcall(M.get_sysroot_triplet, _G.metadata.cc_compiler) - -- pcall(M.get_sysroot_triplet, _G.metadata.cc_compiler) - -- if status and data and data.triplet and data.triplet ~= '' then - -- _G.metadata.triplet = data.triplet - -- _G.metadata.sysroot = data.sysroot - -- _G.metadata.query_driver = data.query_driver - -- _G.metadata.toolchain_root = data.toolchain_root - -- end - local clangConfig = _G.get_clangd_config() -- print(vim.inspect(clangConfig)) vim.lsp.config(name, clangConfig) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 4acd1c33..fdc98e2d 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -356,7 +356,7 @@ function M.start_watchers() end, }, { -- watcher for ./.pio/build/projct.checksum - idedata_path = vim.misc.joinPath(project_root, '.pio/build', active_env, 'idedata.json'), + idedata_path = vim.misc.joinPath(project_root, '.pio/build', active_env, 'idedata.json'),--idedata.json path path = vim.misc.joinPath(project_root, '.pio/build', 'project.checksum'), --checksum_path cb = function(self) local _, current_checksum = vim.misc.readFile(self.path) @@ -378,6 +378,8 @@ function M.start_watchers() targets[1].current_ini_hash = get_hash(targets[1].path) or '' for _, target in ipairs(targets) do + --[[ wrap the callback in a small anonymous function, + so it passes the target (self) back into it.]] local h = watch_file(target.path, function() target.cb(target) end) table.insert(M.watcher_handles, h) end diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 791628df..7a3f136f 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -20,12 +20,8 @@ end -- stylua: ignore function M.jsonFormat(root_data) local buffer = {} - - -- Force input into a table if it's just a single string - local patterns = type(root_data) == "table" and root_data or { root_data } - - -- The stack stores: { value = current_item, level = depth, stage = "start"|"items" } - local stack = { { val = patterns, lvl = 0, stage = 'start' } } + -- Stack stores: { val = item, lvl = depth, stage = "start"|"items", keys = {}, index = 0 } + local stack = { { val = root_data, lvl = 0, stage = 'start' } } local function get_indent(lvl) return string.rep(' ', lvl) end @@ -35,46 +31,50 @@ function M.jsonFormat(root_data) local indent = get_indent(lvl) if type(val) == 'table' then - local is_array = (#val > 0 or next(val) == nil) + -- 1. Determine if Array or Object + local is_array = (#val > 0) or (next(val) == nil) if curr.stage == 'start' then table.insert(buffer, (is_array and '[' or '{') .. '\n') curr.stage = 'items' curr.keys = {} - -- Collect keys to iterate deterministically - if is_array then - for i = #val, 1, -1 do table.insert(curr.keys, i) end + + -- 2. Collect and Sort Keys (CRITICAL for SHA256 stability) + if is_array then for i = 1, #val do table.insert(curr.keys, i) end else - for k, _ in pairs(val) do table.insert(curr.keys, k) end + for k in pairs(val) do table.insert(curr.keys, k) end + table.sort(curr.keys, function(a, b) return tostring(a) < tostring(b) end) end - curr.index = #curr.keys + curr.total = #curr.keys + curr.cursor = 1 -- Point to the first key elseif curr.stage == 'items' then - if curr.index > 0 then - local key = curr.keys[curr.index] + if curr.cursor <= curr.total then + local key = curr.keys[curr.cursor] local item = val[key] - -- Add comma if not the first item - if curr.index < #curr.keys then table.insert(buffer, ',\n') end + -- Add comma for all but the first item + if curr.cursor > 1 then table.insert(buffer, ',\n') end table.insert(buffer, get_indent(lvl + 1)) if not is_array then table.insert(buffer, '"' .. tostring(key) .. '": ') end - curr.index = curr.index - 1 - -- Push next item to stack + curr.cursor = curr.cursor + 1 + -- Push next item to process table.insert(stack, { val = item, lvl = lvl + 1, stage = 'start' }) else - -- No more items, close the block + -- 3. Close the block table.insert(buffer, '\n' .. indent .. (is_array and ']' or '}')) table.remove(stack) end end else - -- Primitive values (String, Number, Bool) + -- 4. Primitives (String, Number, Bool, Nil) local output = '' - if type(val) == 'string' then - -- output = '"' .. val:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"' + if val == nil then output = 'null' + elseif type(val) == 'boolean' then output = tostring(val) + elseif type(val) == 'string' then + -- Normalize Windows paths to Unix for cross-platform checksums output = '"' .. val:gsub('\\', '/'):gsub('"', '\\"') .. '"' - -- output = '"' .. val:gsub('"', '\\"') .. '"' else output = tostring(val) end table.insert(buffer, output) table.remove(stack) @@ -169,66 +169,6 @@ function M.pretty_print(data) -- 48ms else insert(buffer, tostring(item)) end end - -- local function format_item(item, current_level) - -- local insert = table.insert - -- local indent = string.rep(' ', current_level) - -- local next_indent = string.rep(' ', current_level + 1) - -- - -- if type(item) == 'table' then - -- -- Check if table is empty - -- if next(item) == nil then - -- insert(buffer, #item > 0 and '[]' or '{}') - -- return - -- end - -- - -- local is_array = #item > 0 - -- local opener = is_array and '[' or '{' - -- local closer = is_array and ']' or '}' - -- - -- insert(buffer, opener .. '\n') - -- local first = true - -- for k, v in pairs(item) do - -- if not first then - -- insert(buffer, ',\n') - -- end - -- insert(buffer, next_indent) - -- if not is_array then - -- insert(buffer, '"' .. k .. '": ') - -- end - -- format_item(v, current_level + 1) - -- first = false - -- end - -- insert(buffer, '\n' .. indent .. closer) - -- elseif type(item) == 'string' then - -- insert(buffer, '"' .. item:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"') - -- else - -- insert(buffer, tostring(item)) - -- end - -- end - - -- local function format_item(item, current_level) - -- local indent = string.rep(' ', current_level) - -- local next_indent = string.rep(' ', current_level + 1) - -- if type(item) == 'table' then - -- local is_array = #item > 0 - -- local opener = is_array and '[' or '{' - -- local closer = is_array and ']' or '}' - -- insert(buffer, opener .. '\n') - -- local first = true - -- for k, v in pairs(item) do - -- if not first then insert(buffer, ',\n') end - -- insert(buffer, next_indent) - -- if not is_array then insert(buffer, '"' .. k .. '": ') end - -- format_item(v, current_level + 1) - -- first = false - -- end - -- insert(buffer, '\n' .. indent .. closer) - -- elseif type(item) == 'string' then - -- -- Basic escaping for the string content - -- insert(buffer, '"' .. item:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"') - -- else insert(buffer, tostring(item)) end - -- end - format_item(data, 0) return table.concat(buffer) end From 74dee5cef2f3565000030fcf26609d50cf488f06 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 16:04:08 +0300 Subject: [PATCH 1159/1406] update --- lua/platformio/pio_setup.lua | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index fdc98e2d..4b6555d0 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -62,7 +62,7 @@ function M.pio_refresh(callback) -- INFO:------------------------------------------------- -- get pio project metadata info -- stylua: ignore - local function get_metadata(attempts, env) + local function fetch_metadata(attempts, env) local meta = _G.metadata local active_env = env or meta.active_env if not active_env or active_env == '' then @@ -146,7 +146,7 @@ function M.pio_refresh(callback) -- vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env }, { text = true }, function(obj) -- vim.schedule(function() -- if obj.code == 0 thenl - -- get_metadata(attempts, active_env) -- Recursive call after files created + -- fetch_metadata(attempts, active_env) -- Recursive call after files created -- else -- vim.notify('PIO: Initialization failed. Build project manually.', vim.log.levels.ERROR) -- end @@ -163,7 +163,7 @@ function M.pio_refresh(callback) vim.schedule(function() if obj.code ~= 0 then if attempts > 0 then - vim.defer_fn(function() get_metadata(attempts - 1, env) end, 500) + vim.defer_fn(function() fetch_metadata(attempts - 1, env) end, 500) return end return vim.notify('PIO Metadata Error: ' .. (obj.stderr or 'Unknown'), vim.log.levels.WARN) @@ -250,7 +250,7 @@ function M.pio_refresh(callback) -- 6. Trigger next step if meta.active_env ~= "" then vim.notify('PIO: Config sync successful', vim.log.levels.INFO) - get_metadata(1, meta.active_env) + fetch_metadata(1, meta.active_env) else vim.notify('PIO: No [env:] found. Please add a board.', vim.log.levels.ERROR) end @@ -328,7 +328,10 @@ local function watch_file(full_path, callback) return handle:stop() end - if filename == target_file then vim.schedule(callback) end + if filename == target_file then + print('file watched') + vim.schedule(callback) + end end) ) return handle From 0e4103282a6434b0fb811572c73ac4733a810831 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 16:10:11 +0300 Subject: [PATCH 1160/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 4b6555d0..f47b7736 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -284,7 +284,7 @@ function M.run_compiledb() vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) vim.schedule(function() - -- _G.metadata.isBusy = false + _G.metadata.isBusy = false if obj.code == 0 then M.pio_refresh(function() local dbFix = require('platformio.utils.pio').compile_commandsFix From 0f81dd179bb9560f00beeb71d01a5617c8cafded Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 16:13:52 +0300 Subject: [PATCH 1161/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index f47b7736..48efa179 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -284,7 +284,6 @@ function M.run_compiledb() vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) vim.schedule(function() - _G.metadata.isBusy = false if obj.code == 0 then M.pio_refresh(function() local dbFix = require('platformio.utils.pio').compile_commandsFix @@ -293,6 +292,7 @@ function M.run_compiledb() -- pio_generate_db() -- M.run_compiledb() -- lsp_restart('clangd') + _G.metadata.isBusy = false end) -- Use pcall in case M.refresh is defined elsewhere -- pio_refresh(function() From 91cedd462242ad23071a1bda13d704829415410f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 16:23:11 +0300 Subject: [PATCH 1162/1406] update --- lua/platformio/pio_setup.lua | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 48efa179..f884feb2 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -273,8 +273,6 @@ local function get_hash(path) end -- _G.metadata.isBusy = false --- 2. Smart Save/Load: Uses JSON and Hashing --- 3. Robust Execution: Mutes watcher and handles LSP restart function M.run_compiledb() if _G.metadata.isBusy then return @@ -292,7 +290,7 @@ function M.run_compiledb() -- pio_generate_db() -- M.run_compiledb() -- lsp_restart('clangd') - _G.metadata.isBusy = false + -- _G.metadata.isBusy = false end) -- Use pcall in case M.refresh is defined elsewhere -- pio_refresh(function() @@ -343,6 +341,7 @@ function M.start_watchers() -- Clean up any existing watchers first to prevent duplicates M.stop_watchers() + _G.metadata.isBusy = false local project_root = vim.uv.cwd() -- Use dynamic CWD instead of hardcoded path local active_env = _G.metadata.active_env or 'default' From ddce9dff723bb222866f4a872c273ca5f6b688cb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 16:25:40 +0300 Subject: [PATCH 1163/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index f884feb2..b465eb15 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -290,7 +290,7 @@ function M.run_compiledb() -- pio_generate_db() -- M.run_compiledb() -- lsp_restart('clangd') - -- _G.metadata.isBusy = false + _G.metadata.isBusy = false end) -- Use pcall in case M.refresh is defined elsewhere -- pio_refresh(function() From 1758299b1fa5a05ec273800d881763c74139c471 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 16:40:12 +0300 Subject: [PATCH 1164/1406] update --- lua/platformio/pio_setup.lua | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b465eb15..1d59cb41 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -288,18 +288,9 @@ function M.run_compiledb() -- dbFix() vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) -- pio_generate_db() - -- M.run_compiledb() -- lsp_restart('clangd') _G.metadata.isBusy = false end) - -- Use pcall in case M.refresh is defined elsewhere - -- pio_refresh(function() - -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --require('platformio.utils.pio').get_pio_dir('core')) --vim.env.PLATFORMIO_CORE_DIR) - -- pio_generate_db() - -- lsp_restart('clangd') - -- end) - -- else vim.notify('Build Failed', vim.log.levels.ERROR, { title = 'PlatformIO' }) end @@ -323,7 +314,7 @@ local function watch_file(full_path, callback) -- handle:start(parent_dir, {}, function(err, filename) -- if err then if err or filename ~= target_file or _G.metadata.isBusy or not events or not (events.change or events.renamce) then - return handle:stop() + return --handle:stop() end if filename == target_file then From 80f226186450cb8278969e586661b0684af9dd66 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 16:51:52 +0300 Subject: [PATCH 1165/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 1d59cb41..cb091f9e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -313,7 +313,7 @@ local function watch_file(full_path, callback) vim.schedule_wrap(function(err, filename, events) -- handle:start(parent_dir, {}, function(err, filename) -- if err then - if err or filename ~= target_file or _G.metadata.isBusy or not events or not (events.change or events.renamce) then + if err or filename ~= target_file or _G.metadata.isBusy then ---or not events or not (events.change or events.rename) then return --handle:stop() end From b37aa448fd0bbba825c5b097b8573524189437d4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 17:04:24 +0300 Subject: [PATCH 1166/1406] update --- lua/platformio/pio_setup.lua | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index cb091f9e..04f94cd7 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -310,18 +310,25 @@ local function watch_file(full_path, callback) if handle then handle:start( parent_dir, {}, - vim.schedule_wrap(function(err, filename, events) - -- handle:start(parent_dir, {}, function(err, filename) - -- if err then - if err or filename ~= target_file or _G.metadata.isBusy then ---or not events or not (events.change or events.rename) then + function(err, filename, events) + if err or filename ~= target_file or _G.metadata.isBusy or not events or not (events.change or events.rename) then return --handle:stop() end if filename == target_file then - print('file watched') - vim.schedule(callback) + + -- Debounce: Use vim.schedule to ensure we don't fire + -- during the middle of a file-swap operation + vim.schedule(function() + print('file watched') + -- Re-verify file exists before calling + if vim.loop.fs_stat(full_path) then + callback() + end + end) + -- vim.schedule(callback) end - end) + end ) return handle end From acdefb2ca69184dc216e5e430c9efc19b25dd135 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 17:25:14 +0300 Subject: [PATCH 1167/1406] update --- lua/platformio/pio_setup.lua | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 04f94cd7..3fb32448 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -284,7 +284,7 @@ function M.run_compiledb() vim.schedule(function() if obj.code == 0 then M.pio_refresh(function() - local dbFix = require('platformio.utils.pio').compile_commandsFix + -- local dbFix = require('platformio.utils.pio').compile_commandsFix -- dbFix() vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) -- pio_generate_db() @@ -310,8 +310,12 @@ local function watch_file(full_path, callback) if handle then handle:start( parent_dir, {}, - function(err, filename, events) - if err or filename ~= target_file or _G.metadata.isBusy or not events or not (events.change or events.rename) then + function(err, filename) --, events) + if err or filename ~= target_file or _G.metadata.isBusy then --or not events or not (events.change or events.rename) then + -- Use vim.schedule to notify so we don't block the loop + vim.schedule(function() + vim.notify("Watcher error: " .. tostring(err), vim.log.levels.ERROR) + end) return --handle:stop() end From 7b874da962d8e9459dbe98f6149cdbc99089517f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 17:34:27 +0300 Subject: [PATCH 1168/1406] update --- lua/platformio/pio_setup.lua | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 3fb32448..b1cbf42a 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -311,7 +311,9 @@ local function watch_file(full_path, callback) if handle then handle:start( parent_dir, {}, function(err, filename) --, events) - if err or filename ~= target_file or _G.metadata.isBusy then --or not events or not (events.change or events.rename) then + + -- 1. Catch REAL system errors + if err then --or filename ~= target_file or _G.metadata.isBusy or not events or not (events.change or events.rename) then -- Use vim.schedule to notify so we don't block the loop vim.schedule(function() vim.notify("Watcher error: " .. tostring(err), vim.log.levels.ERROR) @@ -319,19 +321,26 @@ local function watch_file(full_path, callback) return --handle:stop() end - if filename == target_file then + -- if filename == target_file then + -- end + + -- 2. SILENTLY ignore events that aren't our target file + -- Or if we are currently busy processing another task + if filename ~= target_file or _G.metadata.isBusy then + return + end -- Debounce: Use vim.schedule to ensure we don't fire -- during the middle of a file-swap operation - vim.schedule(function() - print('file watched') - -- Re-verify file exists before calling - if vim.loop.fs_stat(full_path) then - callback() - end - end) - -- vim.schedule(callback) - end + -- 3. Trigger the callback safely + vim.schedule(function() + print('file watched') + -- Re-verify file exists before calling + if vim.loop.fs_stat(full_path) then + callback() + end + end) + -- vim.schedule(callback) end ) return handle From b9753b16e4e6abacd5309f983dd653f6440433d7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 17:48:55 +0300 Subject: [PATCH 1169/1406] update --- lua/platformio/pio_setup.lua | 130 ++++++++++++++++++++++++++--------- 1 file changed, 98 insertions(+), 32 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b1cbf42a..5249a75a 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -303,50 +303,116 @@ local uv = vim.uv or vim.loop M.watcher_handles = {} -- stylua: ignore +-- Use a single, global-ish timer variable to handle debouncing across all events +local debounce_timer = vim.uv.new_timer() + local function watch_file(full_path, callback) - local handle = uv.new_fs_event() + -- 1. Nil check input parameters + if not full_path or type(callback) ~= 'function' then + vim.notify('watch_file: Invalid path or callback', vim.log.levels.ERROR) + return nil + end + + local handle, init_err = vim.uv.new_fs_event() + if not handle then + vim.notify('watch_file: Failed to create handle: ' .. tostring(init_err), vim.log.levels.ERROR) + return nil + end + local parent_dir = vim.fn.fnamemodify(full_path, ':h') local target_file = vim.fn.fnamemodify(full_path, ':t') - if handle then - handle:start( parent_dir, {}, - function(err, filename) --, events) + -- Start the watcher on the parent directory + handle:start(parent_dir, {}, function(err, filename, events) + -- 2. Robust error checking (tostring handles nil err) + if err then + vim.schedule(function() + vim.notify('Watcher system error: ' .. tostring(err), vim.log.levels.ERROR) + end) + return + end - -- 1. Catch REAL system errors - if err then --or filename ~= target_file or _G.metadata.isBusy or not events or not (events.change or events.rename) then - -- Use vim.schedule to notify so we don't block the loop - vim.schedule(function() - vim.notify("Watcher error: " .. tostring(err), vim.log.levels.ERROR) - end) - return --handle:stop() - end + -- 3. Guard against nil filename and metadata + -- Only proceed if the event is for our target file and we aren't busy + local is_target = (filename == target_file) + local is_busy = (_G.metadata and _G.metadata.isBusy == true) - -- if filename == target_file then - -- end + if not is_target or is_busy then + return + end - -- 2. SILENTLY ignore events that aren't our target file - -- Or if we are currently busy processing another task - if filename ~= target_file or _G.metadata.isBusy then - return - end + if debounce_timer then + -- 4. Debounce Logic with Timer Safety + -- Stop existing timer if it's currently running (debouncing) + if debounce_timer:is_active() then + debounce_timer:stop() + end - -- Debounce: Use vim.schedule to ensure we don't fire - -- during the middle of a file-swap operation - -- 3. Trigger the callback safely - vim.schedule(function() - print('file watched') - -- Re-verify file exists before calling - if vim.loop.fs_stat(full_path) then - callback() + -- Start/Restart the timer + debounce_timer:start( + 500, + 0, + vim.schedule_wrap(function() + -- 5. Final existence check before execution + -- Some editors delete/rename files during save (atomic saves) + local stat = vim.uv.fs_stat(full_path) + if stat and stat.type == 'file' then + print('File settled: ' .. target_file) + callback() end end) - -- vim.schedule(callback) - end - ) - return handle - end + ) + end + end) + + return handle end + +-- local function watch_file(full_path, callback) +-- local handle = uv.new_fs_event() +-- local parent_dir = vim.fn.fnamemodify(full_path, ':h') +-- local target_file = vim.fn.fnamemodify(full_path, ':t') +-- +-- if handle then +-- handle:start( parent_dir, {}, +-- function(err, filename) --, events) +-- +-- -- 1. Catch REAL system errors +-- if err then --or filename ~= target_file or _G.metadata.isBusy or not events or not (events.change or events.rename) then +-- -- Use vim.schedule to notify so we don't block the loop +-- vim.schedule(function() +-- vim.notify("Watcher error: " .. tostring(err), vim.log.levels.ERROR) +-- end) +-- return --handle:stop() +-- end +-- +-- -- if filename == target_file then +-- -- end +-- +-- -- 2. SILENTLY ignore events that aren't our target file +-- -- Or if we are currently busy processing another task +-- if filename ~= target_file or _G.metadata.isBusy then +-- return +-- end +-- +-- -- Debounce: Use vim.schedule to ensure we don't fire +-- -- during the middle of a file-swap operation +-- -- 3. Trigger the callback safely +-- vim.schedule(function() +-- print('file watched') +-- -- Re-verify file exists before calling +-- if vim.loop.fs_stat(full_path) then +-- callback() +-- end +-- end) +-- -- vim.schedule(callback) +-- end +-- ) +-- return handle +-- end +-- end + -- stylua: ignore function M.start_watchers() -- Clean up any existing watchers first to prevent duplicates From 4ce6e296dd8de2b60f8b8e15040702d41e3be1cd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 17:57:40 +0300 Subject: [PATCH 1170/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 5249a75a..7588335c 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -293,13 +293,13 @@ function M.run_compiledb() end) else vim.notify('Build Failed', vim.log.levels.ERROR, { title = 'PlatformIO' }) + _G.metadata.isBusy = false end end) end) end -- Store handles globally within the module so we can stop them -local uv = vim.uv or vim.loop M.watcher_handles = {} -- stylua: ignore From f1eb377fc7d3ed9cead149609a3615ce18b90e5a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 18:10:51 +0300 Subject: [PATCH 1171/1406] update --- lua/platformio/pio_setup.lua | 126 +++++++++++++++++++++++------------ 1 file changed, 83 insertions(+), 43 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 7588335c..cb9acced 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -300,75 +300,115 @@ function M.run_compiledb() end -- Store handles globally within the module so we can stop them -M.watcher_handles = {} -- stylua: ignore --- Use a single, global-ish timer variable to handle debouncing across all events -local debounce_timer = vim.uv.new_timer() +M.watcher_handles = {} +local uv = vim.uv or vim.loop +local timer = uv.new_timer() local function watch_file(full_path, callback) - -- 1. Nil check input parameters - if not full_path or type(callback) ~= 'function' then - vim.notify('watch_file: Invalid path or callback', vim.log.levels.ERROR) - return nil - end + local handle = uv.new_fs_event() + local target_file = vim.fn.fnamemodify(full_path, ':t') + local parent_dir = vim.fn.fnamemodify(full_path, ':h') - local handle, init_err = vim.uv.new_fs_event() if not handle then - vim.notify('watch_file: Failed to create handle: ' .. tostring(init_err), vim.log.levels.ERROR) return nil end - local parent_dir = vim.fn.fnamemodify(full_path, ':h') - local target_file = vim.fn.fnamemodify(full_path, ':t') - - -- Start the watcher on the parent directory - handle:start(parent_dir, {}, function(err, filename, events) - -- 2. Robust error checking (tostring handles nil err) - if err then - vim.schedule(function() - vim.notify('Watcher system error: ' .. tostring(err), vim.log.levels.ERROR) - end) - return - end - - -- 3. Guard against nil filename and metadata - -- Only proceed if the event is for our target file and we aren't busy - local is_target = (filename == target_file) - local is_busy = (_G.metadata and _G.metadata.isBusy == true) - - if not is_target or is_busy then + handle:start(parent_dir, {}, function(err, filename) + -- 1. Strict Filter: Only process if it's our file and we aren't already busy + if err or filename ~= target_file or (_G.metadata and _G.metadata.isBusy) then return end - if debounce_timer then - -- 4. Debounce Logic with Timer Safety - -- Stop existing timer if it's currently running (debouncing) - if debounce_timer:is_active() then - debounce_timer:stop() - end - - -- Start/Restart the timer - debounce_timer:start( + -- 2. Debounce: Reset the timer on every event + -- Only after 500ms of "silence" will the actual callback run + if timer then + timer:stop() + timer:start( 500, 0, vim.schedule_wrap(function() - -- 5. Final existence check before execution - -- Some editors delete/rename files during save (atomic saves) - local stat = vim.uv.fs_stat(full_path) + -- 3. Final Check: Ensure file exists before running heavy logic + local stat = uv.fs_stat(full_path) if stat and stat.type == 'file' then - print('File settled: ' .. target_file) callback() end end) ) end end) - return handle end + +-- Use a single, global-ish timer variable to handle debouncing across all events +-- local debounce_timer = vim.uv.new_timer() +-- +-- local function watch_file(full_path, callback) +-- -- 1. Nil check input parameters +-- if not full_path or type(callback) ~= 'function' then +-- vim.notify('watch_file: Invalid path or callback', vim.log.levels.ERROR) +-- return nil +-- end +-- +-- local handle, init_err = vim.uv.new_fs_event() +-- if not handle then +-- vim.notify('watch_file: Failed to create handle: ' .. tostring(init_err), vim.log.levels.ERROR) +-- return nil +-- end +-- +-- local parent_dir = vim.fn.fnamemodify(full_path, ':h') +-- local target_file = vim.fn.fnamemodify(full_path, ':t') +-- +-- -- Start the watcher on the parent directory +-- handle:start(parent_dir, {}, function(err, filename, events) +-- -- 2. Robust error checking (tostring handles nil err) +-- if err then +-- vim.schedule(function() +-- vim.notify('Watcher system error: ' .. tostring(err), vim.log.levels.ERROR) +-- end) +-- return +-- end +-- +-- -- 3. Guard against nil filename and metadata +-- -- Only proceed if the event is for our target file and we aren't busy +-- local is_target = (filename == target_file) +-- local is_busy = (_G.metadata and _G.metadata.isBusy == true) +-- +-- if not is_target or is_busy then +-- return +-- end +-- +-- if debounce_timer then +-- -- 4. Debounce Logic with Timer Safety +-- -- Stop existing timer if it's currently running (debouncing) +-- if debounce_timer:is_active() then +-- debounce_timer:stop() +-- end +-- +-- -- Start/Restart the timer +-- debounce_timer:start( +-- 500, +-- 0, +-- vim.schedule_wrap(function() +-- -- 5. Final existence check before execution +-- -- Some editors delete/rename files during save (atomic saves) +-- local stat = vim.uv.fs_stat(full_path) +-- if stat and stat.type == 'file' then +-- print('File settled: ' .. target_file) +-- callback() +-- end +-- end) +-- ) +-- end +-- end) +-- +-- return handle +-- end + + -- local function watch_file(full_path, callback) -- local handle = uv.new_fs_event() -- local parent_dir = vim.fn.fnamemodify(full_path, ':h') From 1390975ff810571f08304652e7678d6cab3d41d1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 18:20:00 +0300 Subject: [PATCH 1172/1406] update --- lua/platformio/pio_setup.lua | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index cb9acced..71960c83 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -282,6 +282,7 @@ function M.run_compiledb() vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) vim.schedule(function() + _G.metadata.isBusy = false if obj.code == 0 then M.pio_refresh(function() -- local dbFix = require('platformio.utils.pio').compile_commandsFix @@ -289,11 +290,12 @@ function M.run_compiledb() vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) -- pio_generate_db() -- lsp_restart('clangd') - _G.metadata.isBusy = false end) else - vim.notify('Build Failed', vim.log.levels.ERROR, { title = 'PlatformIO' }) - _G.metadata.isBusy = false + -- If pio failed, check obj.stderr to see why + local msg = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check pio logs' + vim.notify('Build Failed: ' .. msg, vim.log.levels.ERROR, { title = 'PlatformIO' }) + -- vim.notify('Build Failed', vim.log.levels.ERROR, { title = 'PlatformIO' }) end end) end) From aa5988bbf996d4b0895500a48e08f2a2e0e8f559 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 18:56:40 +0300 Subject: [PATCH 1173/1406] update --- lua/platformio/pio_setup.lua | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 71960c83..9d3487d6 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -273,21 +273,28 @@ local function get_hash(path) end -- _G.metadata.isBusy = false +-- stylua: ignore function M.run_compiledb() - if _G.metadata.isBusy then - return - end + if _G.metadata.isBusy then return end _G.metadata.isBusy = true vim.notify('Building Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) vim.schedule(function() - _G.metadata.isBusy = false if obj.code == 0 then + -- 1. Sync the checksum manually so the second watcher ignores this change + local checksum_path = vim.misc.joinPath(vim.uv.cwd(), '.pio/build', 'project.checksum') + local ok, new_checksum = vim.misc.readFile(checksum_path) + if ok then + _G.metadata.last_checksum = new_checksum + end + + -- 2. Refresh M.pio_refresh(function() -- local dbFix = require('platformio.utils.pio').compile_commandsFix -- dbFix() vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) + _G.metadata.isBusy = false -- pio_generate_db() -- lsp_restart('clangd') end) @@ -296,6 +303,7 @@ function M.run_compiledb() local msg = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check pio logs' vim.notify('Build Failed: ' .. msg, vim.log.levels.ERROR, { title = 'PlatformIO' }) -- vim.notify('Build Failed', vim.log.levels.ERROR, { title = 'PlatformIO' }) + _G.metadata.isBusy = false end end) end) From 9b8882cea5b233b9898c67f28530582af4df7014 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 19:03:03 +0300 Subject: [PATCH 1174/1406] update --- lua/platformio/pio_setup.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 9d3487d6..8dfbe43c 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -276,11 +276,13 @@ end -- stylua: ignore function M.run_compiledb() if _G.metadata.isBusy then return end + _G.metadata.isBusy = true vim.notify('Building Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) vim.schedule(function() + _G.metadata.isBusy = false if obj.code == 0 then -- 1. Sync the checksum manually so the second watcher ignores this change local checksum_path = vim.misc.joinPath(vim.uv.cwd(), '.pio/build', 'project.checksum') @@ -294,7 +296,6 @@ function M.run_compiledb() -- local dbFix = require('platformio.utils.pio').compile_commandsFix -- dbFix() vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) - _G.metadata.isBusy = false -- pio_generate_db() -- lsp_restart('clangd') end) @@ -303,7 +304,6 @@ function M.run_compiledb() local msg = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check pio logs' vim.notify('Build Failed: ' .. msg, vim.log.levels.ERROR, { title = 'PlatformIO' }) -- vim.notify('Build Failed', vim.log.levels.ERROR, { title = 'PlatformIO' }) - _G.metadata.isBusy = false end end) end) From e2fa9abc9091e51a3884fc493c4cb4f4e924431d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 19:23:39 +0300 Subject: [PATCH 1175/1406] update --- lua/platformio/pio_setup.lua | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 8dfbe43c..8f8b940c 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -292,13 +292,13 @@ function M.run_compiledb() end -- 2. Refresh - M.pio_refresh(function() - -- local dbFix = require('platformio.utils.pio').compile_commandsFix - -- dbFix() - vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- pio_generate_db() - -- lsp_restart('clangd') - end) + -- M.pio_refresh(function() + -- -- local dbFix = require('platformio.utils.pio').compile_commandsFix + -- -- dbFix() + -- vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- -- pio_generate_db() + -- -- lsp_restart('clangd') + -- end) else -- If pio failed, check obj.stderr to see why local msg = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check pio logs' From 030e8e2c135082e4f33b0bd091c55d6e18f8236b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 19:29:21 +0300 Subject: [PATCH 1176/1406] update --- lua/platformio/pio_setup.lua | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 8f8b940c..47b96439 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -285,17 +285,17 @@ function M.run_compiledb() _G.metadata.isBusy = false if obj.code == 0 then -- 1. Sync the checksum manually so the second watcher ignores this change - local checksum_path = vim.misc.joinPath(vim.uv.cwd(), '.pio/build', 'project.checksum') - local ok, new_checksum = vim.misc.readFile(checksum_path) - if ok then - _G.metadata.last_checksum = new_checksum - end + -- local checksum_path = vim.misc.joinPath(vim.uv.cwd(), '.pio/build', 'project.checksum') + -- local ok, new_checksum = vim.misc.readFile(checksum_path) + -- if ok then + -- _G.metadata.last_checksum = new_checksum + -- end -- 2. Refresh -- M.pio_refresh(function() -- -- local dbFix = require('platformio.utils.pio').compile_commandsFix -- -- dbFix() - -- vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) + vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) -- -- pio_generate_db() -- -- lsp_restart('clangd') -- end) From 4cfb95138178bdc5f77d1a3eeaa333a2c392825f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 19:46:47 +0300 Subject: [PATCH 1177/1406] update --- lua/platformio/pio_setup.lua | 43 ++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 47b96439..01a0a86d 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -282,29 +282,30 @@ function M.run_compiledb() vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) vim.schedule(function() - _G.metadata.isBusy = false - if obj.code == 0 then - -- 1. Sync the checksum manually so the second watcher ignores this change - -- local checksum_path = vim.misc.joinPath(vim.uv.cwd(), '.pio/build', 'project.checksum') - -- local ok, new_checksum = vim.misc.readFile(checksum_path) - -- if ok then - -- _G.metadata.last_checksum = new_checksum - -- end - - -- 2. Refresh - -- M.pio_refresh(function() - -- -- local dbFix = require('platformio.utils.pio').compile_commandsFix - -- -- dbFix() - vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- -- pio_generate_db() - -- -- lsp_restart('clangd') - -- end) - else - -- If pio failed, check obj.stderr to see why + -- 1. Check Execution + if obj.code ~= 0 then + _G.metadata.isBusy = false local msg = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check pio logs' - vim.notify('Build Failed: ' .. msg, vim.log.levels.ERROR, { title = 'PlatformIO' }) - -- vim.notify('Build Failed', vim.log.levels.ERROR, { title = 'PlatformIO' }) + -- vim.notify('PIO run_compiledb Error: ' .. msg, vim.log.levels.ERROR, { title = 'PlatformIO' }) + -- local msg = obj.code == 127 and "'pio' not found" or (obj.stderr or "Unknown Error") + return vim.notify("PIO run_compiledb Error: " .. msg, vim.log.levels.ERROR, { title = 'PlatformIO' }) end + -- 1. Sync the checksum manually so the second watcher ignores this change + -- local checksum_path = vim.misc.joinPath(vim.uv.cwd(), '.pio/build', 'project.checksum') + -- local ok, new_checksum = vim.misc.readFile(checksum_path) + -- if ok then + -- _G.metadata.last_checksum = new_checksum + -- end + + -- 2. Refresh + -- M.pio_refresh(function() + -- -- local dbFix = require('platformio.utils.pio').compile_commandsFix + -- -- dbFix() + vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- -- pio_generate_db() + -- -- lsp_restart('clangd') + -- end) + _G.metadata.isBusy = false end) end) end From 76102f9acd475a0022cc3b915212e2eb157a949e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 19:53:39 +0300 Subject: [PATCH 1178/1406] update --- lua/platformio/pio_setup.lua | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 01a0a86d..1eb37952 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -495,12 +495,13 @@ function M.start_watchers() return end -- Already updated + vim.notify('Checksum change', vim.log.levels.INFO, { title = 'PlatformIO' }) -- STEP 2: Cache Path (idedata.json exists and checksum changed) - M.pio_refresh(function() - -- local dbFix = require('platformio.utils.pio').compile_commandsFix - -- dbFix() - vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) - end) + -- M.pio_refresh(function() + -- -- local dbFix = require('platformio.utils.pio').compile_commandsFix + -- -- dbFix() + -- vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- end) end end, }, From 7db1a5be2c2e6fc96150b3c30d65363ea3111e72 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 19:56:02 +0300 Subject: [PATCH 1179/1406] update --- lua/platformio/pio_setup.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 1eb37952..3b35d890 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -496,6 +496,7 @@ function M.start_watchers() end -- Already updated vim.notify('Checksum change', vim.log.levels.INFO, { title = 'PlatformIO' }) + _G.metadata.isBusy = false -- STEP 2: Cache Path (idedata.json exists and checksum changed) -- M.pio_refresh(function() -- -- local dbFix = require('platformio.utils.pio').compile_commandsFix From c49c54c22cf86c5d67810e002268e2d236808538 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 20:32:54 +0300 Subject: [PATCH 1180/1406] update --- lua/platformio/pio_setup.lua | 42 ++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 3b35d890..8a94cb12 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -485,27 +485,27 @@ function M.start_watchers() end end, }, - { -- watcher for ./.pio/build/projct.checksum - idedata_path = vim.misc.joinPath(project_root, '.pio/build', active_env, 'idedata.json'),--idedata.json path - path = vim.misc.joinPath(project_root, '.pio/build', 'project.checksum'), --checksum_path - cb = function(self) - local _, current_checksum = vim.misc.readFile(self.path) - if current_checksum and current_checksum ~= '' then - if current_checksum == _G.metadata.last_checksum then - return - end -- Already updated - - vim.notify('Checksum change', vim.log.levels.INFO, { title = 'PlatformIO' }) - _G.metadata.isBusy = false - -- STEP 2: Cache Path (idedata.json exists and checksum changed) - -- M.pio_refresh(function() - -- -- local dbFix = require('platformio.utils.pio').compile_commandsFix - -- -- dbFix() - -- vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- end) - end - end, - }, + -- { -- watcher for ./.pio/build/projct.checksum + -- idedata_path = vim.misc.joinPath(project_root, '.pio/build', active_env, 'idedata.json'),--idedata.json path + -- path = vim.misc.joinPath(project_root, '.pio/build', 'project.checksum'), --checksum_path + -- cb = function(self) + -- local _, current_checksum = vim.misc.readFile(self.path) + -- if current_checksum and current_checksum ~= '' then + -- if current_checksum == _G.metadata.last_checksum then + -- return + -- end -- Already updated + -- + -- vim.notify('Checksum change', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- _G.metadata.isBusy = false + -- -- STEP 2: Cache Path (idedata.json exists and checksum changed) + -- -- M.pio_refresh(function() + -- -- -- local dbFix = require('platformio.utils.pio').compile_commandsFix + -- -- -- dbFix() + -- -- vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- -- end) + -- end + -- end, + -- }, } targets[1].current_ini_hash = get_hash(targets[1].path) or '' From 7b933cfce149f7cf3a1a3488153ae05b4a65baec Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 20:39:41 +0300 Subject: [PATCH 1181/1406] update --- lua/platformio/pio_setup.lua | 162 +++++++++++++++++------------------ 1 file changed, 81 insertions(+), 81 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 8a94cb12..26be6a8e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -313,44 +313,44 @@ end -- Store handles globally within the module so we can stop them -- stylua: ignore -M.watcher_handles = {} -local uv = vim.uv or vim.loop -local timer = uv.new_timer() - -local function watch_file(full_path, callback) - local handle = uv.new_fs_event() - local target_file = vim.fn.fnamemodify(full_path, ':t') - local parent_dir = vim.fn.fnamemodify(full_path, ':h') - - if not handle then - return nil - end - - handle:start(parent_dir, {}, function(err, filename) - -- 1. Strict Filter: Only process if it's our file and we aren't already busy - if err or filename ~= target_file or (_G.metadata and _G.metadata.isBusy) then - return - end - - -- 2. Debounce: Reset the timer on every event - -- Only after 500ms of "silence" will the actual callback run - if timer then - timer:stop() - timer:start( - 500, - 0, - vim.schedule_wrap(function() - -- 3. Final Check: Ensure file exists before running heavy logic - local stat = uv.fs_stat(full_path) - if stat and stat.type == 'file' then - callback() - end - end) - ) - end - end) - return handle -end +-- M.watcher_handles = {} +-- local uv = vim.uv or vim.loop +-- local timer = uv.new_timer() +-- +-- local function watch_file(full_path, callback) +-- local handle = uv.new_fs_event() +-- local target_file = vim.fn.fnamemodify(full_path, ':t') +-- local parent_dir = vim.fn.fnamemodify(full_path, ':h') +-- +-- if not handle then +-- return nil +-- end +-- +-- handle:start(parent_dir, {}, function(err, filename) +-- -- 1. Strict Filter: Only process if it's our file and we aren't already busy +-- if err or filename ~= target_file or (_G.metadata and _G.metadata.isBusy) then +-- return +-- end +-- +-- -- 2. Debounce: Reset the timer on every event +-- -- Only after 500ms of "silence" will the actual callback run +-- if timer then +-- timer:stop() +-- timer:start( +-- 500, +-- 0, +-- vim.schedule_wrap(function() +-- -- 3. Final Check: Ensure file exists before running heavy logic +-- local stat = uv.fs_stat(full_path) +-- if stat and stat.type == 'file' then +-- callback() +-- end +-- end) +-- ) +-- end +-- end) +-- return handle +-- end @@ -419,50 +419,50 @@ end -- return handle -- end +-- stylua: ignore +local function watch_file(full_path, callback) + local handle = uv.new_fs_event() + local parent_dir = vim.fn.fnamemodify(full_path, ':h') + local target_file = vim.fn.fnamemodify(full_path, ':t') --- local function watch_file(full_path, callback) --- local handle = uv.new_fs_event() --- local parent_dir = vim.fn.fnamemodify(full_path, ':h') --- local target_file = vim.fn.fnamemodify(full_path, ':t') --- --- if handle then --- handle:start( parent_dir, {}, --- function(err, filename) --, events) --- --- -- 1. Catch REAL system errors --- if err then --or filename ~= target_file or _G.metadata.isBusy or not events or not (events.change or events.rename) then --- -- Use vim.schedule to notify so we don't block the loop --- vim.schedule(function() --- vim.notify("Watcher error: " .. tostring(err), vim.log.levels.ERROR) --- end) --- return --handle:stop() --- end --- --- -- if filename == target_file then --- -- end --- --- -- 2. SILENTLY ignore events that aren't our target file --- -- Or if we are currently busy processing another task --- if filename ~= target_file or _G.metadata.isBusy then --- return --- end --- --- -- Debounce: Use vim.schedule to ensure we don't fire --- -- during the middle of a file-swap operation --- -- 3. Trigger the callback safely --- vim.schedule(function() --- print('file watched') --- -- Re-verify file exists before calling --- if vim.loop.fs_stat(full_path) then --- callback() --- end --- end) --- -- vim.schedule(callback) --- end --- ) --- return handle --- end --- end + if handle then + handle:start( parent_dir, {}, + function(err, filename, events) + + -- 1. Catch REAL system errors + if err or filename ~= target_file or _G.metadata.isBusy or not events or not (events.change or events.rename) then + -- Use vim.schedule to notify so we don't block the loop + vim.schedule(function() + vim.notify("Watcher error: " .. tostring(err), vim.log.levels.ERROR) + end) + return --handle:stop() + end + + -- if filename == target_file then + -- end + + -- 2. SILENTLY ignore events that aren't our target file + -- Or if we are currently busy processing another task + -- if filename ~= target_file or _G.metadata.isBusy then + -- return + -- end + + -- Debounce: Use vim.schedule to ensure we don't fire + -- during the middle of a file-swap operation + -- 3. Trigger the callback safely + vim.schedule(function() + print('file watched') + -- Re-verify file exists before calling + if vim.loop.fs_stat(full_path) then + callback() + end + end) + -- vim.schedule(callback) + end + ) + return handle + end +end -- stylua: ignore function M.start_watchers() From 2eb9a73433cbbfd2d2cdedc6a0704b3b43fec124 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 20:45:45 +0300 Subject: [PATCH 1182/1406] update --- lua/platformio/pio_setup.lua | 63 +++++++++++++++++------------------- 1 file changed, 30 insertions(+), 33 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 26be6a8e..47386fbd 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -313,8 +313,6 @@ end -- Store handles globally within the module so we can stop them -- stylua: ignore --- M.watcher_handles = {} --- local uv = vim.uv or vim.loop -- local timer = uv.new_timer() -- -- local function watch_file(full_path, callback) @@ -420,46 +418,45 @@ end -- end -- stylua: ignore +local uv = vim.uv or vim.loop +M.watcher_handles = {} local function watch_file(full_path, callback) local handle = uv.new_fs_event() local parent_dir = vim.fn.fnamemodify(full_path, ':h') local target_file = vim.fn.fnamemodify(full_path, ':t') if handle then - handle:start( parent_dir, {}, - function(err, filename, events) - - -- 1. Catch REAL system errors - if err or filename ~= target_file or _G.metadata.isBusy or not events or not (events.change or events.rename) then - -- Use vim.schedule to notify so we don't block the loop - vim.schedule(function() - vim.notify("Watcher error: " .. tostring(err), vim.log.levels.ERROR) - end) - return --handle:stop() - end - - -- if filename == target_file then - -- end - - -- 2. SILENTLY ignore events that aren't our target file - -- Or if we are currently busy processing another task - -- if filename ~= target_file or _G.metadata.isBusy then - -- return - -- end - - -- Debounce: Use vim.schedule to ensure we don't fire - -- during the middle of a file-swap operation - -- 3. Trigger the callback safely + handle:start(parent_dir, {}, function(err, filename, events) + -- 1. Catch REAL system errors + if err or filename ~= target_file or _G.metadata.isBusy or not events or not (events.change or events.rename) then + -- Use vim.schedule to notify so we don't block the loop vim.schedule(function() - print('file watched') - -- Re-verify file exists before calling - if vim.loop.fs_stat(full_path) then - callback() - end + vim.notify('Watcher error: ' .. tostring(err), vim.log.levels.ERROR) end) - -- vim.schedule(callback) + return --handle:stop() end - ) + + -- if filename == target_file then + -- end + + -- 2. SILENTLY ignore events that aren't our target file + -- Or if we are currently busy processing another task + -- if filename ~= target_file or _G.metadata.isBusy then + -- return + -- end + + -- Debounce: Use vim.schedule to ensure we don't fire + -- during the middle of a file-swap operation + -- 3. Trigger the callback safely + vim.schedule(function() + print('file watched') + -- Re-verify file exists before calling + if vim.loop.fs_stat(full_path) then + callback() + end + end) + -- vim.schedule(callback) + end) return handle end end From 6da381900a32120e561de54f47940b3890051d7b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 20:57:07 +0300 Subject: [PATCH 1183/1406] update --- lua/platformio/pio_setup.lua | 196 +++++++++++++++++------------------ 1 file changed, 98 insertions(+), 98 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 47386fbd..d47a8554 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -352,115 +352,115 @@ end --- Use a single, global-ish timer variable to handle debouncing across all events --- local debounce_timer = vim.uv.new_timer() --- --- local function watch_file(full_path, callback) --- -- 1. Nil check input parameters --- if not full_path or type(callback) ~= 'function' then --- vim.notify('watch_file: Invalid path or callback', vim.log.levels.ERROR) --- return nil --- end --- --- local handle, init_err = vim.uv.new_fs_event() --- if not handle then --- vim.notify('watch_file: Failed to create handle: ' .. tostring(init_err), vim.log.levels.ERROR) --- return nil --- end --- --- local parent_dir = vim.fn.fnamemodify(full_path, ':h') --- local target_file = vim.fn.fnamemodify(full_path, ':t') --- --- -- Start the watcher on the parent directory --- handle:start(parent_dir, {}, function(err, filename, events) --- -- 2. Robust error checking (tostring handles nil err) --- if err then --- vim.schedule(function() --- vim.notify('Watcher system error: ' .. tostring(err), vim.log.levels.ERROR) --- end) --- return --- end --- --- -- 3. Guard against nil filename and metadata --- -- Only proceed if the event is for our target file and we aren't busy --- local is_target = (filename == target_file) --- local is_busy = (_G.metadata and _G.metadata.isBusy == true) --- --- if not is_target or is_busy then --- return --- end --- --- if debounce_timer then --- -- 4. Debounce Logic with Timer Safety --- -- Stop existing timer if it's currently running (debouncing) --- if debounce_timer:is_active() then --- debounce_timer:stop() --- end --- --- -- Start/Restart the timer --- debounce_timer:start( --- 500, --- 0, --- vim.schedule_wrap(function() --- -- 5. Final existence check before execution --- -- Some editors delete/rename files during save (atomic saves) --- local stat = vim.uv.fs_stat(full_path) --- if stat and stat.type == 'file' then --- print('File settled: ' .. target_file) --- callback() --- end --- end) --- ) --- end --- end) --- --- return handle --- end - --- stylua: ignore local uv = vim.uv or vim.loop M.watcher_handles = {} +-- Use a single, global-ish timer variable to handle debouncing across all events +local debounce_timer = vim.uv.new_timer() + local function watch_file(full_path, callback) - local handle = uv.new_fs_event() + -- 1. Nil check input parameters + if not full_path or type(callback) ~= 'function' then + vim.notify('watch_file: Invalid path or callback', vim.log.levels.ERROR) + return nil + end + + local handle, init_err = vim.uv.new_fs_event() + if not handle then + vim.notify('watch_file: Failed to create handle: ' .. tostring(init_err), vim.log.levels.ERROR) + return nil + end + local parent_dir = vim.fn.fnamemodify(full_path, ':h') local target_file = vim.fn.fnamemodify(full_path, ':t') - if handle then - handle:start(parent_dir, {}, function(err, filename, events) - -- 1. Catch REAL system errors - if err or filename ~= target_file or _G.metadata.isBusy or not events or not (events.change or events.rename) then - -- Use vim.schedule to notify so we don't block the loop - vim.schedule(function() - vim.notify('Watcher error: ' .. tostring(err), vim.log.levels.ERROR) - end) - return --handle:stop() - end + -- Start the watcher on the parent directory + handle:start(parent_dir, {}, function(err, filename, events) + -- 2. Robust error checking (tostring handles nil err) + if err then + vim.schedule(function() + vim.notify('Watcher system error: ' .. tostring(err), vim.log.levels.ERROR) + end) + return + end - -- if filename == target_file then - -- end + -- 3. Guard against nil filename and metadata + -- Only proceed if the event is for our target file and we aren't busy + local is_target = (filename == target_file) + local is_busy = (_G.metadata and _G.metadata.isBusy == true) - -- 2. SILENTLY ignore events that aren't our target file - -- Or if we are currently busy processing another task - -- if filename ~= target_file or _G.metadata.isBusy then - -- return - -- end + if not is_target or is_busy then + return + end - -- Debounce: Use vim.schedule to ensure we don't fire - -- during the middle of a file-swap operation - -- 3. Trigger the callback safely - vim.schedule(function() - print('file watched') - -- Re-verify file exists before calling - if vim.loop.fs_stat(full_path) then - callback() - end - end) - -- vim.schedule(callback) - end) - return handle - end + if debounce_timer then + -- 4. Debounce Logic with Timer Safety + -- Stop existing timer if it's currently running (debouncing) + if debounce_timer:is_active() then + debounce_timer:stop() + end + + -- Start/Restart the timer + debounce_timer:start( + 500, + 0, + vim.schedule_wrap(function() + -- 5. Final existence check before execution + -- Some editors delete/rename files during save (atomic saves) + local stat = vim.uv.fs_stat(full_path) + if stat and stat.type == 'file' then + print('File settled: ' .. target_file) + callback() + end + end) + ) + end + end) + + return handle end +-- stylua: ignore +-- local function watch_file(full_path, callback) +-- local handle = uv.new_fs_event() +-- local parent_dir = vim.fn.fnamemodify(full_path, ':h') +-- local target_file = vim.fn.fnamemodify(full_path, ':t') +-- +-- if handle then +-- handle:start(parent_dir, {}, function(err, filename, events) +-- -- 1. Catch REAL system errors +-- if err or filename ~= target_file or _G.metadata.isBusy or not events or not (events.change or events.rename) then +-- -- Use vim.schedule to notify so we don't block the loop +-- vim.schedule(function() +-- vim.notify('Watcher error: ' .. tostring(err), vim.log.levels.ERROR) +-- end) +-- return --handle:stop() +-- end +-- +-- -- if filename == target_file then +-- -- end +-- +-- -- 2. SILENTLY ignore events that aren't our target file +-- -- Or if we are currently busy processing another task +-- -- if filename ~= target_file or _G.metadata.isBusy then +-- -- return +-- -- end +-- +-- -- Debounce: Use vim.schedule to ensure we don't fire +-- -- during the middle of a file-swap operation +-- -- 3. Trigger the callback safely +-- vim.schedule(function() +-- print('file watched') +-- -- Re-verify file exists before calling +-- if vim.loop.fs_stat(full_path) then +-- callback() +-- end +-- end) +-- -- vim.schedule(callback) +-- end) +-- return handle +-- end +-- end + -- stylua: ignore function M.start_watchers() -- Clean up any existing watchers first to prevent duplicates From bd4c6d44a829b7c82ea9b5601f4320cbefbccfa6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 21:49:04 +0300 Subject: [PATCH 1184/1406] update --- lua/platformio/pio_setup.lua | 7 +++++++ lua/platformio/utils/pio.lua | 12 ++++++++++++ 2 files changed, 19 insertions(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index d47a8554..724154f6 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -479,6 +479,13 @@ function M.start_watchers() if new_hash and new_hash ~= self.current_ini_hash then self.current_ini_hash = new_hash M.run_compiledb() -- Smart: Auto-update DB if config changes + local pio = require('platformio.utils.pio') + pio.run_sequence({ + cmnds = { + 'pio run -t compiledb', + }, + cb = pio.handlePiodb, + }) end end, }, diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 4f1f8081..d516088c 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -250,4 +250,16 @@ function M.handlePiolib(result) _G.metadata.isBusy = false end +function M.handlePiodb(result) + if result == 'INIT' then + term.ToggleTerminal(table.remove(M.queue, 1), 'float') + elseif result == 'DONE' then -- result of the only and the last command + vim.notify('Piodb: Success', vim.log.levels.INFO) + elseif result == 'FAIL' then + end + M.queue = {} + term.stdout_callback = nil + _G.metadata.isBusy = false +end + return M From 2731faddf9d81fd7ce1166e530c120c7294d6eab Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Tue, 28 Apr 2026 21:55:20 +0300 Subject: [PATCH 1185/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 724154f6..0b1840eb 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -617,7 +617,7 @@ function M.init() -- Always start the watcher so it can catch a future 'pio init' -- M.start_pio_watcher() - M.start_watchers() + -- M.start_watchers() -- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) -- If the file already exists, do an initial sync From ab678ee787b826c6b0dbae1d57d3fe43a8b9f7fe Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 06:10:27 +0300 Subject: [PATCH 1186/1406] update --- lua/platformio/pio_setup.lua | 228 ++++++++++++++++++----------------- 1 file changed, 117 insertions(+), 111 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 0b1840eb..03102210 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -276,8 +276,9 @@ end -- stylua: ignore function M.run_compiledb() if _G.metadata.isBusy then return end - _G.metadata.isBusy = true + + M.stop_watchers() -- Kill watchers so they don't fire during the build vim.notify('Building Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) @@ -285,9 +286,8 @@ function M.run_compiledb() -- 1. Check Execution if obj.code ~= 0 then _G.metadata.isBusy = false + M.start_watchers() -- 2. RESTART after success local msg = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check pio logs' - -- vim.notify('PIO run_compiledb Error: ' .. msg, vim.log.levels.ERROR, { title = 'PlatformIO' }) - -- local msg = obj.code == 127 and "'pio' not found" or (obj.stderr or "Unknown Error") return vim.notify("PIO run_compiledb Error: " .. msg, vim.log.levels.ERROR, { title = 'PlatformIO' }) end -- 1. Sync the checksum manually so the second watcher ignores this change @@ -298,14 +298,15 @@ function M.run_compiledb() -- end -- 2. Refresh - -- M.pio_refresh(function() - -- -- local dbFix = require('platformio.utils.pio').compile_commandsFix - -- -- dbFix() - vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- -- pio_generate_db() - -- -- lsp_restart('clangd') - -- end) - _G.metadata.isBusy = false + M.pio_refresh(function() + -- local dbFix = require('platformio.utils.pio').compile_commandsFix + -- dbFix() + vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) + _G.metadata.isBusy = false + M.start_watchers() -- 2. RESTART after success + -- pio_generate_db() + -- lsp_restart('clangd') + end) end) end) end @@ -354,113 +355,113 @@ end local uv = vim.uv or vim.loop M.watcher_handles = {} + -- Use a single, global-ish timer variable to handle debouncing across all events -local debounce_timer = vim.uv.new_timer() +-- local debounce_timer = vim.uv.new_timer() +-- +-- local function watch_file(full_path, callback) +-- -- 1. Nil check input parameters +-- if not full_path or type(callback) ~= 'function' then +-- vim.notify('watch_file: Invalid path or callback', vim.log.levels.ERROR) +-- return nil +-- end +-- +-- local handle, init_err = vim.uv.new_fs_event() +-- if not handle then +-- vim.notify('watch_file: Failed to create handle: ' .. tostring(init_err), vim.log.levels.ERROR) +-- return nil +-- end +-- +-- local parent_dir = vim.fn.fnamemodify(full_path, ':h') +-- local target_file = vim.fn.fnamemodify(full_path, ':t') +-- +-- -- Start the watcher on the parent directory +-- handle:start(parent_dir, {}, function(err, filename, events) +-- -- 2. Robust error checking (tostring handles nil err) +-- if err then +-- vim.schedule(function() +-- vim.notify('Watcher system error: ' .. tostring(err), vim.log.levels.ERROR) +-- end) +-- return +-- end +-- +-- -- 3. Guard against nil filename and metadata +-- -- Only proceed if the event is for our target file and we aren't busy +-- local is_target = (filename == target_file) +-- local is_busy = (_G.metadata and _G.metadata.isBusy == true) +-- +-- if not is_target or is_busy then +-- return +-- end +-- +-- if debounce_timer then +-- -- 4. Debounce Logic with Timer Safety +-- -- Stop existing timer if it's currently running (debouncing) +-- if debounce_timer:is_active() then +-- debounce_timer:stop() +-- end +-- +-- -- Start/Restart the timer +-- debounce_timer:start( +-- 500, +-- 0, +-- vim.schedule_wrap(function() +-- -- 5. Final existence check before execution +-- -- Some editors delete/rename files during save (atomic saves) +-- local stat = vim.uv.fs_stat(full_path) +-- if stat and stat.type == 'file' then +-- print('File settled: ' .. target_file) +-- callback() +-- end +-- end) +-- ) +-- end +-- end) +-- +-- return handle +-- end +-- stylua: ignore local function watch_file(full_path, callback) - -- 1. Nil check input parameters - if not full_path or type(callback) ~= 'function' then - vim.notify('watch_file: Invalid path or callback', vim.log.levels.ERROR) - return nil - end - - local handle, init_err = vim.uv.new_fs_event() - if not handle then - vim.notify('watch_file: Failed to create handle: ' .. tostring(init_err), vim.log.levels.ERROR) - return nil - end - + local handle = uv.new_fs_event() local parent_dir = vim.fn.fnamemodify(full_path, ':h') local target_file = vim.fn.fnamemodify(full_path, ':t') - -- Start the watcher on the parent directory + if not handle then return nil end handle:start(parent_dir, {}, function(err, filename, events) - -- 2. Robust error checking (tostring handles nil err) - if err then - vim.schedule(function() - vim.notify('Watcher system error: ' .. tostring(err), vim.log.levels.ERROR) - end) - return + -- 1. Catch REAL system errors + if err or filename ~= target_file or (_G.metadata and _G.metadata.isBusy) or (events and not (events.change or events.rename)) then + if err then + -- Use vim.schedule to notify so we don't block the loop + vim.schedule(function() + vim.notify('Watcher error: ' .. tostring(err), vim.log.levels.ERROR) + end) + end + return --handle:stop() end - -- 3. Guard against nil filename and metadata - -- Only proceed if the event is for our target file and we aren't busy - local is_target = (filename == target_file) - local is_busy = (_G.metadata and _G.metadata.isBusy == true) - - if not is_target or is_busy then - return - end + -- if filename == target_file then + -- end - if debounce_timer then - -- 4. Debounce Logic with Timer Safety - -- Stop existing timer if it's currently running (debouncing) - if debounce_timer:is_active() then - debounce_timer:stop() - end + -- 2. SILENTLY ignore events that aren't our target file + -- Or if we are currently busy processing another task + -- if filename ~= target_file or _G.metadata.isBusy then + -- return + -- end - -- Start/Restart the timer - debounce_timer:start( - 500, - 0, - vim.schedule_wrap(function() - -- 5. Final existence check before execution - -- Some editors delete/rename files during save (atomic saves) - local stat = vim.uv.fs_stat(full_path) - if stat and stat.type == 'file' then - print('File settled: ' .. target_file) - callback() - end - end) - ) - end + -- Debounce: Use vim.schedule to ensure we don't fire + -- during the middle of a file-swap operation + -- 3. Trigger the callback safely + vim.defer_fn(function() + print('file watched') + -- Re-verify file exists before calling + if vim.loop.fs_stat(full_path) then callback() end + end, 500) + -- vim.schedule(callback) end) - return handle end --- stylua: ignore --- local function watch_file(full_path, callback) --- local handle = uv.new_fs_event() --- local parent_dir = vim.fn.fnamemodify(full_path, ':h') --- local target_file = vim.fn.fnamemodify(full_path, ':t') --- --- if handle then --- handle:start(parent_dir, {}, function(err, filename, events) --- -- 1. Catch REAL system errors --- if err or filename ~= target_file or _G.metadata.isBusy or not events or not (events.change or events.rename) then --- -- Use vim.schedule to notify so we don't block the loop --- vim.schedule(function() --- vim.notify('Watcher error: ' .. tostring(err), vim.log.levels.ERROR) --- end) --- return --handle:stop() --- end --- --- -- if filename == target_file then --- -- end --- --- -- 2. SILENTLY ignore events that aren't our target file --- -- Or if we are currently busy processing another task --- -- if filename ~= target_file or _G.metadata.isBusy then --- -- return --- -- end --- --- -- Debounce: Use vim.schedule to ensure we don't fire --- -- during the middle of a file-swap operation --- -- 3. Trigger the callback safely --- vim.schedule(function() --- print('file watched') --- -- Re-verify file exists before calling --- if vim.loop.fs_stat(full_path) then --- callback() --- end --- end) --- -- vim.schedule(callback) --- end) --- return handle --- end --- end - -- stylua: ignore function M.start_watchers() -- Clean up any existing watchers first to prevent duplicates @@ -479,13 +480,13 @@ function M.start_watchers() if new_hash and new_hash ~= self.current_ini_hash then self.current_ini_hash = new_hash M.run_compiledb() -- Smart: Auto-update DB if config changes - local pio = require('platformio.utils.pio') - pio.run_sequence({ - cmnds = { - 'pio run -t compiledb', - }, - cb = pio.handlePiodb, - }) + -- local pio = require('platformio.utils.pio') + -- pio.run_sequence({ + -- cmnds = { + -- 'pio run -t compiledb', + -- }, + -- cb = pio.handlePiodb, + -- }) end end, }, @@ -523,7 +524,12 @@ end -- stylua: ignore function M.stop_watchers() - for _, handle in ipairs(M.watcher_handles) do handle:stop() end + -- Safety: Ensure it's a table before looping + M.watcher_handles = M.watcher_handles or {} + + for _, handle in ipairs(M.watcher_handles) do + if handle and not handle:is_closing() then handle:stop() end + end M.watcher_handles = {} end From b66491df79a57bbc7458e1fe4c2fec5ed874459b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 06:19:58 +0300 Subject: [PATCH 1187/1406] update --- lua/platformio/pio_setup.lua | 87 ++++++++++++++++++++++++++---------- 1 file changed, 63 insertions(+), 24 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 03102210..e1cdfaec 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -278,39 +278,78 @@ function M.run_compiledb() if _G.metadata.isBusy then return end _G.metadata.isBusy = true - M.stop_watchers() -- Kill watchers so they don't fire during the build - vim.notify('Building Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) + M.stop_watchers() -- 1. Silence watchers to prevent the loop + vim.notify('Building DB...', vim.log.levels.INFO) vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) vim.schedule(function() - -- 1. Check Execution - if obj.code ~= 0 then + if obj.code == 0 then + -- 2. PERFORM CHECKSUM ACTIONS MANUALLY + local checksum_path = vim.misc.joinPath(vim.uv.cwd(), '.pio/build', 'project.checksum') + local ok, new_checksum = vim.misc.readFile(checksum_path) + + if ok then + _G.metadata.last_checksum = new_checksum -- Sync the state + + -- 3. Run the refresh logic (The "Action" normally taken by the watcher) + M.pio_refresh(function() + vim.notify('DB & Cache Updated', vim.log.levels.INFO) + _G.metadata.isBusy = false + M.start_watchers() -- 4. Re-enable watchers for future changes + end) + else + -- If we can't read the checksum, something is wrong with the build output + _G.metadata.isBusy = false + M.start_watchers() + end + else + vim.notify('Build Failed', vim.log.levels.ERROR) _G.metadata.isBusy = false - M.start_watchers() -- 2. RESTART after success - local msg = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check pio logs' - return vim.notify("PIO run_compiledb Error: " .. msg, vim.log.levels.ERROR, { title = 'PlatformIO' }) + M.start_watchers() end - -- 1. Sync the checksum manually so the second watcher ignores this change - -- local checksum_path = vim.misc.joinPath(vim.uv.cwd(), '.pio/build', 'project.checksum') - -- local ok, new_checksum = vim.misc.readFile(checksum_path) - -- if ok then - -- _G.metadata.last_checksum = new_checksum - -- end - - -- 2. Refresh - M.pio_refresh(function() - -- local dbFix = require('platformio.utils.pio').compile_commandsFix - -- dbFix() - vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) - _G.metadata.isBusy = false - M.start_watchers() -- 2. RESTART after success - -- pio_generate_db() - -- lsp_restart('clangd') - end) end) end) end + + +-- function M.run_compiledb() +-- if _G.metadata.isBusy then return end +-- _G.metadata.isBusy = true +-- +-- M.stop_watchers() -- Kill watchers so they don't fire during the build +-- vim.notify('Building Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) +-- +-- vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) +-- vim.schedule(function() +-- -- 1. Check Execution +-- if obj.code ~= 0 then +-- _G.metadata.isBusy = false +-- M.start_watchers() -- 2. RESTART after success +-- local msg = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check pio logs' +-- return vim.notify("PIO run_compiledb Error: " .. msg, vim.log.levels.ERROR, { title = 'PlatformIO' }) +-- end +-- -- 1. Sync the checksum manually so the second watcher ignores this change +-- -- local checksum_path = vim.misc.joinPath(vim.uv.cwd(), '.pio/build', 'project.checksum') +-- -- local ok, new_checksum = vim.misc.readFile(checksum_path) +-- -- if ok then +-- -- _G.metadata.last_checksum = new_checksum +-- -- end +-- +-- -- 2. Refresh +-- M.pio_refresh(function() +-- -- local dbFix = require('platformio.utils.pio').compile_commandsFix +-- -- dbFix() +-- vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) +-- _G.metadata.isBusy = false +-- M.start_watchers() -- 2. RESTART after success +-- -- pio_generate_db() +-- -- lsp_restart('clangd') +-- end) +-- end) +-- end) +-- end + -- Store handles globally within the module so we can stop them -- stylua: ignore From 607be9580185ef256a0ed88b30e6bd0d5187a39c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 06:22:19 +0300 Subject: [PATCH 1188/1406] update --- lua/platformio/pio_setup.lua | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index e1cdfaec..c570f77b 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -661,8 +661,7 @@ function M.init() end -- Always start the watcher so it can catch a future 'pio init' - -- M.start_pio_watcher() - -- M.start_watchers() + M.start_watchers() -- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) -- If the file already exists, do an initial sync From 8a5b88e4f620f060dad06d8ba245027a5c5db85a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 06:38:43 +0300 Subject: [PATCH 1189/1406] update --- lua/platformio/pio_setup.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index c570f77b..d5dc0c69 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -119,6 +119,8 @@ function M.pio_refresh(callback) -- STEP 1: Fast Checksum Check --------------------------------------------------------- local _, current_checksum = vim.misc.readFile(checksum_file) + print('f=' .. current_checksum) + print('g=' .. meta.last_projectChecksum) if current_checksum and current_checksum ~= '' then if current_checksum == meta.last_projectChecksum then vim.notify('PIO: Metadata synced with cache', vim.log.levels.INFO) From 08464dc62ab8d371a7e56159034ebf629da3017a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 06:46:23 +0300 Subject: [PATCH 1190/1406] update --- lua/platformio/pio_setup.lua | 54 ++++++++++++++++++------------------ 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index d5dc0c69..b257c36d 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -291,7 +291,7 @@ function M.run_compiledb() local ok, new_checksum = vim.misc.readFile(checksum_path) if ok then - _G.metadata.last_checksum = new_checksum -- Sync the state + _G.metadata.last_projectChecksum = new_checksum -- Sync the state -- 3. Run the refresh logic (The "Action" normally taken by the watcher) M.pio_refresh(function() @@ -313,10 +313,10 @@ function M.run_compiledb() end) end - - -- function M.run_compiledb() --- if _G.metadata.isBusy then return end +-- if _G.metadata.isBusy then +-- return +-- end -- _G.metadata.isBusy = true -- -- M.stop_watchers() -- Kill watchers so they don't fire during the build @@ -329,13 +329,13 @@ end -- _G.metadata.isBusy = false -- M.start_watchers() -- 2. RESTART after success -- local msg = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check pio logs' --- return vim.notify("PIO run_compiledb Error: " .. msg, vim.log.levels.ERROR, { title = 'PlatformIO' }) +-- return vim.notify('PIO run_compiledb Error: ' .. msg, vim.log.levels.ERROR, { title = 'PlatformIO' }) -- end -- -- 1. Sync the checksum manually so the second watcher ignores this change -- -- local checksum_path = vim.misc.joinPath(vim.uv.cwd(), '.pio/build', 'project.checksum') -- -- local ok, new_checksum = vim.misc.readFile(checksum_path) -- -- if ok then --- -- _G.metadata.last_checksum = new_checksum +-- _G.metadata.last_projectChecksum = new_checksum -- -- end -- -- -- 2. Refresh @@ -531,27 +531,27 @@ function M.start_watchers() end end, }, - -- { -- watcher for ./.pio/build/projct.checksum - -- idedata_path = vim.misc.joinPath(project_root, '.pio/build', active_env, 'idedata.json'),--idedata.json path - -- path = vim.misc.joinPath(project_root, '.pio/build', 'project.checksum'), --checksum_path - -- cb = function(self) - -- local _, current_checksum = vim.misc.readFile(self.path) - -- if current_checksum and current_checksum ~= '' then - -- if current_checksum == _G.metadata.last_checksum then - -- return - -- end -- Already updated - -- - -- vim.notify('Checksum change', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- _G.metadata.isBusy = false - -- -- STEP 2: Cache Path (idedata.json exists and checksum changed) - -- -- M.pio_refresh(function() - -- -- -- local dbFix = require('platformio.utils.pio').compile_commandsFix - -- -- -- dbFix() - -- -- vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- -- end) - -- end - -- end, - -- }, + { -- watcher for ./.pio/build/projct.checksum + idedata_path = vim.misc.joinPath(project_root, '.pio/build', active_env, 'idedata.json'),--idedata.json path + path = vim.misc.joinPath(project_root, '.pio/build', 'project.checksum'), --checksum_path + cb = function(self) + local _, current_checksum = vim.misc.readFile(self.path) + if current_checksum and current_checksum ~= '' then + if current_checksum == _G.metadata.last_projectChecksum then + return + end -- Already updated + + vim.notify('Checksum change', vim.log.levels.INFO, { title = 'PlatformIO' }) + _G.metadata.isBusy = false + -- STEP 2: Cache Path (idedata.json exists and checksum changed) + -- M.pio_refresh(function() + -- -- local dbFix = require('platformio.utils.pio').compile_commandsFix + -- -- dbFix() + -- vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- end) + end + end, + }, } targets[1].current_ini_hash = get_hash(targets[1].path) or '' From 1d723257b7d172b9f48bb9fc7d69f510dbd6f745 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 07:30:10 +0300 Subject: [PATCH 1191/1406] update --- lua/platformio/metadata.lua | 12 ++++++------ lua/platformio/pio_setup.lua | 2 -- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 39c167ab..a9080824 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -154,7 +154,7 @@ function M.load_project_config() end end -- If no file, initialize hash with defaults - last_saved_hash = vim.fn.sha256(vim.json.encode(_pio_metadata)) + last_saved_hash = vim.fn.sha256(vim.misc.pretty_print(_pio_metadata)) end -- 5. Helper for ToggleTerm / Commands @@ -167,10 +167,10 @@ end M.load_project_config() -- Auto-save on exit even if no manual changes were made -vim.api.nvim_create_autocmd('VimLeavePre', { - callback = function() - M.save_project_config(true) - end, -}) +-- vim.api.nvim_create_autocmd('VimLeavePre', { +-- callback = function() +-- M.save_project_config(true) +-- end, +-- }) return M diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b257c36d..51ac6200 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -119,8 +119,6 @@ function M.pio_refresh(callback) -- STEP 1: Fast Checksum Check --------------------------------------------------------- local _, current_checksum = vim.misc.readFile(checksum_file) - print('f=' .. current_checksum) - print('g=' .. meta.last_projectChecksum) if current_checksum and current_checksum ~= '' then if current_checksum == meta.last_projectChecksum then vim.notify('PIO: Metadata synced with cache', vim.log.levels.INFO) From a6da7fb680d64a7360e999e2fa3b7a0ed230b91a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 07:38:01 +0300 Subject: [PATCH 1192/1406] update --- lua/platformio/metadata.lua | 1 + lua/platformio/pio_setup.lua | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index a9080824..bb24c4f8 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -85,6 +85,7 @@ function M.save_project_config(quiet) -- 1. Generate the formatted string directly, pretty_print already returns a string! local ok, pretty_json = pcall(vim.misc.pretty_print, _pio_metadata) + vim.notify('PIO:checksum 5', vim.log.levels.INFO) if not ok or not pretty_json then print('Error formatting metadata') return diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 51ac6200..b9decdd4 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -120,16 +120,20 @@ function M.pio_refresh(callback) --------------------------------------------------------- local _, current_checksum = vim.misc.readFile(checksum_file) if current_checksum and current_checksum ~= '' then + vim.notify('PIO:checksum 1', vim.log.levels.INFO) if current_checksum == meta.last_projectChecksum then vim.notify('PIO: Metadata synced with cache', vim.log.levels.INFO) return end -- Already updated + vim.notify('PIO:checksum 2', vim.log.levels.INFO) -- STEP 2: Cache Path (idedata.json exists and checksum changed) local _, content = vim.misc.readFile(idedata_file) if content then + vim.notify('PIO:checksum 3', vim.log.levels.INFO) local ok, decoded = pcall(vim.json.decode, content) if ok and apply_metadata(decoded, current_checksum) then + vim.notify('PIO:checksum 4', vim.log.levels.INFO) local metadata = require('platformio.metadata') metadata.save_project_config() vim.notify('PIO: Metadata synced from cache', vim.log.levels.INFO) From 719697f868111d0ccae359a257c2743550ee32e0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 08:11:07 +0300 Subject: [PATCH 1193/1406] update --- lua/platformio/pio_setup.lua | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b9decdd4..334a3f45 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -120,20 +120,16 @@ function M.pio_refresh(callback) --------------------------------------------------------- local _, current_checksum = vim.misc.readFile(checksum_file) if current_checksum and current_checksum ~= '' then - vim.notify('PIO:checksum 1', vim.log.levels.INFO) if current_checksum == meta.last_projectChecksum then vim.notify('PIO: Metadata synced with cache', vim.log.levels.INFO) return end -- Already updated - vim.notify('PIO:checksum 2', vim.log.levels.INFO) -- STEP 2: Cache Path (idedata.json exists and checksum changed) local _, content = vim.misc.readFile(idedata_file) if content then - vim.notify('PIO:checksum 3', vim.log.levels.INFO) local ok, decoded = pcall(vim.json.decode, content) if ok and apply_metadata(decoded, current_checksum) then - vim.notify('PIO:checksum 4', vim.log.levels.INFO) local metadata = require('platformio.metadata') metadata.save_project_config() vim.notify('PIO: Metadata synced from cache', vim.log.levels.INFO) @@ -282,7 +278,7 @@ function M.run_compiledb() if _G.metadata.isBusy then return end _G.metadata.isBusy = true - M.stop_watchers() -- 1. Silence watchers to prevent the loop + -- M.stop_watchers() -- 1. Silence watchers to prevent the loop vim.notify('Building DB...', vim.log.levels.INFO) vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) @@ -290,26 +286,26 @@ function M.run_compiledb() if obj.code == 0 then -- 2. PERFORM CHECKSUM ACTIONS MANUALLY local checksum_path = vim.misc.joinPath(vim.uv.cwd(), '.pio/build', 'project.checksum') - local ok, new_checksum = vim.misc.readFile(checksum_path) + -- local ok, new_checksum = vim.misc.readFile(checksum_path) if ok then - _G.metadata.last_projectChecksum = new_checksum -- Sync the state + -- _G.metadata.last_projectChecksum = new_checksum -- Sync the state -- 3. Run the refresh logic (The "Action" normally taken by the watcher) - M.pio_refresh(function() - vim.notify('DB & Cache Updated', vim.log.levels.INFO) - _G.metadata.isBusy = false - M.start_watchers() -- 4. Re-enable watchers for future changes - end) + -- M.pio_refresh(function() + -- vim.notify('DB & Cache Updated', vim.log.levels.INFO) + -- _G.metadata.isBusy = false + -- M.start_watchers() -- 4. Re-enable watchers for future changes + -- end) else -- If we can't read the checksum, something is wrong with the build output _G.metadata.isBusy = false - M.start_watchers() + -- M.start_watchers() end else vim.notify('Build Failed', vim.log.levels.ERROR) _G.metadata.isBusy = false - M.start_watchers() + -- M.start_watchers() end end) end) From e1fc141f1b5b8dcffd029274191865b2258d82df Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 08:17:35 +0300 Subject: [PATCH 1194/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 334a3f45..af84c6df 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -293,7 +293,7 @@ function M.run_compiledb() -- 3. Run the refresh logic (The "Action" normally taken by the watcher) -- M.pio_refresh(function() - -- vim.notify('DB & Cache Updated', vim.log.levels.INFO) + vim.notify('DB & Cache Updated', vim.log.levels.INFO) -- _G.metadata.isBusy = false -- M.start_watchers() -- 4. Re-enable watchers for future changes -- end) From a310d12865c7c6e7be87b870c1371f2d22a5fdde Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 08:23:12 +0300 Subject: [PATCH 1195/1406] update --- lua/platformio/pio_setup.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index af84c6df..8b94c9dc 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -288,7 +288,7 @@ function M.run_compiledb() local checksum_path = vim.misc.joinPath(vim.uv.cwd(), '.pio/build', 'project.checksum') -- local ok, new_checksum = vim.misc.readFile(checksum_path) - if ok then + -- if ok then -- _G.metadata.last_projectChecksum = new_checksum -- Sync the state -- 3. Run the refresh logic (The "Action" normally taken by the watcher) @@ -297,11 +297,11 @@ function M.run_compiledb() -- _G.metadata.isBusy = false -- M.start_watchers() -- 4. Re-enable watchers for future changes -- end) - else + -- else -- If we can't read the checksum, something is wrong with the build output _G.metadata.isBusy = false -- M.start_watchers() - end + -- end else vim.notify('Build Failed', vim.log.levels.ERROR) _G.metadata.isBusy = false From cbff88a177728e5644880212b0b29eee54b364b3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 08:35:15 +0300 Subject: [PATCH 1196/1406] update --- lua/platformio/pio_setup.lua | 90 +++++++++++++++++++++++------------- 1 file changed, 59 insertions(+), 31 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 8b94c9dc..e0fb5a33 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -272,45 +272,73 @@ local function get_hash(path) return (ok and data) and vim.fn.sha256(data) or '' end --- _G.metadata.isBusy = false --- stylua: ignore function M.run_compiledb() - if _G.metadata.isBusy then return end + if _G.metadata.isBusy then + return + end _G.metadata.isBusy = true - -- M.stop_watchers() -- 1. Silence watchers to prevent the loop - vim.notify('Building DB...', vim.log.levels.INFO) - - vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) - vim.schedule(function() - if obj.code == 0 then - -- 2. PERFORM CHECKSUM ACTIONS MANUALLY - local checksum_path = vim.misc.joinPath(vim.uv.cwd(), '.pio/build', 'project.checksum') - - -- local ok, new_checksum = vim.misc.readFile(checksum_path) - -- if ok then - -- _G.metadata.last_projectChecksum = new_checksum -- Sync the state - - -- 3. Run the refresh logic (The "Action" normally taken by the watcher) - -- M.pio_refresh(function() - vim.notify('DB & Cache Updated', vim.log.levels.INFO) - -- _G.metadata.isBusy = false - -- M.start_watchers() -- 4. Re-enable watchers for future changes - -- end) - -- else - -- If we can't read the checksum, something is wrong with the build output - _G.metadata.isBusy = false - -- M.start_watchers() - -- end - else - vim.notify('Build Failed', vim.log.levels.ERROR) + -- Use pcall to catch immediate 'command not found' errors + local ok, result = pcall(function() + return vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) + vim.schedule(function() _G.metadata.isBusy = false - -- M.start_watchers() - end + if obj.code == 0 then + vim.notify('DB Updated', vim.log.levels.INFO) + else + -- Check stderr if code is non-zero + local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Exit code ' .. obj.code + vim.notify('PIO Error: ' .. err, vim.log.levels.ERROR) + end + end) end) end) + + if not ok then + vim.notify('Failed to start PIO: ' .. tostring(result), vim.log.levels.ERROR) + _G.metadata.isBusy = false + end end + +-- _G.metadata.isBusy = false +-- stylua: ignore +-- function M.run_compiledb() +-- if _G.metadata.isBusy then return end +-- _G.metadata.isBusy = true +-- +-- M.stop_watchers() -- 1. Silence watchers to prevent the loop +-- vim.notify('Building DB...', vim.log.levels.INFO) +-- +-- vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) +-- vim.schedule(function() +-- if obj.code == 0 then +-- -- 2. PERFORM CHECKSUM ACTIONS MANUALLY +-- local checksum_path = vim.misc.joinPath(vim.uv.cwd(), '.pio/build', 'project.checksum') +-- local ok, new_checksum = vim.misc.readFile(checksum_path) +-- if ok then +-- _G.metadata.last_projectChecksum = new_checksum -- Sync the state +-- +-- -- 3. Run the refresh logic (The "Action" normally taken by the watcher) +-- M.pio_refresh(function() +-- vim.notify('DB & Cache Updated', vim.log.levels.INFO) +-- _G.metadata.isBusy = false +-- M.start_watchers() -- 4. Re-enable watchers for future changes +-- end) +-- else +-- -- If we can't read the checksum, something is wrong with the build output +-- _G.metadata.isBusy = false +-- M.start_watchers() +-- end +-- else +-- vim.notify('Build Failed', vim.log.levels.ERROR) +-- _G.metadata.isBusy = false +-- M.start_watchers() +-- end +-- end) +-- end) +-- end + -- function M.run_compiledb() -- if _G.metadata.isBusy then -- return From a07b9bfc7656325cc2c97e6fd0708e5ae96e53a4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 08:48:40 +0300 Subject: [PATCH 1197/1406] update --- lua/platformio/pio_setup.lua | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index e0fb5a33..22af4a77 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -546,14 +546,14 @@ function M.start_watchers() local new_hash = get_hash(self.path) or '' if new_hash and new_hash ~= self.current_ini_hash then self.current_ini_hash = new_hash - M.run_compiledb() -- Smart: Auto-update DB if config changes - -- local pio = require('platformio.utils.pio') - -- pio.run_sequence({ - -- cmnds = { - -- 'pio run -t compiledb', - -- }, - -- cb = pio.handlePiodb, - -- }) + -- M.run_compiledb() -- Smart: Auto-update DB if config changes + local pio = require('platformio.utils.pio') + pio.run_sequence({ + cmnds = { + 'pio run -t compiledb', + }, + cb = pio.handlePiodb, + }) end end, }, From abd52ee9e0af10ad6987a33d86da3d3eea80d01b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 09:26:36 +0300 Subject: [PATCH 1198/1406] update --- lua/platformio/pio_setup.lua | 82 +++++++++++++++++++++++++++--------- 1 file changed, 61 insertions(+), 21 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 22af4a77..a9a6ac56 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -273,10 +273,10 @@ local function get_hash(path) end function M.run_compiledb() - if _G.metadata.isBusy then - return - end - _G.metadata.isBusy = true + -- if _G.metadata.isBusy then + -- return + -- end + -- _G.metadata.isBusy = true -- Use pcall to catch immediate 'command not found' errors local ok, result = pcall(function() @@ -546,14 +546,18 @@ function M.start_watchers() local new_hash = get_hash(self.path) or '' if new_hash and new_hash ~= self.current_ini_hash then self.current_ini_hash = new_hash - -- M.run_compiledb() -- Smart: Auto-update DB if config changes - local pio = require('platformio.utils.pio') - pio.run_sequence({ - cmnds = { - 'pio run -t compiledb', - }, - cb = pio.handlePiodb, - }) + if _G.metadata.isBusy then + return + end + _G.metadata.isBusy = true + M.run_compiledb() -- Smart: Auto-update DB if config changes + -- local pio = require('platformio.utils.pio') + -- pio.run_sequence({ + -- cmnds = { + -- 'pio run -t compiledb', + -- }, + -- cb = pio.handlePiodb, + -- }) end end, }, @@ -561,6 +565,10 @@ function M.start_watchers() idedata_path = vim.misc.joinPath(project_root, '.pio/build', active_env, 'idedata.json'),--idedata.json path path = vim.misc.joinPath(project_root, '.pio/build', 'project.checksum'), --checksum_path cb = function(self) + if _G.metadata.isBusy then + return + end + _G.metadata.isBusy = true local _, current_checksum = vim.misc.readFile(self.path) if current_checksum and current_checksum ~= '' then if current_checksum == _G.metadata.last_projectChecksum then @@ -568,13 +576,13 @@ function M.start_watchers() end -- Already updated vim.notify('Checksum change', vim.log.levels.INFO, { title = 'PlatformIO' }) - _G.metadata.isBusy = false -- STEP 2: Cache Path (idedata.json exists and checksum changed) - -- M.pio_refresh(function() - -- -- local dbFix = require('platformio.utils.pio').compile_commandsFix - -- -- dbFix() - -- vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- end) + M.pio_refresh(function() + _G.metadata.isBusy = false + -- local dbFix = require('platformio.utils.pio').compile_commandsFix + -- dbFix() + vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) + end) end end, }, @@ -591,15 +599,30 @@ end -- stylua: ignore function M.stop_watchers() - -- Safety: Ensure it's a table before looping - M.watcher_handles = M.watcher_handles or {} + if type(M.watcher_handles) ~= "table" then + M.watcher_handles = {} + return + end for _, handle in ipairs(M.watcher_handles) do - if handle and not handle:is_closing() then handle:stop() end + if handle and not handle:is_closing() then + handle:stop() + handle:close() -- CRITICAL: Releases the handle so Neovim can quit fast + end end M.watcher_handles = {} end +-- function M.stop_watchers() +-- -- Safety: Ensure it's a table before looping +-- M.watcher_handles = M.watcher_handles or {} +-- +-- for _, handle in ipairs(M.watcher_handles) do +-- if handle and not handle:is_closing() then handle:stop() end +-- end +-- M.watcher_handles = {} +-- end + -- local dir_path = vim.uv.cwd() -- local ini_file = vim.misc.joinPath(dir_path, 'platformio.ini') -- -- INFO: @@ -713,4 +736,21 @@ function M.init() end end +-- Define it here so all functions in this file can access it +local debounce_timer = uv.new_timer() +-- Add this to your main pio_setup.lua +function M.cleanup() + M.stop_watchers() + if debounce_timer and not debounce_timer:is_closing() then + debounce_timer:stop() + debounce_timer:close() + end +end + +-- Force cleanup when leaving Neovim to prevent :qa lag +vim.api.nvim_create_autocmd('VimLeavePre', { + callback = function() + M.cleanup() + end, +}) return M From 2b95964ebfeaef50ac427a4e632116f7f22686e5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 09:39:34 +0300 Subject: [PATCH 1199/1406] update --- lua/platformio/pio_setup.lua | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index a9a6ac56..f394b658 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -497,13 +497,15 @@ local function watch_file(full_path, callback) if not handle then return nil end handle:start(parent_dir, {}, function(err, filename, events) -- 1. Catch REAL system errors - if err or filename ~= target_file or (_G.metadata and _G.metadata.isBusy) or (events and not (events.change or events.rename)) then - if err then + -- if err or filename ~= target_file or (_G.metadata and _G.metadata.isBusy) or (events and not (events.change or events.rename)) then + if err then -- Use vim.schedule to notify so we don't block the loop - vim.schedule(function() - vim.notify('Watcher error: ' .. tostring(err), vim.log.levels.ERROR) - end) - end + vim.schedule(function() + vim.notify('Watcher error: ' .. tostring(err), vim.log.levels.ERROR) + end) + return --handle:stop() + end + if filename ~= target_file or (_G.metadata and _G.metadata.isBusy) then return --handle:stop() end From ddc501edd839d38af395c9746fa7a64f86c9ff23 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 09:49:11 +0300 Subject: [PATCH 1200/1406] update --- lua/platformio/pio_setup.lua | 103 ++++++++++++++++++++++++----------- 1 file changed, 70 insertions(+), 33 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index f394b658..4c56af10 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -422,6 +422,8 @@ end local uv = vim.uv or vim.loop M.watcher_handles = {} +-- Define it here so all functions in this file can access it +local debounce_timer = uv.new_timer() -- Use a single, global-ish timer variable to handle debouncing across all events -- local debounce_timer = vim.uv.new_timer() @@ -489,48 +491,85 @@ M.watcher_handles = {} -- end -- stylua: ignore + +-- Ensure this is at the TOP of your file, outside any functions + local function watch_file(full_path, callback) - local handle = uv.new_fs_event() + local handle = vim.uv.new_fs_event() local parent_dir = vim.fn.fnamemodify(full_path, ':h') local target_file = vim.fn.fnamemodify(full_path, ':t') if not handle then return nil end - handle:start(parent_dir, {}, function(err, filename, events) - -- 1. Catch REAL system errors - -- if err or filename ~= target_file or (_G.metadata and _G.metadata.isBusy) or (events and not (events.change or events.rename)) then - if err then - -- Use vim.schedule to notify so we don't block the loop - vim.schedule(function() - vim.notify('Watcher error: ' .. tostring(err), vim.log.levels.ERROR) - end) - return --handle:stop() - end - if filename ~= target_file or (_G.metadata and _G.metadata.isBusy) then - return --handle:stop() - end - - -- if filename == target_file then - -- end - -- 2. SILENTLY ignore events that aren't our target file - -- Or if we are currently busy processing another task - -- if filename ~= target_file or _G.metadata.isBusy then - -- return - -- end + handle:start(parent_dir, {}, function(err, filename) + if err or filename ~= target_file or (_G.metadata and _G.metadata.isBusy) then + return + end - -- Debounce: Use vim.schedule to ensure we don't fire - -- during the middle of a file-swap operation - -- 3. Trigger the callback safely - vim.defer_fn(function() - print('file watched') - -- Re-verify file exists before calling - if vim.loop.fs_stat(full_path) then callback() end - end, 500) - -- vim.schedule(callback) + -- 1. Check if timer exists and is valid + if debounce_timer then + -- 2. STOP the existing countdown (this is the "debounce") + debounce_timer:stop() + + -- 3. START a new 500ms countdown + debounce_timer:start(500, 0, vim.schedule_wrap(function() + -- This block now ONLY runs once, 500ms after the LAST event + if vim.uv.fs_stat(full_path) then + print('File settled: ' .. target_file) + callback() + end + end)) + end end) return handle end + + + + +-- local function watch_file(full_path, callback) +-- local handle = uv.new_fs_event() +-- local parent_dir = vim.fn.fnamemodify(full_path, ':h') +-- local target_file = vim.fn.fnamemodify(full_path, ':t') +-- +-- if not handle then return nil end +-- handle:start(parent_dir, {}, function(err, filename, events) +-- -- 1. Catch REAL system errors +-- -- if err or filename ~= target_file or (_G.metadata and _G.metadata.isBusy) or (events and not (events.change or events.rename)) then +-- if err then +-- -- Use vim.schedule to notify so we don't block the loop +-- vim.schedule(function() +-- vim.notify('Watcher error: ' .. tostring(err), vim.log.levels.ERROR) +-- end) +-- return --handle:stop() +-- end +-- if filename ~= target_file or (_G.metadata and _G.metadata.isBusy) then +-- return --handle:stop() +-- end +-- +-- -- if filename == target_file then +-- -- end +-- +-- -- 2. SILENTLY ignore events that aren't our target file +-- -- Or if we are currently busy processing another task +-- -- if filename ~= target_file or _G.metadata.isBusy then +-- -- return +-- -- end +-- +-- -- Debounce: Use vim.schedule to ensure we don't fire +-- -- during the middle of a file-swap operation +-- -- 3. Trigger the callback safely +-- vim.defer_fn(function() +-- print('file watched') +-- -- Re-verify file exists before calling +-- if vim.loop.fs_stat(full_path) then callback() end +-- end, 500) +-- -- vim.schedule(callback) +-- end) +-- return handle +-- end + -- stylua: ignore function M.start_watchers() -- Clean up any existing watchers first to prevent duplicates @@ -738,8 +777,6 @@ function M.init() end end --- Define it here so all functions in this file can access it -local debounce_timer = uv.new_timer() -- Add this to your main pio_setup.lua function M.cleanup() M.stop_watchers() From f20dde6e6a5d5908f31c9a0ec724703bf073f669 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 10:07:55 +0300 Subject: [PATCH 1201/1406] update --- lua/platformio/pio_setup.lua | 82 ++++++++++++++++++++++-------------- 1 file changed, 51 insertions(+), 31 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 4c56af10..8d67904e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -273,20 +273,28 @@ local function get_hash(path) end function M.run_compiledb() - -- if _G.metadata.isBusy then - -- return - -- end - -- _G.metadata.isBusy = true + -- Use a local reference to the global table for speed/clarity + local meta = _G.metadata + if not meta then + return + end + + if meta.isBusy then + return + end + meta.isBusy = true + + vim.notify('Building Compilation DB...', vim.log.levels.INFO) - -- Use pcall to catch immediate 'command not found' errors local ok, result = pcall(function() return vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) vim.schedule(function() - _G.metadata.isBusy = false + -- 1. Reset flag IMMEDIATELY when process returns + meta.isBusy = false + if obj.code == 0 then vim.notify('DB Updated', vim.log.levels.INFO) else - -- Check stderr if code is non-zero local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Exit code ' .. obj.code vim.notify('PIO Error: ' .. err, vim.log.levels.ERROR) end @@ -296,11 +304,10 @@ function M.run_compiledb() if not ok then vim.notify('Failed to start PIO: ' .. tostring(result), vim.log.levels.ERROR) - _G.metadata.isBusy = false + meta.isBusy = false end end - -- _G.metadata.isBusy = false -- stylua: ignore -- function M.run_compiledb() @@ -587,10 +594,6 @@ function M.start_watchers() local new_hash = get_hash(self.path) or '' if new_hash and new_hash ~= self.current_ini_hash then self.current_ini_hash = new_hash - if _G.metadata.isBusy then - return - end - _G.metadata.isBusy = true M.run_compiledb() -- Smart: Auto-update DB if config changes -- local pio = require('platformio.utils.pio') -- pio.run_sequence({ @@ -605,27 +608,44 @@ function M.start_watchers() { -- watcher for ./.pio/build/projct.checksum idedata_path = vim.misc.joinPath(project_root, '.pio/build', active_env, 'idedata.json'),--idedata.json path path = vim.misc.joinPath(project_root, '.pio/build', 'project.checksum'), --checksum_path + cb = function(self) - if _G.metadata.isBusy then - return - end + if _G.metadata.isBusy then return end _G.metadata.isBusy = true - local _, current_checksum = vim.misc.readFile(self.path) - if current_checksum and current_checksum ~= '' then - if current_checksum == _G.metadata.last_projectChecksum then - return - end -- Already updated - - vim.notify('Checksum change', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- STEP 2: Cache Path (idedata.json exists and checksum changed) - M.pio_refresh(function() - _G.metadata.isBusy = false - -- local dbFix = require('platformio.utils.pio').compile_commandsFix - -- dbFix() - vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) - end) + + local ok, current_checksum = vim.misc.readFile(self.path) + + -- Check if we should exit early + if not ok or current_checksum == '' or current_checksum == _G.metadata.last_projectChecksum then + _G.metadata.isBusy = false -- CRITICAL: Unlock before returning! + return end - end, + + _G.metadata.last_projectChecksum = current_checksum -- Update the state + M.pio_refresh(function() + _G.metadata.isBusy = false -- Unlock after refresh + vim.notify('DB Updated', vim.log.levels.INFO) + end) + end + -- cb = function(self) + -- if _G.metadata.isBusy then return end + -- _G.metadata.isBusy = true + -- local _, current_checksum = vim.misc.readFile(self.path) + -- if current_checksum and current_checksum ~= '' then + -- if current_checksum == _G.metadata.last_projectChecksum then + -- return + -- end -- Already updated + -- + -- vim.notify('Checksum change', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- -- STEP 2: Cache Path (idedata.json exists and checksum changed) + -- M.pio_refresh(function() + -- _G.metadata.isBusy = false + -- -- local dbFix = require('platformio.utils.pio').compile_commandsFix + -- -- dbFix() + -- vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- end) + -- end + -- end, }, } targets[1].current_ini_hash = get_hash(targets[1].path) or '' From a2d9e631b8c1410b943510d11d95a897f53be018 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 10:17:38 +0300 Subject: [PATCH 1202/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 8d67904e..97a4e66e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -287,7 +287,7 @@ function M.run_compiledb() vim.notify('Building Compilation DB...', vim.log.levels.INFO) local ok, result = pcall(function() - return vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) + return vim.system({ 'pio', 'run', '-t', 'compiledb' }, { shell = true, timeout = 30000 }, function(obj) vim.schedule(function() -- 1. Reset flag IMMEDIATELY when process returns meta.isBusy = false From 7e56f5fa36adb9ab4b3749ef63a9836fc2f43af3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 10:23:32 +0300 Subject: [PATCH 1203/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 97a4e66e..87d6c5a8 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -287,7 +287,7 @@ function M.run_compiledb() vim.notify('Building Compilation DB...', vim.log.levels.INFO) local ok, result = pcall(function() - return vim.system({ 'pio', 'run', '-t', 'compiledb' }, { shell = true, timeout = 30000 }, function(obj) + return vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, shell = true, timeout = 30000 }, function(obj) vim.schedule(function() -- 1. Reset flag IMMEDIATELY when process returns meta.isBusy = false From 7ce1b1d8abe67d30a92f58d37ccf9b1ef3ee33ad Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 11:03:17 +0300 Subject: [PATCH 1204/1406] update --- lua/platformio/pio_setup.lua | 207 +++++++++++++++++++++++------------ 1 file changed, 134 insertions(+), 73 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 87d6c5a8..993f38ef 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -273,41 +273,80 @@ local function get_hash(path) end function M.run_compiledb() - -- Use a local reference to the global table for speed/clarity - local meta = _G.metadata - if not meta then + -- 1. Prevent overlapping builds + if _G.metadata.isBusy then return end + _G.metadata.isBusy = true - if meta.isBusy then - return - end - meta.isBusy = true + vim.notify('PIO: Building Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) - vim.notify('Building Compilation DB...', vim.log.levels.INFO) + -- 2. Run the command asynchronously + -- 'pio run -t compiledb' updates compile_commands.json + vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) + vim.schedule(function() + -- 3. Release the lock immediately when the process returns + _G.metadata.isBusy = false - local ok, result = pcall(function() - return vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, shell = true, timeout = 30000 }, function(obj) - vim.schedule(function() - -- 1. Reset flag IMMEDIATELY when process returns - meta.isBusy = false + if obj.code == 0 then + -- Optional: Sync the hash of platformio.ini so the watcher doesn't refire + -- (Assuming targets[1] is the ini watcher) + -- targets[1].last_hash = get_hash(targets[1].path) - if obj.code == 0 then - vim.notify('DB Updated', vim.log.levels.INFO) - else - local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Exit code ' .. obj.code - vim.notify('PIO Error: ' .. err, vim.log.levels.ERROR) + vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) + + -- Trigger refresh (LSP restart, etc.) + if M.pio_refresh then + M.pio_refresh(function() + -- Post-refresh logic here + end) end - end) + else + -- 4. Handle errors (missing pio, syntax error in config, etc.) + local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' + vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) + end end) end) - - if not ok then - vim.notify('Failed to start PIO: ' .. tostring(result), vim.log.levels.ERROR) - meta.isBusy = false - end end + +-- function M.run_compiledb() +-- -- Use a local reference to the global table for speed/clarity +-- local meta = _G.metadata +-- if not meta then +-- return +-- end +-- +-- if meta.isBusy then +-- return +-- end +-- meta.isBusy = true +-- +-- vim.notify('Building Compilation DB...', vim.log.levels.INFO) +-- +-- local ok, result = pcall(function() +-- return vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, shell = true, timeout = 30000 }, function(obj) +-- vim.schedule(function() +-- -- 1. Reset flag IMMEDIATELY when process returns +-- meta.isBusy = false +-- +-- if obj.code == 0 then +-- vim.notify('DB Updated', vim.log.levels.INFO) +-- else +-- local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Exit code ' .. obj.code +-- vim.notify('PIO Error: ' .. err, vim.log.levels.ERROR) +-- end +-- end) +-- end) +-- end) +-- +-- if not ok then +-- vim.notify('Failed to start PIO: ' .. tostring(result), vim.log.levels.ERROR) +-- meta.isBusy = false +-- end +-- end + -- _G.metadata.isBusy = false -- stylua: ignore -- function M.run_compiledb() @@ -502,35 +541,61 @@ local debounce_timer = uv.new_timer() -- Ensure this is at the TOP of your file, outside any functions local function watch_file(full_path, callback) - local handle = vim.uv.new_fs_event() - local parent_dir = vim.fn.fnamemodify(full_path, ':h') - local target_file = vim.fn.fnamemodify(full_path, ':t') - - if not handle then return nil end + local handle = uv.new_fs_poll() + if not handle then return end - handle:start(parent_dir, {}, function(err, filename) - if err or filename ~= target_file or (_G.metadata and _G.metadata.isBusy) then + -- Poll every 1000ms (1 second). Efficient and ignores "noise". + handle:start(full_path, 1000, function(err, stat) + if err or not stat or (_G.metadata and _G.metadata.isBusy) then return end - -- 1. Check if timer exists and is valid - if debounce_timer then - -- 2. STOP the existing countdown (this is the "debounce") - debounce_timer:stop() - - -- 3. START a new 500ms countdown - debounce_timer:start(500, 0, vim.schedule_wrap(function() - -- This block now ONLY runs once, 500ms after the LAST event - if vim.uv.fs_stat(full_path) then - print('File settled: ' .. target_file) - callback() - end - end)) - end + -- For platformio.ini, we still check the hash to be sure it actually changed + vim.schedule(callback) end) + return handle end +function M.stop_watchers() + if M.watcher_handles then + for _, h in ipairs(M.watcher_handles) do + if h and not h:is_closing() then + h:stop() + h:close() -- CRITICAL: This stops Neovim from freezing on exit + end + end + end + M.watcher_handles = {} + -- local handle = vim.uv.new_fs_event() + -- local parent_dir = vim.fn.fnamemodify(full_path, ':h') + -- local target_file = vim.fn.fnamemodify(full_path, ':t') + -- + -- if not handle then return nil end + -- + -- handle:start(parent_dir, {}, function(err, filename) + -- if err or filename ~= target_file or (_G.metadata and _G.metadata.isBusy) then + -- return + -- end + -- + -- -- 1. Check if timer exists and is valid + -- if debounce_timer then + -- -- 2. STOP the existing countdown (this is the "debounce") + -- debounce_timer:stop() + -- + -- -- 3. START a new 500ms countdown + -- debounce_timer:start(500, 0, vim.schedule_wrap(function() + -- -- This block now ONLY runs once, 500ms after the LAST event + -- if vim.uv.fs_stat(full_path) then + -- print('File settled: ' .. target_file) + -- callback() + -- end + -- end)) + -- end + -- end) + -- return handle +end + @@ -588,12 +653,13 @@ function M.start_watchers() local targets = { { -- watcher for platformio.ini - current_ini_hash = '', + name = 'ini', + last_hash = '', path = vim.misc.joinPath(project_root, 'platformio.ini'), cb = function(self) local new_hash = get_hash(self.path) or '' - if new_hash and new_hash ~= self.current_ini_hash then - self.current_ini_hash = new_hash + if new_hash and new_hash ~= self.last_hash then + self.last_hash = new_hash M.run_compiledb() -- Smart: Auto-update DB if config changes -- local pio = require('platformio.utils.pio') -- pio.run_sequence({ @@ -606,25 +672,20 @@ function M.start_watchers() end, }, { -- watcher for ./.pio/build/projct.checksum + name = 'checksum', + path = vim.misc.joinPath(project_root, '.pio', 'build', 'project.checksum'), --checksum_path idedata_path = vim.misc.joinPath(project_root, '.pio/build', active_env, 'idedata.json'),--idedata.json path - path = vim.misc.joinPath(project_root, '.pio/build', 'project.checksum'), --checksum_path - cb = function(self) - if _G.metadata.isBusy then return end - _G.metadata.isBusy = true - local ok, current_checksum = vim.misc.readFile(self.path) -- Check if we should exit early if not ok or current_checksum == '' or current_checksum == _G.metadata.last_projectChecksum then - _G.metadata.isBusy = false -- CRITICAL: Unlock before returning! return end _G.metadata.last_projectChecksum = current_checksum -- Update the state M.pio_refresh(function() - _G.metadata.isBusy = false -- Unlock after refresh - vim.notify('DB Updated', vim.log.levels.INFO) + vim.notify('PIO: Metadata synced from cache, checksum', vim.log.levels.INFO) end) end -- cb = function(self) @@ -648,31 +709,31 @@ function M.start_watchers() -- end, }, } - targets[1].current_ini_hash = get_hash(targets[1].path) or '' + -- targets[1].last_hash = get_hash(targets[1].path) or '' for _, target in ipairs(targets) do --[[ wrap the callback in a small anonymous function, so it passes the target (self) back into it.]] - local h = watch_file(target.path, function() target.cb(target) end) - table.insert(M.watcher_handles, h) + local handle = watch_file(target.path, function() target.cb(target) end) + if handle then table.insert(M.watcher_handles, handle) end end end -- stylua: ignore -function M.stop_watchers() - if type(M.watcher_handles) ~= "table" then - M.watcher_handles = {} - return - end - - for _, handle in ipairs(M.watcher_handles) do - if handle and not handle:is_closing() then - handle:stop() - handle:close() -- CRITICAL: Releases the handle so Neovim can quit fast - end - end - M.watcher_handles = {} -end +-- function M.stop_watchers() +-- if type(M.watcher_handles) ~= "table" then +-- M.watcher_handles = {} +-- return +-- end +-- +-- for _, handle in ipairs(M.watcher_handles) do +-- if handle and not handle:is_closing() then +-- handle:stop() +-- handle:close() -- CRITICAL: Releases the handle so Neovim can quit fast +-- end +-- end +-- M.watcher_handles = {} +-- end -- function M.stop_watchers() -- -- Safety: Ensure it's a table before looping From 7a8d5ec3e142b9321ff4707161f23f84a5755d37 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 11:22:00 +0300 Subject: [PATCH 1205/1406] update --- lua/platformio/pio_setup.lua | 54 +++++++++++++++++++++--------------- 1 file changed, 32 insertions(+), 22 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 993f38ef..34c09f54 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -272,6 +272,11 @@ local function get_hash(path) return (ok and data) and vim.fn.sha256(data) or '' end +local uv = vim.uv or vim.loop +M.watcher_handles = {} +-- Define it here so all functions in this file can access it +local debounce_timer = uv.new_timer() + function M.run_compiledb() -- 1. Prevent overlapping builds if _G.metadata.isBusy then @@ -283,7 +288,7 @@ function M.run_compiledb() -- 2. Run the command asynchronously -- 'pio run -t compiledb' updates compile_commands.json - vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) + vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) vim.schedule(function() -- 3. Release the lock immediately when the process returns _G.metadata.isBusy = false @@ -296,11 +301,11 @@ function M.run_compiledb() vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) -- Trigger refresh (LSP restart, etc.) - if M.pio_refresh then - M.pio_refresh(function() - -- Post-refresh logic here - end) - end + -- if M.pio_refresh then + -- M.pio_refresh(function() + -- -- Post-refresh logic here + -- end) + -- end else -- 4. Handle errors (missing pio, syntax error in config, etc.) local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' @@ -466,10 +471,6 @@ end -local uv = vim.uv or vim.loop -M.watcher_handles = {} --- Define it here so all functions in this file can access it -local debounce_timer = uv.new_timer() -- Use a single, global-ish timer variable to handle debouncing across all events -- local debounce_timer = vim.uv.new_timer() @@ -544,29 +545,38 @@ local function watch_file(full_path, callback) local handle = uv.new_fs_poll() if not handle then return end - -- Poll every 1000ms (1 second). Efficient and ignores "noise". + -- Poll every 1000ms. This is light on CPU and ignores "save noise". handle:start(full_path, 1000, function(err, stat) - if err or not stat or (_G.metadata and _G.metadata.isBusy) then - return - end - - -- For platformio.ini, we still check the hash to be sure it actually changed + if err or not stat or (_G.metadata and _G.metadata.isBusy) then return end vim.schedule(callback) end) + table.insert(M.watcher_handles, handle) return handle end function M.stop_watchers() - if M.watcher_handles then - for _, h in ipairs(M.watcher_handles) do - if h and not h:is_closing() then - h:stop() - h:close() -- CRITICAL: This stops Neovim from freezing on exit - end + if type(M.watcher_handles) ~= 'table' then + M.watcher_handles = {} + return + end + + for _, handle in ipairs(M.watcher_handles) do + if handle and not handle:is_closing() then + handle:stop() + handle:close() -- CRITICAL: This allows Neovim to quit instantly end end M.watcher_handles = {} + -- if M.watcher_handles then + -- for _, h in ipairs(M.watcher_handles) do + -- if h and not h:is_closing() then + -- h:stop() + -- h:close() -- CRITICAL: This stops Neovim from freezing on exit + -- end + -- end + -- end + -- M.watcher_handles = {} -- local handle = vim.uv.new_fs_event() -- local parent_dir = vim.fn.fnamemodify(full_path, ':h') -- local target_file = vim.fn.fnamemodify(full_path, ':t') From decdda3db309c45268c254dbd2987471c4e84378 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 11:44:33 +0300 Subject: [PATCH 1206/1406] update --- lua/platformio/pio_setup.lua | 494 ++++------------------------------- 1 file changed, 46 insertions(+), 448 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 34c09f54..8fda91ac 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -55,6 +55,7 @@ function M.get_sysroot_triplet(cc_compiler) return nil end +-- ============================================================================= -- stylua: ignore function M.pio_refresh(callback) vim.notify('PIO: Config sync ...', vim.log.levels.INFO) @@ -260,6 +261,7 @@ function M.pio_refresh(callback) fetch_config() end +-- ============================================================================= -- INFO: -- 1. Helper: Unified hashing for change detection local function get_hash(path) @@ -272,17 +274,17 @@ local function get_hash(path) return (ok and data) and vim.fn.sha256(data) or '' end -local uv = vim.uv or vim.loop -M.watcher_handles = {} --- Define it here so all functions in this file can access it -local debounce_timer = uv.new_timer() - +-- ============================================================================= +-- stylua: ignore +-- INFO: +-- 1.run_compiledb function M.run_compiledb() -- 1. Prevent overlapping builds if _G.metadata.isBusy then return end _G.metadata.isBusy = true + M.stop_watchers() vim.notify('PIO: Building Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) @@ -299,6 +301,7 @@ function M.run_compiledb() -- targets[1].last_hash = get_hash(targets[1].path) vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) + M.start_watchers() -- Trigger refresh (LSP restart, etc.) -- if M.pio_refresh then @@ -315,232 +318,46 @@ function M.run_compiledb() end) end +-- ============================================================================= +-- INFO: +-- Ensure this is at the TOP of your file, outside any functions +local uv = vim.uv or vim.loop +M.watcher_handles = {} +local debounce_timer = uv.new_timer() --- function M.run_compiledb() --- -- Use a local reference to the global table for speed/clarity --- local meta = _G.metadata --- if not meta then --- return --- end --- --- if meta.isBusy then --- return --- end --- meta.isBusy = true --- --- vim.notify('Building Compilation DB...', vim.log.levels.INFO) --- --- local ok, result = pcall(function() --- return vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, shell = true, timeout = 30000 }, function(obj) --- vim.schedule(function() --- -- 1. Reset flag IMMEDIATELY when process returns --- meta.isBusy = false --- --- if obj.code == 0 then --- vim.notify('DB Updated', vim.log.levels.INFO) --- else --- local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Exit code ' .. obj.code --- vim.notify('PIO Error: ' .. err, vim.log.levels.ERROR) --- end --- end) --- end) --- end) --- --- if not ok then --- vim.notify('Failed to start PIO: ' .. tostring(result), vim.log.levels.ERROR) --- meta.isBusy = false --- end --- end - --- _G.metadata.isBusy = false +-- ============================================================================= -- stylua: ignore --- function M.run_compiledb() --- if _G.metadata.isBusy then return end --- _G.metadata.isBusy = true --- --- M.stop_watchers() -- 1. Silence watchers to prevent the loop --- vim.notify('Building DB...', vim.log.levels.INFO) --- --- vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) --- vim.schedule(function() --- if obj.code == 0 then --- -- 2. PERFORM CHECKSUM ACTIONS MANUALLY --- local checksum_path = vim.misc.joinPath(vim.uv.cwd(), '.pio/build', 'project.checksum') --- local ok, new_checksum = vim.misc.readFile(checksum_path) --- if ok then --- _G.metadata.last_projectChecksum = new_checksum -- Sync the state --- --- -- 3. Run the refresh logic (The "Action" normally taken by the watcher) --- M.pio_refresh(function() --- vim.notify('DB & Cache Updated', vim.log.levels.INFO) --- _G.metadata.isBusy = false --- M.start_watchers() -- 4. Re-enable watchers for future changes --- end) --- else --- -- If we can't read the checksum, something is wrong with the build output --- _G.metadata.isBusy = false --- M.start_watchers() --- end --- else --- vim.notify('Build Failed', vim.log.levels.ERROR) --- _G.metadata.isBusy = false --- M.start_watchers() --- end --- end) --- end) --- end - --- function M.run_compiledb() --- if _G.metadata.isBusy then --- return --- end --- _G.metadata.isBusy = true --- --- M.stop_watchers() -- Kill watchers so they don't fire during the build --- vim.notify('Building Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) --- --- vim.system({ 'pio', 'run', '-t', 'compiledb' }, {}, function(obj) --- vim.schedule(function() --- -- 1. Check Execution --- if obj.code ~= 0 then --- _G.metadata.isBusy = false --- M.start_watchers() -- 2. RESTART after success --- local msg = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check pio logs' --- return vim.notify('PIO run_compiledb Error: ' .. msg, vim.log.levels.ERROR, { title = 'PlatformIO' }) --- end --- -- 1. Sync the checksum manually so the second watcher ignores this change --- -- local checksum_path = vim.misc.joinPath(vim.uv.cwd(), '.pio/build', 'project.checksum') --- -- local ok, new_checksum = vim.misc.readFile(checksum_path) --- -- if ok then --- _G.metadata.last_projectChecksum = new_checksum --- -- end --- --- -- 2. Refresh --- M.pio_refresh(function() --- -- local dbFix = require('platformio.utils.pio').compile_commandsFix --- -- dbFix() --- vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) --- _G.metadata.isBusy = false --- M.start_watchers() -- 2. RESTART after success --- -- pio_generate_db() --- -- lsp_restart('clangd') --- end) --- end) --- end) --- end - --- Store handles globally within the module so we can stop them +-- INFO: +-- 2.stop_watchers +function M.stop_watchers() + if type(M.watcher_handles) ~= 'table' then M.watcher_handles = {} return end --- stylua: ignore --- local timer = uv.new_timer() --- --- local function watch_file(full_path, callback) --- local handle = uv.new_fs_event() --- local target_file = vim.fn.fnamemodify(full_path, ':t') --- local parent_dir = vim.fn.fnamemodify(full_path, ':h') --- --- if not handle then --- return nil --- end --- --- handle:start(parent_dir, {}, function(err, filename) --- -- 1. Strict Filter: Only process if it's our file and we aren't already busy --- if err or filename ~= target_file or (_G.metadata and _G.metadata.isBusy) then --- return --- end --- --- -- 2. Debounce: Reset the timer on every event --- -- Only after 500ms of "silence" will the actual callback run --- if timer then --- timer:stop() --- timer:start( --- 500, --- 0, --- vim.schedule_wrap(function() --- -- 3. Final Check: Ensure file exists before running heavy logic --- local stat = uv.fs_stat(full_path) --- if stat and stat.type == 'file' then --- callback() --- end --- end) --- ) --- end --- end) --- return handle --- end - - - - --- Use a single, global-ish timer variable to handle debouncing across all events --- local debounce_timer = vim.uv.new_timer() --- --- local function watch_file(full_path, callback) --- -- 1. Nil check input parameters --- if not full_path or type(callback) ~= 'function' then --- vim.notify('watch_file: Invalid path or callback', vim.log.levels.ERROR) --- return nil --- end --- --- local handle, init_err = vim.uv.new_fs_event() --- if not handle then --- vim.notify('watch_file: Failed to create handle: ' .. tostring(init_err), vim.log.levels.ERROR) --- return nil --- end --- --- local parent_dir = vim.fn.fnamemodify(full_path, ':h') --- local target_file = vim.fn.fnamemodify(full_path, ':t') --- --- -- Start the watcher on the parent directory --- handle:start(parent_dir, {}, function(err, filename, events) --- -- 2. Robust error checking (tostring handles nil err) --- if err then --- vim.schedule(function() --- vim.notify('Watcher system error: ' .. tostring(err), vim.log.levels.ERROR) --- end) --- return --- end --- --- -- 3. Guard against nil filename and metadata --- -- Only proceed if the event is for our target file and we aren't busy --- local is_target = (filename == target_file) --- local is_busy = (_G.metadata and _G.metadata.isBusy == true) --- --- if not is_target or is_busy then --- return --- end --- --- if debounce_timer then --- -- 4. Debounce Logic with Timer Safety --- -- Stop existing timer if it's currently running (debouncing) --- if debounce_timer:is_active() then --- debounce_timer:stop() --- end --- --- -- Start/Restart the timer --- debounce_timer:start( --- 500, --- 0, --- vim.schedule_wrap(function() --- -- 5. Final existence check before execution --- -- Some editors delete/rename files during save (atomic saves) --- local stat = vim.uv.fs_stat(full_path) --- if stat and stat.type == 'file' then --- print('File settled: ' .. target_file) --- callback() --- end --- end) --- ) --- end --- end) --- --- return handle --- end + for _, handle in ipairs(M.watcher_handles) do + if handle and not handle:is_closing() then + handle:stop() + handle:close() -- CRITICAL: This allows Neovim to quit instantly + end + end + M.watcher_handles = {} +end +-- ============================================================================= -- stylua: ignore +-- INFO: +-- 3.watcher cleanup +function M.cleanup() + M.stop_watchers() + if debounce_timer and not debounce_timer:is_closing() then + debounce_timer:stop() + debounce_timer:close() + end +end --- Ensure this is at the TOP of your file, outside any functions - +-- ============================================================================= +-- stylua: ignore +-- INFO: +-- 4. watch_file +-- stylua: ignore local function watch_file(full_path, callback) local handle = uv.new_fs_poll() if not handle then return end @@ -555,104 +372,10 @@ local function watch_file(full_path, callback) return handle end -function M.stop_watchers() - if type(M.watcher_handles) ~= 'table' then - M.watcher_handles = {} - return - end - - for _, handle in ipairs(M.watcher_handles) do - if handle and not handle:is_closing() then - handle:stop() - handle:close() -- CRITICAL: This allows Neovim to quit instantly - end - end - M.watcher_handles = {} - -- if M.watcher_handles then - -- for _, h in ipairs(M.watcher_handles) do - -- if h and not h:is_closing() then - -- h:stop() - -- h:close() -- CRITICAL: This stops Neovim from freezing on exit - -- end - -- end - -- end - -- M.watcher_handles = {} - -- local handle = vim.uv.new_fs_event() - -- local parent_dir = vim.fn.fnamemodify(full_path, ':h') - -- local target_file = vim.fn.fnamemodify(full_path, ':t') - -- - -- if not handle then return nil end - -- - -- handle:start(parent_dir, {}, function(err, filename) - -- if err or filename ~= target_file or (_G.metadata and _G.metadata.isBusy) then - -- return - -- end - -- - -- -- 1. Check if timer exists and is valid - -- if debounce_timer then - -- -- 2. STOP the existing countdown (this is the "debounce") - -- debounce_timer:stop() - -- - -- -- 3. START a new 500ms countdown - -- debounce_timer:start(500, 0, vim.schedule_wrap(function() - -- -- This block now ONLY runs once, 500ms after the LAST event - -- if vim.uv.fs_stat(full_path) then - -- print('File settled: ' .. target_file) - -- callback() - -- end - -- end)) - -- end - -- end) - -- return handle -end - - - - - --- local function watch_file(full_path, callback) --- local handle = uv.new_fs_event() --- local parent_dir = vim.fn.fnamemodify(full_path, ':h') --- local target_file = vim.fn.fnamemodify(full_path, ':t') --- --- if not handle then return nil end --- handle:start(parent_dir, {}, function(err, filename, events) --- -- 1. Catch REAL system errors --- -- if err or filename ~= target_file or (_G.metadata and _G.metadata.isBusy) or (events and not (events.change or events.rename)) then --- if err then --- -- Use vim.schedule to notify so we don't block the loop --- vim.schedule(function() --- vim.notify('Watcher error: ' .. tostring(err), vim.log.levels.ERROR) --- end) --- return --handle:stop() --- end --- if filename ~= target_file or (_G.metadata and _G.metadata.isBusy) then --- return --handle:stop() --- end --- --- -- if filename == target_file then --- -- end --- --- -- 2. SILENTLY ignore events that aren't our target file --- -- Or if we are currently busy processing another task --- -- if filename ~= target_file or _G.metadata.isBusy then --- -- return --- -- end --- --- -- Debounce: Use vim.schedule to ensure we don't fire --- -- during the middle of a file-swap operation --- -- 3. Trigger the callback safely --- vim.defer_fn(function() --- print('file watched') --- -- Re-verify file exists before calling --- if vim.loop.fs_stat(full_path) then callback() end --- end, 500) --- -- vim.schedule(callback) --- end) --- return handle --- end - +-- ============================================================================= -- stylua: ignore +-- INFO: +-- 5. start_watches function M.start_watchers() -- Clean up any existing watchers first to prevent duplicates M.stop_watchers() @@ -698,25 +421,6 @@ function M.start_watchers() vim.notify('PIO: Metadata synced from cache, checksum', vim.log.levels.INFO) end) end - -- cb = function(self) - -- if _G.metadata.isBusy then return end - -- _G.metadata.isBusy = true - -- local _, current_checksum = vim.misc.readFile(self.path) - -- if current_checksum and current_checksum ~= '' then - -- if current_checksum == _G.metadata.last_projectChecksum then - -- return - -- end -- Already updated - -- - -- vim.notify('Checksum change', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- -- STEP 2: Cache Path (idedata.json exists and checksum changed) - -- M.pio_refresh(function() - -- _G.metadata.isBusy = false - -- -- local dbFix = require('platformio.utils.pio').compile_commandsFix - -- -- dbFix() - -- vim.notify('DB Updated', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- end) - -- end - -- end, }, } -- targets[1].last_hash = get_hash(targets[1].path) or '' @@ -729,105 +433,8 @@ function M.start_watchers() end end +-- ============================================================================= -- stylua: ignore --- function M.stop_watchers() --- if type(M.watcher_handles) ~= "table" then --- M.watcher_handles = {} --- return --- end --- --- for _, handle in ipairs(M.watcher_handles) do --- if handle and not handle:is_closing() then --- handle:stop() --- handle:close() -- CRITICAL: Releases the handle so Neovim can quit fast --- end --- end --- M.watcher_handles = {} --- end - --- function M.stop_watchers() --- -- Safety: Ensure it's a table before looping --- M.watcher_handles = M.watcher_handles or {} --- --- for _, handle in ipairs(M.watcher_handles) do --- if handle and not handle:is_closing() then handle:stop() end --- end --- M.watcher_handles = {} --- end - --- local dir_path = vim.uv.cwd() --- local ini_file = vim.misc.joinPath(dir_path, 'platformio.ini') --- -- INFO: --- -- 4. Simple Watcher: Only triggers if the FILE CONTENT changed --- function M.start_watcher() --- if not dir_path or vim.fn.filereadable(ini_file) == 0 then --- return --- end --- local current_ini_hash = get_hash(ini_file) --- _G.metadata.isBusy = false --- --- local handle = vim.uv.new_fs_event() --- if handle then --- handle:start( --- dir_path, --- { recursive = false }, --- vim.schedule_wrap(function(err, fname, events) --- if err or fname ~= 'platformio.ini' or _G.metadata.isBusy or not events or not (events.change or events.renamce) then --- return handle:stop() --- end --- --- if _G.metadata.isBusy then --- return --- end --- --- local new_hash = get_hash(ini_file) --- if new_hash and new_hash ~= current_ini_hash then --- current_ini_hash = new_hash --- M.run_compiledb() -- Smart: Auto-update DB if config changes --- end --- end) --- ) --- end --- end - ----------------------------------------------------------------------------------------------- --- local function start_pio_watcher() --- local dir_path = vim.uv.cwd() --- if not dir_path then return end --- --- -- Create a directory watcher --- local handle = vim.uv.new_fs_event() --- if not handle then return end --- --- -- local last_trigger = 0 --- -- Watch the directory for platformio.ini creation or changes --- handle:start( --- dir_path, --- { --- watch_entry = false, -- watch the file/dir itself --- stat = false, -- use stat to detect changes (slower but more reliable on some FS) --- recursive = false, -- watch subdirectories (if path is a directory) --- }, --- vim.schedule_wrap(function(err, filename, events) --- if err or not events or not events.change then return end --- -- Trigger only if the changed file is platformio.ini --- if filename == 'platformio.ini' and (events.change or events.rename) then --- if debounce_timer then --- debounce_timer:stop() --- debounce_timer:start( --- 500, --- 0, --- vim.schedule_wrap(function() --- pio_refresh(function() --- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) --- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --- -- boilerplate_gen([[.clangd]], vim.env.XDG_CONFIG_HOME .. '/clangd', 'config.yaml') --- pio_generate_db() --- lsp_restart('clangd') --- -- end) --- end) end)) end end end)) --- end ------------------------------------------------------------------------------------------------------- -- INFO: 6. Exported setup function function M.init() local config = require('platformio').config @@ -868,15 +475,6 @@ function M.init() end end --- Add this to your main pio_setup.lua -function M.cleanup() - M.stop_watchers() - if debounce_timer and not debounce_timer:is_closing() then - debounce_timer:stop() - debounce_timer:close() - end -end - -- Force cleanup when leaving Neovim to prevent :qa lag vim.api.nvim_create_autocmd('VimLeavePre', { callback = function() From 8b9f7bb6643129bf0ac1216482cc4de6221e8685 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 12:48:46 +0300 Subject: [PATCH 1207/1406] update --- lua/platformio/pio_setup.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 8fda91ac..30d82498 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -313,6 +313,7 @@ function M.run_compiledb() -- 4. Handle errors (missing pio, syntax error in config, etc.) local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) + M.start_watchers() end end) end) From e5186a84ccba9db0b86179374f280ca18b5af8c8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 13:06:48 +0300 Subject: [PATCH 1208/1406] update --- lua/platformio/pio_setup.lua | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 30d82498..e962485c 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -331,7 +331,7 @@ local debounce_timer = uv.new_timer() -- INFO: -- 2.stop_watchers function M.stop_watchers() - if type(M.watcher_handles) ~= 'table' then M.watcher_handles = {} return end + if not M.watcher_handles or (type(M.watcher_handles) ~= 'table') then M.watcher_handles = {} return end for _, handle in ipairs(M.watcher_handles) do if handle and not handle:is_closing() then @@ -373,6 +373,15 @@ local function watch_file(full_path, callback) return handle end +-- ============================================================================= +-- INFO: +-- 5.Force cleanup when leaving Neovim to prevent :qa lag +vim.api.nvim_create_autocmd('VimLeavePre', { + callback = function() + M.cleanup() + end, +}) + -- ============================================================================= -- stylua: ignore -- INFO: @@ -394,14 +403,14 @@ function M.start_watchers() local new_hash = get_hash(self.path) or '' if new_hash and new_hash ~= self.last_hash then self.last_hash = new_hash - M.run_compiledb() -- Smart: Auto-update DB if config changes - -- local pio = require('platformio.utils.pio') - -- pio.run_sequence({ - -- cmnds = { - -- 'pio run -t compiledb', - -- }, - -- cb = pio.handlePiodb, - -- }) + -- M.run_compiledb() -- Smart: Auto-update DB if config changes + local pio = require('platformio.utils.pio') + pio.run_sequence({ + cmnds = { + 'pio run -t compiledb', + }, + cb = pio.handlePiodb, + }) end end, }, @@ -436,7 +445,7 @@ end -- ============================================================================= -- stylua: ignore --- INFO: 6. Exported setup function +-- INFO: 7. Exported setup function function M.init() local config = require('platformio').config if config.lspClangd.enabled == true then @@ -476,10 +485,4 @@ function M.init() end end --- Force cleanup when leaving Neovim to prevent :qa lag -vim.api.nvim_create_autocmd('VimLeavePre', { - callback = function() - M.cleanup() - end, -}) return M From 62f08a23f279b387c3be700612568d94e8800135 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 13:12:29 +0300 Subject: [PATCH 1209/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index e962485c..c8a7e10b 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -388,7 +388,7 @@ vim.api.nvim_create_autocmd('VimLeavePre', { -- 5. start_watches function M.start_watchers() -- Clean up any existing watchers first to prevent duplicates - M.stop_watchers() + if next(M.watcher_handles) then M.stop_watchers() end _G.metadata.isBusy = false local project_root = vim.uv.cwd() -- Use dynamic CWD instead of hardcoded path From bb2143aee401eb346da911508f1122e4212ea9d8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 13:16:23 +0300 Subject: [PATCH 1210/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index c8a7e10b..b43e9052 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -407,7 +407,7 @@ function M.start_watchers() local pio = require('platformio.utils.pio') pio.run_sequence({ cmnds = { - 'pio run -t compiledb', + 'pio run -t build', }, cb = pio.handlePiodb, }) From 8ef9632814f3e2ea5cacad9274287a5477e820ad Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 13:20:31 +0300 Subject: [PATCH 1211/1406] update --- lua/platformio/pio_setup.lua | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b43e9052..446e17cb 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -404,13 +404,15 @@ function M.start_watchers() if new_hash and new_hash ~= self.last_hash then self.last_hash = new_hash -- M.run_compiledb() -- Smart: Auto-update DB if config changes - local pio = require('platformio.utils.pio') - pio.run_sequence({ - cmnds = { - 'pio run -t build', - }, - cb = pio.handlePiodb, - }) + vim.schedule(function() + local pio = require('platformio.utils.pio') + pio.run_sequence({ + cmnds = { + 'pio run -t build', + }, + cb = pio.handlePiodb, + }) + end) end end, }, From 9b14a1531c267e029d9843db553dd4042eaf2be0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 13:23:50 +0300 Subject: [PATCH 1212/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 446e17cb..a18f6876 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -408,7 +408,7 @@ function M.start_watchers() local pio = require('platformio.utils.pio') pio.run_sequence({ cmnds = { - 'pio run -t build', + 'pio run -t compiledb', }, cb = pio.handlePiodb, }) From 99f130c226bb54c0003ea081361b5c224b06947a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 13:27:12 +0300 Subject: [PATCH 1213/1406] update --- lua/platformio/pio_setup.lua | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index a18f6876..eca75c73 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -403,15 +403,15 @@ function M.start_watchers() local new_hash = get_hash(self.path) or '' if new_hash and new_hash ~= self.last_hash then self.last_hash = new_hash - -- M.run_compiledb() -- Smart: Auto-update DB if config changes vim.schedule(function() - local pio = require('platformio.utils.pio') - pio.run_sequence({ - cmnds = { - 'pio run -t compiledb', - }, - cb = pio.handlePiodb, - }) + M.run_compiledb() -- Smart: Auto-update DB if config changes + -- local pio = require('platformio.utils.pio') + -- pio.run_sequence({ + -- cmnds = { + -- 'pio run -t compiledb', + -- }, + -- cb = pio.handlePiodb, + -- }) end) end end, From 0b231d12e104b7a43d8831002ffc5067a372952b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 14:18:35 +0300 Subject: [PATCH 1214/1406] update --- lua/platformio/pio_setup.lua | 55 ++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 31 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index eca75c73..7f0308ec 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -59,7 +59,6 @@ end -- stylua: ignore function M.pio_refresh(callback) vim.notify('PIO: Config sync ...', vim.log.levels.INFO) - -- INFO:------------------------------------------------- -- get pio project metadata info -- stylua: ignore @@ -278,13 +277,10 @@ end -- stylua: ignore -- INFO: -- 1.run_compiledb -function M.run_compiledb() +function M.run_compiledb(target) -- 1. Prevent overlapping builds - if _G.metadata.isBusy then - return - end - _G.metadata.isBusy = true - M.stop_watchers() + if target.isBusy then return end + target.isBusy = true vim.notify('PIO: Building Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) @@ -293,7 +289,7 @@ function M.run_compiledb() vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) vim.schedule(function() -- 3. Release the lock immediately when the process returns - _G.metadata.isBusy = false + target.isBusy = false if obj.code == 0 then -- Optional: Sync the hash of platformio.ini so the watcher doesn't refire @@ -301,19 +297,15 @@ function M.run_compiledb() -- targets[1].last_hash = get_hash(targets[1].path) vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) - M.start_watchers() -- Trigger refresh (LSP restart, etc.) - -- if M.pio_refresh then - -- M.pio_refresh(function() - -- -- Post-refresh logic here - -- end) - -- end + M.pio_refresh(function() + -- Post-refresh logic here + end) else -- 4. Handle errors (missing pio, syntax error in config, etc.) local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) - M.start_watchers() end end) end) @@ -397,41 +389,42 @@ function M.start_watchers() local targets = { { -- watcher for platformio.ini name = 'ini', + isBusy = false, last_hash = '', path = vim.misc.joinPath(project_root, 'platformio.ini'), cb = function(self) + if self.isBusy then return end local new_hash = get_hash(self.path) or '' if new_hash and new_hash ~= self.last_hash then self.last_hash = new_hash vim.schedule(function() - M.run_compiledb() -- Smart: Auto-update DB if config changes - -- local pio = require('platformio.utils.pio') - -- pio.run_sequence({ - -- cmnds = { - -- 'pio run -t compiledb', - -- }, - -- cb = pio.handlePiodb, - -- }) + M.run_compiledb(self) -- Smart: Auto-update DB if config changes end) end end, }, { -- watcher for ./.pio/build/projct.checksum name = 'checksum', + isBusy = false, path = vim.misc.joinPath(project_root, '.pio', 'build', 'project.checksum'), --checksum_path - idedata_path = vim.misc.joinPath(project_root, '.pio/build', active_env, 'idedata.json'),--idedata.json path cb = function(self) + if self.isBusy then return end local ok, current_checksum = vim.misc.readFile(self.path) -- Check if we should exit early - if not ok or current_checksum == '' or current_checksum == _G.metadata.last_projectChecksum then - return - end + if ok and type(current_checksum) == 'string' and current_checksum ~= '' then + if current_checksum == _G.metadata.last_projectChecksum then + return + end - _G.metadata.last_projectChecksum = current_checksum -- Update the state - M.pio_refresh(function() - vim.notify('PIO: Metadata synced from cache, checksum', vim.log.levels.INFO) - end) + self.isBusy = true + vim.schedule(function () + M.pio_refresh(function() + self.isBusy = false + vim.notify('PIO: Metadata synced from cache, checksum', vim.log.levels.INFO) + end) + end) + end end }, } From ed7eec8eb24bfcab4a7b87d6e638156c44881af2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 14:26:02 +0300 Subject: [PATCH 1215/1406] update --- lua/platformio/pio_setup.lua | 46 ++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 7f0308ec..e80ebf42 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -286,27 +286,29 @@ function M.run_compiledb(target) -- 2. Run the command asynchronously -- 'pio run -t compiledb' updates compile_commands.json - vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) - vim.schedule(function() - -- 3. Release the lock immediately when the process returns - target.isBusy = false - - if obj.code == 0 then - -- Optional: Sync the hash of platformio.ini so the watcher doesn't refire - -- (Assuming targets[1] is the ini watcher) - -- targets[1].last_hash = get_hash(targets[1].path) - - vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) - - -- Trigger refresh (LSP restart, etc.) - M.pio_refresh(function() - -- Post-refresh logic here - end) - else - -- 4. Handle errors (missing pio, syntax error in config, etc.) - local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' - vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) - end + vim.schedule(function () + vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) + vim.schedule(function() + -- 3. Release the lock immediately when the process returns + target.isBusy = false + + if obj.code == 0 then + -- Optional: Sync the hash of platformio.ini so the watcher doesn't refire + -- (Assuming targets[1] is the ini watcher) + -- targets[1].last_hash = get_hash(targets[1].path) + + vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) + + -- Trigger refresh (LSP restart, etc.) + M.pio_refresh(function() + -- Post-refresh logic here + end) + else + -- 4. Handle errors (missing pio, syntax error in config, etc.) + local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' + vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) + end + end) end) end) end @@ -382,9 +384,7 @@ function M.start_watchers() -- Clean up any existing watchers first to prevent duplicates if next(M.watcher_handles) then M.stop_watchers() end - _G.metadata.isBusy = false local project_root = vim.uv.cwd() -- Use dynamic CWD instead of hardcoded path - local active_env = _G.metadata.active_env or 'default' local targets = { { -- watcher for platformio.ini From 5a859c3cb7a5dfe813e01b22e5726a0247102d43 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 14:52:09 +0300 Subject: [PATCH 1216/1406] update --- lua/platformio/pio_setup.lua | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index e80ebf42..3110fc0b 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -286,8 +286,8 @@ function M.run_compiledb(target) -- 2. Run the command asynchronously -- 'pio run -t compiledb' updates compile_commands.json - vim.schedule(function () - vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) + -- vim.schedule(function() + vim.system({ 'pio', 'run', '-t', 'compiledb', '--skip-project-check' }, { detach = true, text = true }, function(obj) vim.schedule(function() -- 3. Release the lock immediately when the process returns target.isBusy = false @@ -310,7 +310,7 @@ function M.run_compiledb(target) end end) end) - end) + -- end) end -- ============================================================================= @@ -353,14 +353,16 @@ end -- INFO: -- 4. watch_file -- stylua: ignore -local function watch_file(full_path, callback) +local function watch_file(full_path, callback, target) local handle = uv.new_fs_poll() if not handle then return end -- Poll every 1000ms. This is light on CPU and ignores "save noise". handle:start(full_path, 1000, function(err, stat) - if err or not stat or (_G.metadata and _G.metadata.isBusy) then return end - vim.schedule(callback) + if err or not stat or (target and target.isBusy) then return end + vim.schedule(function () + callback(target) + end) end) table.insert(M.watcher_handles, handle) @@ -433,7 +435,7 @@ function M.start_watchers() for _, target in ipairs(targets) do --[[ wrap the callback in a small anonymous function, so it passes the target (self) back into it.]] - local handle = watch_file(target.path, function() target.cb(target) end) + local handle = watch_file(target.path, function() target.cb(target) end, target) if handle then table.insert(M.watcher_handles, handle) end end end From 532641ba69faa933f42b9272f0c176d8435d9472 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 14:58:44 +0300 Subject: [PATCH 1217/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 3110fc0b..abe27ef7 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -287,7 +287,7 @@ function M.run_compiledb(target) -- 2. Run the command asynchronously -- 'pio run -t compiledb' updates compile_commands.json -- vim.schedule(function() - vim.system({ 'pio', 'run', '-t', 'compiledb', '--skip-project-check' }, { detach = true, text = true }, function(obj) + vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) vim.schedule(function() -- 3. Release the lock immediately when the process returns target.isBusy = false From 37dd1cde7237874a10b0707da0421c15708e77f0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 15:46:50 +0300 Subject: [PATCH 1218/1406] update --- lua/platformio/pio_setup.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index abe27ef7..e4efc6d9 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -286,7 +286,7 @@ function M.run_compiledb(target) -- 2. Run the command asynchronously -- 'pio run -t compiledb' updates compile_commands.json - -- vim.schedule(function() + vim.schedule(function() vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) vim.schedule(function() -- 3. Release the lock immediately when the process returns @@ -310,7 +310,7 @@ function M.run_compiledb(target) end end) end) - -- end) + end) end -- ============================================================================= From 542f639e2d3ec4d4dc8b6bc22c5990efbc701ec8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 15:50:32 +0300 Subject: [PATCH 1219/1406] update --- mini_nvimPlatformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 27624caa..d47dca75 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -253,7 +253,7 @@ local plugins = { }, opts = { filesystem = { - use_libuv_file_watcher = true, + -- use_libuv_file_watcher = true, filtered_items = { hide_dotfiles = false, hide_gitignored = true, From 79cdb9669ac85aa73e08b690071785c5b0686da7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 16:29:34 +0300 Subject: [PATCH 1220/1406] update --- lua/platformio/pio_setup.lua | 39 ++++++++++++++++++------------------ 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index e4efc6d9..19f09f0a 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -275,7 +275,7 @@ end -- ============================================================================= -- stylua: ignore --- INFO: +--INFO: -- 1.run_compiledb function M.run_compiledb(target) -- 1. Prevent overlapping builds @@ -314,7 +314,7 @@ function M.run_compiledb(target) end -- ============================================================================= --- INFO: +--INFO: -- Ensure this is at the TOP of your file, outside any functions local uv = vim.uv or vim.loop M.watcher_handles = {} @@ -322,7 +322,7 @@ local debounce_timer = uv.new_timer() -- ============================================================================= -- stylua: ignore --- INFO: +--INFO: -- 2.stop_watchers function M.stop_watchers() if not M.watcher_handles or (type(M.watcher_handles) ~= 'table') then M.watcher_handles = {} return end @@ -338,7 +338,7 @@ end -- ============================================================================= -- stylua: ignore --- INFO: +--INFO: -- 3.watcher cleanup function M.cleanup() M.stop_watchers() @@ -347,18 +347,26 @@ function M.cleanup() debounce_timer:close() end end +-- ============================================================================= +--INFO: +-- Force cleanup when leaving Neovim to prevent :qa lag +vim.api.nvim_create_autocmd('VimLeavePre', { + callback = function() + M.cleanup() + end, +}) -- ============================================================================= -- stylua: ignore --- INFO: +--INFO: -- 4. watch_file -- stylua: ignore -local function watch_file(full_path, callback, target) +local function watch_file(target, callback) local handle = uv.new_fs_poll() if not handle then return end -- Poll every 1000ms. This is light on CPU and ignores "save noise". - handle:start(full_path, 1000, function(err, stat) + handle:start(target.path, 1000, function(err, stat) if err or not stat or (target and target.isBusy) then return end vim.schedule(function () callback(target) @@ -369,18 +377,10 @@ local function watch_file(full_path, callback, target) return handle end --- ============================================================================= --- INFO: --- 5.Force cleanup when leaving Neovim to prevent :qa lag -vim.api.nvim_create_autocmd('VimLeavePre', { - callback = function() - M.cleanup() - end, -}) -- ============================================================================= -- stylua: ignore --- INFO: +--INFO: -- 5. start_watches function M.start_watchers() -- Clean up any existing watchers first to prevent duplicates @@ -435,14 +435,13 @@ function M.start_watchers() for _, target in ipairs(targets) do --[[ wrap the callback in a small anonymous function, so it passes the target (self) back into it.]] - local handle = watch_file(target.path, function() target.cb(target) end, target) - if handle then table.insert(M.watcher_handles, handle) end + watch_file(target, target.cb) end end -- ============================================================================= -- stylua: ignore --- INFO: 7. Exported setup function +--INFO: 6. Exported setup function function M.init() local config = require('platformio').config if config.lspClangd.enabled == true then @@ -464,7 +463,7 @@ function M.init() -- If the file already exists, do an initial sync if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then ---------------------------------------------------------------------------------------- - -- INFO: create clangd required files + --INFO: create clangd required files ----------------------------------------------------------------------------------------- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') From 965c8ff32ab71c41e6c62add5e4c68ef8394467c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 16:33:13 +0300 Subject: [PATCH 1221/1406] update --- mini_nvimPlatformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index d47dca75..27624caa 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -253,7 +253,7 @@ local plugins = { }, opts = { filesystem = { - -- use_libuv_file_watcher = true, + use_libuv_file_watcher = true, filtered_items = { hide_dotfiles = false, hide_gitignored = true, From 5a4f909fdf42012ec4c1f4dde3fe539ae5ff7935 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 16:37:22 +0300 Subject: [PATCH 1222/1406] update --- lua/platformio/pio_setup.lua | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 19f09f0a..44fc9d08 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -284,33 +284,25 @@ function M.run_compiledb(target) vim.notify('PIO: Building Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- 2. Run the command asynchronously - -- 'pio run -t compiledb' updates compile_commands.json - vim.schedule(function() + -- vim.schedule(function() vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) vim.schedule(function() - -- 3. Release the lock immediately when the process returns + target.isBusy = false if obj.code == 0 then - -- Optional: Sync the hash of platformio.ini so the watcher doesn't refire - -- (Assuming targets[1] is the ini watcher) - -- targets[1].last_hash = get_hash(targets[1].path) - vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- Trigger refresh (LSP restart, etc.) M.pio_refresh(function() - -- Post-refresh logic here + vim.notify('PIO: after platformio.ini Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) end) else - -- 4. Handle errors (missing pio, syntax error in config, etc.) local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) end end) end) - end) + -- end) end -- ============================================================================= From 318d634173a1bd050b59da03545a38cc3a969929 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 16:40:14 +0300 Subject: [PATCH 1223/1406] update --- mini_nvimPlatformio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 27624caa..d47dca75 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -253,7 +253,7 @@ local plugins = { }, opts = { filesystem = { - use_libuv_file_watcher = true, + -- use_libuv_file_watcher = true, filtered_items = { hide_dotfiles = false, hide_gitignored = true, From 43fb20d1d343556b50f34bec4497c771579b6275 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 16:57:29 +0300 Subject: [PATCH 1224/1406] update --- lua/platformio/pio_setup.lua | 74 ++++++++++++++++++++++++++++-------- mini_nvimPlatformio.lua | 5 ++- 2 files changed, 62 insertions(+), 17 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 44fc9d08..795ce0a9 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -317,17 +317,30 @@ local debounce_timer = uv.new_timer() --INFO: -- 2.stop_watchers function M.stop_watchers() - if not M.watcher_handles or (type(M.watcher_handles) ~= 'table') then M.watcher_handles = {} return end - - for _, handle in ipairs(M.watcher_handles) do - if handle and not handle:is_closing() then - handle:stop() - handle:close() -- CRITICAL: This allows Neovim to quit instantly + if not M.watcher_handles then return end + for _, item in ipairs(M.watcher_handles) do + if type(item.stop) == "function" then + item.stop() -- Call the stop function returned by vim._watch end end M.watcher_handles = {} end + + + +-- function M.stop_watchers() +-- if not M.watcher_handles or (type(M.watcher_handles) ~= 'table') then M.watcher_handles = {} return end +-- +-- for _, handle in ipairs(M.watcher_handles) do +-- if handle and not handle:is_closing() then +-- handle:stop() +-- handle:close() -- CRITICAL: This allows Neovim to quit instantly +-- end +-- end +-- M.watcher_handles = {} +-- end + -- ============================================================================= -- stylua: ignore --INFO: @@ -354,22 +367,51 @@ vim.api.nvim_create_autocmd('VimLeavePre', { -- 4. watch_file -- stylua: ignore local function watch_file(target, callback) - local handle = uv.new_fs_poll() - if not handle then return end - - -- Poll every 1000ms. This is light on CPU and ignores "save noise". - handle:start(target.path, 1000, function(err, stat) - if err or not stat or (target and target.isBusy) then return end - vim.schedule(function () - callback(target) + -- vim._watch is the modern, shared way to watch files in Neovim + -- It plays much better with other plugins like neo-tree + local w = require('vim._watch') + + local stop_watch = w.watch(target.path, { + debounce = 500, -- Built-in debouncing! + }, function(path, _) + -- 1. Standard guards + if not path or (target and target.isBusy) then return end + + -- 2. Schedule the callback + vim.schedule(function() + -- Double check file exists to handle neo-tree's temporary locks + if vim.uv.fs_stat(target.path) then + callback(target) + end end) end) - table.insert(M.watcher_handles, handle) - return handle + -- The return value of vim._watch.watch is a 'stop' function, + -- so we store that instead of a handle. + table.insert(M.watcher_handles, { stop = stop_watch }) + return stop_watch end + + +-- local function watch_file(target, callback) +-- local handle = uv.new_fs_poll() +-- if not handle then return end +-- +-- -- Poll every 1000ms. This is light on CPU and ignores "save noise". +-- handle:start(target.path, 1000, function(err, stat) +-- if err or not stat or (target and target.isBusy) then return end +-- vim.schedule(function () +-- callback(target) +-- end) +-- end) +-- +-- table.insert(M.watcher_handles, handle) +-- return handle +-- end + + -- ============================================================================= -- stylua: ignore --INFO: diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index d47dca75..e6fd1b87 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -253,10 +253,13 @@ local plugins = { }, opts = { filesystem = { - -- use_libuv_file_watcher = true, + use_libuv_file_watcher = true, filtered_items = { hide_dotfiles = false, hide_gitignored = true, + hide_by_name = { + '.pio', + }, never_show = { -- Add any massive folders here -- '.cache', -- '.git', From bfbdfe00cb2ee27bdaf9f3511376a8db84595ba3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 17:04:39 +0300 Subject: [PATCH 1225/1406] update --- lua/platformio/pio_setup.lua | 73 +++++++++--------------------------- 1 file changed, 17 insertions(+), 56 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 795ce0a9..7e24ea17 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -317,30 +317,17 @@ local debounce_timer = uv.new_timer() --INFO: -- 2.stop_watchers function M.stop_watchers() - if not M.watcher_handles then return end - for _, item in ipairs(M.watcher_handles) do - if type(item.stop) == "function" then - item.stop() -- Call the stop function returned by vim._watch + if not M.watcher_handles or (type(M.watcher_handles) ~= 'table') then M.watcher_handles = {} return end + + for _, handle in ipairs(M.watcher_handles) do + if handle and not handle:is_closing() then + handle:stop() + handle:close() -- CRITICAL: This allows Neovim to quit instantly end end M.watcher_handles = {} end - - - --- function M.stop_watchers() --- if not M.watcher_handles or (type(M.watcher_handles) ~= 'table') then M.watcher_handles = {} return end --- --- for _, handle in ipairs(M.watcher_handles) do --- if handle and not handle:is_closing() then --- handle:stop() --- handle:close() -- CRITICAL: This allows Neovim to quit instantly --- end --- end --- M.watcher_handles = {} --- end - -- ============================================================================= -- stylua: ignore --INFO: @@ -367,51 +354,25 @@ vim.api.nvim_create_autocmd('VimLeavePre', { -- 4. watch_file -- stylua: ignore local function watch_file(target, callback) - -- vim._watch is the modern, shared way to watch files in Neovim - -- It plays much better with other plugins like neo-tree - local w = require('vim._watch') - - local stop_watch = w.watch(target.path, { - debounce = 500, -- Built-in debouncing! - }, function(path, _) - -- 1. Standard guards - if not path or (target and target.isBusy) then return end - - -- 2. Schedule the callback - vim.schedule(function() - -- Double check file exists to handle neo-tree's temporary locks - if vim.uv.fs_stat(target.path) then + local handle = uv.new_fs_poll() + if not handle then return end + + -- Poll every 1000ms. This is light on CPU and ignores "save noise". + handle:start(target.path, 1000, function(err, stat) + if err or not stat or (target and target.isBusy) then return end + vim.schedule(function () + local current_stat = vim.uv.fs_stat(target.path) + if current_stat then callback(target) end end) end) - -- The return value of vim._watch.watch is a 'stop' function, - -- so we store that instead of a handle. - table.insert(M.watcher_handles, { stop = stop_watch }) - return stop_watch + table.insert(M.watcher_handles, handle) + return handle end - - --- local function watch_file(target, callback) --- local handle = uv.new_fs_poll() --- if not handle then return end --- --- -- Poll every 1000ms. This is light on CPU and ignores "save noise". --- handle:start(target.path, 1000, function(err, stat) --- if err or not stat or (target and target.isBusy) then return end --- vim.schedule(function () --- callback(target) --- end) --- end) --- --- table.insert(M.watcher_handles, handle) --- return handle --- end - - -- ============================================================================= -- stylua: ignore --INFO: From 7d20f6ba13c1fd6ac42404f929278b3ad4caa8de Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 17:14:59 +0300 Subject: [PATCH 1226/1406] update --- lua/platformio/pio_setup.lua | 6 ++++-- mini_nvimPlatformio.lua | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 7e24ea17..7849c983 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -293,8 +293,10 @@ function M.run_compiledb(target) if obj.code == 0 then vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) -- Trigger refresh (LSP restart, etc.) - M.pio_refresh(function() - vim.notify('PIO: after platformio.ini Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) + vim.schedule(function () + M.pio_refresh(function() + vim.notify('PIO: after platformio.ini Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) + end) end) else local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index e6fd1b87..36fddfbf 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -253,7 +253,7 @@ local plugins = { }, opts = { filesystem = { - use_libuv_file_watcher = true, + -- use_libuv_file_watcher = true, filtered_items = { hide_dotfiles = false, hide_gitignored = true, From 1aee9bda0bcc9ca3e9d62dc66924748f6eb9cbe1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 17:39:06 +0300 Subject: [PATCH 1227/1406] update --- lua/platformio/pio_setup.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 7849c983..b3aa2f47 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -293,11 +293,11 @@ function M.run_compiledb(target) if obj.code == 0 then vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) -- Trigger refresh (LSP restart, etc.) - vim.schedule(function () + -- vim.schedule(function () M.pio_refresh(function() vim.notify('PIO: after platformio.ini Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) end) - end) + -- end) else local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) From 6d2e50cc3e946d74f1bf316fe569337c8d7c9d59 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 18:07:04 +0300 Subject: [PATCH 1228/1406] update --- lua/platformio/pio_setup.lua | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b3aa2f47..06b8e812 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -118,18 +118,19 @@ function M.pio_refresh(callback) --------------------------------------------------------- -- STEP 1: Fast Checksum Check --------------------------------------------------------- - local _, current_checksum = vim.misc.readFile(checksum_file) - if current_checksum and current_checksum ~= '' then + local ok, current_checksum = vim.misc.readFile(checksum_file) + if ok and (type(current_checksum) == 'string' and current_checksum ~= '') then if current_checksum == meta.last_projectChecksum then vim.notify('PIO: Metadata synced with cache', vim.log.levels.INFO) - return + if callback then callback() end + return true end -- Already updated -- STEP 2: Cache Path (idedata.json exists and checksum changed) - local _, content = vim.misc.readFile(idedata_file) - if content then - local ok, decoded = pcall(vim.json.decode, content) - if ok and apply_metadata(decoded, current_checksum) then + local idok, content = vim.misc.readFile(idedata_file) + if idok and (type(content) == 'string' and content ~= '') then + local cok, decoded = pcall(vim.json.decode, content) + if cok and apply_metadata(decoded, current_checksum) then local metadata = require('platformio.metadata') metadata.save_project_config() vim.notify('PIO: Metadata synced from cache', vim.log.levels.INFO) @@ -169,10 +170,10 @@ function M.pio_refresh(callback) return vim.notify('PIO Metadata Error: ' .. (obj.stderr or 'Unknown'), vim.log.levels.WARN) end - local ok, raw_data = pcall(vim.json.decode, obj.stdout or '') + local ook, raw_data = pcall(vim.json.decode, obj.stdout or '') local _, data = next(raw_data or {}) - if ok and apply_metadata(data, current_checksum) then + if ook and apply_metadata(data, current_checksum) then vim.notify('PIO: Metadata synced from CLI', vim.log.levels.INFO) else vim.notify('PIO: Failed to parse metadata output', vim.log.levels.WARN) @@ -270,7 +271,7 @@ local function get_hash(path) -- local ok, data = pcall(vim.fn.readfile, path) -- readfile is safer than io.open -- return ok and vim.fn.sha256(table.concat(data, '\n')) or nil local ok, data = vim.misc.readFile(path) -- readfile is safer than io.open - return (ok and data) and vim.fn.sha256(data) or '' + return (ok and type(data) == 'string' and data ~= '') and vim.fn.sha256(data) or '' end -- ============================================================================= @@ -409,7 +410,6 @@ function M.start_watchers() cb = function(self) if self.isBusy then return end local ok, current_checksum = vim.misc.readFile(self.path) - -- Check if we should exit early if ok and type(current_checksum) == 'string' and current_checksum ~= '' then if current_checksum == _G.metadata.last_projectChecksum then From f17ea1fb84575ba62f1af7c7e815d3815c22f29c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 18:10:17 +0300 Subject: [PATCH 1229/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 06b8e812..5889463e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -111,7 +111,7 @@ function M.pio_refresh(callback) meta.last_projectChecksum = checksum pcall(M.get_sysroot_triplet, meta.cc_compiler) - if callback then callback() end + if callback then vim.schedule(callback) end return true end From 0ccf02c806c8f7cb5e24c0616b361bdc358e9323 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 18:17:12 +0300 Subject: [PATCH 1230/1406] update --- lua/platformio/pio_setup.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 5889463e..ee13d7f1 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -292,12 +292,12 @@ function M.run_compiledb(target) target.isBusy = false if obj.code == 0 then - vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) -- Trigger refresh (LSP restart, etc.) -- vim.schedule(function () - M.pio_refresh(function() + -- M.pio_refresh(function() vim.notify('PIO: after platformio.ini Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) - end) + -- end) -- end) else local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' From 98dfe4de7779c086b400aa52759d89932a399790 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 18:22:31 +0300 Subject: [PATCH 1231/1406] update --- lua/platformio/pio_setup.lua | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index ee13d7f1..78dd81a8 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -111,7 +111,7 @@ function M.pio_refresh(callback) meta.last_projectChecksum = checksum pcall(M.get_sysroot_triplet, meta.cc_compiler) - if callback then vim.schedule(callback) end + -- if callback then vim.schedule(callback) end return true end @@ -122,7 +122,8 @@ function M.pio_refresh(callback) if ok and (type(current_checksum) == 'string' and current_checksum ~= '') then if current_checksum == meta.last_projectChecksum then vim.notify('PIO: Metadata synced with cache', vim.log.levels.INFO) - if callback then callback() end + -- if callback then callback() end + if callback then vim.schedule(callback) end return true end -- Already updated @@ -134,7 +135,8 @@ function M.pio_refresh(callback) local metadata = require('platformio.metadata') metadata.save_project_config() vim.notify('PIO: Metadata synced from cache', vim.log.levels.INFO) - return + if callback then vim.schedule(callback) end + return true end end end @@ -175,6 +177,7 @@ function M.pio_refresh(callback) if ook and apply_metadata(data, current_checksum) then vim.notify('PIO: Metadata synced from CLI', vim.log.levels.INFO) + if callback then vim.schedule(callback) end else vim.notify('PIO: Failed to parse metadata output', vim.log.levels.WARN) end From 4ec7e2da7642625cd9856003c2cd5dc716ab09bc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 18:57:49 +0300 Subject: [PATCH 1232/1406] update --- lua/platformio/pio_setup.lua | 41 ++++++++++++++++++------------------ lua/platformio/utils/pio.lua | 4 ++-- 2 files changed, 23 insertions(+), 22 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 78dd81a8..0774f0e3 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -57,8 +57,9 @@ end -- ============================================================================= -- stylua: ignore -function M.pio_refresh(callback) - vim.notify('PIO: Config sync ...', vim.log.levels.INFO) +function M.pio_refresh(from, callback) + local msg = (type(from)=='string' and from ~= '') and from or 'PIO: ' + vim.notify(msg ..'Config sync ...', vim.log.levels.INFO) -- INFO:------------------------------------------------- -- get pio project metadata info -- stylua: ignore @@ -121,7 +122,7 @@ function M.pio_refresh(callback) local ok, current_checksum = vim.misc.readFile(checksum_file) if ok and (type(current_checksum) == 'string' and current_checksum ~= '') then if current_checksum == meta.last_projectChecksum then - vim.notify('PIO: Metadata synced with cache', vim.log.levels.INFO) + vim.notify(msg .. 'Metadata synced with cache', vim.log.levels.INFO) -- if callback then callback() end if callback then vim.schedule(callback) end return true @@ -134,7 +135,7 @@ function M.pio_refresh(callback) if cok and apply_metadata(decoded, current_checksum) then local metadata = require('platformio.metadata') metadata.save_project_config() - vim.notify('PIO: Metadata synced from cache', vim.log.levels.INFO) + vim.notify(msg .. 'Metadata synced from cache', vim.log.levels.INFO) if callback then vim.schedule(callback) end return true end @@ -145,13 +146,13 @@ function M.pio_refresh(callback) -- STEP 3: Auto-Initialize (If files are missing) --------------------------------------------------------- -- if not current_checksum then - -- vim.notify('PIO: Initializing project metadata...', vim.log.levels.WARN) + -- vim.notify(msg .. 'Initializing project metadata...', vim.log.levels.WARN) -- vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env }, { text = true }, function(obj) -- vim.schedule(function() -- if obj.code == 0 thenl -- fetch_metadata(attempts, active_env) -- Recursive call after files created -- else - -- vim.notify('PIO: Initialization failed. Build project manually.', vim.log.levels.ERROR) + -- vim.notify(msg .. 'Initialization failed. Build project manually.', vim.log.levels.ERROR) -- end -- end) -- end) @@ -161,7 +162,7 @@ function M.pio_refresh(callback) --------------------------------------------------------- -- STEP 4: Standard CLI Fallback (The Slow Path) --------------------------------------------------------- - vim.notify('PIO: Metadata sync ...', vim.log.levels.INFO) + vim.notify(msg .. 'Metadata sync ...', vim.log.levels.INFO) vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(obj) vim.schedule(function() if obj.code ~= 0 then @@ -169,17 +170,17 @@ function M.pio_refresh(callback) vim.defer_fn(function() fetch_metadata(attempts - 1, env) end, 500) return end - return vim.notify('PIO Metadata Error: ' .. (obj.stderr or 'Unknown'), vim.log.levels.WARN) + return vim.notify(msg .. 'Metadata Error: ' .. (obj.stderr or 'Unknown'), vim.log.levels.WARN) end local ook, raw_data = pcall(vim.json.decode, obj.stdout or '') local _, data = next(raw_data or {}) if ook and apply_metadata(data, current_checksum) then - vim.notify('PIO: Metadata synced from CLI', vim.log.levels.INFO) + vim.notify(msg .. 'Metadata synced from CLI', vim.log.levels.INFO) if callback then vim.schedule(callback) end else - vim.notify('PIO: Failed to parse metadata output', vim.log.levels.WARN) + vim.notify(msg .. 'Failed to parse metadata output', vim.log.levels.WARN) end end) end) @@ -198,14 +199,14 @@ function M.pio_refresh(callback) vim.schedule(function() -- 1. Check Execution if obj.code ~= 0 then - local msg = obj.code == 127 and "'pio' not found" or (obj.stderr or "Unknown Error") - return vim.notify("PIO Config Error: " .. msg, vim.log.levels.ERROR) + local errmsg = obj.code == 127 and "'pio' not found" or (obj.stderr or "Unknown Error") + return vim.notify(msg .. "Config Error: " .. errmsg, vim.log.levels.ERROR) end -- 2. Decode JSON safely local ok, decoded = pcall(vim.json.decode, obj.stdout or "") if not ok or type(decoded) ~= "table" then - return vim.notify("PIO: Failed to decode config JSON", vim.log.levels.ERROR) + return vim.notify(msg .. "Failed to decode config JSON", vim.log.levels.ERROR) end -- Reset core structure @@ -253,10 +254,10 @@ function M.pio_refresh(callback) -- 6. Trigger next step if meta.active_env ~= "" then - vim.notify('PIO: Config sync successful', vim.log.levels.INFO) + vim.notify(msg .. 'Config sync successful', vim.log.levels.INFO) fetch_metadata(1, meta.active_env) else - vim.notify('PIO: No [env:] found. Please add a board.', vim.log.levels.ERROR) + vim.notify(msg .. 'No [env:] found. Please add a board.', vim.log.levels.ERROR) end end) end) @@ -298,8 +299,8 @@ function M.run_compiledb(target) -- vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) -- Trigger refresh (LSP restart, etc.) -- vim.schedule(function () - -- M.pio_refresh(function() - vim.notify('PIO: after platformio.ini Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- M.pio_refresh('PIO platformio.ini change: ', function() + vim.notify('PIO platformio.ini change: after Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) -- end) -- end) else @@ -421,9 +422,9 @@ function M.start_watchers() self.isBusy = true vim.schedule(function () - M.pio_refresh(function() + M.pio_refresh('PIO checksum: ',function() self.isBusy = false - vim.notify('PIO: Metadata synced from cache, checksum', vim.log.levels.INFO) + vim.notify('PIO checksum: Metadata synced from cache, checksum', vim.log.levels.INFO) end) end) end @@ -472,7 +473,7 @@ function M.init() boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) --------------------------------------------------------------------------------- -- M.run_compiledb() -- Smart: Auto-update DB if config changes - M.pio_refresh(function() + M.pio_refresh('PIO start: ', function() -- vim.schedule(function() -- lsp_restart('clangd') -- end) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index d516088c..67418791 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -185,7 +185,7 @@ function M.handlePioinitDb(result) M.queue = {} term.stdout_callback = nil local pio_refresh = require('platformio.pio_setup').pio_refresh - pio_refresh(function() + pio_refresh('PIO init+db: ', function() vim.misc.gitignore_lsp_configs('compile_commands.json') lsp_restart('clangd') -- _G.metadata.dbTrigger = true @@ -223,7 +223,7 @@ function M.handlePioinit(result) vim.schedule(function() vim.notify('Pioinit: Done ..', vim.log.levels.INFO) local pio_refresh = require('platformio.pio_setup').pio_refresh - pio_refresh(function() + pio_refresh('PIO init: ', function() vim.misc.gitignore_lsp_configs('compile_commands.json') local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], _G.metadata.core_dir) From 9e8b1b1d793b8f6bd7a415166bede131f8203fc8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 19:24:05 +0300 Subject: [PATCH 1233/1406] update --- lua/platformio/metadata.lua | 7 +++---- lua/platformio/pio_setup.lua | 4 ++-- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index bb24c4f8..af4cda24 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -50,7 +50,7 @@ _G.metadata = setmetatable({}, { local binPath = value .. '/bin' local sep = (vim.fn.has('win32') == 1 and ';' or ':') vim.env.PATH = binPath .. sep .. vim.env.PATH - vim.notify('Env: ' .. binPath .. ' added to path', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) + vim.notify('PIO env: ' .. binPath .. ' added to path', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) -- vim.notify('Env: ' .. value, vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) -- pcall(function() -- if _pio_metadata.dbTrigger then @@ -85,7 +85,6 @@ function M.save_project_config(quiet) -- 1. Generate the formatted string directly, pretty_print already returns a string! local ok, pretty_json = pcall(vim.misc.pretty_print, _pio_metadata) - vim.notify('PIO:checksum 5', vim.log.levels.INFO) if not ok or not pretty_json then print('Error formatting metadata') return @@ -100,10 +99,10 @@ function M.save_project_config(quiet) if status then last_saved_hash = current_hash if not quiet then - vim.notify('Config synced', vim.log.levels.INFO, { title = 'PlatformIO' }) + vim.notify('PIO save config: success', vim.log.levels.INFO, { title = 'PlatformIO' }) end else - vim.notify('Write failed: ' .. (err or 'unknown error'), vim.log.levels.ERROR) + vim.notify('PIO save config: failed==> ' .. (err or 'unknown error'), vim.log.levels.ERROR) end end end diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 0774f0e3..419afdc6 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -287,7 +287,7 @@ function M.run_compiledb(target) if target.isBusy then return end target.isBusy = true - vim.notify('PIO: Building Compilation DB...', vim.log.levels.INFO, { title = 'PlatformIO' }) + vim.notify('PIO platformio.ini change: update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) -- vim.schedule(function() vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) @@ -300,7 +300,7 @@ function M.run_compiledb(target) -- Trigger refresh (LSP restart, etc.) -- vim.schedule(function () -- M.pio_refresh('PIO platformio.ini change: ', function() - vim.notify('PIO platformio.ini change: after Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) + vim.notify('PIO platformio.ini change: Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) -- end) -- end) else From 74d005eae3076819a99bd2ae379e50e8cfcc8774 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 19:31:28 +0300 Subject: [PATCH 1234/1406] update --- lua/platformio/pio_setup.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 419afdc6..4a24c3c4 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -421,12 +421,12 @@ function M.start_watchers() end self.isBusy = true - vim.schedule(function () + vim.defer_fn(function () M.pio_refresh('PIO checksum: ',function() self.isBusy = false vim.notify('PIO checksum: Metadata synced from cache, checksum', vim.log.levels.INFO) end) - end) + end, 500) end end }, @@ -446,7 +446,7 @@ end function M.init() local config = require('platformio').config if config.lspClangd.enabled == true then - vim.notify('PIO setup initialize', vim.log.levels.INFO) + vim.notify('PIO start: initialize', vim.log.levels.INFO) -- activate meta save and upload and env switch local metadata = require('platformio.metadata') From 2b4f77aa5508d5118170812edd082c38d3cd3fbc Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 19:35:06 +0300 Subject: [PATCH 1235/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 4a24c3c4..bd8f3d77 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -424,7 +424,7 @@ function M.start_watchers() vim.defer_fn(function () M.pio_refresh('PIO checksum: ',function() self.isBusy = false - vim.notify('PIO checksum: Metadata synced from cache, checksum', vim.log.levels.INFO) + vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) end) end, 500) end From 55389398a72f654e087cc3a2ee6e9b49208fcee5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 19:41:37 +0300 Subject: [PATCH 1236/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index bd8f3d77..0e684662 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -426,7 +426,7 @@ function M.start_watchers() self.isBusy = false vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) end) - end, 500) + end, 1500) end end }, From 3345b9ece51fba2c283b0228d39ac66a7618afc3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 19:50:03 +0300 Subject: [PATCH 1237/1406] update --- lua/platformio/pio_setup.lua | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 0e684662..fc37fdcd 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -286,6 +286,7 @@ function M.run_compiledb(target) -- 1. Prevent overlapping builds if target.isBusy then return end target.isBusy = true + _G.metadata.isBusy = true vim.notify('PIO platformio.ini change: update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) @@ -307,6 +308,7 @@ function M.run_compiledb(target) local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) end + _G.metadata.isBusy = false end) end) -- end) @@ -420,13 +422,15 @@ function M.start_watchers() return end - self.isBusy = true - vim.defer_fn(function () - M.pio_refresh('PIO checksum: ',function() - self.isBusy = false - vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) - end) - end, 1500) + while _G.metadata.isBusy do + self.isBusy = true + vim.defer_fn(function () + M.pio_refresh('PIO checksum: ',function() + self.isBusy = false + vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) + end) + end, 1500) + end end end }, From b7ccc0475ea9e613b79e26559bd12ab8ad427080 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 20:42:46 +0300 Subject: [PATCH 1238/1406] update --- lua/platformio/pio_setup.lua | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index fc37fdcd..b4c6d969 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -422,15 +422,30 @@ function M.start_watchers() return end - while _G.metadata.isBusy do - self.isBusy = true - vim.defer_fn(function () - M.pio_refresh('PIO checksum: ',function() - self.isBusy = false - vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) - end) - end, 1500) + local attempts = 0 + local function run_when_ready() + if _G.metadata.isBusy and attempts < 50 then -- Timeout after 5 seconds + attempts = attempts + 1 + vim.defer_fn(run_when_ready, 100) + return + end + self.isBusy = true + vim.defer_fn(function() + M.pio_refresh('PIO checksum: ', function() + self.isBusy = false + vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) + end) + end, 500) end + run_when_ready() + + -- self.isBusy = true + -- vim.defer_fn(function () + -- M.pio_refresh('PIO checksum: ',function() + -- self.isBusy = false + -- vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) + -- end) + -- end, 500) end end }, From 28fd8cd3d9036e3ab7d0706e6dd2285059ac58b7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 20:48:45 +0300 Subject: [PATCH 1239/1406] update --- lua/platformio/pio_setup.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b4c6d969..e8d57486 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -291,7 +291,8 @@ function M.run_compiledb(target) vim.notify('PIO platformio.ini change: update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) -- vim.schedule(function() - vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) + vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) + -- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) vim.schedule(function() target.isBusy = false From 04ec9281d999aacd9ee101511a58d0e8ef068d05 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Wed, 29 Apr 2026 23:11:18 +0300 Subject: [PATCH 1240/1406] update --- lua/platformio/pio_setup.lua | 61 ++++++++++++++++-------------------- 1 file changed, 27 insertions(+), 34 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index e8d57486..895a14ae 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -216,16 +216,11 @@ function M.pio_refresh(from, callback) -- 3. Parse Sections for _, section in ipairs(decoded) do local name, data = section[1], section[2] - if name == 'platformio' then - for _, kv in ipairs(data) do - meta[kv[1]] = kv[2] - end + if name == 'platformio' then for _, kv in ipairs(data) do meta[kv[1]] = kv[2] end elseif name:match('^env:') then local env_name = name:match('^env:(.+)') meta.envs[env_name] = {} - for _, kv in ipairs(data) do - meta.envs[env_name][kv[1]] = kv[2] - end + for _, kv in ipairs(data) do meta.envs[env_name][kv[1]] = kv[2] end end end @@ -242,9 +237,7 @@ function M.pio_refresh(from, callback) for _, item in ipairs(path_map) do local val = meta[item.key] -- Fallback chain - if not val or val == "" then - val = os.getenv(item.env) or (home .. item.sub) - end + if not val or val == "" then val = os.getenv(item.env) or (home .. item.sub) end -- Expand variables and Normalize if type(val) == "string" then val = val:gsub('%%${platformio.core_dir}', meta.core_dir or "") @@ -423,30 +416,30 @@ function M.start_watchers() return end - local attempts = 0 - local function run_when_ready() - if _G.metadata.isBusy and attempts < 50 then -- Timeout after 5 seconds - attempts = attempts + 1 - vim.defer_fn(run_when_ready, 100) - return - end - self.isBusy = true - vim.defer_fn(function() - M.pio_refresh('PIO checksum: ', function() - self.isBusy = false - vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) - end) - end, 500) - end - run_when_ready() - - -- self.isBusy = true - -- vim.defer_fn(function () - -- M.pio_refresh('PIO checksum: ',function() - -- self.isBusy = false - -- vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) - -- end) - -- end, 500) + -- local attempts = 0 + -- local function run_when_ready() + -- if _G.metadata.isBusy and attempts < 50 then -- Timeout after 5 seconds + -- attempts = attempts + 1 + -- vim.defer_fn(run_when_ready, 100) + -- return + -- end + -- self.isBusy = true + -- vim.defer_fn(function() + -- M.pio_refresh('PIO checksum: ', function() + -- self.isBusy = false + -- vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) + -- end) + -- end, 500) + -- end + -- run_when_ready() + + self.isBusy = true + vim.defer_fn(function () + M.pio_refresh('PIO checksum: ',function() + self.isBusy = false + vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) + end) + end, 500) end end }, From 16494e89a1a8716e1b3853f0436d90815d4e6cba Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 07:37:07 +0300 Subject: [PATCH 1241/1406] update --- lua/platformio/pio_setup.lua | 52 +++++++++++++++++++++-------------- lua/platformio/utils/misc.lua | 42 ++++++++++++++++++++++++++++ lua/platformio/utils/pio.lua | 3 +- 3 files changed, 75 insertions(+), 22 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 895a14ae..7258c56a 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -283,28 +283,38 @@ function M.run_compiledb(target) vim.notify('PIO platformio.ini change: update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- vim.schedule(function() - vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) - -- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) - vim.schedule(function() - - target.isBusy = false + local pio = require('platformio.utils.pio') + pio.run_sequence({ + cmnds = { + 'pio run -t compiledb' .. ' env=' .. vim.misc.get_active__env(), + }, + cb = function (result) + pio.handlePioinit(target, result) + end + }) - if obj.code == 0 then - -- vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- Trigger refresh (LSP restart, etc.) - -- vim.schedule(function () - -- M.pio_refresh('PIO platformio.ini change: ', function() - vim.notify('PIO platformio.ini change: Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- end) - -- end) - else - local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' - vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) - end - _G.metadata.isBusy = false - end) - end) + -- vim.schedule(function() + -- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) + -- -- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) + -- vim.schedule(function() + -- + -- target.isBusy = false + -- + -- if obj.code == 0 then + -- -- vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- -- Trigger refresh (LSP restart, etc.) + -- -- vim.schedule(function () + -- -- M.pio_refresh('PIO platformio.ini change: ', function() + -- vim.notify('PIO platformio.ini change: Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- -- end) + -- -- end) + -- else + -- local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' + -- vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) + -- end + -- _G.metadata.isBusy = false + -- end) + -- end) -- end) end diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 7a3f136f..e9158475 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -8,6 +8,48 @@ M.devNul = M.is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' +------------------------------------------------------ +--INFO: +-- stylua: ignore +-- Fast environment detection (no external calls) +function M.get_active__env() + local default_env, first_env + local in_platformio_block = false + local path = '' + + for _, dir in ipairs({ vim.api.nvim_buf_get_name(0):match('(.*[/\\])'), (vim.uv.cwd() .. '/') }) do + local tmp = dir .. 'platformio.ini' + if vim.uv.fs_stat(tmp) then path = vim.fs.normalize(tmp) end + end + if path == '' then return vim.notify('PIO: platformio.ini not found or no [env] defined.', vim.log.levels.ERROR) end + + local ok, content = vim.misc.readFile(path) + if not ok or not content then return vim.notify('PIO: platformio.ini not found in ' .. path, vim.log.levels.WARN) end + + for line in vim.gsplit(content, '\n') do + -- Detect the section headers [section] + local section = line:match('^%s*%[(.+)%]%s*$') + if section then + in_platformio_block = (section == 'platformio') + -- Capture the first env name seen + local env_name = section:match('^env:(.+)') + if env_name and not first_env then first_env = env_name end + end + + -- If inside [platformio], look for default_envs + if in_platformio_block then + local def = line:match('^%s*default_envs%s*=%s*([^%s,]+)') + if def then + default_env = def + if first_env then break end + end + end + end + + return default_env or first_env +end + +------------------------------------------------------ --INFO: -- Version-Safe Path Joining (Fallback for Neovim < 0.10.0) -- stylua: ignore diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 67418791..497390f5 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -250,10 +250,11 @@ function M.handlePiolib(result) _G.metadata.isBusy = false end -function M.handlePiodb(result) +function M.handlePiodb(target, result) if result == 'INIT' then term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'DONE' then -- result of the only and the last command + target.isBusy = false vim.notify('Piodb: Success', vim.log.levels.INFO) elseif result == 'FAIL' then end From e8fd6f979d01a6c87b43ba358cd19e6f51320646 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 07:39:44 +0300 Subject: [PATCH 1242/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 7258c56a..b183956b 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -289,7 +289,7 @@ function M.run_compiledb(target) 'pio run -t compiledb' .. ' env=' .. vim.misc.get_active__env(), }, cb = function (result) - pio.handlePioinit(target, result) + pio.handlePiodb(target, result) end }) From 3cdb06f0ae2769e728dd096204bdc9f9fbfe12b2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 07:43:39 +0300 Subject: [PATCH 1243/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b183956b..05be9329 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -286,7 +286,7 @@ function M.run_compiledb(target) local pio = require('platformio.utils.pio') pio.run_sequence({ cmnds = { - 'pio run -t compiledb' .. ' env=' .. vim.misc.get_active__env(), + 'pio run -t compiledb -e ' .. vim.misc.get_active__env(), }, cb = function (result) pio.handlePiodb(target, result) From f23aa374d5d2d0529ed5d4b72df069c1a9d78dd6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 07:52:15 +0300 Subject: [PATCH 1244/1406] update --- lua/platformio/utils/pio.lua | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 497390f5..c52658e7 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -195,6 +195,9 @@ function M.handlePioinitDb(result) -- end end) end) + M.queue = {} + term.stdout_callback = nil + _G.metadata.isBusy = false elseif result == 'FAIL' then M.queue = {} term.stdout_callback = nil @@ -229,11 +232,14 @@ function M.handlePioinit(result) boilerplate_gen([[.clangd]], _G.metadata.core_dir) end) end) + M.queue = {} + term.stdout_callback = nil + _G.metadata.isBusy = false elseif result == 'FAIL' then + M.queue = {} + term.stdout_callback = nil + _G.metadata.isBusy = false end - M.queue = {} - term.stdout_callback = nil - _G.metadata.isBusy = false end ------------------------------------------------------ @@ -243,24 +249,31 @@ function M.handlePiolib(result) term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'DONE' then -- result of the only and the last command vim.notify('Piolib: Success', vim.log.levels.INFO) + M.queue = {} + term.stdout_callback = nil + _G.metadata.isBusy = false elseif result == 'FAIL' then + M.queue = {} + term.stdout_callback = nil + _G.metadata.isBusy = false end - M.queue = {} - term.stdout_callback = nil - _G.metadata.isBusy = false end function M.handlePiodb(target, result) if result == 'INIT' then term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'DONE' then -- result of the only and the last command - target.isBusy = false vim.notify('Piodb: Success', vim.log.levels.INFO) + target.isBusy = false + M.queue = {} + term.stdout_callback = nil + _G.metadata.isBusy = false elseif result == 'FAIL' then + target.isBusy = false + M.queue = {} + term.stdout_callback = nil + _G.metadata.isBusy = false end - M.queue = {} - term.stdout_callback = nil - _G.metadata.isBusy = false end return M From 3d86208f0d318e68d0312b6abb1f840877e40287 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 07:59:59 +0300 Subject: [PATCH 1245/1406] update --- lua/platformio/pio_setup.lua | 59 ++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 30 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 05be9329..e8fcd097 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -283,38 +283,37 @@ function M.run_compiledb(target) vim.notify('PIO platformio.ini change: update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) - local pio = require('platformio.utils.pio') - pio.run_sequence({ - cmnds = { - 'pio run -t compiledb -e ' .. vim.misc.get_active__env(), - }, - cb = function (result) - pio.handlePiodb(target, result) - end - }) + -- local pio = require('platformio.utils.pio') + -- pio.run_sequence({ + -- cmnds = { + -- 'pio run -t compiledb -e ' .. vim.misc.get_active__env(), + -- }, + -- cb = function (result) + -- pio.handlePiodb(target, result) + -- end + -- }) -- vim.schedule(function() - -- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { text = true }, function(obj) - -- -- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) - -- vim.schedule(function() - -- - -- target.isBusy = false - -- - -- if obj.code == 0 then - -- -- vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- -- Trigger refresh (LSP restart, etc.) - -- -- vim.schedule(function () - -- -- M.pio_refresh('PIO platformio.ini change: ', function() - -- vim.notify('PIO platformio.ini change: Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- -- end) - -- -- end) - -- else - -- local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' - -- vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) - -- end - -- _G.metadata.isBusy = false - -- end) - -- end) + vim.system({ 'pio', 'run', '-t', 'compiledb -s -e ' .. vim.misc.get_active__env() }, { text = true }, function(obj) + -- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) + vim.schedule(function() + target.isBusy = false + + if obj.code == 0 then + -- vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- Trigger refresh (LSP restart, etc.) + -- vim.schedule(function () + -- M.pio_refresh('PIO platformio.ini change: ', function() + vim.notify('PIO platformio.ini change: Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- end) + -- end) + else + local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' + vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) + end + _G.metadata.isBusy = false + end) + end) -- end) end From 5a3a997882bd598b687e57743012d886893d24fb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 08:04:30 +0300 Subject: [PATCH 1246/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index e8fcd097..4ce748d2 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -294,7 +294,7 @@ function M.run_compiledb(target) -- }) -- vim.schedule(function() - vim.system({ 'pio', 'run', '-t', 'compiledb -s -e ' .. vim.misc.get_active__env() }, { text = true }, function(obj) + vim.system({ 'pio', 'run', '-t', 'compiledb', '-s', '-e', vim.misc.get_active__env() }, { text = true }, function(obj) -- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) vim.schedule(function() target.isBusy = false From 0e2caaa17fd94c5b6d5a57de4d854a1d1fed88af Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 13:27:57 +0300 Subject: [PATCH 1247/1406] update --- lua/platformio/pio_setup.lua | 4 ++++ lua/platformio/utils/misc.lua | 17 +++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 4ce748d2..f2e7edda 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -209,6 +209,10 @@ function M.pio_refresh(from, callback) return vim.notify(msg .. "Failed to decode config JSON", vim.log.levels.ERROR) end + local formated = vim.misc.jsonFormat(decoded) + local file = vim.uv.cwd() .. 'config.json' + vim.mis.writeFile(file, formated, {}) + -- Reset core structure meta.envs = {} meta.default_envs = {} diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index e9158475..f4636a21 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -8,6 +8,23 @@ M.devNul = M.is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' +------------------------------------------------------ +--INFO: +--- stylua: ignore +function M.delete_file(path) + local file = vim.fn.fnamemodify(path, ':p') + if vim.fn.filereadable(path) == 1 then + local success = vim.fn.delete(path) + + if success == 0 then + vim.notify('PlatformIO: ' .. file .. ' file removed', vim.log.levels.INFO) + else + vim.notify('PlatformIO: Failed to delete ' .. file, vim.log.levels.ERROR) + end + else + vim.notify('PlatformIO: ' .. file .. ' file not found', vim.log.levels.WARN) + end +end ------------------------------------------------------ --INFO: -- stylua: ignore From fd59bfcd14cbc157e2c5c15cff078b5ddea1fe91 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 13:29:37 +0300 Subject: [PATCH 1248/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index f2e7edda..ba48d447 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -211,7 +211,7 @@ function M.pio_refresh(from, callback) local formated = vim.misc.jsonFormat(decoded) local file = vim.uv.cwd() .. 'config.json' - vim.mis.writeFile(file, formated, {}) + vim.misc.writeFile(file, formated, {}) -- Reset core structure meta.envs = {} From a58808845505071d13261ece6f4547fb2fe15b9a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 13:39:05 +0300 Subject: [PATCH 1249/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index ba48d447..5804dc1e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -210,7 +210,7 @@ function M.pio_refresh(from, callback) end local formated = vim.misc.jsonFormat(decoded) - local file = vim.uv.cwd() .. 'config.json' + local file = vim.misc.joinPath(vim.uv.cwd(), 'config.json') vim.misc.writeFile(file, formated, {}) -- Reset core structure From 479a09a39c82d631a8a5305bb20577a47e0fe92c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 14:10:00 +0300 Subject: [PATCH 1250/1406] update --- lua/platformio/pio_setup.lua | 20 ++++++++++++++------ lua/platformio/utils/misc.lua | 2 +- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 5804dc1e..c5a88729 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -376,12 +376,20 @@ local function watch_file(target, callback) -- Poll every 1000ms. This is light on CPU and ignores "save noise". handle:start(target.path, 1000, function(err, stat) if err or not stat or (target and target.isBusy) then return end - vim.schedule(function () - local current_stat = vim.uv.fs_stat(target.path) - if current_stat then - callback(target) - end - end) + + -- vim.schedule(function () + -- if vim.loop.fs_stat(target.path) then callback(target) end + -- end) + + if debounce_timer then + -- Stop any existing timer to "debounce" + debounce_timer:stop() + debounce_timer:start(500, 0, vim.schedule_wrap(function() + vim.schedule(function () + if vim.loop.fs_stat(target.path) then callback(target) end + end) + end)) + end end) table.insert(M.watcher_handles, handle) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index f4636a21..7e961f89 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -12,7 +12,7 @@ M.devNul = M.is_windows and ' 2>./nul' or ' 2>/dev/null' --INFO: --- stylua: ignore function M.delete_file(path) - local file = vim.fn.fnamemodify(path, ':p') + local file = vim.fn.fnamemodify(path, ':t') if vim.fn.filereadable(path) == 1 then local success = vim.fn.delete(path) From f0d01037d7ef72bf34e7258f699658757795d9ea Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 14:13:10 +0300 Subject: [PATCH 1251/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index c5a88729..e9b0bb36 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -384,7 +384,7 @@ local function watch_file(target, callback) if debounce_timer then -- Stop any existing timer to "debounce" debounce_timer:stop() - debounce_timer:start(500, 0, vim.schedule_wrap(function() + debounce_timer:start(1500, 0, vim.schedule_wrap(function() vim.schedule(function () if vim.loop.fs_stat(target.path) then callback(target) end end) From a7ad3b909c966d447a795c665c29a3fd05bca411 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 14:52:54 +0300 Subject: [PATCH 1252/1406] update --- lua/platformio/pio_setup.lua | 27 +++++++++++++++------------ lua/platformio/utils/misc.lua | 2 +- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index e9b0bb36..c3e99ca9 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -373,21 +373,24 @@ local function watch_file(target, callback) local handle = uv.new_fs_poll() if not handle then return end - -- Poll every 1000ms. This is light on CPU and ignores "save noise". - handle:start(target.path, 1000, function(err, stat) - if err or not stat or (target and target.isBusy) then return end - - -- vim.schedule(function () - -- if vim.loop.fs_stat(target.path) then callback(target) end - -- end) + -- Poll every 1500ms. This is light on CPU and ignores "save noise". + handle:start(target.path, 1500, function(err, stat) + -- if err or not stat or (target and target.isBusy) then return end + if err or not stat then return end + -- 2. Debounce: Reset the timer on every event + -- Only after 500ms of "silence" will the actual callback run if debounce_timer then -- Stop any existing timer to "debounce" - debounce_timer:stop() - debounce_timer:start(1500, 0, vim.schedule_wrap(function() - vim.schedule(function () - if vim.loop.fs_stat(target.path) then callback(target) end - end) + if debounce_timer:is_active() then debounce_timer:stop() end + debounce_timer:start(1000, 0, vim.schedule_wrap(function() + -- vim.schedule(function () + local filestat = uv.fs_stat(target.path) + if filestat and filestat.type == 'file' then + callback(target) + end + -- if vim.loop.fs_stat(target.path) then callback(target) end + -- end) end)) end end) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 7e961f89..f33c8cea 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -30,7 +30,7 @@ end -- stylua: ignore -- Fast environment detection (no external calls) function M.get_active__env() - local default_env, first_env + local default_env, first_env = '', '' local in_platformio_block = false local path = '' From 8870d3e2a10fbf5290d39743dbf5856206bcf366 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 15:11:02 +0300 Subject: [PATCH 1253/1406] update --- lua/platformio/pio_setup.lua | 131 +++++++++++++++++++++++++++++++---- 1 file changed, 116 insertions(+), 15 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index c3e99ca9..84b2e906 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -4,6 +4,85 @@ M = {} local boilerplate = require('platformio.boilerplate') local boilerplate_gen = boilerplate.boilerplate_gen +function M.fetch_config(from) + local msg = (type(from) == 'string' and from ~= '') and from or 'PIO: ' + local meta = _G.metadata + local home = (os.getenv('HOME') or os.getenv('USERPROFILE') or ''):gsub('[\\/]+$', '') + + vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) + vim.schedule(function() + -- 1. Check Execution + if obj.code ~= 0 then + local errmsg = obj.code == 127 and "'pio' not found" or (obj.stderr or 'Unknown Error') + return vim.notify(msg .. 'Config Error: ' .. errmsg, vim.log.levels.ERROR) + end + + -- 2. Decode JSON safely + local ok, decoded = pcall(vim.json.decode, obj.stdout or '') + if not ok or type(decoded) ~= 'table' then + return vim.notify(msg .. 'Failed to decode config JSON', vim.log.levels.ERROR) + end + + local formated = vim.misc.jsonFormat(decoded) + local file = vim.misc.joinPath(vim.uv.cwd(), 'config.json') + vim.misc.writeFile(file, formated, {}) + + -- Reset core structure + meta.envs = {} + meta.default_envs = {} + + -- 3. Parse Sections + for _, section in ipairs(decoded) do + local name, data = section[1], section[2] + if name == 'platformio' then + for _, kv in ipairs(data) do + meta[kv[1]] = kv[2] + end + elseif name:match('^env:') then + local env_name = name:match('^env:(.+)') + meta.envs[env_name] = {} + for _, kv in ipairs(data) do + meta.envs[env_name][kv[1]] = kv[2] + end + end + end + + -- 4. Assign active_env + meta.active_env = meta.default_envs[1] or next(meta.envs) or '' + + -- 5. Resolve Paths (INI -> Env -> Default) + local path_map = { + { key = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, + { key = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, + { key = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, + } + + for _, item in ipairs(path_map) do + local val = meta[item.key] + -- Fallback chain + if not val or val == '' then + val = os.getenv(item.env) or (home .. item.sub) + end + -- Expand variables and Normalize + if type(val) == 'string' then + val = val:gsub('%%${platformio.core_dir}', meta.core_dir or '') + meta[item.key] = vim.misc.normalizePath(val) + end + end + + -- 6. Trigger next step + if meta.active_env ~= '' then + vim.notify(msg .. 'Config sync successful', vim.log.levels.INFO) + return meta.active_env + else + vim.notify(msg .. 'No [env:] found. Please add a board.', vim.log.levels.ERROR) + end + end) + end) +end + + + -- local debounce_timer = vim.uv.new_timer() -- INFO: -- ============================================================================= @@ -373,27 +452,49 @@ local function watch_file(target, callback) local handle = uv.new_fs_poll() if not handle then return end - -- Poll every 1500ms. This is light on CPU and ignores "save noise". handle:start(target.path, 1500, function(err, stat) - -- if err or not stat or (target and target.isBusy) then return end if err or not stat then return end - -- 2. Debounce: Reset the timer on every event - -- Only after 500ms of "silence" will the actual callback run if debounce_timer then - -- Stop any existing timer to "debounce" - if debounce_timer:is_active() then debounce_timer:stop() end - debounce_timer:start(1000, 0, vim.schedule_wrap(function() - -- vim.schedule(function () - local filestat = uv.fs_stat(target.path) - if filestat and filestat.type == 'file' then - callback(target) - end - -- if vim.loop.fs_stat(target.path) then callback(target) end - -- end) - end)) + debounce_timer:stop() + -- Define the logic in a local variable so it can "call itself" for retries + local function attempt_callback() + if target.isBusy then + -- Retry in 1000ms if still busy + debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) + return + end + + local filestat = uv.fs_stat(target.path) + if filestat and filestat.type == 'file' then + callback(target) + end + end + -- Initial start + debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) end end) + -- Poll every 1000ms. This is light on CPU and ignores "save noise". + -- handle:start(target.path, 1000, function(err, stat) + -- -- if err or not stat or (target and target.isBusy) then return end + -- if err or not stat then return end + -- + -- -- 2. Debounce: Reset the timer on every event + -- -- Only after 500ms of "silence" will the actual callback run + -- if debounce_timer then + -- -- Stop any existing timer to "debounce" + -- if debounce_timer:is_active() then debounce_timer:stop() end + -- debounce_timer:start(500, 0, vim.schedule_wrap(function() + -- -- vim.schedule(function () + -- local filestat = uv.fs_stat(target.path) + -- if filestat and filestat.type == 'file' then + -- callback(target) + -- end + -- -- if vim.loop.fs_stat(target.path) then callback(target) end + -- -- end) + -- end)) + -- end + -- end) table.insert(M.watcher_handles, handle) return handle From 602f2808e31c13984e214e12f5ece3e5e7e33580 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 15:22:48 +0300 Subject: [PATCH 1254/1406] update --- lua/platformio/pio_setup.lua | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 84b2e906..ee1357d2 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -452,7 +452,7 @@ local function watch_file(target, callback) local handle = uv.new_fs_poll() if not handle then return end - handle:start(target.path, 1500, function(err, stat) + handle:start(target.path, 1000, function(err, stat) if err or not stat then return end if debounce_timer then @@ -461,17 +461,15 @@ local function watch_file(target, callback) local function attempt_callback() if target.isBusy then -- Retry in 1000ms if still busy - debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) + debounce_timer:start(1500, 0, vim.schedule_wrap(attempt_callback)) return end local filestat = uv.fs_stat(target.path) - if filestat and filestat.type == 'file' then - callback(target) - end + if filestat and filestat.type == 'file' then callback(target) end end -- Initial start - debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) + debounce_timer:start(1500, 0, vim.schedule_wrap(attempt_callback)) end end) -- Poll every 1000ms. This is light on CPU and ignores "save noise". From fa02a3160ce103a301c956e08316925d15b247df Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 15:48:19 +0300 Subject: [PATCH 1255/1406] update --- lua/platformio/boilerplate.lua | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 2cac8fa8..5a1d386e 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -40,6 +40,7 @@ default_envs = ;-------------------------------------------------------------------------- [env] +framework = arduino upload_speed = 115200 monitor_speed = 9600 @@ -52,6 +53,10 @@ extra_scripts = lib_ldf_mode = chain ;Library dependencies Finder ldf +[env:seeed_xiao_esp32c3] +platform = espressif32 +board = seeed_xiao_esp32c3 + ]], content = function(self) -- local pio = require('platformio.utils.pio') From 11d2ef804ed0aba63b2007b0a7ab6b8dc867863f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 16:01:35 +0300 Subject: [PATCH 1256/1406] update --- lua/platformio/pio_setup.lua | 45 +++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index ee1357d2..572bb3c5 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -376,28 +376,31 @@ function M.run_compiledb(target) -- end -- }) - -- vim.schedule(function() - vim.system({ 'pio', 'run', '-t', 'compiledb', '-s', '-e', vim.misc.get_active__env() }, { text = true }, function(obj) - -- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) - vim.schedule(function() - target.isBusy = false - - if obj.code == 0 then - -- vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- Trigger refresh (LSP restart, etc.) - -- vim.schedule(function () - -- M.pio_refresh('PIO platformio.ini change: ', function() - vim.notify('PIO platformio.ini change: Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- end) - -- end) - else - local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' - vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) - end - _G.metadata.isBusy = false + local env = vim.misc.get_active__env() + if env and env ~= '' then + -- vim.schedule(function() + vim.system({ 'pio', 'run', '-t', 'compiledb', '-s', '-e', env }, { text = true }, function(obj) + -- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) + vim.schedule(function() + target.isBusy = false + + if obj.code == 0 then + -- vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- Trigger refresh (LSP restart, etc.) + -- vim.schedule(function () + -- M.pio_refresh('PIO platformio.ini change: ', function() + vim.notify('PIO platformio.ini change: Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) + -- end) + -- end) + else + local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' + vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) + end + _G.metadata.isBusy = false + end) end) - end) - -- end) + -- end) + end end -- ============================================================================= From 87e482c9e039c396d70a2caf37d9c63bb5f8efa1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 16:08:23 +0300 Subject: [PATCH 1257/1406] update --- lua/platformio/pio_setup.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 572bb3c5..8ce0a48a 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -364,7 +364,6 @@ function M.run_compiledb(target) target.isBusy = true _G.metadata.isBusy = true - vim.notify('PIO platformio.ini change: update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) -- local pio = require('platformio.utils.pio') -- pio.run_sequence({ @@ -377,7 +376,8 @@ function M.run_compiledb(target) -- }) local env = vim.misc.get_active__env() - if env and env ~= '' then + -- if env and env ~= '' then + vim.notify('PIO platformio.ini change: update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) -- vim.schedule(function() vim.system({ 'pio', 'run', '-t', 'compiledb', '-s', '-e', env }, { text = true }, function(obj) -- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) @@ -400,7 +400,7 @@ function M.run_compiledb(target) end) end) -- end) - end + -- end end -- ============================================================================= From 2b9891e2ec03f3db279b0e432d442eaece60de0d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 16:26:17 +0300 Subject: [PATCH 1258/1406] update --- lua/platformio/pio_setup.lua | 71 ++++++++++++++++++----------------- lua/platformio/utils/misc.lua | 6 ++- 2 files changed, 41 insertions(+), 36 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 8ce0a48a..b9a56136 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -455,48 +455,49 @@ local function watch_file(target, callback) local handle = uv.new_fs_poll() if not handle then return end - handle:start(target.path, 1000, function(err, stat) - if err or not stat then return end - - if debounce_timer then - debounce_timer:stop() - -- Define the logic in a local variable so it can "call itself" for retries - local function attempt_callback() - if target.isBusy then - -- Retry in 1000ms if still busy - debounce_timer:start(1500, 0, vim.schedule_wrap(attempt_callback)) - return - end - - local filestat = uv.fs_stat(target.path) - if filestat and filestat.type == 'file' then callback(target) end - end - -- Initial start - debounce_timer:start(1500, 0, vim.schedule_wrap(attempt_callback)) - end - end) - -- Poll every 1000ms. This is light on CPU and ignores "save noise". -- handle:start(target.path, 1000, function(err, stat) - -- -- if err or not stat or (target and target.isBusy) then return end -- if err or not stat then return end -- - -- -- 2. Debounce: Reset the timer on every event - -- -- Only after 500ms of "silence" will the actual callback run -- if debounce_timer then - -- -- Stop any existing timer to "debounce" - -- if debounce_timer:is_active() then debounce_timer:stop() end - -- debounce_timer:start(500, 0, vim.schedule_wrap(function() - -- -- vim.schedule(function () - -- local filestat = uv.fs_stat(target.path) - -- if filestat and filestat.type == 'file' then - -- callback(target) - -- end - -- -- if vim.loop.fs_stat(target.path) then callback(target) end - -- -- end) - -- end)) + -- debounce_timer:stop() + -- -- Define the logic in a local variable so it can "call itself" for retries + -- local function attempt_callback() + -- if target.isBusy then + -- -- Retry in 1000ms if still busy + -- debounce_timer:start(1500, 0, vim.schedule_wrap(attempt_callback)) + -- return + -- end + -- + -- local filestat = uv.fs_stat(target.path) + -- if filestat and filestat.type == 'file' then callback(target) end + -- end + -- -- Initial start + -- debounce_timer:start(1500, 0, vim.schedule_wrap(attempt_callback)) -- end -- end) + -- Poll every 1000ms. This is light on CPU and ignores "save noise". + handle:start(target.path, 1000, function(err, stat) + -- if err or not stat or (target and target.isBusy) then return end + if err or not stat then return end + + -- 2. Debounce: Reset the timer on every event + -- Only after 500ms of "silence" will the actual callback run + if debounce_timer then + -- Stop any existing timer to "debounce" + if debounce_timer:is_active() then debounce_timer:stop() end + debounce_timer:start(500, 0, vim.schedule_wrap(function() + -- vim.schedule(function () + local filestat = uv.fs_stat(target.path) + if filestat and filestat.type == 'file' then + callback(target) + end + -- if vim.loop.fs_stat(target.path) then callback(target) end + -- end) + end)) + end + end) + table.insert(M.watcher_handles, handle) return handle end diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index f33c8cea..87577952 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -36,7 +36,11 @@ function M.get_active__env() for _, dir in ipairs({ vim.api.nvim_buf_get_name(0):match('(.*[/\\])'), (vim.uv.cwd() .. '/') }) do local tmp = dir .. 'platformio.ini' - if vim.uv.fs_stat(tmp) then path = vim.fs.normalize(tmp) end + local filestat = vim.uv.fs_stat(tmp) + if filestat and filestat.type == 'file' then + path = vim.fs.normalize(tmp) + break + end end if path == '' then return vim.notify('PIO: platformio.ini not found or no [env] defined.', vim.log.levels.ERROR) end From cc8779bdbc6eb048439e7cbbb43cfcecfcf82a6b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 17:11:46 +0300 Subject: [PATCH 1259/1406] update --- lua/platformio/pio_setup.lua | 78 +++++++++++++++++++++++++++--------- 1 file changed, 58 insertions(+), 20 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b9a56136..7e634186 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -452,9 +452,47 @@ vim.api.nvim_create_autocmd('VimLeavePre', { -- 4. watch_file -- stylua: ignore local function watch_file(target, callback) + -- Extract directory path from target.path (filename) + local folder_path = target.path:match("(.*[/\\])") + -- local filename = target.path:match("[^/\\]+$") + local handle = uv.new_fs_poll() if not handle then return end + local last_mtime = 0 + + handle:start(folder_path, 1500, function(err) + if err then return end + + -- 1. EARLY EXIT: Check the specific file immediately + local filestat = uv.fs_stat(target.path) + if not filestat or filestat.mtime.sec <= last_mtime then + return -- Quit early! This wasn't the file we care about. + end + + -- 2. ONLY NOW do we start the debounce/busy logic + if debounce_timer then + debounce_timer:stop() + local retries = 0 + + local function attempt_callback() + if target.isBusy and retries < 10 then + retries = retries + 1 + debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) + return + end + + -- Final confirmation and update timestamp + local final_stat = uv.fs_stat(target.path) + if final_stat and final_stat.mtime.sec > last_mtime then + last_mtime = final_stat.mtime.sec + callback(target) + end + end + + debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) + end + end) -- handle:start(target.path, 1000, function(err, stat) -- if err or not stat then return end -- @@ -477,26 +515,26 @@ local function watch_file(target, callback) -- end) -- Poll every 1000ms. This is light on CPU and ignores "save noise". - handle:start(target.path, 1000, function(err, stat) - -- if err or not stat or (target and target.isBusy) then return end - if err or not stat then return end - - -- 2. Debounce: Reset the timer on every event - -- Only after 500ms of "silence" will the actual callback run - if debounce_timer then - -- Stop any existing timer to "debounce" - if debounce_timer:is_active() then debounce_timer:stop() end - debounce_timer:start(500, 0, vim.schedule_wrap(function() - -- vim.schedule(function () - local filestat = uv.fs_stat(target.path) - if filestat and filestat.type == 'file' then - callback(target) - end - -- if vim.loop.fs_stat(target.path) then callback(target) end - -- end) - end)) - end - end) + -- handle:start(target.path, 1000, function(err, stat) + -- -- if err or not stat or (target and target.isBusy) then return end + -- if err or not stat then return end + -- + -- -- 2. Debounce: Reset the timer on every event + -- -- Only after 500ms of "silence" will the actual callback run + -- if debounce_timer then + -- -- Stop any existing timer to "debounce" + -- if debounce_timer:is_active() then debounce_timer:stop() end + -- debounce_timer:start(500, 0, vim.schedule_wrap(function() + -- -- vim.schedule(function () + -- local filestat = uv.fs_stat(target.path) + -- if filestat and filestat.type == 'file' then + -- callback(target) + -- end + -- -- if vim.loop.fs_stat(target.path) then callback(target) end + -- -- end) + -- end)) + -- end + -- end) table.insert(M.watcher_handles, handle) return handle From 3812f90ac6888c0e20908f1b855c0e37a14fe45d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 17:16:40 +0300 Subject: [PATCH 1260/1406] update --- lua/platformio/pio_setup.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 7e634186..ffa90750 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -477,6 +477,7 @@ local function watch_file(target, callback) local function attempt_callback() if target.isBusy and retries < 10 then + print(retries) retries = retries + 1 debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) return From 07ac077f0d6bfa27045edd38f3b3ce88bff7adb3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 17:29:22 +0300 Subject: [PATCH 1261/1406] update --- lua/platformio/pio_setup.lua | 168 ++++++++++++++++++++--------------- 1 file changed, 95 insertions(+), 73 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index ffa90750..e4a585ee 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -448,100 +448,122 @@ vim.api.nvim_create_autocmd('VimLeavePre', { -- ============================================================================= -- stylua: ignore +--INFO: +-- 4. watch_file +-- stylua: ignore +-- local function watch_file(target, callback) +-- local handle = uv.new_fs_poll() +-- if not handle then return end +-- +-- -- handle:start(target.path, 1000, function(err, stat) +-- -- if err or not stat then return end +-- -- +-- -- if debounce_timer then +-- -- debounce_timer:stop() +-- -- -- Define the logic in a local variable so it can "call itself" for retries +-- -- local function attempt_callback() +-- -- if target.isBusy then +-- -- -- Retry in 1000ms if still busy +-- -- debounce_timer:start(1500, 0, vim.schedule_wrap(attempt_callback)) +-- -- return +-- -- end +-- -- +-- -- local filestat = uv.fs_stat(target.path) +-- -- if filestat and filestat.type == 'file' then callback(target) end +-- -- end +-- -- -- Initial start +-- -- debounce_timer:start(1500, 0, vim.schedule_wrap(attempt_callback)) +-- -- end +-- -- end) +-- +-- -- Poll every 1000ms. This is light on CPU and ignores "save noise". +-- -- handle:start(target.path, 1000, function(err, stat) +-- -- -- if err or not stat or (target and target.isBusy) then return end +-- -- if err or not stat then return end +-- -- +-- -- -- 2. Debounce: Reset the timer on every event +-- -- -- Only after 500ms of "silence" will the actual callback run +-- -- if debounce_timer then +-- -- -- Stop any existing timer to "debounce" +-- -- if debounce_timer:is_active() then debounce_timer:stop() end +-- -- debounce_timer:start(500, 0, vim.schedule_wrap(function() +-- -- -- vim.schedule(function () +-- -- local filestat = uv.fs_stat(target.path) +-- -- if filestat and filestat.type == 'file' then +-- -- callback(target) +-- -- end +-- -- -- if vim.loop.fs_stat(target.path) then callback(target) end +-- -- -- end) +-- -- end)) +-- -- end +-- -- end) +-- +-- table.insert(M.watcher_handles, handle) +-- return handle +-- end + --INFO: -- 4. watch_file -- stylua: ignore local function watch_file(target, callback) - -- Extract directory path from target.path (filename) + -- 1. Setup paths local folder_path = target.path:match("(.*[/\\])") - -- local filename = target.path:match("[^/\\]+$") + local target_filename = target.path:match("[^/\\]+$") + local last_mtime = 0 - local handle = uv.new_fs_poll() + local handle = uv.new_fs_event() if not handle then return end - local last_mtime = 0 - - handle:start(folder_path, 1500, function(err) + -- 2. Start watching the folder + handle:start(folder_path, {}, function(err, filename, events) if err then return end - -- 1. EARLY EXIT: Check the specific file immediately - local filestat = uv.fs_stat(target.path) - if not filestat or filestat.mtime.sec <= last_mtime then - return -- Quit early! This wasn't the file we care about. + -- EARLY EXIT: If the changed file isn't our target, quit immediately + -- Note: Some OS events might not provide the filename; we fallback to a stat check + if filename and filename ~= target_filename then + return end - -- 2. ONLY NOW do we start the debounce/busy logic - if debounce_timer then - debounce_timer:stop() - local retries = 0 - - local function attempt_callback() - if target.isBusy and retries < 10 then - print(retries) - retries = retries + 1 - debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) - return - end + -- 3. Verify actual modification (avoids triggers on just 'opening' the file) + local stat = uv.fs_stat(target.path) + if not stat or stat.mtime.sec <= last_mtime then + return + end - -- Final confirmation and update timestamp - local final_stat = uv.fs_stat(target.path) - if final_stat and final_stat.mtime.sec > last_mtime then - last_mtime = final_stat.mtime.sec - callback(target) + -- 4. Debounce and Busy-Retry Logic + vim.schedule(function() + if debounce_timer then + debounce_timer:stop() + local retries = 0 + + local function attempt_callback() + if target.isBusy then + if retries < 10 then + retries = retries + 1 + debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) + return + end + vim.notify("PIO: Sync timed out (busy)", vim.log.levels.ERROR) + return + end + + -- Final Check & Execution + local final_stat = uv.fs_stat(target.path) + if final_stat and final_stat.mtime.sec > last_mtime then + last_mtime = final_stat.mtime.sec + callback(target) + end end - end - debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) - end + debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) + end + end) end) - -- handle:start(target.path, 1000, function(err, stat) - -- if err or not stat then return end - -- - -- if debounce_timer then - -- debounce_timer:stop() - -- -- Define the logic in a local variable so it can "call itself" for retries - -- local function attempt_callback() - -- if target.isBusy then - -- -- Retry in 1000ms if still busy - -- debounce_timer:start(1500, 0, vim.schedule_wrap(attempt_callback)) - -- return - -- end - -- - -- local filestat = uv.fs_stat(target.path) - -- if filestat and filestat.type == 'file' then callback(target) end - -- end - -- -- Initial start - -- debounce_timer:start(1500, 0, vim.schedule_wrap(attempt_callback)) - -- end - -- end) - - -- Poll every 1000ms. This is light on CPU and ignores "save noise". - -- handle:start(target.path, 1000, function(err, stat) - -- -- if err or not stat or (target and target.isBusy) then return end - -- if err or not stat then return end - -- - -- -- 2. Debounce: Reset the timer on every event - -- -- Only after 500ms of "silence" will the actual callback run - -- if debounce_timer then - -- -- Stop any existing timer to "debounce" - -- if debounce_timer:is_active() then debounce_timer:stop() end - -- debounce_timer:start(500, 0, vim.schedule_wrap(function() - -- -- vim.schedule(function () - -- local filestat = uv.fs_stat(target.path) - -- if filestat and filestat.type == 'file' then - -- callback(target) - -- end - -- -- if vim.loop.fs_stat(target.path) then callback(target) end - -- -- end) - -- end)) - -- end - -- end) table.insert(M.watcher_handles, handle) return handle end - -- ============================================================================= -- stylua: ignore --INFO: From 08524a05c3fb0ae3f0f3fba2961fa4efd74b9c29 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 17:53:10 +0300 Subject: [PATCH 1262/1406] update --- lua/platformio/pio_setup.lua | 124 ++++++++++++++++++----------------- 1 file changed, 63 insertions(+), 61 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index e4a585ee..10f3645b 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -409,6 +409,7 @@ end local uv = vim.uv or vim.loop M.watcher_handles = {} local debounce_timer = uv.new_timer() +local last_mtime = 0 -- ============================================================================= -- stylua: ignore @@ -446,6 +447,68 @@ vim.api.nvim_create_autocmd('VimLeavePre', { end, }) +-- stylua: ignore +-- 3. MAIN WATCHER: Efficient Folder Monitoring +function M.watch_file(target, callback) + local folder_path = target.path:match('(.*[/\\])') + local target_filename = target.path:match('[^/\\]+$') + + local handle = uv.new_fs_event() + if not handle then return end + + handle:start(folder_path, {}, function(err, filename) + if err then return end + + -- Early Exit Filters + if filename and filename ~= target_filename then return end + if not uv.fs_access(target.path, 'R') then return end + + -- Protected Execution + local ok, result = pcall(function() + local stat = uv.fs_stat(target.path) + if not stat or stat.mtime.sec <= last_mtime then return end + + vim.schedule(function() + if debounce_timer then + debounce_timer:stop() + local retries = 0 + local max_retries = 15 -- 15 seconds max wait + + local function attempt_callback() + -- Check if busy (checks both local M and global _G) + if M.isBusy or (_G.metadata and _G.metadata.isBusy) then + if retries < max_retries then + retries = retries + 1 + debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) + return + end + vim.notify('PIO: Sync timed out (busy)', vim.log.levels.ERROR) + return + end + + -- Final validation & run + local final_stat = uv.fs_stat(target.path) + if final_stat and final_stat.mtime.sec > last_mtime then + last_mtime = final_stat.mtime.sec + callback(target) + end + end + + debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) + end + end) + end) + + if not ok then + vim.schedule(function() + vim.notify('PIO Watcher Error: ' .. tostring(result), vim.log.levels.ERROR) + end) + end + end) + + table.insert(M.watcher_handles, handle) + return handle +end -- ============================================================================= -- stylua: ignore --INFO: @@ -502,67 +565,6 @@ vim.api.nvim_create_autocmd('VimLeavePre', { -- return handle -- end ---INFO: --- 4. watch_file --- stylua: ignore -local function watch_file(target, callback) - -- 1. Setup paths - local folder_path = target.path:match("(.*[/\\])") - local target_filename = target.path:match("[^/\\]+$") - local last_mtime = 0 - - local handle = uv.new_fs_event() - if not handle then return end - - -- 2. Start watching the folder - handle:start(folder_path, {}, function(err, filename, events) - if err then return end - - -- EARLY EXIT: If the changed file isn't our target, quit immediately - -- Note: Some OS events might not provide the filename; we fallback to a stat check - if filename and filename ~= target_filename then - return - end - - -- 3. Verify actual modification (avoids triggers on just 'opening' the file) - local stat = uv.fs_stat(target.path) - if not stat or stat.mtime.sec <= last_mtime then - return - end - - -- 4. Debounce and Busy-Retry Logic - vim.schedule(function() - if debounce_timer then - debounce_timer:stop() - local retries = 0 - - local function attempt_callback() - if target.isBusy then - if retries < 10 then - retries = retries + 1 - debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) - return - end - vim.notify("PIO: Sync timed out (busy)", vim.log.levels.ERROR) - return - end - - -- Final Check & Execution - local final_stat = uv.fs_stat(target.path) - if final_stat and final_stat.mtime.sec > last_mtime then - last_mtime = final_stat.mtime.sec - callback(target) - end - end - - debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) - end - end) - end) - - table.insert(M.watcher_handles, handle) - return handle -end -- ============================================================================= -- stylua: ignore From 4aec6dee305e49dd3b68793fde7c8e5c6d39b6f5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 17:55:58 +0300 Subject: [PATCH 1263/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 10f3645b..1b1d1609 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -449,7 +449,7 @@ vim.api.nvim_create_autocmd('VimLeavePre', { -- stylua: ignore -- 3. MAIN WATCHER: Efficient Folder Monitoring -function M.watch_file(target, callback) +local function watch_file(target, callback) local folder_path = target.path:match('(.*[/\\])') local target_filename = target.path:match('[^/\\]+$') From 092bd152a3aaf25d484fb26dc1967b68f854e0ff Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 18:11:19 +0300 Subject: [PATCH 1264/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 1b1d1609..ca2b60dc 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -476,7 +476,7 @@ local function watch_file(target, callback) local function attempt_callback() -- Check if busy (checks both local M and global _G) - if M.isBusy or (_G.metadata and _G.metadata.isBusy) then + if target.isBusy then --or (_G.metadata and _G.metadata.isBusy) then if retries < max_retries then retries = retries + 1 debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) From ddf56b1823e30fd131459f65e387b9f879c0740c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 18:19:39 +0300 Subject: [PATCH 1265/1406] update --- lua/platformio/pio_setup.lua | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index ca2b60dc..b048d59c 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -461,7 +461,12 @@ local function watch_file(target, callback) -- Early Exit Filters if filename and filename ~= target_filename then return end - if not uv.fs_access(target.path, 'R') then return end + + local f = io.open(target.path, "r") + if f then f:close() + else return end -- Not readable (protected, locked, or missing) + + -- if not uv.fs_access(target.path, 'R') then return end -- Protected Execution local ok, result = pcall(function() From 7ad8d91dce32a119b786623029499cb3c5ff9420 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 19:43:20 +0300 Subject: [PATCH 1266/1406] update --- lua/platformio/pio_setup.lua | 2 +- lua/platformio/utils/misc.lua | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index b048d59c..51cf04c9 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -460,7 +460,7 @@ local function watch_file(target, callback) if err then return end -- Early Exit Filters - if filename and filename ~= target_filename then return end + if target.isBusy or (filename and filename ~= target_filename) then return end local f = io.open(target.path, "r") if f then f:close() diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 87577952..00878b53 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -47,6 +47,7 @@ function M.get_active__env() local ok, content = vim.misc.readFile(path) if not ok or not content then return vim.notify('PIO: platformio.ini not found in ' .. path, vim.log.levels.WARN) end + print(content) for line in vim.gsplit(content, '\n') do -- Detect the section headers [section] local section = line:match('^%s*%[(.+)%]%s*$') From 52c6c6d5a3d234acd145a72397ede47a7693f764 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 19:47:46 +0300 Subject: [PATCH 1267/1406] update --- lua/platformio/utils/misc.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 00878b53..ebd889ad 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -30,7 +30,7 @@ end -- stylua: ignore -- Fast environment detection (no external calls) function M.get_active__env() - local default_env, first_env = '', '' + local default_env, first_env-- = '', '' local in_platformio_block = false local path = '' From d3a3197537dbd54378e7d33fd7e098b86e144349 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 22:33:48 +0300 Subject: [PATCH 1268/1406] update --- lua/platformio/pio_setup.lua | 368 +--------------------- lua/platformio/utils/misc.lua | 57 ++-- lua/platformio/utils/pio.lua | 273 ++++++++++++++++ pio_setup.lua | 570 ++++++++++++++++++++++++++++++++++ 4 files changed, 891 insertions(+), 377 deletions(-) create mode 100644 pio_setup.lua diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 51cf04c9..7e83fe46 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -4,341 +4,18 @@ M = {} local boilerplate = require('platformio.boilerplate') local boilerplate_gen = boilerplate.boilerplate_gen -function M.fetch_config(from) - local msg = (type(from) == 'string' and from ~= '') and from or 'PIO: ' - local meta = _G.metadata - local home = (os.getenv('HOME') or os.getenv('USERPROFILE') or ''):gsub('[\\/]+$', '') - - vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) - vim.schedule(function() - -- 1. Check Execution - if obj.code ~= 0 then - local errmsg = obj.code == 127 and "'pio' not found" or (obj.stderr or 'Unknown Error') - return vim.notify(msg .. 'Config Error: ' .. errmsg, vim.log.levels.ERROR) - end - - -- 2. Decode JSON safely - local ok, decoded = pcall(vim.json.decode, obj.stdout or '') - if not ok or type(decoded) ~= 'table' then - return vim.notify(msg .. 'Failed to decode config JSON', vim.log.levels.ERROR) - end - - local formated = vim.misc.jsonFormat(decoded) - local file = vim.misc.joinPath(vim.uv.cwd(), 'config.json') - vim.misc.writeFile(file, formated, {}) - - -- Reset core structure - meta.envs = {} - meta.default_envs = {} - - -- 3. Parse Sections - for _, section in ipairs(decoded) do - local name, data = section[1], section[2] - if name == 'platformio' then - for _, kv in ipairs(data) do - meta[kv[1]] = kv[2] - end - elseif name:match('^env:') then - local env_name = name:match('^env:(.+)') - meta.envs[env_name] = {} - for _, kv in ipairs(data) do - meta.envs[env_name][kv[1]] = kv[2] - end - end - end - - -- 4. Assign active_env - meta.active_env = meta.default_envs[1] or next(meta.envs) or '' - - -- 5. Resolve Paths (INI -> Env -> Default) - local path_map = { - { key = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, - { key = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, - { key = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, - } - - for _, item in ipairs(path_map) do - local val = meta[item.key] - -- Fallback chain - if not val or val == '' then - val = os.getenv(item.env) or (home .. item.sub) - end - -- Expand variables and Normalize - if type(val) == 'string' then - val = val:gsub('%%${platformio.core_dir}', meta.core_dir or '') - meta[item.key] = vim.misc.normalizePath(val) - end - end - - -- 6. Trigger next step - if meta.active_env ~= '' then - vim.notify(msg .. 'Config sync successful', vim.log.levels.INFO) - return meta.active_env - else - vim.notify(msg .. 'No [env:] found. Please add a board.', vim.log.levels.ERROR) - end - end) - end) -end - -- local debounce_timer = vim.uv.new_timer() --- INFO: --- ============================================================================= --- UNIVERSAL TOOLCHAIN DETECTION --- ============================================================================= --- stylua: ignore -function M.get_sysroot_triplet(cc_compiler) - local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') - - -- Early exit if path is nil or not a directory - if not bin_path or vim.fn.isdirectory(bin_path) == 0 then return nil end - - -- Normalize backslashes to forward slashes for cross-platform consistency - bin_path = bin_path:gsub('\\', '/') - local files = vim.fn.readdir(bin_path) - local triplet = nil - - -- Loop through files to find the compiler and extract the triplet - for _, name in ipairs(files) do - -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ - local match = name:match('^(.*)%-g[c%+][c%+]') - if match then triplet = vim.misc.normalizePath(match) break - end - end - - -- Return nil if no compiler was found in the bin directory - if not triplet then return nil end - - -- toolchain_root is the parent of the 'bin' folder - local toolchain_root = vim.misc.normalizePath(vim.fn.fnamemodify(bin_path, ':h')) - -- sysroot folder is expected to have the same name as the triplet - local sysroot = vim.misc.normalizePath(toolchain_root .. '/' .. triplet) - local query_driver = vim.misc.normalizePath(bin_path .. '/' .. triplet .. '-*') - - -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) - -- Only return data if the sysroot folder actually exists on disk - if vim.fn.isdirectory(sysroot) == 1 then - _G.metadata.triplet = triplet - _G.metadata.sysroot = sysroot - _G.metadata.toolchain_root = toolchain_root - _G.metadata.query_driver = query_driver - return { - triplet = triplet, - sysroot = sysroot, - toolchain_root = toolchain_root, - query_driver = query_driver, - } - end - return nil -end - -- ============================================================================= -- stylua: ignore -function M.pio_refresh(from, callback) +function M.pio_refresh(callback, from) local msg = (type(from)=='string' and from ~= '') and from or 'PIO: ' vim.notify(msg ..'Config sync ...', vim.log.levels.INFO) - -- INFO:------------------------------------------------- - -- get pio project metadata info - -- stylua: ignore - local function fetch_metadata(attempts, env) - local meta = _G.metadata - local active_env = env or meta.active_env - if not active_env or active_env == '' then - return - end - - -- Set up file paths - local build_dir = vim.misc.joinPath(vim.uv.cwd(), '.pio', 'build') - local build_env_dir = vim.misc.joinPath(build_dir, active_env) - local checksum_file = vim.misc.joinPath(build_dir, 'project.checksum') - local idedata_file = vim.misc.joinPath(build_env_dir, 'idedata.json') - - --------------------------------------------------------- - -- INTERNAL PROCESSOR: Applies parsed data to _G.metadata - local function apply_metadata(data, checksum) - if not data then return false end - - local norm = function(p) return vim.misc.normalizePath(p) or '' end - - -- Helper for flags/defines to keep order and formatting - local quote_map = function(list, prefix) - local res = {} - for _, v in ipairs(list or {}) do - local val = prefix and (prefix .. norm(v)) or v - table.insert(res, string.format('%s', val)) - end - return res - end - - -- 1. Base Paths & Compilers - meta.cc_path = norm(data.cc_path) - meta.cc_compiler = meta.cc_path - meta.cxx_path = norm(data.cxx_path) - meta.gdb_path = norm(data.gdb_path) - - -- 2. Flags & Defines - meta.cc_flags = quote_map(data.cc_flags) - meta.cxx_flags = quote_map(data.cxx_flags) - meta.defines = quote_map(data.defines) - - -- 3. Includes (Build, Toolchain, Compatlib) - local inc = data.includes or {} - meta.includes_build = quote_map(inc.build, '-I') - meta.includes_toolchain = quote_map(inc.toolchain, '-isystem') - meta.includes_compatlib = quote_map(inc.compatlib, '-isystem') - meta.last_projectChecksum = checksum - pcall(M.get_sysroot_triplet, meta.cc_compiler) - - -- if callback then vim.schedule(callback) end - return true - end - - --------------------------------------------------------- - -- STEP 1: Fast Checksum Check - --------------------------------------------------------- - local ok, current_checksum = vim.misc.readFile(checksum_file) - if ok and (type(current_checksum) == 'string' and current_checksum ~= '') then - if current_checksum == meta.last_projectChecksum then - vim.notify(msg .. 'Metadata synced with cache', vim.log.levels.INFO) - -- if callback then callback() end - if callback then vim.schedule(callback) end - return true - end -- Already updated - - -- STEP 2: Cache Path (idedata.json exists and checksum changed) - local idok, content = vim.misc.readFile(idedata_file) - if idok and (type(content) == 'string' and content ~= '') then - local cok, decoded = pcall(vim.json.decode, content) - if cok and apply_metadata(decoded, current_checksum) then - local metadata = require('platformio.metadata') - metadata.save_project_config() - vim.notify(msg .. 'Metadata synced from cache', vim.log.levels.INFO) - if callback then vim.schedule(callback) end - return true - end - end - end - - --------------------------------------------------------- - -- STEP 3: Auto-Initialize (If files are missing) - --------------------------------------------------------- - -- if not current_checksum then - -- vim.notify(msg .. 'Initializing project metadata...', vim.log.levels.WARN) - -- vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env }, { text = true }, function(obj) - -- vim.schedule(function() - -- if obj.code == 0 thenl - -- fetch_metadata(attempts, active_env) -- Recursive call after files created - -- else - -- vim.notify(msg .. 'Initialization failed. Build project manually.', vim.log.levels.ERROR) - -- end - -- end) - -- end) - -- return - -- end - - --------------------------------------------------------- - -- STEP 4: Standard CLI Fallback (The Slow Path) - --------------------------------------------------------- - vim.notify(msg .. 'Metadata sync ...', vim.log.levels.INFO) - vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(obj) - vim.schedule(function() - if obj.code ~= 0 then - if attempts > 0 then - vim.defer_fn(function() fetch_metadata(attempts - 1, env) end, 500) - return - end - return vim.notify(msg .. 'Metadata Error: ' .. (obj.stderr or 'Unknown'), vim.log.levels.WARN) - end - - local ook, raw_data = pcall(vim.json.decode, obj.stdout or '') - local _, data = next(raw_data or {}) - - if ook and apply_metadata(data, current_checksum) then - vim.notify(msg .. 'Metadata synced from CLI', vim.log.levels.INFO) - if callback then vim.schedule(callback) end - else - vim.notify(msg .. 'Failed to parse metadata output', vim.log.levels.WARN) - end - end) - end) - end - ------------------------------------------------------------------------------------------------------------- - - -- INFO:------------------------------------------------- - -- get pio project config info - --------------------------------------------------------- - -- stylua: ignore - local function fetch_config() - local meta = _G.metadata - local home = (os.getenv('HOME') or os.getenv('USERPROFILE') or ""):gsub('[\\/]+$', '') - - vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) - vim.schedule(function() - -- 1. Check Execution - if obj.code ~= 0 then - local errmsg = obj.code == 127 and "'pio' not found" or (obj.stderr or "Unknown Error") - return vim.notify(msg .. "Config Error: " .. errmsg, vim.log.levels.ERROR) - end - - -- 2. Decode JSON safely - local ok, decoded = pcall(vim.json.decode, obj.stdout or "") - if not ok or type(decoded) ~= "table" then - return vim.notify(msg .. "Failed to decode config JSON", vim.log.levels.ERROR) - end - - local formated = vim.misc.jsonFormat(decoded) - local file = vim.misc.joinPath(vim.uv.cwd(), 'config.json') - vim.misc.writeFile(file, formated, {}) - - -- Reset core structure - meta.envs = {} - meta.default_envs = {} - - -- 3. Parse Sections - for _, section in ipairs(decoded) do - local name, data = section[1], section[2] - if name == 'platformio' then for _, kv in ipairs(data) do meta[kv[1]] = kv[2] end - elseif name:match('^env:') then - local env_name = name:match('^env:(.+)') - meta.envs[env_name] = {} - for _, kv in ipairs(data) do meta.envs[env_name][kv[1]] = kv[2] end - end - end - - -- 4. Assign active_env - meta.active_env = meta.default_envs[1] or next(meta.envs) or "" - - -- 5. Resolve Paths (INI -> Env -> Default) - local path_map = { - { key = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, - { key = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, - { key = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, - } - - for _, item in ipairs(path_map) do - local val = meta[item.key] - -- Fallback chain - if not val or val == "" then val = os.getenv(item.env) or (home .. item.sub) end - -- Expand variables and Normalize - if type(val) == "string" then - val = val:gsub('%%${platformio.core_dir}', meta.core_dir or "") - meta[item.key] = vim.misc.normalizePath(val) - end - end - - -- 6. Trigger next step - if meta.active_env ~= "" then - vim.notify(msg .. 'Config sync successful', vim.log.levels.INFO) - fetch_metadata(1, meta.active_env) - else - vim.notify(msg .. 'No [env:] found. Please add a board.', vim.log.levels.ERROR) - end - end) - end) + local active_env = vim.pio.fetch_config(from) + if active_env then + vim.pio.fetch_metadata(callback, active_env, from, 1) end - fetch_config() end -- ============================================================================= @@ -388,9 +65,9 @@ function M.run_compiledb(target) -- vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) -- Trigger refresh (LSP restart, etc.) -- vim.schedule(function () - -- M.pio_refresh('PIO platformio.ini change: ', function() + -- M.pio_refresh(function() vim.notify('PIO platformio.ini change: Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- end) + -- end, 'PIO platformio.ini change: ') -- end) else local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' @@ -462,11 +139,11 @@ local function watch_file(target, callback) -- Early Exit Filters if target.isBusy or (filename and filename ~= target_filename) then return end - local f = io.open(target.path, "r") - if f then f:close() - else return end -- Not readable (protected, locked, or missing) + -- local f = io.open(target.path, "r") + -- if f then f:close() + -- else return end -- Not readable (protected, locked, or missing) - -- if not uv.fs_access(target.path, 'R') then return end + if not uv.fs_access(target.path, 'R') then return end -- Protected Execution local ok, result = pcall(function() @@ -611,29 +288,12 @@ function M.start_watchers() return end - -- local attempts = 0 - -- local function run_when_ready() - -- if _G.metadata.isBusy and attempts < 50 then -- Timeout after 5 seconds - -- attempts = attempts + 1 - -- vim.defer_fn(run_when_ready, 100) - -- return - -- end - -- self.isBusy = true - -- vim.defer_fn(function() - -- M.pio_refresh('PIO checksum: ', function() - -- self.isBusy = false - -- vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) - -- end) - -- end, 500) - -- end - -- run_when_ready() - self.isBusy = true vim.defer_fn(function () - M.pio_refresh('PIO checksum: ',function() + M.pio_refresh(function() self.isBusy = false vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) - end) + end, 'PIO checksum: ') end, 500) end end @@ -681,11 +341,11 @@ function M.init() boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) --------------------------------------------------------------------------------- -- M.run_compiledb() -- Smart: Auto-update DB if config changes - M.pio_refresh('PIO start: ', function() + M.pio_refresh(function() -- vim.schedule(function() -- lsp_restart('clangd') -- end) - end) + end, 'PIO start: ') end end end diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index ebd889ad..427448cd 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -30,9 +30,7 @@ end -- stylua: ignore -- Fast environment detection (no external calls) function M.get_active__env() - local default_env, first_env-- = '', '' - local in_platformio_block = false - local path = '' + local path for _, dir in ipairs({ vim.api.nvim_buf_get_name(0):match('(.*[/\\])'), (vim.uv.cwd() .. '/') }) do local tmp = dir .. 'platformio.ini' @@ -42,33 +40,46 @@ function M.get_active__env() break end end - if path == '' then return vim.notify('PIO: platformio.ini not found or no [env] defined.', vim.log.levels.ERROR) end + if not path or path == '' then return vim.notify('PIO: platformio.ini not found or no [env] defined.', vim.log.levels.ERROR) end + -- Read file content (returns string or nil) local ok, content = vim.misc.readFile(path) if not ok or not content then return vim.notify('PIO: platformio.ini not found in ' .. path, vim.log.levels.WARN) end - print(content) + local default_envs_raw = '' + local first_env = nil + local valid_envs = {} + local in_platformio_block = false + + -- Iterate lines from the content string for line in vim.gsplit(content, '\n') do - -- Detect the section headers [section] + -- Section Detection: [section_name] local section = line:match('^%s*%[(.+)%]%s*$') if section then in_platformio_block = (section == 'platformio') - -- Capture the first env name seen local env_name = section:match('^env:(.+)') - if env_name and not first_env then first_env = env_name end + if env_name then + if not first_env then first_env = env_name end + valid_envs[env_name] = true + end end - -- If inside [platformio], look for default_envs + -- Collect the default_envs string from [platformio] block if in_platformio_block then - local def = line:match('^%s*default_envs%s*=%s*([^%s,]+)') - if def then - default_env = def - if first_env then break end - end + local def = line:match('^%s*default_envs%s*=%s*(.+)') + if def then default_envs_raw = def end + end + end + + -- Validation: Find the first default_env that actually exists as a block + if default_envs_raw ~= '' then + for env_name in default_envs_raw:gmatch('([^%s,]+)') do + if valid_envs[env_name] then return env_name end end end - return default_env or first_env + -- Fallback to the very first [env:...] block found in the file + return first_env end ------------------------------------------------------ @@ -265,14 +276,6 @@ function M.readFile(path) end ------------------------------------------------------ ---INFO: --- Example --- local ok, err = writeFiile(path, json) --- if ok then print("Write complete!") end --- stylua: ignore ----@param path string ----@param data string ----@param opts table -- function M.writeFile(path, data, opts) -- local uv = vim.uv or vim.loop -- @@ -308,6 +311,14 @@ end -- return true, 'writeFile: complete' -- end +--INFO: +-- Example +-- local ok, err = writeFiile(path, json) +-- if ok then print("Write complete!") end +-- stylua: ignore +---@param path string +---@param data string +---@param opts table function M.writeFile(path, data, opts) local uv = vim.uv or vim.loop diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index c52658e7..4435e230 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -12,6 +12,279 @@ M.queue = {} local term = require('platformio.utils.term') local lsp_restart = require('platformio.lspConfig.tools').lsp_restart +-- INFO: +-- ============================================================================= +-- UNIVERSAL TOOLCHAIN DETECTION +-- ============================================================================= +-- stylua: ignore +function M.get_sysroot_triplet(cc_compiler) + local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') + + -- Early exit if path is nil or not a directory + if not bin_path or vim.fn.isdirectory(bin_path) == 0 then return nil end + + -- Normalize backslashes to forward slashes for cross-platform consistency + bin_path = bin_path:gsub('\\', '/') + local files = vim.fn.readdir(bin_path) + local triplet = nil + + -- Loop through files to find the compiler and extract the triplet + for _, name in ipairs(files) do + -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ + local match = name:match('^(.*)%-g[c%+][c%+]') + if match then triplet = vim.misc.normalizePath(match) break + end + end + + -- Return nil if no compiler was found in the bin directory + if not triplet then return nil end + + -- toolchain_root is the parent of the 'bin' folder + local toolchain_root = vim.misc.normalizePath(vim.fn.fnamemodify(bin_path, ':h')) + -- sysroot folder is expected to have the same name as the triplet + local sysroot = vim.misc.normalizePath(toolchain_root .. '/' .. triplet) + local query_driver = vim.misc.normalizePath(bin_path .. '/' .. triplet .. '-*') + + -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) + -- Only return data if the sysroot folder actually exists on disk + if vim.fn.isdirectory(sysroot) == 1 then + _G.metadata.triplet = triplet + _G.metadata.sysroot = sysroot + _G.metadata.toolchain_root = toolchain_root + _G.metadata.query_driver = query_driver + return { + triplet = triplet, + sysroot = sysroot, + toolchain_root = toolchain_root, + query_driver = query_driver, + } + end + return nil +end + +-- INFO:------------------------------------------------- +-- get pio project metadata info +-- stylua: ignore +function M.fetch_metadata(callback, env, from, attempts) + local msg = (type(from)=='string' and from ~= '') and from or 'PIO: ' + local meta = _G.metadata + local active_env = env or meta.active_env + if not active_env or active_env == '' then + return + end + + -- Set up file paths + local build_dir = vim.misc.joinPath(vim.uv.cwd(), '.pio', 'build') + local build_env_dir = vim.misc.joinPath(build_dir, active_env) + local checksum_file = vim.misc.joinPath(build_dir, 'project.checksum') + local idedata_file = vim.misc.joinPath(build_env_dir, 'idedata.json') + + --------------------------------------------------------- + -- INTERNAL PROCESSOR: Applies parsed data to _G.metadata + local function apply_metadata(data, checksum) + if not data then return false end + + local norm = function(p) return vim.misc.normalizePath(p) or '' end + + -- Helper for flags/defines to keep order and formatting + local quote_map = function(list, prefix) + local res = {} + for _, v in ipairs(list or {}) do + local val = prefix and (prefix .. norm(v)) or v + table.insert(res, string.format('%s', val)) + end + return res + end + + -- 1. Base Paths & Compilers + meta.cc_path = norm(data.cc_path) + meta.cc_compiler = meta.cc_path + meta.cxx_path = norm(data.cxx_path) + meta.gdb_path = norm(data.gdb_path) + + -- 2. Flags & Defines + meta.cc_flags = quote_map(data.cc_flags) + meta.cxx_flags = quote_map(data.cxx_flags) + meta.defines = quote_map(data.defines) + + -- 3. Includes (Build, Toolchain, Compatlib) + local inc = data.includes or {} + meta.includes_build = quote_map(inc.build, '-I') + meta.includes_toolchain = quote_map(inc.toolchain, '-isystem') + meta.includes_compatlib = quote_map(inc.compatlib, '-isystem') + meta.last_projectChecksum = checksum + pcall(M.get_sysroot_triplet, meta.cc_compiler) + + -- if callback then vim.schedule(callback) end + return true + end + + --------------------------------------------------------- + -- STEP 1: Fast Checksum Check + --------------------------------------------------------- + local ok, current_checksum = vim.misc.readFile(checksum_file) + if ok and (type(current_checksum) == 'string' and current_checksum ~= '') then + if current_checksum == meta.last_projectChecksum then + vim.notify(msg .. 'Metadata synced with cache', vim.log.levels.INFO) + -- if callback then callback() end + if callback then vim.schedule(callback) end + return true + end -- Already updated + + -- STEP 2: Cache Path (idedata.json exists and checksum changed) + local idok, content = vim.misc.readFile(idedata_file) + if idok and (type(content) == 'string' and content ~= '') then + local cok, decoded = pcall(vim.json.decode, content) + if cok and apply_metadata(decoded, current_checksum) then + local metadata = require('platformio.metadata') + metadata.save_project_config() + vim.notify(msg .. 'Metadata synced from cache', vim.log.levels.INFO) + if callback then vim.schedule(callback) end + return true + end + end + end + + --------------------------------------------------------- + -- STEP 3: Auto-Initialize (If files are missing) + --------------------------------------------------------- + if not current_checksum then + vim.notify(msg .. 'Initializing project metadata...', vim.log.levels.WARN) + vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env }, { text = true }, function(obj) + vim.schedule(function() + if obj.code == 0 then + M.fetch_metadata(callback, active_env, from, attempts - 1) -- Recursive call after files created + else + vim.notify(msg .. 'Initialization failed. Build project manually.', vim.log.levels.ERROR) + end + end) + end) + return + end + + --------------------------------------------------------- + -- STEP 4: Standard CLI Fallback (The Slow Path) + --------------------------------------------------------- + -- vim.notify(msg .. 'Metadata sync ...', vim.log.levels.INFO) + -- vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(obj) + -- vim.schedule(function() + -- if obj.code ~= 0 then + -- if attempts > 0 then + -- vim.defer_fn(function() M.fetch_metadata(attempts - 1, env) end, 500) + -- return + -- end + -- return vim.notify(msg .. 'Metadata Error: ' .. (obj.stderr or 'Unknown'), vim.log.levels.WARN) + -- end + -- + -- local ook, raw_data = pcall(vim.json.decode, obj.stdout or '') + -- local _, data = next(raw_data or {}) + -- + -- if ook and apply_metadata(data, current_checksum) then + -- vim.notify(msg .. 'Metadata synced from CLI', vim.log.levels.INFO) + -- if callback then vim.schedule(callback) end + -- else + -- vim.notify(msg .. 'Failed to parse metadata output', vim.log.levels.WARN) + -- end + -- end) + -- end) +end + + + + +-- INFO: +-- ============================================================================= +-- Get project infomation +-- ============================================================================= +-- stylua: ignore +function M.fetch_config(from) + local msg = (type(from) == 'string' and from ~= '') and from or 'PIO: ' + local meta = _G.metadata + local home = (os.getenv('HOME') or os.getenv('USERPROFILE') or ''):gsub('[\\/]+$', '') + + local active_env + vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) + vim.schedule(function() + -- 1. Check Execution + if obj.code ~= 0 then + local errmsg = obj.code == 127 and "'pio' not found" or (obj.stderr or 'Unknown Error') + return vim.notify(msg .. 'Config Error: ' .. errmsg, vim.log.levels.ERROR) + end + + -- 2. Decode JSON safely + local ok, decoded = pcall(vim.json.decode, obj.stdout or '') + if not ok or type(decoded) ~= 'table' then + return vim.notify(msg .. 'Failed to decode config JSON', vim.log.levels.ERROR) + end + + local formated = vim.misc.jsonFormat(decoded) + local file = vim.misc.joinPath(vim.uv.cwd(), 'config.json') + vim.misc.writeFile(file, formated, {}) + + -- Reset core structure + meta.envs = {} + meta.default_envs = {} + local valid_envs = {} + + -- 3. Parse Sections + for _, section in ipairs(decoded) do + local name, data = section[1], section[2] + if name == 'platformio' then + for _, kv in ipairs(data) do + meta[kv[1]] = kv[2] + end + elseif name:match('^env:') then + local env_name = name:match('^env:(.+)') + if not active_env then active_env = env_name end + valid_envs[env_name] = true + meta.envs[env_name] = {} + for _, kv in ipairs(data) do + meta.envs[env_name][kv[1]] = kv[2] + end + end + end + + -- 4. Assign active_env + -- Validation: Find the first default_env that actually exists as a block + for _, env_name in ipairs(meta.default_envs) do + if valid_envs[env_name] then + active_env = env_name + break + end + end + meta.active_env = active_env or '' + + -- 5. Resolve Paths (INI -> Env -> Default) + local path_map = { + { key = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, + { key = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, + { key = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, + } + + for _, item in ipairs(path_map) do + local val = meta[item.key] + -- Fallback chain + if not val or val == '' then + val = os.getenv(item.env) or (home .. item.sub) + end + -- Expand variables and Normalize + if type(val) == 'string' then + val = val:gsub('%%${platformio.core_dir}', meta.core_dir or '') + meta[item.key] = vim.misc.normalizePath(val) + end + end + + -- 6. Trigger next step + if meta.active_env ~= '' then + vim.notify(msg .. 'Config sync successful', vim.log.levels.INFO) + else + vim.notify(msg .. 'No [env:] found. Please add a board.', vim.log.levels.ERROR) + end + end) + end) + return active_env +end + -- INFO: -- ============================================================================= -- UNIVERSAL TOOLCHAIN DETECTION diff --git a/pio_setup.lua b/pio_setup.lua new file mode 100644 index 00000000..2819875f --- /dev/null +++ b/pio_setup.lua @@ -0,0 +1,570 @@ +-- M = {} +-- +-- -- local lsp_restart = require('platformio.lspConfig.tools').lsp_restart +-- local boilerplate = require('platformio.boilerplate') +-- local boilerplate_gen = boilerplate.boilerplate_gen +-- +-- +-- +-- -- local debounce_timer = vim.uv.new_timer() +-- -- ============================================================================= +-- -- stylua: ignore +-- function M.pio_refresh(callback, from) +-- local msg = (type(from)=='string' and from ~= '') and from or 'PIO: ' +-- vim.notify(msg ..'Config sync ...', vim.log.levels.INFO) +-- -- -- INFO:------------------------------------------------- +-- -- -- get pio project metadata info +-- -- -- stylua: ignore +-- -- local function fetch_metadata(attempts, env) +-- -- local meta = _G.metadata +-- -- local active_env = env or meta.active_env +-- -- if not active_env or active_env == '' then +-- -- return +-- -- end +-- -- +-- -- -- Set up file paths +-- -- local build_dir = vim.misc.joinPath(vim.uv.cwd(), '.pio', 'build') +-- -- local build_env_dir = vim.misc.joinPath(build_dir, active_env) +-- -- local checksum_file = vim.misc.joinPath(build_dir, 'project.checksum') +-- -- local idedata_file = vim.misc.joinPath(build_env_dir, 'idedata.json') +-- -- +-- -- --------------------------------------------------------- +-- -- -- INTERNAL PROCESSOR: Applies parsed data to _G.metadata +-- -- local function apply_metadata(data, checksum) +-- -- if not data then return false end +-- -- +-- -- local norm = function(p) return vim.misc.normalizePath(p) or '' end +-- -- +-- -- -- Helper for flags/defines to keep order and formatting +-- -- local quote_map = function(list, prefix) +-- -- local res = {} +-- -- for _, v in ipairs(list or {}) do +-- -- local val = prefix and (prefix .. norm(v)) or v +-- -- table.insert(res, string.format('%s', val)) +-- -- end +-- -- return res +-- -- end +-- -- +-- -- -- 1. Base Paths & Compilers +-- -- meta.cc_path = norm(data.cc_path) +-- -- meta.cc_compiler = meta.cc_path +-- -- meta.cxx_path = norm(data.cxx_path) +-- -- meta.gdb_path = norm(data.gdb_path) +-- -- +-- -- -- 2. Flags & Defines +-- -- meta.cc_flags = quote_map(data.cc_flags) +-- -- meta.cxx_flags = quote_map(data.cxx_flags) +-- -- meta.defines = quote_map(data.defines) +-- -- +-- -- -- 3. Includes (Build, Toolchain, Compatlib) +-- -- local inc = data.includes or {} +-- -- meta.includes_build = quote_map(inc.build, '-I') +-- -- meta.includes_toolchain = quote_map(inc.toolchain, '-isystem') +-- -- meta.includes_compatlib = quote_map(inc.compatlib, '-isystem') +-- -- meta.last_projectChecksum = checksum +-- -- pcall(M.get_sysroot_triplet, meta.cc_compiler) +-- -- +-- -- -- if callback then vim.schedule(callback) end +-- -- return true +-- -- end +-- -- +-- -- --------------------------------------------------------- +-- -- -- STEP 1: Fast Checksum Check +-- -- --------------------------------------------------------- +-- -- local ok, current_checksum = vim.misc.readFile(checksum_file) +-- -- if ok and (type(current_checksum) == 'string' and current_checksum ~= '') then +-- -- if current_checksum == meta.last_projectChecksum then +-- -- vim.notify(msg .. 'Metadata synced with cache', vim.log.levels.INFO) +-- -- -- if callback then callback() end +-- -- if callback then vim.schedule(callback) end +-- -- return true +-- -- end -- Already updated +-- -- +-- -- -- STEP 2: Cache Path (idedata.json exists and checksum changed) +-- -- local idok, content = vim.misc.readFile(idedata_file) +-- -- if idok and (type(content) == 'string' and content ~= '') then +-- -- local cok, decoded = pcall(vim.json.decode, content) +-- -- if cok and apply_metadata(decoded, current_checksum) then +-- -- local metadata = require('platformio.metadata') +-- -- metadata.save_project_config() +-- -- vim.notify(msg .. 'Metadata synced from cache', vim.log.levels.INFO) +-- -- if callback then vim.schedule(callback) end +-- -- return true +-- -- end +-- -- end +-- -- end +-- -- +-- -- --------------------------------------------------------- +-- -- -- STEP 3: Auto-Initialize (If files are missing) +-- -- --------------------------------------------------------- +-- -- -- if not current_checksum then +-- -- -- vim.notify(msg .. 'Initializing project metadata...', vim.log.levels.WARN) +-- -- -- vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env }, { text = true }, function(obj) +-- -- -- vim.schedule(function() +-- -- -- if obj.code == 0 thenl +-- -- -- fetch_metadata(attempts, active_env) -- Recursive call after files created +-- -- -- else +-- -- -- vim.notify(msg .. 'Initialization failed. Build project manually.', vim.log.levels.ERROR) +-- -- -- end +-- -- -- end) +-- -- -- end) +-- -- -- return +-- -- -- end +-- -- +-- -- --------------------------------------------------------- +-- -- -- STEP 4: Standard CLI Fallback (The Slow Path) +-- -- --------------------------------------------------------- +-- -- vim.notify(msg .. 'Metadata sync ...', vim.log.levels.INFO) +-- -- vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(obj) +-- -- vim.schedule(function() +-- -- if obj.code ~= 0 then +-- -- if attempts > 0 then +-- -- vim.defer_fn(function() fetch_metadata(attempts - 1, env) end, 500) +-- -- return +-- -- end +-- -- return vim.notify(msg .. 'Metadata Error: ' .. (obj.stderr or 'Unknown'), vim.log.levels.WARN) +-- -- end +-- -- +-- -- local ook, raw_data = pcall(vim.json.decode, obj.stdout or '') +-- -- local _, data = next(raw_data or {}) +-- -- +-- -- if ook and apply_metadata(data, current_checksum) then +-- -- vim.notify(msg .. 'Metadata synced from CLI', vim.log.levels.INFO) +-- -- if callback then vim.schedule(callback) end +-- -- else +-- -- vim.notify(msg .. 'Failed to parse metadata output', vim.log.levels.WARN) +-- -- end +-- -- end) +-- -- end) +-- -- end +-- ------------------------------------------------------------------------------------------------------------- +-- +-- -- INFO:------------------------------------------------- +-- -- get pio project config info +-- --------------------------------------------------------- +-- -- stylua: ignore +-- -- local function fetch_config() +-- -- local meta = _G.metadata +-- -- local home = (os.getenv('HOME') or os.getenv('USERPROFILE') or ""):gsub('[\\/]+$', '') +-- -- +-- -- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) +-- -- vim.schedule(function() +-- -- -- 1. Check Execution +-- -- if obj.code ~= 0 then +-- -- local errmsg = obj.code == 127 and "'pio' not found" or (obj.stderr or "Unknown Error") +-- -- return vim.notify(msg .. "Config Error: " .. errmsg, vim.log.levels.ERROR) +-- -- end +-- -- +-- -- -- 2. Decode JSON safely +-- -- local ok, decoded = pcall(vim.json.decode, obj.stdout or "") +-- -- if not ok or type(decoded) ~= "table" then +-- -- return vim.notify(msg .. "Failed to decode config JSON", vim.log.levels.ERROR) +-- -- end +-- -- +-- -- local formated = vim.misc.jsonFormat(decoded) +-- -- local file = vim.misc.joinPath(vim.uv.cwd(), 'config.json') +-- -- vim.misc.writeFile(file, formated, {}) +-- -- +-- -- -- Reset core structure +-- -- meta.envs = {} +-- -- meta.default_envs = {} +-- -- +-- -- -- 3. Parse Sections +-- -- for _, section in ipairs(decoded) do +-- -- local name, data = section[1], section[2] +-- -- if name == 'platformio' then for _, kv in ipairs(data) do meta[kv[1]] = kv[2] end +-- -- elseif name:match('^env:') then +-- -- local env_name = name:match('^env:(.+)') +-- -- meta.envs[env_name] = {} +-- -- for _, kv in ipairs(data) do meta.envs[env_name][kv[1]] = kv[2] end +-- -- end +-- -- end +-- -- +-- -- -- 4. Assign active_env +-- -- meta.active_env = meta.default_envs[1] or next(meta.envs) or "" +-- -- +-- -- -- 5. Resolve Paths (INI -> Env -> Default) +-- -- local path_map = { +-- -- { key = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, +-- -- { key = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, +-- -- { key = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, +-- -- } +-- -- +-- -- for _, item in ipairs(path_map) do +-- -- local val = meta[item.key] +-- -- -- Fallback chain +-- -- if not val or val == "" then val = os.getenv(item.env) or (home .. item.sub) end +-- -- -- Expand variables and Normalize +-- -- if type(val) == "string" then +-- -- val = val:gsub('%%${platformio.core_dir}', meta.core_dir or "") +-- -- meta[item.key] = vim.misc.normalizePath(val) +-- -- end +-- -- end +-- -- +-- -- -- 6. Trigger next step +-- -- if meta.active_env ~= "" then +-- -- vim.notify(msg .. 'Config sync successful', vim.log.levels.INFO) +-- -- fetch_metadata(1, meta.active_env) +-- -- else +-- -- vim.notify(msg .. 'No [env:] found. Please add a board.', vim.log.levels.ERROR) +-- -- end +-- -- end) +-- -- end) +-- -- end +-- local active_env = vim.pio.fetch_config(from) +-- if active_env then +-- vim.pio.fetch_metadata(callback, active_env, from, 1) +-- end +-- -- fetch_config() +-- end +-- +-- -- ============================================================================= +-- -- INFO: +-- -- 1. Helper: Unified hashing for change detection +-- local function get_hash(path) +-- if vim.fn.filereadable(path) == 0 then +-- return nil +-- end +-- -- local ok, data = pcall(vim.fn.readfile, path) -- readfile is safer than io.open +-- -- return ok and vim.fn.sha256(table.concat(data, '\n')) or nil +-- local ok, data = vim.misc.readFile(path) -- readfile is safer than io.open +-- return (ok and type(data) == 'string' and data ~= '') and vim.fn.sha256(data) or '' +-- end +-- +-- -- ============================================================================= +-- -- stylua: ignore +-- --INFO: +-- -- 1.run_compiledb +-- function M.run_compiledb(target) +-- -- 1. Prevent overlapping builds +-- if target.isBusy then return end +-- target.isBusy = true +-- _G.metadata.isBusy = true +-- +-- +-- -- local pio = require('platformio.utils.pio') +-- -- pio.run_sequence({ +-- -- cmnds = { +-- -- 'pio run -t compiledb -e ' .. vim.misc.get_active__env(), +-- -- }, +-- -- cb = function (result) +-- -- pio.handlePiodb(target, result) +-- -- end +-- -- }) +-- +-- local env = vim.misc.get_active__env() +-- -- if env and env ~= '' then +-- vim.notify('PIO platformio.ini change: update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) +-- -- vim.schedule(function() +-- vim.system({ 'pio', 'run', '-t', 'compiledb', '-s', '-e', env }, { text = true }, function(obj) +-- -- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) +-- vim.schedule(function() +-- target.isBusy = false +-- +-- if obj.code == 0 then +-- -- vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) +-- -- Trigger refresh (LSP restart, etc.) +-- -- vim.schedule(function () +-- -- M.pio_refresh(function() +-- vim.notify('PIO platformio.ini change: Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) +-- -- end, 'PIO platformio.ini change: ') +-- -- end) +-- else +-- local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' +-- vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) +-- end +-- _G.metadata.isBusy = false +-- end) +-- end) +-- -- end) +-- -- end +-- end +-- +-- -- ============================================================================= +-- --INFO: +-- -- Ensure this is at the TOP of your file, outside any functions +-- local uv = vim.uv or vim.loop +-- M.watcher_handles = {} +-- local debounce_timer = uv.new_timer() +-- local last_mtime = 0 +-- +-- -- ============================================================================= +-- -- stylua: ignore +-- --INFO: +-- -- 2.stop_watchers +-- function M.stop_watchers() +-- if not M.watcher_handles or (type(M.watcher_handles) ~= 'table') then M.watcher_handles = {} return end +-- +-- for _, handle in ipairs(M.watcher_handles) do +-- if handle and not handle:is_closing() then +-- handle:stop() +-- handle:close() -- CRITICAL: This allows Neovim to quit instantly +-- end +-- end +-- M.watcher_handles = {} +-- end +-- +-- -- ============================================================================= +-- -- stylua: ignore +-- --INFO: +-- -- 3.watcher cleanup +-- function M.cleanup() +-- M.stop_watchers() +-- if debounce_timer and not debounce_timer:is_closing() then +-- debounce_timer:stop() +-- debounce_timer:close() +-- end +-- end +-- -- ============================================================================= +-- --INFO: +-- -- Force cleanup when leaving Neovim to prevent :qa lag +-- vim.api.nvim_create_autocmd('VimLeavePre', { +-- callback = function() +-- M.cleanup() +-- end, +-- }) +-- +-- -- stylua: ignore +-- -- 3. MAIN WATCHER: Efficient Folder Monitoring +-- local function watch_file(target, callback) +-- local folder_path = target.path:match('(.*[/\\])') +-- local target_filename = target.path:match('[^/\\]+$') +-- +-- local handle = uv.new_fs_event() +-- if not handle then return end +-- +-- handle:start(folder_path, {}, function(err, filename) +-- if err then return end +-- +-- -- Early Exit Filters +-- if target.isBusy or (filename and filename ~= target_filename) then return end +-- +-- local f = io.open(target.path, "r") +-- if f then f:close() +-- else return end -- Not readable (protected, locked, or missing) +-- +-- -- if not uv.fs_access(target.path, 'R') then return end +-- +-- -- Protected Execution +-- local ok, result = pcall(function() +-- local stat = uv.fs_stat(target.path) +-- if not stat or stat.mtime.sec <= last_mtime then return end +-- +-- vim.schedule(function() +-- if debounce_timer then +-- debounce_timer:stop() +-- local retries = 0 +-- local max_retries = 15 -- 15 seconds max wait +-- +-- local function attempt_callback() +-- -- Check if busy (checks both local M and global _G) +-- if target.isBusy then --or (_G.metadata and _G.metadata.isBusy) then +-- if retries < max_retries then +-- retries = retries + 1 +-- debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) +-- return +-- end +-- vim.notify('PIO: Sync timed out (busy)', vim.log.levels.ERROR) +-- return +-- end +-- +-- -- Final validation & run +-- local final_stat = uv.fs_stat(target.path) +-- if final_stat and final_stat.mtime.sec > last_mtime then +-- last_mtime = final_stat.mtime.sec +-- callback(target) +-- end +-- end +-- +-- debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) +-- end +-- end) +-- end) +-- +-- if not ok then +-- vim.schedule(function() +-- vim.notify('PIO Watcher Error: ' .. tostring(result), vim.log.levels.ERROR) +-- end) +-- end +-- end) +-- +-- table.insert(M.watcher_handles, handle) +-- return handle +-- end +-- -- ============================================================================= +-- -- stylua: ignore +-- --INFO: +-- -- 4. watch_file +-- -- stylua: ignore +-- -- local function watch_file(target, callback) +-- -- local handle = uv.new_fs_poll() +-- -- if not handle then return end +-- -- +-- -- -- handle:start(target.path, 1000, function(err, stat) +-- -- -- if err or not stat then return end +-- -- -- +-- -- -- if debounce_timer then +-- -- -- debounce_timer:stop() +-- -- -- -- Define the logic in a local variable so it can "call itself" for retries +-- -- -- local function attempt_callback() +-- -- -- if target.isBusy then +-- -- -- -- Retry in 1000ms if still busy +-- -- -- debounce_timer:start(1500, 0, vim.schedule_wrap(attempt_callback)) +-- -- -- return +-- -- -- end +-- -- -- +-- -- -- local filestat = uv.fs_stat(target.path) +-- -- -- if filestat and filestat.type == 'file' then callback(target) end +-- -- -- end +-- -- -- -- Initial start +-- -- -- debounce_timer:start(1500, 0, vim.schedule_wrap(attempt_callback)) +-- -- -- end +-- -- -- end) +-- -- +-- -- -- Poll every 1000ms. This is light on CPU and ignores "save noise". +-- -- -- handle:start(target.path, 1000, function(err, stat) +-- -- -- -- if err or not stat or (target and target.isBusy) then return end +-- -- -- if err or not stat then return end +-- -- -- +-- -- -- -- 2. Debounce: Reset the timer on every event +-- -- -- -- Only after 500ms of "silence" will the actual callback run +-- -- -- if debounce_timer then +-- -- -- -- Stop any existing timer to "debounce" +-- -- -- if debounce_timer:is_active() then debounce_timer:stop() end +-- -- -- debounce_timer:start(500, 0, vim.schedule_wrap(function() +-- -- -- -- vim.schedule(function () +-- -- -- local filestat = uv.fs_stat(target.path) +-- -- -- if filestat and filestat.type == 'file' then +-- -- -- callback(target) +-- -- -- end +-- -- -- -- if vim.loop.fs_stat(target.path) then callback(target) end +-- -- -- -- end) +-- -- -- end)) +-- -- -- end +-- -- -- end) +-- -- +-- -- table.insert(M.watcher_handles, handle) +-- -- return handle +-- -- end +-- +-- +-- -- ============================================================================= +-- -- stylua: ignore +-- --INFO: +-- -- 5. start_watches +-- function M.start_watchers() +-- -- Clean up any existing watchers first to prevent duplicates +-- if next(M.watcher_handles) then M.stop_watchers() end +-- +-- local project_root = vim.uv.cwd() -- Use dynamic CWD instead of hardcoded path +-- +-- local targets = { +-- { -- watcher for platformio.ini +-- name = 'ini', +-- isBusy = false, +-- last_hash = '', +-- path = vim.misc.joinPath(project_root, 'platformio.ini'), +-- cb = function(self) +-- if self.isBusy then return end +-- local new_hash = get_hash(self.path) or '' +-- if new_hash and new_hash ~= self.last_hash then +-- self.last_hash = new_hash +-- vim.schedule(function() +-- M.run_compiledb(self) -- Smart: Auto-update DB if config changes +-- end) +-- end +-- end, +-- }, +-- { -- watcher for ./.pio/build/projct.checksum +-- name = 'checksum', +-- isBusy = false, +-- path = vim.misc.joinPath(project_root, '.pio', 'build', 'project.checksum'), --checksum_path +-- cb = function(self) +-- if self.isBusy then return end +-- local ok, current_checksum = vim.misc.readFile(self.path) +-- -- Check if we should exit early +-- if ok and type(current_checksum) == 'string' and current_checksum ~= '' then +-- if current_checksum == _G.metadata.last_projectChecksum then +-- return +-- end +-- +-- -- local attempts = 0 +-- -- local function run_when_ready() +-- -- if _G.metadata.isBusy and attempts < 50 then -- Timeout after 5 seconds +-- -- attempts = attempts + 1 +-- -- vim.defer_fn(run_when_ready, 100) +-- -- return +-- -- end +-- -- self.isBusy = true +-- -- vim.defer_fn(function() +-- -- M.pio_refresh(function() +-- -- self.isBusy = false +-- -- vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) +-- -- end, 'PIO checksum: ') +-- -- end, 500) +-- -- end +-- -- run_when_ready() +-- +-- self.isBusy = true +-- vim.defer_fn(function () +-- M.pio_refresh(function() +-- self.isBusy = false +-- vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) +-- end, 'PIO checksum: ') +-- end, 500) +-- end +-- end +-- }, +-- } +-- -- targets[1].last_hash = get_hash(targets[1].path) or '' +-- +-- for _, target in ipairs(targets) do +-- --[[ wrap the callback in a small anonymous function, +-- so it passes the target (self) back into it.]] +-- watch_file(target, target.cb) +-- end +-- end +-- +-- -- ============================================================================= +-- -- stylua: ignore +-- --INFO: 6. Exported setup function +-- function M.init() +-- local config = require('platformio').config +-- if config.lspClangd.enabled == true then +-- vim.notify('PIO start: initialize', vim.log.levels.INFO) +-- +-- -- activate meta save and upload and env switch +-- local metadata = require('platformio.metadata') +-- metadata.load_project_config() +-- +-- require('platformio.lspConfig.clangd') +-- if config.lspClangd.attach.enabled then +-- require('platformio.lspConfig.attach') +-- end +-- +-- -- Always start the watcher so it can catch a future 'pio init' +-- M.start_watchers() +-- +-- -- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) +-- -- If the file already exists, do an initial sync +-- if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then +-- ---------------------------------------------------------------------------------------- +-- --INFO: create clangd required files +-- ----------------------------------------------------------------------------------------- +-- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +-- -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') +-- -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) +-- boilerplate.core_dir = _G.metadata.core_dir +-- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) +-- --------------------------------------------------------------------------------- +-- -- M.run_compiledb() -- Smart: Auto-update DB if config changes +-- M.pio_refresh(function() +-- -- vim.schedule(function() +-- -- lsp_restart('clangd') +-- -- end) +-- end, 'PIO start: ') +-- end +-- end +-- end +-- +-- return M From 1a22a6a0910c282b00505f9b5594c0e1aac2704e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 23:08:12 +0300 Subject: [PATCH 1269/1406] update --- lua/platformio/pioinit2.lua | 26 ++++----- lua/platformio/utils/pio.lua | 107 +++++++++++++++++------------------ 2 files changed, 64 insertions(+), 69 deletions(-) diff --git a/lua/platformio/pioinit2.lua b/lua/platformio/pioinit2.lua index eec9c30a..93a5c414 100644 --- a/lua/platformio/pioinit2.lua +++ b/lua/platformio/pioinit2.lua @@ -46,14 +46,10 @@ local function finalize_setup() local sample_flag = wizard_data.sample == 'Yes' and ' --sample-code' or '' local init_cmd = string.format('pio project init --ide vim --board %s -O "framework=%s"%s', wizard_data.board_id, wizard_data.framework, sample_flag) + local db_cmd = string.format('pio run -t compiledb -e %s', wizard_data.board_id) - local commands = { init_cmd } - local final_cb = pio.handlePioinit - - if wizard_data.use_compiledb == 'Yes' then - table.insert(commands, 'pio run -t compiledb') - final_cb = pio.handlePioinitDb - end + local commands = { init_cmd, db_cmd } + local final_cb = pio.handlePioinitDb notify('Starting project setup for ' .. wizard_data.board_id .. '...') pio.run_sequence({ cmnds = commands, cb = final_cb }) @@ -62,18 +58,19 @@ end --- SEQUENTIAL STEPS --- -- Step 4: CompileDB -local function pick_compiledb() - small_menu('Generate Compilation Database (LSP)?', { 'Yes', 'No' }, function(choice) - wizard_data.use_compiledb = choice - finalize_setup() - end) -end +-- local function pick_compiledb() +-- small_menu('Generate Compilation Database (LSP)?', { 'Yes', 'No' }, function(choice) +-- wizard_data.use_compiledb = choice +-- finalize_setup() +-- end) +-- end -- Step 3: Sample Code local function pick_sample() small_menu('Include Sample Code?', { 'Yes', 'No' }, function(choice) wizard_data.sample = choice - pick_compiledb() + -- pick_compiledb() + finalize_setup() end) end @@ -86,7 +83,6 @@ local function pick_framework(board_details) end -- Step 1: Board (Entry Point) - local function pick_board(json_data) pickers .new({}, { diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 4435e230..c840559a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -417,7 +417,7 @@ M.run_sequence = function(tasks) callBack = tasks.cb -- 1. Save the callback in a local variable - commandPassed = 0 + commandPassed = 1 _G.metadata.isBusy = true term.stdout_callback = M.stdoutcallback @@ -442,30 +442,23 @@ function M.handlePioinitDb(result) term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'PASS' then + -- if commandPassed == 1 then + -- elseif commandPassed == 2 then -- if you sned more than 2 commands you need this + -- end + vim.notify('PIO init+db: pass ' .. commandPassed, vim.log.levels.INFO) commandPassed = commandPassed + 1 - if commandPassed == 1 then - vim.schedule(function() - vim.notify('Pioinit: Done ..', vim.log.levels.INFO) - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen([[.clangd]], _G.metadata.core_dir) - end) - -- elseif commandPassed == 2 then -- if you sned more than 2 commands you need this - end term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'DONE' then -- result of the last command vim.schedule(function() - vim.notify('compiledb: Done ..', vim.log.levels.INFO) - M.queue = {} - term.stdout_callback = nil + vim.notify('PIO init+db: pass ' .. commandPassed, vim.log.levels.INFO) + vim.notify('PIO init+db: Done', vim.log.levels.INFO) + vim.misc.gitignore_lsp_configs('compile_commands.json') + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen([[.clangd]], _G.metadata.core_dir) + local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh('PIO init+db: ', function() - vim.misc.gitignore_lsp_configs('compile_commands.json') lsp_restart('clangd') - -- _G.metadata.dbTrigger = true - -- local ok, _ = pcall(M.compile_commandsFix) - -- if not ok then - -- print('Env: dbTrigger, fail to call dbFix') - -- end end) end) M.queue = {} @@ -480,40 +473,42 @@ end ------------------------------------------------------ -- Handle after pioinit execution -function M.handlePioinit(result) - if result == 'INIT' then - local boilerplate = require('platformio.boilerplate') - local boilerplate_gen = boilerplate.boilerplate_gen - - boilerplate.core_dir = _G.metadata.core_dir - boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) - - boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) - - boilerplate_gen([[.clangd]], vim.g.platformioRootDir) - -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) - -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') - - term.ToggleTerminal(table.remove(M.queue, 1), 'float') - elseif result == 'DONE' then -- result of the last command - vim.schedule(function() - vim.notify('Pioinit: Done ..', vim.log.levels.INFO) - local pio_refresh = require('platformio.pio_setup').pio_refresh - pio_refresh('PIO init: ', function() - vim.misc.gitignore_lsp_configs('compile_commands.json') - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen([[.clangd]], _G.metadata.core_dir) - end) - end) - M.queue = {} - term.stdout_callback = nil - _G.metadata.isBusy = false - elseif result == 'FAIL' then - M.queue = {} - term.stdout_callback = nil - _G.metadata.isBusy = false - end -end +-- function M.handlePioinit(result) +-- if result == 'INIT' then +-- local boilerplate = require('platformio.boilerplate') +-- local boilerplate_gen = boilerplate.boilerplate_gen +-- +-- boilerplate.core_dir = _G.metadata.core_dir +-- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) +-- +-- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) +-- +-- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +-- -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) +-- -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') +-- +-- term.ToggleTerminal(table.remove(M.queue, 1), 'float') +-- elseif result == 'DONE' then -- result of the last command +-- vim.notify('PIO init: pass ' .. commandPassed, vim.log.levels.INFO) +-- vim.notify('PIO init: Done', vim.log.levels.INFO) +-- commandPassed = commandPassed + 1 +-- vim.misc.gitignore_lsp_configs('compile_commands.json') +-- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +-- boilerplate_gen([[.clangd]], _G.metadata.core_dir) +-- +-- local pio_refresh = require('platformio.pio_setup').pio_refresh +-- pio_refresh('PIO init: ', function() +-- lsp_restart('clangd') +-- end) +-- M.queue = {} +-- term.stdout_callback = nil +-- _G.metadata.isBusy = false +-- elseif result == 'FAIL' then +-- M.queue = {} +-- term.stdout_callback = nil +-- _G.metadata.isBusy = false +-- end +-- end ------------------------------------------------------ -- Handle after piolib execution @@ -521,7 +516,9 @@ function M.handlePiolib(result) if result == 'INIT' then term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'DONE' then -- result of the only and the last command - vim.notify('Piolib: Success', vim.log.levels.INFO) + vim.notify('PIO lib: pass ' .. commandPassed, vim.log.levels.INFO) + vim.notify('PIO lib: Done', vim.log.levels.INFO) + commandPassed = commandPassed + 1 M.queue = {} term.stdout_callback = nil _G.metadata.isBusy = false @@ -536,7 +533,9 @@ function M.handlePiodb(target, result) if result == 'INIT' then term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'DONE' then -- result of the only and the last command - vim.notify('Piodb: Success', vim.log.levels.INFO) + vim.notify('PIO db: pass ' .. commandPassed, vim.log.levels.INFO) + vim.notify('PIO db: Done', vim.log.levels.INFO) + commandPassed = commandPassed + 1 target.isBusy = false M.queue = {} term.stdout_callback = nil From ee6ecf6772fb104692ba5df2fcb05a3bfaa4a618 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 23:22:46 +0300 Subject: [PATCH 1270/1406] update --- lua/platformio/utils/pio.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index c840559a..b28e21c8 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -148,11 +148,12 @@ function M.fetch_metadata(callback, env, from, attempts) --------------------------------------------------------- -- STEP 3: Auto-Initialize (If files are missing) --------------------------------------------------------- - if not current_checksum then + if not ok or not current_checksum then vim.notify(msg .. 'Initializing project metadata...', vim.log.levels.WARN) vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env }, { text = true }, function(obj) vim.schedule(function() if obj.code == 0 then + vim.notify(msg .. 'Initializing project metadata success.', vim.log.levels.ERROR) M.fetch_metadata(callback, active_env, from, attempts - 1) -- Recursive call after files created else vim.notify(msg .. 'Initialization failed. Build project manually.', vim.log.levels.ERROR) From bef94d00fc710895f45e4bd2c1c05c7d6da7e907 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 23:28:33 +0300 Subject: [PATCH 1271/1406] update --- lua/platformio/utils/pio.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index b28e21c8..d2ab75e0 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -253,7 +253,7 @@ function M.fetch_config(from) break end end - meta.active_env = active_env or '' + meta.active_env = active_env -- 5. Resolve Paths (INI -> Env -> Default) local path_map = { @@ -283,6 +283,7 @@ function M.fetch_config(from) end end) end) + vim.notify(msg .. 'active_env= ' .. active_env, vim.log.levels.INFO) return active_env end From 62c5991f75572af11031d118ea8fe423f21e9ac7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 30 Apr 2026 23:34:29 +0300 Subject: [PATCH 1272/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index d2ab75e0..3b0512b9 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -275,6 +275,7 @@ function M.fetch_config(from) end end + vim.notify(msg .. 'active_env= ' .. active_env, vim.log.levels.INFO) -- 6. Trigger next step if meta.active_env ~= '' then vim.notify(msg .. 'Config sync successful', vim.log.levels.INFO) @@ -283,7 +284,6 @@ function M.fetch_config(from) end end) end) - vim.notify(msg .. 'active_env= ' .. active_env, vim.log.levels.INFO) return active_env end From edde844930e609a9f8023bb2c4c47ad518ebb32f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 00:11:49 +0300 Subject: [PATCH 1273/1406] update --- lua/platformio/pio_setup.lua | 9 ++++++--- lua/platformio/utils/pio.lua | 38 ++++++++++++++++++++++++++++++++++-- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 7e83fe46..e1de75a8 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -12,10 +12,13 @@ local boilerplate_gen = boilerplate.boilerplate_gen function M.pio_refresh(callback, from) local msg = (type(from)=='string' and from ~= '') and from or 'PIO: ' vim.notify(msg ..'Config sync ...', vim.log.levels.INFO) - local active_env = vim.pio.fetch_config(from) - if active_env then - vim.pio.fetch_metadata(callback, active_env, from, 1) + + local function on_done(active_env) + if active_env then + vim.pio.fetch_metadata(callback, active_env, from, 1) + end end + vim.pio.fetch_config(on_done, from) end -- ============================================================================= diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 3b0512b9..0f540b9b 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -190,7 +190,38 @@ function M.fetch_metadata(callback, env, from, attempts) -- end) end +-- ============================================================================= +-- stylua: ignore +function M.pioConfig(callback) + -- 'pio project config --json' is the only way to get FINAL computed paths + vim.system({ 'pio', 'project', 'config', '--json' }, { text = true }, function(obj) + if obj.code ~= 0 then return end + + local ok, data = pcall(vim.json.decode, obj.stdout) + if not ok or type(data) ~= 'table' then return end + + local paths = {} + -- PlatformIO JSON output groups options by section + for _, section_data in pairs(data) do + for _, item in ipairs(section_data) do + if item.option == 'core_dir' then paths.core = item.value end + if item.option == 'packages_dir' then paths.packages = item.value end + if item.option == 'platforms_dir' then paths.platforms = item.value end + end + end + -- Fill in defaults if not explicitly overridden + local home = vim.uv.os_homedir() + paths.core = paths.core or (home .. '/.platformio') + paths.packages = paths.packages or (paths.core .. '/packages') + paths.platforms = paths.platforms or (paths.core .. '/platforms') + + vim.schedule(function() + _G.metadata.paths = paths -- Cache the results + if callback then callback(paths) end + end) + end) +end -- INFO: @@ -198,7 +229,7 @@ end -- Get project infomation -- ============================================================================= -- stylua: ignore -function M.fetch_config(from) +function M.fetch_config(on_done, from) local msg = (type(from) == 'string' and from ~= '') and from or 'PIO: ' local meta = _G.metadata local home = (os.getenv('HOME') or os.getenv('USERPROFILE') or ''):gsub('[\\/]+$', '') @@ -282,9 +313,12 @@ function M.fetch_config(from) else vim.notify(msg .. 'No [env:] found. Please add a board.', vim.log.levels.ERROR) end + + if on_done then + vim.schedule(function() on_done(active_env) end) + end end) end) - return active_env end -- INFO: From feb429facb9cadd453c4211fb20da3b21fcbfb0e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 00:18:36 +0300 Subject: [PATCH 1274/1406] update --- lua/platformio/pio_setup.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index e1de75a8..362ba83f 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -15,9 +15,11 @@ function M.pio_refresh(callback, from) local function on_done(active_env) if active_env then + print(active_env) vim.pio.fetch_metadata(callback, active_env, from, 1) end end + vim.pio.fetch_config(on_done, from) end From e4ee0b58a9349951ddd72a52b7ed8abddc8309f6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 00:37:51 +0300 Subject: [PATCH 1275/1406] update --- lua/platformio/utils/pio.lua | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 0f540b9b..d7b65faf 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -139,7 +139,15 @@ function M.fetch_metadata(callback, env, from, attempts) local metadata = require('platformio.metadata') metadata.save_project_config() vim.notify(msg .. 'Metadata synced from cache', vim.log.levels.INFO) - if callback then vim.schedule(callback) end + -- if callback then vim.schedule(callback) end + + if type(callback) == "function" then + vim.schedule(callback) + else + -- If it's not a function, just do nothing or print a debug message + print("Debug: callback was " .. type(callback)) + end + return true end end @@ -493,9 +501,9 @@ function M.handlePioinitDb(result) boilerplate_gen([[.clangd]], _G.metadata.core_dir) local pio_refresh = require('platformio.pio_setup').pio_refresh - pio_refresh('PIO init+db: ', function() + pio_refresh(function() lsp_restart('clangd') - end) + end, 'PIO init+db: ') end) M.queue = {} term.stdout_callback = nil From 70ee8141d85de49319c4b1989dedb1524f9cff44 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 01:13:13 +0300 Subject: [PATCH 1276/1406] update --- lua/platformio/pio_setup.lua | 148 ++++++++------------------ lua/platformio/utils/misc.lua | 56 ---------- lua/platformio/utils/pio.lua | 191 ++++++++++++++++++++-------------- 3 files changed, 158 insertions(+), 237 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 362ba83f..31cfedc9 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -4,42 +4,48 @@ M = {} local boilerplate = require('platformio.boilerplate') local boilerplate_gen = boilerplate.boilerplate_gen +-- ============================================================================= +-- INFO: +-- Unified hashing for change detection +local function get_hash(path) + if vim.fn.filereadable(path) == 0 then + return nil + end + -- local ok, data = pcall(vim.fn.readfile, path) -- readfile is safer than io.open + -- return ok and vim.fn.sha256(table.concat(data, '\n')) or nil + local ok, data = vim.misc.readFile(path) -- readfile is safer than io.open + return (ok and type(data) == 'string' and data ~= '') and vim.fn.sha256(data) or '' +end --- local debounce_timer = vim.uv.new_timer() --- ============================================================================= --- stylua: ignore +--INFO: +--stylua: ignore +--============================================================================= function M.pio_refresh(callback, from) local msg = (type(from)=='string' and from ~= '') and from or 'PIO: ' vim.notify(msg ..'Config sync ...', vim.log.levels.INFO) local function on_done(active_env) - if active_env then - print(active_env) - vim.pio.fetch_metadata(callback, active_env, from, 1) - end + if active_env then vim.pio.fetch_metadata(callback, active_env, from, 1) end end vim.pio.fetch_config(on_done, from) end --- ============================================================================= --- INFO: --- 1. Helper: Unified hashing for change detection -local function get_hash(path) - if vim.fn.filereadable(path) == 0 then - return nil - end - -- local ok, data = pcall(vim.fn.readfile, path) -- readfile is safer than io.open - -- return ok and vim.fn.sha256(table.concat(data, '\n')) or nil - local ok, data = vim.misc.readFile(path) -- readfile is safer than io.open - return (ok and type(data) == 'string' and data ~= '') and vim.fn.sha256(data) or '' -end +--INFO: +--============================================================================= +-- watchers setup +--============================================================================= +-- Ensure this is at the TOP of your file, outside any functions +local uv = vim.uv or vim.loop +M.watcher_handles = {} +local debounce_timer = uv.new_timer() +local last_mtime = 0 --- ============================================================================= --- stylua: ignore --INFO: --- 1.run_compiledb +--stylua: ignore +--1.run_compiledb after platformio.ini changed +--============================================================================= function M.run_compiledb(target) -- 1. Prevent overlapping builds if target.isBusy then return end @@ -57,7 +63,7 @@ function M.run_compiledb(target) -- end -- }) - local env = vim.misc.get_active__env() + local env = vim.pio.get_active__env() -- if env and env ~= '' then vim.notify('PIO platformio.ini change: update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) -- vim.schedule(function() @@ -85,18 +91,10 @@ function M.run_compiledb(target) -- end end --- ============================================================================= --INFO: --- Ensure this is at the TOP of your file, outside any functions -local uv = vim.uv or vim.loop -M.watcher_handles = {} -local debounce_timer = uv.new_timer() -local last_mtime = 0 - --- ============================================================================= --- stylua: ignore ---INFO: --- 2.stop_watchers +--stylua: ignore +--2.stop_watchers +--============================================================================= function M.stop_watchers() if not M.watcher_handles or (type(M.watcher_handles) ~= 'table') then M.watcher_handles = {} return end @@ -109,10 +107,10 @@ function M.stop_watchers() M.watcher_handles = {} end --- ============================================================================= --- stylua: ignore --INFO: --- 3.watcher cleanup +--stylua: ignore +--3.watcher cleanup +--============================================================================= function M.cleanup() M.stop_watchers() if debounce_timer and not debounce_timer:is_closing() then @@ -120,8 +118,7 @@ function M.cleanup() debounce_timer:close() end end --- ============================================================================= ---INFO: + -- Force cleanup when leaving Neovim to prevent :qa lag vim.api.nvim_create_autocmd('VimLeavePre', { callback = function() @@ -129,8 +126,10 @@ vim.api.nvim_create_autocmd('VimLeavePre', { end, }) --- stylua: ignore --- 3. MAIN WATCHER: Efficient Folder Monitoring +--INFO: +--stylua: ignore +--4. MAIN WATCHER: Efficient Folder Monitoring +--============================================================================= local function watch_file(target, callback) local folder_path = target.path:match('(.*[/\\])') local target_filename = target.path:match('[^/\\]+$') @@ -196,67 +195,11 @@ local function watch_file(target, callback) table.insert(M.watcher_handles, handle) return handle end --- ============================================================================= --- stylua: ignore ---INFO: --- 4. watch_file --- stylua: ignore --- local function watch_file(target, callback) --- local handle = uv.new_fs_poll() --- if not handle then return end --- --- -- handle:start(target.path, 1000, function(err, stat) --- -- if err or not stat then return end --- -- --- -- if debounce_timer then --- -- debounce_timer:stop() --- -- -- Define the logic in a local variable so it can "call itself" for retries --- -- local function attempt_callback() --- -- if target.isBusy then --- -- -- Retry in 1000ms if still busy --- -- debounce_timer:start(1500, 0, vim.schedule_wrap(attempt_callback)) --- -- return --- -- end --- -- --- -- local filestat = uv.fs_stat(target.path) --- -- if filestat and filestat.type == 'file' then callback(target) end --- -- end --- -- -- Initial start --- -- debounce_timer:start(1500, 0, vim.schedule_wrap(attempt_callback)) --- -- end --- -- end) --- --- -- Poll every 1000ms. This is light on CPU and ignores "save noise". --- -- handle:start(target.path, 1000, function(err, stat) --- -- -- if err or not stat or (target and target.isBusy) then return end --- -- if err or not stat then return end --- -- --- -- -- 2. Debounce: Reset the timer on every event --- -- -- Only after 500ms of "silence" will the actual callback run --- -- if debounce_timer then --- -- -- Stop any existing timer to "debounce" --- -- if debounce_timer:is_active() then debounce_timer:stop() end --- -- debounce_timer:start(500, 0, vim.schedule_wrap(function() --- -- -- vim.schedule(function () --- -- local filestat = uv.fs_stat(target.path) --- -- if filestat and filestat.type == 'file' then --- -- callback(target) --- -- end --- -- -- if vim.loop.fs_stat(target.path) then callback(target) end --- -- -- end) --- -- end)) --- -- end --- -- end) --- --- table.insert(M.watcher_handles, handle) --- return handle --- end - --- ============================================================================= --- stylua: ignore --INFO: --- 5. start_watches +--stylua: ignore +--5. start_watches +--============================================================================= function M.start_watchers() -- Clean up any existing watchers first to prevent duplicates if next(M.watcher_handles) then M.stop_watchers() end @@ -304,7 +247,6 @@ function M.start_watchers() end }, } - -- targets[1].last_hash = get_hash(targets[1].path) or '' for _, target in ipairs(targets) do --[[ wrap the callback in a small anonymous function, @@ -313,9 +255,9 @@ function M.start_watchers() end end --- ============================================================================= --- stylua: ignore --INFO: 6. Exported setup function +--stylua: ignore +--============================================================================= function M.init() local config = require('platformio').config if config.lspClangd.enabled == true then diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 427448cd..5b9ab04c 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -25,62 +25,6 @@ function M.delete_file(path) vim.notify('PlatformIO: ' .. file .. ' file not found', vim.log.levels.WARN) end end ------------------------------------------------------- ---INFO: --- stylua: ignore --- Fast environment detection (no external calls) -function M.get_active__env() - local path - - for _, dir in ipairs({ vim.api.nvim_buf_get_name(0):match('(.*[/\\])'), (vim.uv.cwd() .. '/') }) do - local tmp = dir .. 'platformio.ini' - local filestat = vim.uv.fs_stat(tmp) - if filestat and filestat.type == 'file' then - path = vim.fs.normalize(tmp) - break - end - end - if not path or path == '' then return vim.notify('PIO: platformio.ini not found or no [env] defined.', vim.log.levels.ERROR) end - - -- Read file content (returns string or nil) - local ok, content = vim.misc.readFile(path) - if not ok or not content then return vim.notify('PIO: platformio.ini not found in ' .. path, vim.log.levels.WARN) end - - local default_envs_raw = '' - local first_env = nil - local valid_envs = {} - local in_platformio_block = false - - -- Iterate lines from the content string - for line in vim.gsplit(content, '\n') do - -- Section Detection: [section_name] - local section = line:match('^%s*%[(.+)%]%s*$') - if section then - in_platformio_block = (section == 'platformio') - local env_name = section:match('^env:(.+)') - if env_name then - if not first_env then first_env = env_name end - valid_envs[env_name] = true - end - end - - -- Collect the default_envs string from [platformio] block - if in_platformio_block then - local def = line:match('^%s*default_envs%s*=%s*(.+)') - if def then default_envs_raw = def end - end - end - - -- Validation: Find the first default_env that actually exists as a block - if default_envs_raw ~= '' then - for env_name in default_envs_raw:gmatch('([^%s,]+)') do - if valid_envs[env_name] then return env_name end - end - end - - -- Fallback to the very first [env:...] block found in the file - return first_env -end ------------------------------------------------------ --INFO: diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index d7b65faf..c1639156 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -62,9 +62,68 @@ function M.get_sysroot_triplet(cc_compiler) return nil end --- INFO:------------------------------------------------- +--INFO: +-- Fast environment detection from platformio.ini file(no external calls) +-- stylua: ignore +--============================================================================= +function M.get_active__env() + local path + + for _, dir in ipairs({ vim.api.nvim_buf_get_name(0):match('(.*[/\\])'), (vim.uv.cwd() .. '/') }) do + local tmp = dir .. 'platformio.ini' + local filestat = vim.uv.fs_stat(tmp) + if filestat and filestat.type == 'file' then + path = vim.fs.normalize(tmp) + break + end + end + if not path or path == '' then return vim.notify('PIO: platformio.ini not found or no [env] defined.', vim.log.levels.ERROR) end + + -- Read file content (returns string or nil) + local ok, content = vim.misc.readFile(path) + if not ok or not content then return vim.notify('PIO: platformio.ini not found in ' .. path, vim.log.levels.WARN) end + + local default_envs_raw = '' + local first_env = nil + local valid_envs = {} + local in_platformio_block = false + + -- Iterate lines from the content string + for line in vim.gsplit(content, '\n') do + -- Section Detection: [section_name] + local section = line:match('^%s*%[(.+)%]%s*$') + if section then + in_platformio_block = (section == 'platformio') + local env_name = section:match('^env:(.+)') + if env_name then + if not first_env then first_env = env_name end + valid_envs[env_name] = true + end + end + + -- Collect the default_envs string from [platformio] block + if in_platformio_block then + local def = line:match('^%s*default_envs%s*=%s*(.+)') + if def then default_envs_raw = def end + end + end + + -- Validation: Find the first default_env that actually exists as a block + if default_envs_raw ~= '' then + for env_name in default_envs_raw:gmatch('([^%s,]+)') do + if valid_envs[env_name] then return env_name end + end + end + + -- Fallback to the very first [env:...] block found in the file + return first_env +end + + +-- INFO: -- get pio project metadata info -- stylua: ignore +--============================================================================= function M.fetch_metadata(callback, env, from, attempts) local msg = (type(from)=='string' and from ~= '') and from or 'PIO: ' local meta = _G.metadata @@ -198,43 +257,44 @@ function M.fetch_metadata(callback, env, from, attempts) -- end) end --- ============================================================================= +-- INFO: -- stylua: ignore -function M.pioConfig(callback) - -- 'pio project config --json' is the only way to get FINAL computed paths - vim.system({ 'pio', 'project', 'config', '--json' }, { text = true }, function(obj) - if obj.code ~= 0 then return end - - local ok, data = pcall(vim.json.decode, obj.stdout) - if not ok or type(data) ~= 'table' then return end - - local paths = {} - -- PlatformIO JSON output groups options by section - for _, section_data in pairs(data) do - for _, item in ipairs(section_data) do - if item.option == 'core_dir' then paths.core = item.value end - if item.option == 'packages_dir' then paths.packages = item.value end - if item.option == 'platforms_dir' then paths.platforms = item.value end - end - end - - -- Fill in defaults if not explicitly overridden - local home = vim.uv.os_homedir() - paths.core = paths.core or (home .. '/.platformio') - paths.packages = paths.packages or (paths.core .. '/packages') - paths.platforms = paths.platforms or (paths.core .. '/platforms') - - vim.schedule(function() - _G.metadata.paths = paths -- Cache the results - if callback then callback(paths) end - end) - end) -end +--============================================================================= +-- function M.pioConfig(callback) +-- -- 'pio project config --json' is the only way to get FINAL computed paths +-- vim.system({ 'pio', 'project', 'config', '--json' }, { text = true }, function(obj) +-- if obj.code ~= 0 then return end +-- +-- local ok, data = pcall(vim.json.decode, obj.stdout) +-- if not ok or type(data) ~= 'table' then return end +-- +-- local paths = {} +-- -- PlatformIO JSON output groups options by section +-- for _, section_data in pairs(data) do +-- for _, item in ipairs(section_data) do +-- if item.option == 'core_dir' then paths.core = item.value end +-- if item.option == 'packages_dir' then paths.packages = item.value end +-- if item.option == 'platforms_dir' then paths.platforms = item.value end +-- end +-- end +-- +-- -- Fill in defaults if not explicitly overridden +-- local home = vim.uv.os_homedir() +-- paths.core = paths.core or (home .. '/.platformio') +-- paths.packages = paths.packages or (paths.core .. '/packages') +-- paths.platforms = paths.platforms or (paths.core .. '/platforms') +-- +-- vim.schedule(function() +-- _G.metadata.paths = paths -- Cache the results +-- if callback then callback(paths) end +-- end) +-- end) +-- end -- INFO: -- ============================================================================= --- Get project infomation +-- Get project configuration -- ============================================================================= -- stylua: ignore function M.fetch_config(on_done, from) @@ -314,7 +374,9 @@ function M.fetch_config(on_done, from) end end - vim.notify(msg .. 'active_env= ' .. active_env, vim.log.levels.INFO) + if active_env then + vim.notify(msg .. 'active_env= ' .. active_env, vim.log.levels.INFO) + end -- 6. Trigger next step if meta.active_env ~= '' then vim.notify(msg .. 'Config sync successful', vim.log.levels.INFO) @@ -330,10 +392,9 @@ function M.fetch_config(on_done, from) end -- INFO: --- ============================================================================= --- UNIVERSAL TOOLCHAIN DETECTION --- ============================================================================= +-- Fix compile_commands.json file with absoulute paths -- stylua: ignore +-- ============================================================================= function M.compile_commandsFix() --M.dbPathsFix() local filename = vim.fs.joinpath(vim.uv.cwd(), 'compile_commands.json') local content = vim.fn.readfile(filename) @@ -410,11 +471,18 @@ function M.compile_commandsFix() --M.dbPathsFix() _G.metadata.isBusy = false end + +-- INFO: +--configuration for running sequential commands on ToggleTerminal +-- stylua: ignore +-- ============================================================================= +-- ============================================================================= local callBack = nil local pio_buffer = '' -- Persistent stream buffer ------------------------------------------------------- + -- INFO: ToggleTerminal commands stdout filter -- stylua: ignore +-- ============================================================================= function M.stdoutcallback(_, _, data) if not data then return end @@ -441,9 +509,11 @@ function M.stdoutcallback(_, _, data) end local commandPassed = 0 ------------------------------------------------------- + + -- INFO: commands sequencer -- stylua: ignore +-- ============================================================================= M.run_sequence = function(tasks) M.queue = {} local commands = tasks.cmnds @@ -470,6 +540,7 @@ end ------------------------------------------------------ -- Handle after pioinit execution +-- ============================================================================= function M.handlePioinitDb(result) if result == 'INIT' then local boilerplate = require('platformio.boilerplate') @@ -515,47 +586,9 @@ function M.handlePioinitDb(result) end end ------------------------------------------------------- --- Handle after pioinit execution --- function M.handlePioinit(result) --- if result == 'INIT' then --- local boilerplate = require('platformio.boilerplate') --- local boilerplate_gen = boilerplate.boilerplate_gen --- --- boilerplate.core_dir = _G.metadata.core_dir --- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) --- --- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) --- --- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) --- -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --- -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') --- --- term.ToggleTerminal(table.remove(M.queue, 1), 'float') --- elseif result == 'DONE' then -- result of the last command --- vim.notify('PIO init: pass ' .. commandPassed, vim.log.levels.INFO) --- vim.notify('PIO init: Done', vim.log.levels.INFO) --- commandPassed = commandPassed + 1 --- vim.misc.gitignore_lsp_configs('compile_commands.json') --- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen --- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --- --- local pio_refresh = require('platformio.pio_setup').pio_refresh --- pio_refresh('PIO init: ', function() --- lsp_restart('clangd') --- end) --- M.queue = {} --- term.stdout_callback = nil --- _G.metadata.isBusy = false --- elseif result == 'FAIL' then --- M.queue = {} --- term.stdout_callback = nil --- _G.metadata.isBusy = false --- end --- end - ------------------------------------------------------ -- Handle after piolib execution +-- ============================================================================= function M.handlePiolib(result) if result == 'INIT' then term.ToggleTerminal(table.remove(M.queue, 1), 'float') @@ -573,6 +606,8 @@ function M.handlePiolib(result) end end +------------------------------------------------------ +-- ============================================================================= function M.handlePiodb(target, result) if result == 'INIT' then term.ToggleTerminal(table.remove(M.queue, 1), 'float') From 420b4f73302b9fae9bf255c876c3654fc62921f2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 04:05:27 +0300 Subject: [PATCH 1277/1406] update --- lua/platformio/utils/pio.lua | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index c1639156..2d350a2f 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -192,8 +192,22 @@ function M.fetch_metadata(callback, env, from, attempts) -- STEP 2: Cache Path (idedata.json exists and checksum changed) local idok, content = vim.misc.readFile(idedata_file) + + + + + if idok and (type(content) == 'string' and content ~= '') then local cok, decoded = pcall(vim.json.decode, content) + + + local formated = vim.misc.jsonFormat(decoded) + local file = vim.misc.joinPath(vim.uv.cwd(), 'idedata.json') + vim.misc.writeFile(file, formated, {}) + + + + if cok and apply_metadata(decoded, current_checksum) then local metadata = require('platformio.metadata') metadata.save_project_config() From 99a37191c6e20b4479a330cc9b43c12feb138edd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 04:53:29 +0300 Subject: [PATCH 1278/1406] update --- lua/platformio/utils/misc.lua | 13 +++++++++++-- lua/platformio/utils/pio.lua | 7 ------- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 5b9ab04c..3e632408 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -51,7 +51,16 @@ function M.jsonFormat(root_data) if type(val) == 'table' then -- 1. Determine if Array or Object - local is_array = (#val > 0) or (next(val) == nil) + local is_array = false + + -- Check if it's explicitly marked as an array by the Neovim parser + local mt = getmetatable(val) + if mt and mt.__jsontype == 'array' then + is_array = true + -- If not marked, check if it has indexed items or is literally an empty table + elseif #val > 0 or next(val) == nil then + is_array = true + end if curr.stage == 'start' then table.insert(buffer, (is_array and '[' or '{') .. '\n') @@ -89,7 +98,7 @@ function M.jsonFormat(root_data) else -- 4. Primitives (String, Number, Bool, Nil) local output = '' - if val == nil then output = 'null' + if val == nil or val == vim.NIL then output = 'null' elseif type(val) == 'boolean' then output = tostring(val) elseif type(val) == 'string' then -- Normalize Windows paths to Unix for cross-platform checksums diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 2d350a2f..e1397e81 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -192,11 +192,6 @@ function M.fetch_metadata(callback, env, from, attempts) -- STEP 2: Cache Path (idedata.json exists and checksum changed) local idok, content = vim.misc.readFile(idedata_file) - - - - - if idok and (type(content) == 'string' and content ~= '') then local cok, decoded = pcall(vim.json.decode, content) @@ -206,8 +201,6 @@ function M.fetch_metadata(callback, env, from, attempts) vim.misc.writeFile(file, formated, {}) - - if cok and apply_metadata(decoded, current_checksum) then local metadata = require('platformio.metadata') metadata.save_project_config() From 8bb749fbc029494476ee690d7b841db73c463dfb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 05:29:27 +0300 Subject: [PATCH 1279/1406] update --- lua/platformio/utils/misc.lua | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 3e632408..63df296c 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -44,6 +44,17 @@ function M.jsonFormat(root_data) local function get_indent(lvl) return string.rep(' ', lvl) end + -- Full JSON Escape Table + local escapes = { + ['\\'] = '\\\\', + ['"'] = '\\"', + ['\b'] = '\\b', + ['\f'] = '\\f', + ['\n'] = '\\n', + ['\r'] = '\\r', + ['\t'] = '\\t', + } + while #stack > 0 do local curr = stack[#stack] local val, lvl = curr.val, curr.lvl @@ -99,10 +110,22 @@ function M.jsonFormat(root_data) -- 4. Primitives (String, Number, Bool, Nil) local output = '' if val == nil or val == vim.NIL then output = 'null' + elseif val == vim.empty_dict then output = '{}' elseif type(val) == 'boolean' then output = tostring(val) elseif type(val) == 'string' then - -- Normalize Windows paths to Unix for cross-platform checksums - output = '"' .. val:gsub('\\', '/'):gsub('"', '\\"') .. '"' + -- A. Handle standard escapes (\n, \t, etc.) + local s = val:gsub('[\\"\b\f\n\r\t]', escapes) + + -- B. Handle unprintable control characters (U+0000 to U+001F) + s = s:gsub('[%z\1-\31]', function(c) + return string.format('\\u%04x', string.byte(c)) + end) + + -- C. Normalize Windows paths to Unix for cross-platform SHA256 stability + -- We flip double-backslashes (\\) resulting from the escape to (/) + s = s:gsub('\\\\', '/') + + output = '"' .. s .. '"' else output = tostring(val) end table.insert(buffer, output) table.remove(stack) From b1fbb30b08e25b8162a8e840e80c541a7962d5d7 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 05:37:02 +0300 Subject: [PATCH 1280/1406] update --- lua/platformio/utils/misc.lua | 91 +++++++++++++++++++++++++++-------- 1 file changed, 71 insertions(+), 20 deletions(-) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 63df296c..18e91377 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -172,54 +172,105 @@ end -- stylua: ignore -- local function pretty_print(data) -- 48ms function M.pretty_print(data) -- 48ms - -- Force input into a table if it's just a single string local buffer = {} + local insert = table.insert + + -- Table of standard JSON escape sequences + local escapes = { + ['\\'] = '\\\\', + ['"'] = '\\"', + ['\b'] = '\\b', + ['\f'] = '\\f', + ['\n'] = '\\n', + ['\r'] = '\\r', + ['\t'] = '\\t', + } local function format_item(item, current_level) - local insert = table.insert local indent = string.rep(' ', current_level) local next_indent = string.rep(' ', current_level + 1) + -- 1. Handle Neovim-specific Nulls and Empty Objects + -- vim.NIL represents a JSON 'null' (distinct from Lua nil) + if item == nil or item == vim.NIL then + insert(buffer, 'null') + return + elseif item == vim.empty_dict then + insert(buffer, '{}') + return + end + if type(item) == 'table' then - -- 1. TRULY EMPTY CHECK + -- 2. Determine if Table should be an Array [] or an Object {} + local is_array = false + local mt = getmetatable(item) + + -- If decoded by Neovim, it likely has a __jsontype marker + if mt and mt.__jsontype == 'array' then is_array = true + -- If not marked, treat as array if it has indexed items or is a plain empty table + elseif #item > 0 or (next(item) == nil and mt == nil) then is_array = true end + + -- 3. Handle Empty Structures Immediately if next(item) == nil then - -- In PIO metadata, most empty fields are intended to be arrays [] - -- But we use {} as a safe JSON default for generic tables. - insert(buffer, '{}') + insert(buffer, is_array and '[]' or '{}') return end - -- 2. DETERMINE IF ARRAY OR OBJECT - -- A table is an array if it has a value at index 1 - local is_array = item[1] ~= nil local opener = is_array and '[' or '{' local closer = is_array and ']' or '}' - insert(buffer, opener .. '\n') - -- 3. SORT KEYS (Crucial for consistent SHA256 hashes) + -- 4. Key Management & Sorting + -- Sorting is mandatory for consistent SHA256 hashes across different systems local keys = {} - for k in pairs(item) do table.insert(keys, k) end - if not is_array then table.sort(keys) end + for k in pairs(item) do insert(keys, k) end - local first = true - for _, k in ipairs(keys) do + -- Sort object keys alphabetically + if not is_array then table.sort(keys, function(a, b) return tostring(a) < tostring(b) end) + -- Ensure array indices [1, 2, 3] are processed in order + else table.sort(keys) end + + -- 5. Iterate through items + for i, k in ipairs(keys) do local v = item[k] - if not first then insert(buffer, ',\n') end + if i > 1 then insert(buffer, ',\n') end -- Standard JSON comma placement insert(buffer, next_indent) + -- If it's an object, add the "key": prefix if not is_array then insert(buffer, '"' .. tostring(k) .. '": ') end + -- Recurse for nested tables format_item(v, current_level + 1) - first = false end + insert(buffer, '\n' .. indent .. closer) + elseif type(item) == 'string' then - -- Escape backslashes for Windows paths and quotes - insert(buffer, '"' .. item:gsub('[\\]+', '/'):gsub('"', '\\"') .. '"') - else insert(buffer, tostring(item)) end + -- 6. String Escaping & Path Normalization + -- A. Apply standard escapes (newline, tab, etc.) + local s = item:gsub('[\\"\b\f\n\r\t]', escapes) + + -- B. Convert unprintable control characters to \u00xx format + s = s:gsub('[%z\1-\31]', function(c) + return string.format('\\u%04x', string.byte(c)) + end) + + -- C. Normalize Windows paths to Unix style + -- We flip double-backslashes (\\) to (/) so SHA256 matches across OSs + s = s:gsub('\\\\', '/') + + insert(buffer, '"' .. s .. '"') + + elseif type(item) == 'boolean' or type(item) == 'number' then + -- 7. Primitives + insert(buffer, tostring(item)) + else + -- 8. Fallback for anything else + insert(buffer, '"' .. tostring(item) .. '"') + end end + -- Start recursion at level 0 format_item(data, 0) return table.concat(buffer) end From a903be91d530e1575352c66e19270d3a768f6d5e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 05:45:22 +0300 Subject: [PATCH 1281/1406] update --- lua/platformio/utils/pio.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index e1397e81..bf209945 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -179,7 +179,7 @@ function M.fetch_metadata(callback, env, from, attempts) end --------------------------------------------------------- - -- STEP 1: Fast Checksum Check + -- STEP 1: Fast Checksum Check (project.checksum and idedata.json) --------------------------------------------------------- local ok, current_checksum = vim.misc.readFile(checksum_file) if ok and (type(current_checksum) == 'string' and current_checksum ~= '') then @@ -220,11 +220,11 @@ function M.fetch_metadata(callback, env, from, attempts) end --------------------------------------------------------- - -- STEP 3: Auto-Initialize (If files are missing) + -- STEP 3: Auto-Initialize (If files project.checksum and idedata.json are missing) --------------------------------------------------------- if not ok or not current_checksum then vim.notify(msg .. 'Initializing project metadata...', vim.log.levels.WARN) - vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env }, { text = true }, function(obj) + vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env, '-s' }, { text = true }, function(obj) vim.schedule(function() if obj.code == 0 then vim.notify(msg .. 'Initializing project metadata success.', vim.log.levels.ERROR) From f5fda16bafd6906465f5c75a5f5a17fcee9b1557 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 05:58:08 +0300 Subject: [PATCH 1282/1406] update --- lua/platformio/boilerplate.lua | 49 +++++++++++++++++----------------- 1 file changed, 25 insertions(+), 24 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 5a1d386e..baf37c23 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -33,7 +33,7 @@ boilerplate['platformio.ini'] = { core_dir = %s platforms_dir = ${platformio.core_dir}/platforms packages_dir = ${platformio.core_dir}/packages -libdeps_dir = ./external_libs +;libdeps_dir = ./external_libs default_envs = ;default_envs = uno, nodemcu @@ -53,9 +53,9 @@ extra_scripts = lib_ldf_mode = chain ;Library dependencies Finder ldf -[env:seeed_xiao_esp32c3] -platform = espressif32 -board = seeed_xiao_esp32c3 +;[env:seeed_xiao_esp32c3] +;platform = espressif32 +;board = seeed_xiao_esp32c3 ]], content = function(self) @@ -170,6 +170,27 @@ boilerplate['.clangd_config'] = { -- External: -- File: .clangd_index +-- CompileFlags: +-- Add: +-- - "-xc++" +-- - "-std=c++17" +-- Remove: +-- - "-Winclude-next-outside-header" +-- - "-fno-fat-lto-objects" +-- - "-fno%%-fat%%-lto%%-objects" +-- - "-fno%%-canonical%%-system%%-headers" +-- - "-misc-definitions-in-headers" +-- - "-fno-tree-switch-conversion" +-- - "-mtext-section-literals" +-- - "-mlong-calls" +-- - "-mlongcalls" +-- - "-fstrict-volatile-bitfields" +-- - "-free*" +-- - "-fipa-pta*" +-- - "-march=*" +-- - "-mabi=*" +-- - "-mcpu=*" + -- INFO: .clangd -- boilerplate['.clangd'] = { boilerplate['.clangd'] = { @@ -179,26 +200,6 @@ boilerplate['.clangd'] = { -- - "-std=gnu++17" -- template = [[ content = [[ -CompileFlags: - Add: - - "-xc++" - - "-std=c++17" - Remove: - - "-Winclude-next-outside-header" - - "-fno-fat-lto-objects" - - "-fno%%-fat%%-lto%%-objects" - - "-fno%%-canonical%%-system%%-headers" - - "-misc-definitions-in-headers" - - "-fno-tree-switch-conversion" - - "-mtext-section-literals" - - "-mlong-calls" - - "-mlongcalls" - - "-fstrict-volatile-bitfields" - - "-free*" - - "-fipa-pta*" - - "-march=*" - - "-mabi=*" - - "-mcpu=*" Diagnostics: Suppress: - "misc-definitions-in-headers" From ed8e1efce179c7b5f1a5ab56eb1a065de748e6ea Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 06:04:27 +0300 Subject: [PATCH 1283/1406] update --- lua/platformio/pio_setup.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 31cfedc9..a20aaf4c 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -64,6 +64,7 @@ function M.run_compiledb(target) -- }) local env = vim.pio.get_active__env() + print(env) -- if env and env ~= '' then vim.notify('PIO platformio.ini change: update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) -- vim.schedule(function() From 89f6e1f79533d5cbd7e552f877a6de5bce66f24a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 06:15:08 +0300 Subject: [PATCH 1284/1406] update --- lua/platformio/pio_setup.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index a20aaf4c..f8305b72 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -49,6 +49,8 @@ local last_mtime = 0 function M.run_compiledb(target) -- 1. Prevent overlapping builds if target.isBusy then return end + local env = vim.pio.get_active__env() + if not env then return end target.isBusy = true _G.metadata.isBusy = true @@ -63,7 +65,6 @@ function M.run_compiledb(target) -- end -- }) - local env = vim.pio.get_active__env() print(env) -- if env and env ~= '' then vim.notify('PIO platformio.ini change: update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) From 352b57c4ab331c4e85d8ee425c03fc1ba1e61d89 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 06:29:07 +0300 Subject: [PATCH 1285/1406] update --- lua/platformio/pioinit.lua | 2 +- lua/platformio/utils/pio.lua | 39 ++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index d0a44ce2..dd9b713f 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -62,7 +62,7 @@ local function pick_framework(board_details) pio.run_sequence({ cmnds = { 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', - 'pio run -t compiledb', + -- 'pio run -t compiledb', }, cb = pio.handlePioinit, }) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index bf209945..b53c142b 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -593,6 +593,45 @@ function M.handlePioinitDb(result) end end +---------------------------------------------------- +-- Handle after pioinit execution +function M.handlePioinit(result) + if result == 'INIT' then + local boilerplate = require('platformio.boilerplate') + local boilerplate_gen = boilerplate.boilerplate_gen + + boilerplate.core_dir = _G.metadata.core_dir + boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) + + boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) + + boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) + -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') + + term.ToggleTerminal(table.remove(M.queue, 1), 'float') + elseif result == 'DONE' then -- result of the last command + vim.notify('PIO init: pass ' .. commandPassed, vim.log.levels.INFO) + vim.notify('PIO init: Done', vim.log.levels.INFO) + commandPassed = commandPassed + 1 + vim.misc.gitignore_lsp_configs('compile_commands.json') + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen([[.clangd]], _G.metadata.core_dir) + + local pio_refresh = require('platformio.pio_setup').pio_refresh + pio_refresh('PIO init: ', function() + lsp_restart('clangd') + end) + M.queue = {} + term.stdout_callback = nil + _G.metadata.isBusy = false + elseif result == 'FAIL' then + M.queue = {} + term.stdout_callback = nil + _G.metadata.isBusy = false + end +end + ------------------------------------------------------ -- Handle after piolib execution -- ============================================================================= From eba32661d92d6befec18cab97d95e3e2196fb5ca Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 06:37:08 +0300 Subject: [PATCH 1286/1406] update --- lua/platformio/utils/pio.lua | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index b53c142b..21f71bbb 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -611,16 +611,17 @@ function M.handlePioinit(result) term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'DONE' then -- result of the last command - vim.notify('PIO init: pass ' .. commandPassed, vim.log.levels.INFO) - vim.notify('PIO init: Done', vim.log.levels.INFO) - commandPassed = commandPassed + 1 - vim.misc.gitignore_lsp_configs('compile_commands.json') - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen([[.clangd]], _G.metadata.core_dir) + vim.schedule(function() + vim.notify('PIO init: pass ' .. commandPassed, vim.log.levels.INFO) + vim.notify('PIO init: Done', vim.log.levels.INFO) + vim.misc.gitignore_lsp_configs('compile_commands.json') + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen([[.clangd]], _G.metadata.core_dir) - local pio_refresh = require('platformio.pio_setup').pio_refresh - pio_refresh('PIO init: ', function() - lsp_restart('clangd') + local pio_refresh = require('platformio.pio_setup').pio_refresh + pio_refresh(function() + lsp_restart('clangd') + end, 'PIO init: ') end) M.queue = {} term.stdout_callback = nil From e73e49580e3ceb0b4eef7fab379c8f9dc3c62339 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 06:46:20 +0300 Subject: [PATCH 1287/1406] update --- lua/platformio/pio_setup.lua | 4 ++++ lua/platformio/utils/pio.lua | 6 +++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index f8305b72..8d13e23b 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -26,6 +26,10 @@ function M.pio_refresh(callback, from) vim.notify(msg ..'Config sync ...', vim.log.levels.INFO) local function on_done(active_env) + + if active_env then + vim.notify(msg .. 'active_env= ' .. active_env, vim.log.levels.INFO) + end if active_env then vim.pio.fetch_metadata(callback, active_env, from, 1) end end diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 21f71bbb..b76ffa81 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -381,9 +381,9 @@ function M.fetch_config(on_done, from) end end - if active_env then - vim.notify(msg .. 'active_env= ' .. active_env, vim.log.levels.INFO) - end + -- if active_env then + -- vim.notify(msg .. 'active_env= ' .. active_env, vim.log.levels.INFO) + -- end -- 6. Trigger next step if meta.active_env ~= '' then vim.notify(msg .. 'Config sync successful', vim.log.levels.INFO) From 3000fa4e1de3c113eaa91558412e2a2b64cc10ea Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 06:46:46 +0300 Subject: [PATCH 1288/1406] update --- lua/platformio/pio_setup.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 8d13e23b..a7fb45c6 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -69,7 +69,6 @@ function M.run_compiledb(target) -- end -- }) - print(env) -- if env and env ~= '' then vim.notify('PIO platformio.ini change: update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) -- vim.schedule(function() From 3d3e3b42577f9f9dcc12c8b7b7e0b3708a1032a0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 06:52:55 +0300 Subject: [PATCH 1289/1406] update --- lua/platformio/pio_setup.lua | 6 +----- lua/platformio/utils/pio.lua | 7 ++++--- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index a7fb45c6..e33d0ec7 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -26,13 +26,9 @@ function M.pio_refresh(callback, from) vim.notify(msg ..'Config sync ...', vim.log.levels.INFO) local function on_done(active_env) - - if active_env then - vim.notify(msg .. 'active_env= ' .. active_env, vim.log.levels.INFO) - end + if active_env then vim.notify(msg .. 'active_env= ' .. active_env, vim.log.levels.INFO) end if active_env then vim.pio.fetch_metadata(callback, active_env, from, 1) end end - vim.pio.fetch_config(on_done, from) end diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index b76ffa81..e1197508 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -120,13 +120,14 @@ function M.get_active__env() end --- INFO: +--INFO: -- get pio project metadata info -- stylua: ignore --============================================================================= function M.fetch_metadata(callback, env, from, attempts) local msg = (type(from)=='string' and from ~= '') and from or 'PIO: ' local meta = _G.metadata + print(env) local active_env = env or meta.active_env if not active_env or active_env == '' then return @@ -138,8 +139,9 @@ function M.fetch_metadata(callback, env, from, attempts) local checksum_file = vim.misc.joinPath(build_dir, 'project.checksum') local idedata_file = vim.misc.joinPath(build_env_dir, 'idedata.json') + --INFO: + --INTERNAL PROCESSOR: Applies parsed data to _G.metadata --------------------------------------------------------- - -- INTERNAL PROCESSOR: Applies parsed data to _G.metadata local function apply_metadata(data, checksum) if not data then return false end @@ -174,7 +176,6 @@ function M.fetch_metadata(callback, env, from, attempts) meta.last_projectChecksum = checksum pcall(M.get_sysroot_triplet, meta.cc_compiler) - -- if callback then vim.schedule(callback) end return true end From d296e83570e02146fe28e50d335be7e364b41231 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 06:58:13 +0300 Subject: [PATCH 1290/1406] update --- lua/platformio/utils/pio.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index e1197508..778bd939 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -127,12 +127,12 @@ end function M.fetch_metadata(callback, env, from, attempts) local msg = (type(from)=='string' and from ~= '') and from or 'PIO: ' local meta = _G.metadata - print(env) local active_env = env or meta.active_env if not active_env or active_env == '' then return end + print(active_env) -- Set up file paths local build_dir = vim.misc.joinPath(vim.uv.cwd(), '.pio', 'build') local build_env_dir = vim.misc.joinPath(build_dir, active_env) @@ -220,6 +220,7 @@ function M.fetch_metadata(callback, env, from, attempts) end end + vim.notify(msg .. 'Metadata syncing .....', vim.log.levels.INFO) --------------------------------------------------------- -- STEP 3: Auto-Initialize (If files project.checksum and idedata.json are missing) --------------------------------------------------------- From f745b1f6e5537af05a920772a5f0fbcc48fd4045 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 07:13:59 +0300 Subject: [PATCH 1291/1406] update --- lua/platformio/utils/pio.lua | 48 ++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 16 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 778bd939..83389497 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -132,7 +132,6 @@ function M.fetch_metadata(callback, env, from, attempts) return end - print(active_env) -- Set up file paths local build_dir = vim.misc.joinPath(vim.uv.cwd(), '.pio', 'build') local build_env_dir = vim.misc.joinPath(build_dir, active_env) @@ -178,6 +177,21 @@ function M.fetch_metadata(callback, env, from, attempts) return true end + local function buildIdedata() + vim.notify(msg .. 'Initializing project metadata...', vim.log.levels.WARN) + vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env, '-s' }, { text = true }, function(obj) + vim.schedule(function() + if obj.code == 0 then + vim.notify(msg .. 'Initializing project metadata success.', vim.log.levels.ERROR) + M.fetch_metadata(callback, active_env, from, attempts - 1) -- Recursive call after files created + else + vim.notify(msg .. 'Initialization failed. Build project manually.', vim.log.levels.ERROR) + end + end) + end) + return true + + end --------------------------------------------------------- -- STEP 1: Fast Checksum Check (project.checksum and idedata.json) @@ -217,27 +231,29 @@ function M.fetch_metadata(callback, env, from, attempts) return true end + -- else end + -- else end + buildIdedata() - vim.notify(msg .. 'Metadata syncing .....', vim.log.levels.INFO) --------------------------------------------------------- -- STEP 3: Auto-Initialize (If files project.checksum and idedata.json are missing) --------------------------------------------------------- - if not ok or not current_checksum then - vim.notify(msg .. 'Initializing project metadata...', vim.log.levels.WARN) - vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env, '-s' }, { text = true }, function(obj) - vim.schedule(function() - if obj.code == 0 then - vim.notify(msg .. 'Initializing project metadata success.', vim.log.levels.ERROR) - M.fetch_metadata(callback, active_env, from, attempts - 1) -- Recursive call after files created - else - vim.notify(msg .. 'Initialization failed. Build project manually.', vim.log.levels.ERROR) - end - end) - end) - return - end + -- if not ok or not current_checksum then + -- vim.notify(msg .. 'Initializing project metadata...', vim.log.levels.WARN) + -- vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env, '-s' }, { text = true }, function(obj) + -- vim.schedule(function() + -- if obj.code == 0 then + -- vim.notify(msg .. 'Initializing project metadata success.', vim.log.levels.ERROR) + -- M.fetch_metadata(callback, active_env, from, attempts - 1) -- Recursive call after files created + -- else + -- vim.notify(msg .. 'Initialization failed. Build project manually.', vim.log.levels.ERROR) + -- end + -- end) + -- end) + -- return + -- end --------------------------------------------------------- -- STEP 4: Standard CLI Fallback (The Slow Path) From b63ef15f61f3d88d38905761588104b27c16bad1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 07:18:24 +0300 Subject: [PATCH 1292/1406] update --- lua/platformio/utils/pio.lua | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 83389497..3fff7928 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -177,12 +177,16 @@ function M.fetch_metadata(callback, env, from, attempts) return true end + + --INFO: + --Generate idedata.json + --------------------------------------------------------- local function buildIdedata() - vim.notify(msg .. 'Initializing project metadata...', vim.log.levels.WARN) + vim.notify(msg .. 'Initializing project metadata...', vim.log.levels.INFO) vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env, '-s' }, { text = true }, function(obj) vim.schedule(function() if obj.code == 0 then - vim.notify(msg .. 'Initializing project metadata success.', vim.log.levels.ERROR) + vim.notify(msg .. 'Initializing project metadata success.', vim.log.levels.INFO) M.fetch_metadata(callback, active_env, from, attempts - 1) -- Recursive call after files created else vim.notify(msg .. 'Initialization failed. Build project manually.', vim.log.levels.ERROR) From 03c6d792f022127062ba011d35143351c1220528 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 07:25:05 +0300 Subject: [PATCH 1293/1406] update --- lua/platformio/utils/pio.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 3fff7928..5e68822a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -640,9 +640,11 @@ function M.handlePioinit(result) local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], _G.metadata.core_dir) + term.ToggleTerminal('echo ************ Please wait for project Initialization to finish ************', 'float') local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() lsp_restart('clangd') + term.ToggleTerminal('echo ************ project Initialization success ************', 'float') end, 'PIO init: ') end) M.queue = {} From 0375c45eb9986e2f9c3b835bd80d1c5dd5e1a3db Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 07:28:14 +0300 Subject: [PATCH 1294/1406] update --- lua/platformio/utils/pio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 5e68822a..422a0a1a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -640,11 +640,11 @@ function M.handlePioinit(result) local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], _G.metadata.core_dir) - term.ToggleTerminal('echo ************ Please wait for project Initialization to finish ************', 'float') + term.ToggleTerminal('echo "************ Please wait for project Initialization to finish ************"', 'float') local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() lsp_restart('clangd') - term.ToggleTerminal('echo ************ project Initialization success ************', 'float') + term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') end, 'PIO init: ') end) M.queue = {} From e1ed1cf4efa858be4927d63ec7c6a17bdfc6ca1e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 07:44:10 +0300 Subject: [PATCH 1295/1406] update --- lua/platformio/utils/pio.lua | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 422a0a1a..8879c75b 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -640,11 +640,14 @@ function M.handlePioinit(result) local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], _G.metadata.core_dir) - term.ToggleTerminal('echo "************ Please wait for project Initialization to finish ************"', 'float') + local msg = '************ Please wait for project Initialization to finish ************' + vim.api.nvim_chan_send(vim.b[term.bufnr].terminal_job_id, '\r\n' .. msg .. '\r\n') + + -- term.ToggleTerminal('echo "************ Please wait for project Initialization to finish ************"', 'float') local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() lsp_restart('clangd') - term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') + -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') end, 'PIO init: ') end) M.queue = {} From e7c0b6bd15a46b67404a7af4e5a91f66f8152f82 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 08:42:04 +0300 Subject: [PATCH 1296/1406] update --- lua/platformio/utils/pio.lua | 2 +- lua/platformio/utils/term.lua | 18 +++++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 8879c75b..8b20ef8a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -641,7 +641,7 @@ function M.handlePioinit(result) boilerplate_gen([[.clangd]], _G.metadata.core_dir) local msg = '************ Please wait for project Initialization to finish ************' - vim.api.nvim_chan_send(vim.b[term.bufnr].terminal_job_id, '\r\n' .. msg .. '\r\n') + vim.api.nvim_chan_send(vim.b[term:bufnri(term)].terminal_job_id, '\r\n' .. msg .. '\r\n') -- term.ToggleTerminal('echo "************ Please wait for project Initialization to finish ************"', 'float') local pio_refresh = require('platformio.pio_setup').pio_refresh diff --git a/lua/platformio/utils/term.lua b/lua/platformio/utils/term.lua index 4eed338b..e022e975 100644 --- a/lua/platformio/utils/term.lua +++ b/lua/platformio/utils/term.lua @@ -40,8 +40,22 @@ function M.enter() end end +-- 1. Tell the LSP what a "Terminal" object looks like (simplified) +---@class Terminal +---@field id number +---@field bufnr number +---@field window number +---@field close function +---@field toggle function -- INFO: get previous window local function getPreviousWindow(orig_window) + -- 2. Define your context class + ---@class PioPrevContext + ---@field term Terminal|nil -- Handle for horizontal terminal + ---@field mon Terminal|nil + ---@field cli Terminal|nil + ---@field float boolean -- flag float terminal + ---@field orig_window number|nil local prev = { orig_window = orig_window, term = nil, --active terminal @@ -130,6 +144,7 @@ function M.ToggleTerminal(command, direction) local orig_window = prev.orig_window if string.find(command, ' monitor') then + prev.mon = prev.mon or {} --???? if prev.mon then -- INFO: if previous monitor terminal already opened ==> reopen prev.mon.display_name = 'piomon:' .. orig_window local win_type = vim.fn.win_gettype(prev.mon.window) @@ -146,6 +161,7 @@ function M.ToggleTerminal(command, direction) pioOpts.id = 98 pioOpts.on_stdout = nil else -- INFO: if previous cli terminal already opened ==> reopen + prev.cli = prev.cli or {} --???? if prev.cli then prev.cli.display_name = 'piocli:' .. orig_window local win_type = vim.fn.win_gettype(prev.cli.window) @@ -312,7 +328,7 @@ function M.ToggleTerminal(command, direction) -- INFO: create new terminal local terminal = require('toggleterm.terminal').Terminal:new(termConfig) if prev.term and prev.float then - prev.term:close() + prev.term.close() end terminal:toggle() vim.defer_fn(function() From 36999e29298bba5809664c3933c6fc85190d2062 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 08:47:59 +0300 Subject: [PATCH 1297/1406] update --- lua/platformio/utils/pio.lua | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 8b20ef8a..c251356e 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -641,7 +641,15 @@ function M.handlePioinit(result) boilerplate_gen([[.clangd]], _G.metadata.core_dir) local msg = '************ Please wait for project Initialization to finish ************' - vim.api.nvim_chan_send(vim.b[term:bufnri(term)].terminal_job_id, '\r\n' .. msg .. '\r\n') + + -- ToggleTerm objects have a .bufnr property and a .job_id property + if term and term.bufnr then + local chan_id = vim.b[term.bufnr].terminal_job_id + if chan_id then + vim.api.nvim_chan_send(chan_id, '\r\n' .. msg .. '\r\n') + end + end + -- vim.api.nvim_chan_send(vim.b[term:bufnri(term)].terminal_job_id, '\r\n' .. msg .. '\r\n') -- term.ToggleTerminal('echo "************ Please wait for project Initialization to finish ************"', 'float') local pio_refresh = require('platformio.pio_setup').pio_refresh From cc55b61a2574eca3e950f1003135a433ec7582a6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 09:04:07 +0300 Subject: [PATCH 1298/1406] update --- lua/platformio/utils/pio.lua | 7 ++++--- lua/platformio/utils/term.lua | 3 +-- lua/platformio/utils/pio2.lua => pio2.lua | 0 lua/platformio/utils/term2.lua => term2.lua | 0 4 files changed, 5 insertions(+), 5 deletions(-) rename lua/platformio/utils/pio2.lua => pio2.lua (100%) rename lua/platformio/utils/term2.lua => term2.lua (100%) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index c251356e..c424ff56 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -567,6 +567,7 @@ M.run_sequence = function(tasks) vim.schedule(function() if callBack then callBack('INIT') end end) end +local trm ------------------------------------------------------ -- Handle after pioinit execution -- ============================================================================= @@ -631,7 +632,7 @@ function M.handlePioinit(result) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') - term.ToggleTerminal(table.remove(M.queue, 1), 'float') + trm = term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'DONE' then -- result of the last command vim.schedule(function() vim.notify('PIO init: pass ' .. commandPassed, vim.log.levels.INFO) @@ -643,8 +644,8 @@ function M.handlePioinit(result) local msg = '************ Please wait for project Initialization to finish ************' -- ToggleTerm objects have a .bufnr property and a .job_id property - if term and term.bufnr then - local chan_id = vim.b[term.bufnr].terminal_job_id + if trm and trm.bufnr then + local chan_id = vim.b[trm.bufnr].terminal_job_id if chan_id then vim.api.nvim_chan_send(chan_id, '\r\n' .. msg .. '\r\n') end diff --git a/lua/platformio/utils/term.lua b/lua/platformio/utils/term.lua index e022e975..c8cb46c3 100644 --- a/lua/platformio/utils/term.lua +++ b/lua/platformio/utils/term.lua @@ -144,7 +144,6 @@ function M.ToggleTerminal(command, direction) local orig_window = prev.orig_window if string.find(command, ' monitor') then - prev.mon = prev.mon or {} --???? if prev.mon then -- INFO: if previous monitor terminal already opened ==> reopen prev.mon.display_name = 'piomon:' .. orig_window local win_type = vim.fn.win_gettype(prev.mon.window) @@ -161,7 +160,6 @@ function M.ToggleTerminal(command, direction) pioOpts.id = 98 pioOpts.on_stdout = nil else -- INFO: if previous cli terminal already opened ==> reopen - prev.cli = prev.cli or {} --???? if prev.cli then prev.cli.display_name = 'piocli:' .. orig_window local win_type = vim.fn.win_gettype(prev.cli.window) @@ -336,6 +334,7 @@ function M.ToggleTerminal(command, direction) send(terminal, command) end end, 50) -- 50ms delay, adjust as needed sgget + return terminal end return M diff --git a/lua/platformio/utils/pio2.lua b/pio2.lua similarity index 100% rename from lua/platformio/utils/pio2.lua rename to pio2.lua diff --git a/lua/platformio/utils/term2.lua b/term2.lua similarity index 100% rename from lua/platformio/utils/term2.lua rename to term2.lua From 064c6248e86f8534436a82707d351b57df6ba83c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 09:13:01 +0300 Subject: [PATCH 1299/1406] update --- lua/platformio/utils/pio.lua | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index c424ff56..e60691a3 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -641,15 +641,26 @@ function M.handlePioinit(result) local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], _G.metadata.core_dir) + -- 1. \r clears the current prompt line visually + -- 2. Clear-Host or [Console]::CursorLeft=0 resets the line + -- 3. Write-Host outputs the text directly + -- 4. \n executes it local msg = '************ Please wait for project Initialization to finish ************' - -- ToggleTerm objects have a .bufnr property and a .job_id property - if trm and trm.bufnr then - local chan_id = vim.b[trm.bufnr].terminal_job_id - if chan_id then - vim.api.nvim_chan_send(chan_id, '\r\n' .. msg .. '\r\n') - end - end + -- The leading space ' ' prevents some shells from saving it to history + -- [Console]::CursorLeft=0 moves the cursor back to hide the "echo" part + local cmd = string.format(" [Console]::CursorLeft=0; Write-Host '%s'\n", msg) + + vim.api.nvim_chan_send(term.job_id, '\r' .. cmd) + + -- local msg = '************ Please wait for project Initialization to finish ************' + -- -- ToggleTerm objects have a .bufnr property and a .job_id property + -- if trm and trm.bufnr then + -- local chan_id = vim.b[trm.bufnr].terminal_job_id + -- if chan_id then + -- vim.api.nvim_chan_send(chan_id, '\r\n' .. msg .. '\r\n') + -- end + -- end -- vim.api.nvim_chan_send(vim.b[term:bufnri(term)].terminal_job_id, '\r\n' .. msg .. '\r\n') -- term.ToggleTerminal('echo "************ Please wait for project Initialization to finish ************"', 'float') From f455e5de3ccaa4b59ffda26778f066ecdcd52e78 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 09:14:24 +0300 Subject: [PATCH 1300/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index e60691a3..fbf60a1f 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -651,7 +651,7 @@ function M.handlePioinit(result) -- [Console]::CursorLeft=0 moves the cursor back to hide the "echo" part local cmd = string.format(" [Console]::CursorLeft=0; Write-Host '%s'\n", msg) - vim.api.nvim_chan_send(term.job_id, '\r' .. cmd) + vim.api.nvim_chan_send(trm.job_id, '\r' .. cmd) -- local msg = '************ Please wait for project Initialization to finish ************' -- -- ToggleTerm objects have a .bufnr property and a .job_id property From 5bca3ee359e62e55bec308c8eb02c0cfb62380f5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 09:16:47 +0300 Subject: [PATCH 1301/1406] update --- lua/platformio/utils/pio.lua | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index fbf60a1f..fdb5b553 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -647,11 +647,11 @@ function M.handlePioinit(result) -- 4. \n executes it local msg = '************ Please wait for project Initialization to finish ************' - -- The leading space ' ' prevents some shells from saving it to history - -- [Console]::CursorLeft=0 moves the cursor back to hide the "echo" part - local cmd = string.format(" [Console]::CursorLeft=0; Write-Host '%s'\n", msg) - - vim.api.nvim_chan_send(trm.job_id, '\r' .. cmd) + -- -- The leading space ' ' prevents some shells from saving it to history + -- -- [Console]::CursorLeft=0 moves the cursor back to hide the "echo" part + -- local cmd = string.format(" [Console]::CursorLeft=0; Write-Host '%s'\n", msg) + -- + -- vim.api.nvim_chan_send(trm.job_id, '\r' .. cmd) -- local msg = '************ Please wait for project Initialization to finish ************' -- -- ToggleTerm objects have a .bufnr property and a .job_id property @@ -663,7 +663,7 @@ function M.handlePioinit(result) -- end -- vim.api.nvim_chan_send(vim.b[term:bufnri(term)].terminal_job_id, '\r\n' .. msg .. '\r\n') - -- term.ToggleTerminal('echo "************ Please wait for project Initialization to finish ************"', 'float') + term.ToggleTerminal(msg, 'float') local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() lsp_restart('clangd') From 54ac4809569cf6156edf80a4925812a277ca628b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 09:22:35 +0300 Subject: [PATCH 1302/1406] update --- lua/platformio/utils/pio.lua | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index fdb5b553..95c761df 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -647,11 +647,10 @@ function M.handlePioinit(result) -- 4. \n executes it local msg = '************ Please wait for project Initialization to finish ************' - -- -- The leading space ' ' prevents some shells from saving it to history - -- -- [Console]::CursorLeft=0 moves the cursor back to hide the "echo" part - -- local cmd = string.format(" [Console]::CursorLeft=0; Write-Host '%s'\n", msg) - -- - -- vim.api.nvim_chan_send(trm.job_id, '\r' .. cmd) + -- The leading space ' ' prevents some shells from saving it to history + -- [Console]::CursorLeft=0 moves the cursor back to hide the "echo" part + local cmd = string.format(" [Console]::CursorLeft=0; Write-Host '%s'\n", msg) + vim.api.nvim_chan_send(trm.job_id, '\r' .. cmd) -- local msg = '************ Please wait for project Initialization to finish ************' -- -- ToggleTerm objects have a .bufnr property and a .job_id property @@ -663,7 +662,7 @@ function M.handlePioinit(result) -- end -- vim.api.nvim_chan_send(vim.b[term:bufnri(term)].terminal_job_id, '\r\n' .. msg .. '\r\n') - term.ToggleTerminal(msg, 'float') + -- term.ToggleTerminal(msg, 'float') local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() lsp_restart('clangd') From 4244140a2f53b37e7b548b0fec39fc111493bfd6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 09:26:54 +0300 Subject: [PATCH 1303/1406] update --- lua/platformio/utils/pio.lua | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 95c761df..0a7cd1ca 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -646,11 +646,16 @@ function M.handlePioinit(result) -- 3. Write-Host outputs the text directly -- 4. \n executes it local msg = '************ Please wait for project Initialization to finish ************' - - -- The leading space ' ' prevents some shells from saving it to history - -- [Console]::CursorLeft=0 moves the cursor back to hide the "echo" part - local cmd = string.format(" [Console]::CursorLeft=0; Write-Host '%s'\n", msg) - vim.api.nvim_chan_send(trm.job_id, '\r' .. cmd) + -- \r : Moves cursor to the start of the current line (over prompt) + -- \27[K : ANSI Escape code to "Clear from cursor to end of line" + -- \r\n : Move to a fresh new line so we don't mess up the current prompt + local stealth_msg = string.format('\r\27[K%s\r\n', msg) + vim.api.nvim_chan_send(trm.job_id, stealth_msg) + + -- -- The leading space ' ' prevents some shells from saving it to history + -- -- [Console]::CursorLeft=0 moves the cursor back to hide the "echo" part + -- local cmd = string.format(" [Console]::CursorLeft=0; Write-Host '%s'\n", msg) + -- vim.api.nvim_chan_send(trm.job_id, '\r' .. cmd) -- local msg = '************ Please wait for project Initialization to finish ************' -- -- ToggleTerm objects have a .bufnr property and a .job_id property From 5e305cd0497de88235b0e829c1de28f43a66dd09 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 09:30:56 +0300 Subject: [PATCH 1304/1406] update --- lua/platformio/utils/pio.lua | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 0a7cd1ca..1b087405 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -641,16 +641,20 @@ function M.handlePioinit(result) local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], _G.metadata.core_dir) - -- 1. \r clears the current prompt line visually - -- 2. Clear-Host or [Console]::CursorLeft=0 resets the line - -- 3. Write-Host outputs the text directly - -- 4. \n executes it local msg = '************ Please wait for project Initialization to finish ************' - -- \r : Moves cursor to the start of the current line (over prompt) - -- \27[K : ANSI Escape code to "Clear from cursor to end of line" - -- \r\n : Move to a fresh new line so we don't mess up the current prompt - local stealth_msg = string.format('\r\27[K%s\r\n', msg) - vim.api.nvim_chan_send(trm.job_id, stealth_msg) + + -- \27[s : Save current cursor position (the prompt) + -- \r : Go to start of line + -- \27[A : Move cursor UP one line (to space above prompt) + -- \27[K : Clear that line + -- \27[33m : Color Yellow (optional) + -- %s : Your message + -- \27[0m : Reset color + -- \27[u : Restore cursor back to the prompt + + local ghost_msg = string.format('\27[s\r\27[A\27[K\27[33m%s\27[0m\27[u', msg) + + vim.api.nvim_chan_send(trm.job_id, ghost_msg) -- -- The leading space ' ' prevents some shells from saving it to history -- -- [Console]::CursorLeft=0 moves the cursor back to hide the "echo" part From 5693b3cff8fec227fa99fb333de3b753954efd9c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 09:35:30 +0300 Subject: [PATCH 1305/1406] update --- lua/platformio/utils/pio.lua | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 1b087405..c2a51fac 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -651,10 +651,8 @@ function M.handlePioinit(result) -- %s : Your message -- \27[0m : Reset color -- \27[u : Restore cursor back to the prompt - - local ghost_msg = string.format('\27[s\r\27[A\27[K\27[33m%s\27[0m\27[u', msg) - - vim.api.nvim_chan_send(trm.job_id, ghost_msg) + local safe_msg = string.format('\27[G\r\n\27[33m%s\27[0m\r\n', msg) + vim.api.nvim_chan_send(term.job_id, safe_msg) -- -- The leading space ' ' prevents some shells from saving it to history -- -- [Console]::CursorLeft=0 moves the cursor back to hide the "echo" part From dc4cf677468aa99d01d030662f93abee697eeb91 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 09:36:47 +0300 Subject: [PATCH 1306/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index c2a51fac..1303b7d6 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -652,7 +652,7 @@ function M.handlePioinit(result) -- \27[0m : Reset color -- \27[u : Restore cursor back to the prompt local safe_msg = string.format('\27[G\r\n\27[33m%s\27[0m\r\n', msg) - vim.api.nvim_chan_send(term.job_id, safe_msg) + vim.api.nvim_chan_send(trm.job_id, safe_msg) -- -- The leading space ' ' prevents some shells from saving it to history -- -- [Console]::CursorLeft=0 moves the cursor back to hide the "echo" part From c2448b67ce4a8b093d03df3d8b01dfcf9a63b015 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 09:39:58 +0300 Subject: [PATCH 1307/1406] update --- lua/platformio/utils/pio.lua | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 1303b7d6..32e05b12 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -651,8 +651,10 @@ function M.handlePioinit(result) -- %s : Your message -- \27[0m : Reset color -- \27[u : Restore cursor back to the prompt - local safe_msg = string.format('\27[G\r\n\27[33m%s\27[0m\r\n', msg) - vim.api.nvim_chan_send(trm.job_id, safe_msg) + + -- IMPORTANT: No \n at the end, so it doesn't execute + local clean_msg = string.format('\27[G\27[2K\27[33m%s\27[0m', msg) + vim.api.nvim_chan_send(trm.job_id, clean_msg) -- -- The leading space ' ' prevents some shells from saving it to history -- -- [Console]::CursorLeft=0 moves the cursor back to hide the "echo" part From de123a701a1087d05018e628d1a37332ade5615a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 09:44:50 +0300 Subject: [PATCH 1308/1406] update --- lua/platformio/utils/pio.lua | 26 +++++++------------------- 1 file changed, 7 insertions(+), 19 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 32e05b12..dee9b3ef 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -641,8 +641,6 @@ function M.handlePioinit(result) local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], _G.metadata.core_dir) - local msg = '************ Please wait for project Initialization to finish ************' - -- \27[s : Save current cursor position (the prompt) -- \r : Go to start of line -- \27[A : Move cursor UP one line (to space above prompt) @@ -653,25 +651,15 @@ function M.handlePioinit(result) -- \27[u : Restore cursor back to the prompt -- IMPORTANT: No \n at the end, so it doesn't execute - local clean_msg = string.format('\27[G\27[2K\27[33m%s\27[0m', msg) - vim.api.nvim_chan_send(trm.job_id, clean_msg) - - -- -- The leading space ' ' prevents some shells from saving it to history - -- -- [Console]::CursorLeft=0 moves the cursor back to hide the "echo" part - -- local cmd = string.format(" [Console]::CursorLeft=0; Write-Host '%s'\n", msg) - -- vim.api.nvim_chan_send(trm.job_id, '\r' .. cmd) - -- local msg = '************ Please wait for project Initialization to finish ************' - -- -- ToggleTerm objects have a .bufnr property and a .job_id property - -- if trm and trm.bufnr then - -- local chan_id = vim.b[trm.bufnr].terminal_job_id - -- if chan_id then - -- vim.api.nvim_chan_send(chan_id, '\r\n' .. msg .. '\r\n') - -- end - -- end - -- vim.api.nvim_chan_send(vim.b[term:bufnri(term)].terminal_job_id, '\r\n' .. msg .. '\r\n') + -- local clean_msg = string.format('\27[G\27[2K\27[33m%s\27[0m', msg) + -- vim.api.nvim_chan_send(trm.job_id, clean_msg) + + vim.notify('Project Initialization in Progress...', vim.log.levels.INFO, { + title = 'PlatformIO', + timeout = 3000, -- Auto-close in 3 seconds + }) - -- term.ToggleTerminal(msg, 'float') local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() lsp_restart('clangd') From 3bc63eec53ddeefc3a238fa30e0d7fb2800e15f4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 09:57:02 +0300 Subject: [PATCH 1309/1406] update --- lua/platformio/utils/misc.lua | 39 +++++++++++++++++++++++++++++++++++ lua/platformio/utils/pio.lua | 7 +------ 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 18e91377..0cf1e811 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -8,6 +8,45 @@ M.devNul = M.is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' +------------------------------------------------------ +--INFO: +--- stylua: ignore +function M.showMessage(msg, timeout) + -- 1. Create a scratch buffer (not listed, no file) + local bufnr = vim.api.nvim_create_buf(false, true) + + -- 2. Set the text (with a little padding) + local text = ' ' .. msg .. ' ' + vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, { '', text, '' }) + + -- 3. Calculate window size and position + local width = #text + 2 + local height = 3 + local opts = { + relative = 'editor', + row = 2, -- Top of the screen + col = vim.o.columns - width - 2, -- Right side + width = width, + height = height, + style = 'minimal', + border = 'rounded', + focusable = false, -- Don't let the cursor jump into it + } + + -- 4. Open the window + local win = vim.api.nvim_open_win(bufnr, false, opts) + + -- 5. Optional: Highlight as "Warning" or "Info" + vim.api.nvim_set_option_value('winhl', 'Normal:DiagnosticInfo', { scope = 'local', win = win }) + + -- 6. Auto-close after timeout (default 3s) + vim.defer_fn(function() + if vim.api.nvim_win_is_valid(win) then + vim.api.nvim_win_close(win, true) + end + end, timeout or 3000) +end + ------------------------------------------------------ --INFO: --- stylua: ignore diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index dee9b3ef..73f05948 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -649,17 +649,12 @@ function M.handlePioinit(result) -- %s : Your message -- \27[0m : Reset color -- \27[u : Restore cursor back to the prompt - -- IMPORTANT: No \n at the end, so it doesn't execute -- local msg = '************ Please wait for project Initialization to finish ************' -- local clean_msg = string.format('\27[G\27[2K\27[33m%s\27[0m', msg) -- vim.api.nvim_chan_send(trm.job_id, clean_msg) - vim.notify('Project Initialization in Progress...', vim.log.levels.INFO, { - title = 'PlatformIO', - timeout = 3000, -- Auto-close in 3 seconds - }) - + vim.misc.showMessage('************ Project Initializing ************', 5000) local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() lsp_restart('clangd') From c0b59ad6da3d58d521e1289de134fe3e4ce23666 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 10:01:06 +0300 Subject: [PATCH 1310/1406] update --- lua/platformio/utils/misc.lua | 55 ++++++++++++++++++++++++++++------- 1 file changed, 44 insertions(+), 11 deletions(-) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 0cf1e811..1af86685 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -11,35 +11,32 @@ M.devNul = M.is_windows and ' 2>./nul' or ' 2>/dev/null' ------------------------------------------------------ --INFO: --- stylua: ignore + function M.showMessage(msg, timeout) - -- 1. Create a scratch buffer (not listed, no file) local bufnr = vim.api.nvim_create_buf(false, true) - - -- 2. Set the text (with a little padding) local text = ' ' .. msg .. ' ' vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, { '', text, '' }) - -- 3. Calculate window size and position local width = #text + 2 local height = 3 local opts = { relative = 'editor', - row = 2, -- Top of the screen - col = vim.o.columns - width - 2, -- Right side + row = 2, + col = vim.o.columns - width - 4, -- Shifted slightly more left for safety width = width, height = height, style = 'minimal', border = 'rounded', - focusable = false, -- Don't let the cursor jump into it + focusable = false, + -- CRITICAL: Higher than ToggleTerm's zindex to stay on top + zindex = 150, } - -- 4. Open the window local win = vim.api.nvim_open_win(bufnr, false, opts) - -- 5. Optional: Highlight as "Warning" or "Info" - vim.api.nvim_set_option_value('winhl', 'Normal:DiagnosticInfo', { scope = 'local', win = win }) + -- Use a high-contrast highlight so it's readable over the terminal + vim.api.nvim_set_option_value('winhl', 'Normal:Pmenu,FloatBorder:DiagnosticInfo', { scope = 'local', win = win }) - -- 6. Auto-close after timeout (default 3s) vim.defer_fn(function() if vim.api.nvim_win_is_valid(win) then vim.api.nvim_win_close(win, true) @@ -47,6 +44,42 @@ function M.showMessage(msg, timeout) end, timeout or 3000) end +-- function M.showMessage(msg, timeout) +-- -- 1. Create a scratch buffer (not listed, no file) +-- local bufnr = vim.api.nvim_create_buf(false, true) +-- +-- -- 2. Set the text (with a little padding) +-- local text = ' ' .. msg .. ' ' +-- vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, { '', text, '' }) +-- +-- -- 3. Calculate window size and position +-- local width = #text + 2 +-- local height = 3 +-- local opts = { +-- relative = 'editor', +-- row = 2, -- Top of the screen +-- col = vim.o.columns - width - 2, -- Right side +-- width = width, +-- height = height, +-- style = 'minimal', +-- border = 'rounded', +-- focusable = false, -- Don't let the cursor jump into it +-- } +-- +-- -- 4. Open the window +-- local win = vim.api.nvim_open_win(bufnr, false, opts) +-- +-- -- 5. Optional: Highlight as "Warning" or "Info" +-- vim.api.nvim_set_option_value('winhl', 'Normal:DiagnosticInfo', { scope = 'local', win = win }) +-- +-- -- 6. Auto-close after timeout (default 3s) +-- vim.defer_fn(function() +-- if vim.api.nvim_win_is_valid(win) then +-- vim.api.nvim_win_close(win, true) +-- end +-- end, timeout or 3000) +-- end + ------------------------------------------------------ --INFO: --- stylua: ignore From 0844a2732a29efa5255f9df5fad7913f16b57059 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 10:08:52 +0300 Subject: [PATCH 1311/1406] update --- lua/platformio/utils/misc.lua | 70 ++++++++++------------------------- lua/platformio/utils/pio.lua | 6 ++- 2 files changed, 23 insertions(+), 53 deletions(-) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 1af86685..f89b2dcd 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -11,75 +11,43 @@ M.devNul = M.is_windows and ' 2>./nul' or ' 2>/dev/null' ------------------------------------------------------ --INFO: --- stylua: ignore - -function M.showMessage(msg, timeout) +function M.showMessage(msg) local bufnr = vim.api.nvim_create_buf(false, true) local text = ' ' .. msg .. ' ' vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, { '', text, '' }) local width = #text + 2 local height = 3 + + -- Calculate center of the screen + local row = math.floor((vim.o.lines - height) / 2) + local col = math.floor((vim.o.columns - width) / 2) + local opts = { relative = 'editor', - row = 2, - col = vim.o.columns - width - 4, -- Shifted slightly more left for safety + row = row, + col = col, width = width, height = height, style = 'minimal', - border = 'rounded', + border = 'double', focusable = false, - -- CRITICAL: Higher than ToggleTerm's zindex to stay on top - zindex = 150, + zindex = 200, -- High zindex to stay above ToggleTerm } - local win = vim.api.nvim_open_win(bufnr, false, opts) + local win_id = vim.api.nvim_open_win(bufnr, false, opts) - -- Use a high-contrast highlight so it's readable over the terminal - vim.api.nvim_set_option_value('winhl', 'Normal:Pmenu,FloatBorder:DiagnosticInfo', { scope = 'local', win = win }) + -- Apply a solid background so you can't see the terminal text through it + vim.api.nvim_set_option_value('winhl', 'Normal:NormalFloat,FloatBorder:DiagnosticInfo', { scope = 'local', win = win_id }) - vim.defer_fn(function() - if vim.api.nvim_win_is_valid(win) then - vim.api.nvim_win_close(win, true) - end - end, timeout or 3000) + return win_id end --- function M.showMessage(msg, timeout) --- -- 1. Create a scratch buffer (not listed, no file) --- local bufnr = vim.api.nvim_create_buf(false, true) --- --- -- 2. Set the text (with a little padding) --- local text = ' ' .. msg .. ' ' --- vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, { '', text, '' }) --- --- -- 3. Calculate window size and position --- local width = #text + 2 --- local height = 3 --- local opts = { --- relative = 'editor', --- row = 2, -- Top of the screen --- col = vim.o.columns - width - 2, -- Right side --- width = width, --- height = height, --- style = 'minimal', --- border = 'rounded', --- focusable = false, -- Don't let the cursor jump into it --- } --- --- -- 4. Open the window --- local win = vim.api.nvim_open_win(bufnr, false, opts) --- --- -- 5. Optional: Highlight as "Warning" or "Info" --- vim.api.nvim_set_option_value('winhl', 'Normal:DiagnosticInfo', { scope = 'local', win = win }) --- --- -- 6. Auto-close after timeout (default 3s) --- vim.defer_fn(function() --- if vim.api.nvim_win_is_valid(win) then --- vim.api.nvim_win_close(win, true) --- end --- end, timeout or 3000) --- end - +function M.closeMessage(win_id) + if win_id and vim.api.nvim_win_is_valid(win_id) then + vim.api.nvim_win_close(win_id, true) + end +end ------------------------------------------------------ --INFO: --- stylua: ignore diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 73f05948..1e4f85ff 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -616,6 +616,7 @@ function M.handlePioinitDb(result) end end +local win_id ---------------------------------------------------- -- Handle after pioinit execution function M.handlePioinit(result) @@ -632,7 +633,7 @@ function M.handlePioinit(result) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') - trm = term.ToggleTerminal(table.remove(M.queue, 1), 'float') + term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'DONE' then -- result of the last command vim.schedule(function() vim.notify('PIO init: pass ' .. commandPassed, vim.log.levels.INFO) @@ -654,10 +655,11 @@ function M.handlePioinit(result) -- local clean_msg = string.format('\27[G\27[2K\27[33m%s\27[0m', msg) -- vim.api.nvim_chan_send(trm.job_id, clean_msg) - vim.misc.showMessage('************ Project Initializing ************', 5000) + win_id = vim.misc.showMessage('************ Project Initializing ************') local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() lsp_restart('clangd') + vim.misc.closeMessage(win_id) -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') end, 'PIO init: ') end) From f3524e1239ba59fab1363641debcb66d56557fc1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 10:14:57 +0300 Subject: [PATCH 1312/1406] update --- lua/platformio/pioinit2.lua | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/lua/platformio/pioinit2.lua b/lua/platformio/pioinit2.lua index 93a5c414..7c8c7680 100644 --- a/lua/platformio/pioinit2.lua +++ b/lua/platformio/pioinit2.lua @@ -46,10 +46,13 @@ local function finalize_setup() local sample_flag = wizard_data.sample == 'Yes' and ' --sample-code' or '' local init_cmd = string.format('pio project init --ide vim --board %s -O "framework=%s"%s', wizard_data.board_id, wizard_data.framework, sample_flag) - local db_cmd = string.format('pio run -t compiledb -e %s', wizard_data.board_id) - local commands = { init_cmd, db_cmd } - local final_cb = pio.handlePioinitDb + -- local db_cmd = string.format('pio run -t compiledb -e %s', wizard_data.board_id) + -- local commands = { init_cmd, db_cmd } + -- local final_cb = pio.handlePioinitDb + + local commands = { init_cmd } + local final_cb = pio.handlePioinit notify('Starting project setup for ' .. wizard_data.board_id .. '...') pio.run_sequence({ cmnds = commands, cb = final_cb }) From 52fab794ef4df703670dc923fbce41a50623a547 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 10:24:34 +0300 Subject: [PATCH 1313/1406] update --- lua/platformio/utils/misc.lua | 97 +++++++++++++++++++++++++++++------ 1 file changed, 80 insertions(+), 17 deletions(-) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index f89b2dcd..c6a0fc54 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -10,20 +10,19 @@ M.devNul = M.is_windows and ' 2>./nul' or ' 2>/dev/null' ------------------------------------------------------ --INFO: ---- stylua: ignore +local uv = vim.uv or vim.loop + +-- stylua: ignore function M.showMessage(msg) local bufnr = vim.api.nvim_create_buf(false, true) local text = ' ' .. msg .. ' ' vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, { '', text, '' }) - local width = #text + 2 - local height = 3 - - -- Calculate center of the screen + local width, height = #text + 2, 3 local row = math.floor((vim.o.lines - height) / 2) local col = math.floor((vim.o.columns - width) / 2) - local opts = { + local win_id = vim.api.nvim_open_win(bufnr, false, { relative = 'editor', row = row, col = col, @@ -31,23 +30,87 @@ function M.showMessage(msg) height = height, style = 'minimal', border = 'double', - focusable = false, - zindex = 200, -- High zindex to stay above ToggleTerm - } - - local win_id = vim.api.nvim_open_win(bufnr, false, opts) + zindex = 250, + }) - -- Apply a solid background so you can't see the terminal text through it - vim.api.nvim_set_option_value('winhl', 'Normal:NormalFloat,FloatBorder:DiagnosticInfo', { scope = 'local', win = win_id }) + -- Define the "Glow" colors + -- We use 'IncSearch' or 'CurSearch' for a bright, glowing look + local hl_on = 'Normal:IncSearch,FloatBorder:IncSearch' + local hl_off = 'Normal:NormalFloat,FloatBorder:NormalFloat' + + -- Create a timer for the blinking effect + local blink_timer = uv.new_timer() + local is_on = true + + if blink_timer then + blink_timer:start( + 0, + 500, + vim.schedule_wrap(function() + if vim.api.nvim_win_is_valid(win_id) then + vim.api.nvim_set_option_value('winhl', is_on and hl_on or hl_off, { scope = 'local', win = win_id }) + is_on = not is_on + else + blink_timer:stop() + blink_timer:close() + end + end) + ) + end - return win_id + -- Return both so you can kill them later + return { win = win_id, timer = blink_timer } end -function M.closeMessage(win_id) - if win_id and vim.api.nvim_win_is_valid(win_id) then - vim.api.nvim_win_close(win_id, true) +function M.closeMessage(status_obj) + if status_obj then + if status_obj.timer then + status_obj.timer:stop() + status_obj.timer:close() + end + if status_obj.win and vim.api.nvim_win_is_valid(status_obj.win) then + vim.api.nvim_win_close(status_obj.win, true) + end end end + +-- function M.showMessage(msg) +-- local bufnr = vim.api.nvim_create_buf(false, true) +-- local text = ' ' .. msg .. ' ' +-- vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, { '', text, '' }) +-- +-- local width = #text + 2 +-- local height = 3 +-- +-- -- Calculate center of the screen +-- local row = math.floor((vim.o.lines - height) / 2) +-- local col = math.floor((vim.o.columns - width) / 2) +-- +-- local opts = { +-- relative = 'editor', +-- row = row, +-- col = col, +-- width = width, +-- height = height, +-- style = 'minimal', +-- border = 'double', +-- focusable = false, +-- zindex = 200, -- High zindex to stay above ToggleTerm +-- } +-- +-- local win_id = vim.api.nvim_open_win(bufnr, false, opts) +-- +-- -- Apply a solid background so you can't see the terminal text through it +-- vim.api.nvim_set_option_value('winhl', 'Normal:NormalFloat,FloatBorder:DiagnosticInfo', { scope = 'local', win = win_id }) +-- +-- return win_id +-- end + +-- function M.closeMessage(win_id) +-- if win_id and vim.api.nvim_win_is_valid(win_id) then +-- vim.api.nvim_win_close(win_id, true) +-- end +-- end ------------------------------------------------------ --INFO: --- stylua: ignore From 9ebca942511944403a4a9cf075e2be13c13de96e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 10:27:43 +0300 Subject: [PATCH 1314/1406] update --- lua/platformio/utils/pio.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 1e4f85ff..bd899f04 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -633,6 +633,7 @@ function M.handlePioinit(result) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') + win_id = vim.misc.showMessage('************ Project Initializing ************') term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'DONE' then -- result of the last command vim.schedule(function() @@ -655,7 +656,6 @@ function M.handlePioinit(result) -- local clean_msg = string.format('\27[G\27[2K\27[33m%s\27[0m', msg) -- vim.api.nvim_chan_send(trm.job_id, clean_msg) - win_id = vim.misc.showMessage('************ Project Initializing ************') local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() lsp_restart('clangd') @@ -667,6 +667,7 @@ function M.handlePioinit(result) term.stdout_callback = nil _G.metadata.isBusy = false elseif result == 'FAIL' then + vim.misc.closeMessage(win_id) M.queue = {} term.stdout_callback = nil _G.metadata.isBusy = false From 227acf649fddc433cffdcdb5ac7db917961aba95 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 10:30:23 +0300 Subject: [PATCH 1315/1406] update --- lua/platformio/utils/pio.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index bd899f04..fe0ba7cc 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -660,6 +660,7 @@ function M.handlePioinit(result) pio_refresh(function() lsp_restart('clangd') vim.misc.closeMessage(win_id) + term.toggle() -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') end, 'PIO init: ') end) @@ -668,6 +669,7 @@ function M.handlePioinit(result) _G.metadata.isBusy = false elseif result == 'FAIL' then vim.misc.closeMessage(win_id) + term.toggle() M.queue = {} term.stdout_callback = nil _G.metadata.isBusy = false From 8b8e9235491efd8a901e4f12e49b810ca6804762 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 10:35:30 +0300 Subject: [PATCH 1316/1406] update --- lua/platformio/utils/pio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index fe0ba7cc..e1e0033c 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -660,7 +660,7 @@ function M.handlePioinit(result) pio_refresh(function() lsp_restart('clangd') vim.misc.closeMessage(win_id) - term.toggle() + term.toggle_all() -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') end, 'PIO init: ') end) @@ -669,7 +669,7 @@ function M.handlePioinit(result) _G.metadata.isBusy = false elseif result == 'FAIL' then vim.misc.closeMessage(win_id) - term.toggle() + term.toggle_all() M.queue = {} term.stdout_callback = nil _G.metadata.isBusy = false From 6ba58b9d8b2801484ac6f18135ca1c40820ca2dd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 10:38:21 +0300 Subject: [PATCH 1317/1406] update --- lua/platformio/utils/pio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index e1e0033c..40fa9516 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -660,7 +660,7 @@ function M.handlePioinit(result) pio_refresh(function() lsp_restart('clangd') vim.misc.closeMessage(win_id) - term.toggle_all() + term.close() -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') end, 'PIO init: ') end) @@ -669,7 +669,7 @@ function M.handlePioinit(result) _G.metadata.isBusy = false elseif result == 'FAIL' then vim.misc.closeMessage(win_id) - term.toggle_all() + term.close() M.queue = {} term.stdout_callback = nil _G.metadata.isBusy = false From 69376102e58c43477a17db4a46ff0992d2716a48 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 10:40:45 +0300 Subject: [PATCH 1318/1406] update --- lua/platformio/utils/pio.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 40fa9516..c45f7078 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -634,7 +634,7 @@ function M.handlePioinit(result) -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') win_id = vim.misc.showMessage('************ Project Initializing ************') - term.ToggleTerminal(table.remove(M.queue, 1), 'float') + trm = term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'DONE' then -- result of the last command vim.schedule(function() vim.notify('PIO init: pass ' .. commandPassed, vim.log.levels.INFO) @@ -660,7 +660,7 @@ function M.handlePioinit(result) pio_refresh(function() lsp_restart('clangd') vim.misc.closeMessage(win_id) - term.close() + trm.toggle() -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') end, 'PIO init: ') end) @@ -669,7 +669,7 @@ function M.handlePioinit(result) _G.metadata.isBusy = false elseif result == 'FAIL' then vim.misc.closeMessage(win_id) - term.close() + trm.toggle() M.queue = {} term.stdout_callback = nil _G.metadata.isBusy = false From e6d3289a35b05f768d0efc6786aca91b0f94b830 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 10:43:27 +0300 Subject: [PATCH 1319/1406] update --- lua/platformio/utils/pio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index c45f7078..46dfcc27 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -660,18 +660,18 @@ function M.handlePioinit(result) pio_refresh(function() lsp_restart('clangd') vim.misc.closeMessage(win_id) - trm.toggle() -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') end, 'PIO init: ') end) M.queue = {} term.stdout_callback = nil + trm.close() _G.metadata.isBusy = false elseif result == 'FAIL' then vim.misc.closeMessage(win_id) - trm.toggle() M.queue = {} term.stdout_callback = nil + trm.close() _G.metadata.isBusy = false end end From af86f3e504d3c19c7ad59238e21f39f5ed7d6c9a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 10:49:30 +0300 Subject: [PATCH 1320/1406] update --- lua/platformio/utils/pio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 46dfcc27..f09431ea 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -665,13 +665,13 @@ function M.handlePioinit(result) end) M.queue = {} term.stdout_callback = nil - trm.close() + trm:close() _G.metadata.isBusy = false elseif result == 'FAIL' then vim.misc.closeMessage(win_id) M.queue = {} term.stdout_callback = nil - trm.close() + trm:close() _G.metadata.isBusy = false end end From ef62e698b0f1f1d7552c3a306845600f366fff1a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 11:17:27 +0300 Subject: [PATCH 1321/1406] update --- lua/platformio/utils/pio.lua | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f09431ea..f5d6296f 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -665,13 +665,15 @@ function M.handlePioinit(result) end) M.queue = {} term.stdout_callback = nil - trm:close() + term:close() + -- trm:close() _G.metadata.isBusy = false elseif result == 'FAIL' then vim.misc.closeMessage(win_id) M.queue = {} term.stdout_callback = nil - trm:close() + term:close() + -- trm:close() _G.metadata.isBusy = false end end From a7941fa31f41ba4d5f00596ce05c8e98035daddd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 11:19:26 +0300 Subject: [PATCH 1322/1406] update --- lua/platformio/utils/pio.lua | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f5d6296f..f09431ea 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -665,15 +665,13 @@ function M.handlePioinit(result) end) M.queue = {} term.stdout_callback = nil - term:close() - -- trm:close() + trm:close() _G.metadata.isBusy = false elseif result == 'FAIL' then vim.misc.closeMessage(win_id) M.queue = {} term.stdout_callback = nil - term:close() - -- trm:close() + trm:close() _G.metadata.isBusy = false end end From cb121587ec7f8155a9beeba6b629c0f2c2e6cf7c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 17:19:43 +0300 Subject: [PATCH 1323/1406] update --- lua/platformio/boilerplate.lua | 1 + lua/platformio/utils/pio.lua | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index baf37c23..43a9ed85 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -202,6 +202,7 @@ boilerplate['.clangd'] = { content = [[ Diagnostics: Suppress: + - "pragma_system_header_ignored" - "misc-definitions-in-headers" - "pp_including_mainfile_in_preamble" - "misc-unused-using-decls" diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f09431ea..bb012924 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -583,7 +583,7 @@ function M.handlePioinitDb(result) boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) - -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') + boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'PASS' then From 3bf7626375968a5497975b352a4d06b133ac6490 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 17:29:52 +0300 Subject: [PATCH 1324/1406] update --- lua/platformio/boilerplate.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 43a9ed85..24ed7253 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -487,6 +487,7 @@ function M.boilerplate_gen(framework, src_path, filename) if not entry then return '' end -- local file_path = src_path .. '/' .. filename + print(file_path) if vim.uv.fs_stat(file_path) then if not entry.rewrite then if entry.read then From eb42c6585287543750505d8113a3ba0a66504a19 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 17:37:50 +0300 Subject: [PATCH 1325/1406] update --- lua/platformio/boilerplate.lua | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 24ed7253..e3d1e184 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -485,8 +485,7 @@ function M.boilerplate_gen(framework, src_path, filename) filename = filename or framework local entry = boilerplate[framework] if not entry then return '' end - -- - local file_path = src_path .. '/' .. filename + local file_path = vim.fs.normalize(src_path .. '/' .. filename) print(file_path) if vim.uv.fs_stat(file_path) then if not entry.rewrite then From da6732d1b6ad1dc42903e9a5ded17ce5e55a4b67 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 17:50:08 +0300 Subject: [PATCH 1326/1406] update --- lua/platformio/utils/pio.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index bb012924..78e82928 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -631,7 +631,8 @@ function M.handlePioinit(result) boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) - -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') + print(vim.env.XDG_CONFIG_HOME) + boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') win_id = vim.misc.showMessage('************ Project Initializing ************') trm = term.ToggleTerminal(table.remove(M.queue, 1), 'float') From fef48d1a99c2595f1379facccd637fb543c89078 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 17:53:44 +0300 Subject: [PATCH 1327/1406] update --- lua/platformio/utils/pio.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 78e82928..ba37c31d 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -641,8 +641,6 @@ function M.handlePioinit(result) vim.notify('PIO init: pass ' .. commandPassed, vim.log.levels.INFO) vim.notify('PIO init: Done', vim.log.levels.INFO) vim.misc.gitignore_lsp_configs('compile_commands.json') - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen([[.clangd]], _G.metadata.core_dir) -- \27[s : Save current cursor position (the prompt) -- \r : Go to start of line @@ -659,6 +657,8 @@ function M.handlePioinit(result) local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen([[.clangd]], _G.metadata.core_dir) lsp_restart('clangd') vim.misc.closeMessage(win_id) -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') From 8e8f1fcd6443fec41c8313ebc07372f603daa3ac Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 18:52:26 +0300 Subject: [PATCH 1328/1406] update --- mini_nvimPlatformio.lua | 62 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 55 insertions(+), 7 deletions(-) diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 36fddfbf..69969c29 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -1,4 +1,5 @@ -local isWindows = jit.os == 'Windows' +local isWindows = vim.fn.has('win32') == 1 --jit.os == 'Windows' +local isMac = vim.fn.has('mac') == 1 ---------------------------------------------------------------------------------------- -- INFO: Set options @@ -38,12 +39,7 @@ vim.g.have_nerd_font = true vim.g.mapleader = ' ' vim.g.maplocalleader = ' ' -if not isWindows then - vim.g.shell = '/bin/bash' -- or '/bin/zsh', '/usr/bin/fish', etc. - vim.g.shellcmdflag = '-c' -- Executes the command passed as a string - vim.g.shellpipe = '|' -- Pipes output of external commands - vim.g.shellredir = '> ' -- Redirects output of external commands -else +if isWindows then local pwsh = vim.fn.executable('pwsh') == 1 and 'pwsh' or 'powershell' vim.opt.shell = pwsh vim.opt.shellcmdflag = @@ -52,7 +48,15 @@ else vim.opt.shellpipe = '2>&1 | Out-File -Encoding UTF8 %s; exit $LastExitCode' vim.opt.shellquote = '' vim.opt.shellxquote = '' + +--elseif vim.fn.has("mac") == 1 then +else + vim.g.shell = '/bin/bash' -- or '/bin/zsh', '/usr/bin/fish', etc. + vim.g.shellcmdflag = '-c' -- Executes the command passed as a string + vim.g.shellpipe = '|' -- Pipes output of external commands + vim.g.shellredir = '> ' -- Redirects output of external commands end + vim.hl = vim.highlight vim.api.nvim_set_hl(0, 'PioStatus', { fg = '#e0af68', -- Dark text @@ -163,8 +167,52 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) -- INFO: Set mini lazy config ---------------------------------------------------------------------------------------- ---[[ +local function setup_xdg_paths() + local is_win = vim.fn.has('win32') == 1 + local is_mac = vim.fn.has('mac') == 1 + local home = vim.env.HOME or vim.env.USERPROFILE or '' + local app_name = 'nvim-pio' -- pick a temp root + + -- Helper to ensure we never gsub a nil and always use forward slashes + local function normalize(path) + return path:gsub('\\', '/') + end + + -- 1. XDG_CONFIG_HOME (Settings/Configs) + if not vim.env.XDG_CONFIG_HOME then + local path = is_win and (vim.env.LOCALAPPDATA or (home .. '/AppData/Local')) or is_mac and (home .. '/Library/Preferences') or (home .. '/.config') + vim.env.XDG_CONFIG_HOME = normalize(vim.fs.joinpath(path, app_name)) + end + + -- 2. XDG_DATA_HOME (Large data/Databases) + if not vim.env.XDG_DATA_HOME then + local path = is_win and (vim.env.LOCALAPPDATA or (home .. '/AppData/Local')) + or is_mac and (home .. '/Library/Application Support') + or (home .. '/.local/share') + vim.env.XDG_DATA_HOME = normalize(vim.fs.joinpath(path, app_name)) + end + + -- 3. XDG_STATE_HOME (Logs/History/Persistent State) + if not vim.env.XDG_STATE_HOME then + local path = is_win and (vim.env.LOCALAPPDATA or (home .. '/AppData/Local')) + or is_mac and (home .. '/Library/Application Support') + or (home .. '/.local/state') + vim.env.XDG_STATE_HOME = normalize(vim.fs.joinpath(path, app_name)) + end + + -- 4. XDG_CACHE_HOME (Temporary/Disposable data) + if not vim.env.XDG_CACHE_HOME then + local path = is_win and (vim.env.TEMP or (home .. '/AppData/Local/Temp')) or is_mac and (home .. '/Library/Caches') or (home .. '/.cache') + vim.env.XDG_CACHE_HOME = normalize(vim.fs.joinpath(path, app_name)) + end +end + +setup_xdg_paths() +---]] +--[[ local app_name = 'nvim-pio' -- pick a temp root local home = isWindows and vim.env.LOCALAPPDATA:gsub('\\', '/') or vim.env.HOME +-- local home = vim.env.HOME or vim.env.USERPROFILE or "" home = home .. '/' .. app_name -- local home = vim.loop.os_tmpdir():gsub('\\', '/') .. '/' .. app_name From 60c507f7d7731b47af6daf190be08e1d230374eb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 19:18:15 +0300 Subject: [PATCH 1329/1406] update --- lua/platformio/boilerplate.lua | 2 +- mini_nvimPlatformio.lua | 35 +++++++++------------------------- 2 files changed, 10 insertions(+), 27 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index e3d1e184..24b44a6e 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -86,7 +86,7 @@ boilerplate['.clangd_config'] = { "--completion-style=detailed", "--header-insertion=iwyu", "--fallback-style=llvm", - "--log=error", + "--log=verbose", "--pch-storage=memory", "--pretty", "--ranking-model=decision_forest", diff --git a/mini_nvimPlatformio.lua b/mini_nvimPlatformio.lua index 69969c29..25388fcd 100644 --- a/mini_nvimPlatformio.lua +++ b/mini_nvimPlatformio.lua @@ -139,17 +139,6 @@ keymap('n', 'bd', function() pcall(vim.api.nvim_buf_delete, bufnr, { force = false }) end, { desc = '[D]elete Buffer' }) --- keymap('n', 'bP', 'BufferLineGroupClose ungrouped', { desc = 'Delete Non-Pinned Buffers' }) --- keymap('n', 'bo', 'BufferLineCloseOthers', { desc = 'Delete Other Buffers' }) --- keymap('n', 'br', 'BufferLineCloseRight', { desc = 'Delete Buffers to the Right' }) --- keymap('n', 'bl', 'BufferLineCloseLeft', { desc = 'Delete Buffers to the Left' }) --- keymap('n', '', 'BufferLineCyclePrev', { desc = 'Prev Buffer' }) --- keymap('n', '', 'BufferLineCycleNext', { desc = 'Next Buffer' }) --- keymap('n', '[b', 'BufferLineCyclePrev', { desc = 'Prev Buffer' }) --- keymap('n', ']b', 'BufferLineCycleNext', { desc = 'Next Buffer' }) --- keymap('n', '[B', 'BufferLineMovePrev', { desc = 'Move buffer prev' }) --- keymap('n', ']B', 'BufferLineMoveNext', { desc = 'Move buffer next' }) - keymap('n', 'e', 'Neotree document_symbols', { desc = 'NeoTreeToggle' }) keymap('n', '\\', 'Neotree toggle', { desc = 'NeoTreeToggle' }) -- keymap('n', 'e', 'NvimTreeToggle', { desc = 'NvimTreeToggle' }) @@ -168,8 +157,8 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) ---------------------------------------------------------------------------------------- ---[[ local function setup_xdg_paths() - local is_win = vim.fn.has('win32') == 1 - local is_mac = vim.fn.has('mac') == 1 + -- local isWindows = vim.fn.has('win32') == 1 + -- local isMac = vim.fn.has('mac') == 1 local home = vim.env.HOME or vim.env.USERPROFILE or '' local app_name = 'nvim-pio' -- pick a temp root @@ -180,29 +169,29 @@ local function setup_xdg_paths() -- 1. XDG_CONFIG_HOME (Settings/Configs) if not vim.env.XDG_CONFIG_HOME then - local path = is_win and (vim.env.LOCALAPPDATA or (home .. '/AppData/Local')) or is_mac and (home .. '/Library/Preferences') or (home .. '/.config') + local path = isWindows and (vim.env.LOCALAPPDATA or (home .. '/AppData/Local')) or isMac and (home .. '/Library/Preferences') or (home .. '/.config') vim.env.XDG_CONFIG_HOME = normalize(vim.fs.joinpath(path, app_name)) end -- 2. XDG_DATA_HOME (Large data/Databases) if not vim.env.XDG_DATA_HOME then - local path = is_win and (vim.env.LOCALAPPDATA or (home .. '/AppData/Local')) - or is_mac and (home .. '/Library/Application Support') + local path = isWindows and (vim.env.LOCALAPPDATA or (home .. '/AppData/Local')) + or isMac and (home .. '/Library/Application Support') or (home .. '/.local/share') vim.env.XDG_DATA_HOME = normalize(vim.fs.joinpath(path, app_name)) end -- 3. XDG_STATE_HOME (Logs/History/Persistent State) if not vim.env.XDG_STATE_HOME then - local path = is_win and (vim.env.LOCALAPPDATA or (home .. '/AppData/Local')) - or is_mac and (home .. '/Library/Application Support') + local path = isWindows and (vim.env.LOCALAPPDATA or (home .. '/AppData/Local')) + or isMac and (home .. '/Library/Application Support') or (home .. '/.local/state') vim.env.XDG_STATE_HOME = normalize(vim.fs.joinpath(path, app_name)) end -- 4. XDG_CACHE_HOME (Temporary/Disposable data) if not vim.env.XDG_CACHE_HOME then - local path = is_win and (vim.env.TEMP or (home .. '/AppData/Local/Temp')) or is_mac and (home .. '/Library/Caches') or (home .. '/.cache') + local path = isWindows and (vim.env.TEMP or (home .. '/AppData/Local/Temp')) or isMac and (home .. '/Library/Caches') or (home .. '/.cache') vim.env.XDG_CACHE_HOME = normalize(vim.fs.joinpath(path, app_name)) end end @@ -307,6 +296,7 @@ local plugins = { hide_gitignored = true, hide_by_name = { '.pio', + '.cache', }, never_show = { -- Add any massive folders here -- '.cache', @@ -317,13 +307,6 @@ local plugins = { }, }, }, - -- filesystem = { - -- hijack_netrw_behavior = 'open_default', - -- use_libuv_file_watcher = true, -- This will use the OS level file watchers to detect changes - -- filtered_items = { - -- never_show = { '.cache', '.git', '.pio' }, - -- }, - -- }, }, }, From 93781abb300c0c73fcf70f3b2d988c81062b561a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 19:53:22 +0300 Subject: [PATCH 1330/1406] update --- lua/platformio/lspConfig/clangd.lua | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index ecb1839b..c1fe9515 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -113,19 +113,20 @@ function _G.get_clangd_config() if _G.metadata.triplet and _G.metadata.triplet ~= '' then -- local include_flags = table.concat(_G.metadata.fallbackFlags, ", ") local includes_toolchain = table.concat(_G.metadata.includes_toolchain, ", ") - f_flags = string.format([["-std=c++17", "-xc++", "-D__cplusplus=201703L", "--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, includes_toolchain) + f_flags = [["-std=c++17", "-xc++"]] + -- f_flags = string.format([["-std=c++17", "-xc++", "-D__cplusplus=201703L", "--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, includes_toolchain) -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) - -- q_driver = '**' --_G.metadata.query_driver .. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" - q_driver = _G.metadata.query_driver --.. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" + -- q_driver = '**' --_G.metadata.query_driver .. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" + q_driver = _G.metadata.query_driver --.. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" end end -- 3. Format your template string local table_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) - -- local formatted_str = string.format(table_config, q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) - local formatted_str = string.format(table_config or '', q_driver, '', vim.misc.normalizePath(new_root_dir)) + local formatted_str = string.format(table_config or '', q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) + -- local formatted_str = string.format(table_config or '', q_driver, '', vim.misc.normalizePath(new_root_dir)) -- 4. Load the config table local cok, clangd_config = pcall(function() return load('return ' .. formatted_str)() end) From 1d0544a427d27e619c5ef2db8081e0f70bc99fee Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 20:27:16 +0300 Subject: [PATCH 1331/1406] update --- lua/platformio/boilerplate.lua | 35 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 24b44a6e..6f6f04b1 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -170,27 +170,9 @@ boilerplate['.clangd_config'] = { -- External: -- File: .clangd_index --- CompileFlags: -- Add: -- - "-xc++" -- - "-std=c++17" --- Remove: --- - "-Winclude-next-outside-header" --- - "-fno-fat-lto-objects" --- - "-fno%%-fat%%-lto%%-objects" --- - "-fno%%-canonical%%-system%%-headers" --- - "-misc-definitions-in-headers" --- - "-fno-tree-switch-conversion" --- - "-mtext-section-literals" --- - "-mlong-calls" --- - "-mlongcalls" --- - "-fstrict-volatile-bitfields" --- - "-free*" --- - "-fipa-pta*" --- - "-march=*" --- - "-mabi=*" --- - "-mcpu=*" - -- INFO: .clangd -- boilerplate['.clangd'] = { boilerplate['.clangd'] = { @@ -201,6 +183,23 @@ boilerplate['.clangd'] = { -- template = [[ content = [[ Diagnostics: +CompileFlags: +Remove: + - "-Winclude-next-outside-header" + - "-fno-fat-lto-objects" + - "-fno%%-fat%%-lto%%-objects" + - "-fno%%-canonical%%-system%%-headers" + - "-misc-definitions-in-headers" + - "-fno-tree-switch-conversion" + - "-mtext-section-literals" + - "-mlong-calls" + - "-mlongcalls" + - "-fstrict-volatile-bitfields" + - "-free*" + - "-fipa-pta*" + - "-march=*" + - "-mabi=*" + - "-mcpu=*" Suppress: - "pragma_system_header_ignored" - "misc-definitions-in-headers" From 5fe62faacb467dc3805da034b5108a05c096d8ca Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 20:29:05 +0300 Subject: [PATCH 1332/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 6f6f04b1..5d51a626 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -182,7 +182,6 @@ boilerplate['.clangd'] = { -- - "-std=gnu++17" -- template = [[ content = [[ -Diagnostics: CompileFlags: Remove: - "-Winclude-next-outside-header" @@ -200,6 +199,7 @@ Remove: - "-march=*" - "-mabi=*" - "-mcpu=*" +Diagnostics: Suppress: - "pragma_system_header_ignored" - "misc-definitions-in-headers" From 0a7746693c6f7b50fddd339d6d87d98e554d3f15 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 20:54:49 +0300 Subject: [PATCH 1333/1406] update --- lua/platformio/boilerplate.lua | 32 ++++++++++++++-------------- lua/platformio/lspConfig/attach.lua | 4 ++-- lua/platformio/lspConfig/clangd.lua | 6 +++--- lua/platformio/lspConfig/keymaps.lua | 2 +- lua/platformio/lspConfig/tools.lua | 5 +++-- lua/platformio/pioCommands.lua | 2 +- lua/platformio/pio_setup.lua | 4 +++- lua/platformio/utils/pio.lua | 8 +++---- 8 files changed, 33 insertions(+), 30 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 5d51a626..4f2f65b5 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -183,22 +183,22 @@ boilerplate['.clangd'] = { -- template = [[ content = [[ CompileFlags: -Remove: - - "-Winclude-next-outside-header" - - "-fno-fat-lto-objects" - - "-fno%%-fat%%-lto%%-objects" - - "-fno%%-canonical%%-system%%-headers" - - "-misc-definitions-in-headers" - - "-fno-tree-switch-conversion" - - "-mtext-section-literals" - - "-mlong-calls" - - "-mlongcalls" - - "-fstrict-volatile-bitfields" - - "-free*" - - "-fipa-pta*" - - "-march=*" - - "-mabi=*" - - "-mcpu=*" + Remove: + - "-Winclude-next-outside-header" + - "-fno-fat-lto-objects" + - "-fno%%-fat%%-lto%%-objects" + - "-fno%%-canonical%%-system%%-headers" + - "-misc-definitions-in-headers" + - "-fno-tree-switch-conversion" + - "-mtext-section-literals" + - "-mlong-calls" + - "-mlongcalls" + - "-fstrict-volatile-bitfields" + - "-free*" + - "-fipa-pta*" + - "-march=*" + - "-mabi=*" + - "-mcpu=*" Diagnostics: Suppress: - "pragma_system_header_ignored" diff --git a/lua/platformio/lspConfig/attach.lua b/lua/platformio/lspConfig/attach.lua index 394e14d6..b2f7e76f 100644 --- a/lua/platformio/lspConfig/attach.lua +++ b/lua/platformio/lspConfig/attach.lua @@ -19,11 +19,11 @@ vim.api.nvim_create_autocmd('LspAttach', { local params = vim.lsp.util.make_text_document_params(bufnr) client:request('textDocument/switchSourceHeader', params, function(err, result) if err then - vim.notify('Clangd Error: ' .. tostring(err), vim.log.levels.ERROR) + vim.notify('LSP Attach: Clangd Error ' .. tostring(err), vim.log.levels.ERROR) return end if not result or result == '' then - vim.notify('Corresponding file cannot be determined', vim.log.levels.WARN) + vim.notify('LSP Attach: Corresponding file cannot be determined', vim.log.levels.WARN) return end -- Use vim.schedule to ensure we aren't editing while the LSP is in a callback diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index c1fe9515..861e9df2 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -45,19 +45,19 @@ mr.refresh(function() result:install({}, function(success, _) if not success then vim.defer_fn(function() - vim.notify(tool .. ' failed to install', vim.log.levels.ERROR) + vim.notify('LSP: clangd; ' .. tool .. ' failed to install', vim.log.levels.ERROR) end, 0) end end) else vim.defer_fn(function() - vim.notify(tool .. ' already installed', vim.log.levels.WARN) + vim.notify('LSP: clangd; ' .. tool .. ' already installed', vim.log.levels.WARN) end, 0) end end else vim.defer_fn(function() - vim.notify('Failed to get package: ' .. tool, vim.log.levels.WARN) + vim.notify('LSP: clangd; Failed to get package: ' .. tool, vim.log.levels.WARN) end, 0) end end diff --git a/lua/platformio/lspConfig/keymaps.lua b/lua/platformio/lspConfig/keymaps.lua index cb58c3ba..a757b8b9 100644 --- a/lua/platformio/lspConfig/keymaps.lua +++ b/lua/platformio/lspConfig/keymaps.lua @@ -119,7 +119,7 @@ function K.lspKeymaps(client, bufnr) return c.id == client.id end, }) - print('lsp formatting') + print('LSP: clangd formatting') -- end end, }) diff --git a/lua/platformio/lspConfig/tools.lua b/lua/platformio/lspConfig/tools.lua index bed705ea..ed133426 100644 --- a/lua/platformio/lspConfig/tools.lua +++ b/lua/platformio/lspConfig/tools.lua @@ -3,9 +3,10 @@ local M = {} -- -- INFO: --- stylua: ignore -function M.lsp_restart(name) +function M.clangdRestart() + local name = 'clangd' -- vim.schedule_wrap(function() - vim.notify('LSP restart.', vim.log.levels.WARN) + vim.notify('LSP: Clangd restart.', vim.log.levels.WARN) local clangConfig = _G.get_clangd_config() -- print(vim.inspect(clangConfig)) diff --git a/lua/platformio/pioCommands.lua b/lua/platformio/pioCommands.lua index a24a5036..6b6448c3 100644 --- a/lua/platformio/pioCommands.lua +++ b/lua/platformio/pioCommands.lua @@ -5,7 +5,7 @@ local ToggleTerminal = require('platformio.utils.term').ToggleTerminal -- stylua: ignore function M.piolsp() - require('platformio.lspConfig.tools').lsp_restart('clangd') + require('platformio.lspConfig.tools').clangdRestart() end function M.piocmd(cmd_table, direction) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index e33d0ec7..5013b4af 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -1,6 +1,6 @@ M = {} --- local lsp_restart = require('platformio.lspConfig.tools').lsp_restart +local clangdRestart = require('platformio.lspConfig.tools').clangdRestart local boilerplate = require('platformio.boilerplate') local boilerplate_gen = boilerplate.boilerplate_gen @@ -78,6 +78,7 @@ function M.run_compiledb(target) -- Trigger refresh (LSP restart, etc.) -- vim.schedule(function () -- M.pio_refresh(function() + clangdRestart() vim.notify('PIO platformio.ini change: Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) -- end, 'PIO platformio.ini change: ') -- end) @@ -242,6 +243,7 @@ function M.start_watchers() M.pio_refresh(function() self.isBusy = false vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) + clangdRestart() end, 'PIO checksum: ') end, 500) end diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index ba37c31d..ad444b4c 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -10,7 +10,7 @@ M.is_processing = false M.queue = {} local term = require('platformio.utils.term') -local lsp_restart = require('platformio.lspConfig.tools').lsp_restart +local clangdRestart = require('platformio.lspConfig.tools').clangdRestart -- INFO: -- ============================================================================= @@ -495,7 +495,7 @@ function M.compile_commandsFix() --M.dbPathsFix() local end_time = vim.loop.hrtime() local duration = (end_time - start_time) / 1e6 vim.notify(string.format('compiledb: paths fixed in %.2fms', duration), vim.log.levels.INFO) - lsp_restart('clangd') + clangdRestart() end _G.metadata.isBusy = false end @@ -603,7 +603,7 @@ function M.handlePioinitDb(result) local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() - lsp_restart('clangd') + clangdRestart() end, 'PIO init+db: ') end) M.queue = {} @@ -659,7 +659,7 @@ function M.handlePioinit(result) pio_refresh(function() local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], _G.metadata.core_dir) - lsp_restart('clangd') + clangdRestart() vim.misc.closeMessage(win_id) -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') end, 'PIO init: ') From d86b903660ab2d2e79ded0e39552dc9faaa0ae46 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 21:11:34 +0300 Subject: [PATCH 1334/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/pio_setup.lua | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 4f2f65b5..6ccac18a 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -485,7 +485,7 @@ function M.boilerplate_gen(framework, src_path, filename) local entry = boilerplate[framework] if not entry then return '' end local file_path = vim.fs.normalize(src_path .. '/' .. filename) - print(file_path) + print(framework .. ':' ..file_path) if vim.uv.fs_stat(file_path) then if not entry.rewrite then if entry.read then diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 5013b4af..d0e15fd1 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -284,7 +284,7 @@ function M.init() ---------------------------------------------------------------------------------------- --INFO: create clangd required files ----------------------------------------------------------------------------------------- - boilerplate_gen([[.clangd]], vim.g.platformioRootDir) + -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) boilerplate.core_dir = _G.metadata.core_dir From 1b0f72b87f53fd11f189f7570bdd9cce8cfb6c7a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 21:18:23 +0300 Subject: [PATCH 1335/1406] update --- lua/platformio/boilerplate.lua | 1 - lua/platformio/utils/pio.lua | 1 - 2 files changed, 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 6ccac18a..2c8d92d2 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -485,7 +485,6 @@ function M.boilerplate_gen(framework, src_path, filename) local entry = boilerplate[framework] if not entry then return '' end local file_path = vim.fs.normalize(src_path .. '/' .. filename) - print(framework .. ':' ..file_path) if vim.uv.fs_stat(file_path) then if not entry.rewrite then if entry.read then diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index ad444b4c..37b2f6f0 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -631,7 +631,6 @@ function M.handlePioinit(result) boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) - print(vim.env.XDG_CONFIG_HOME) boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') win_id = vim.misc.showMessage('************ Project Initializing ************') From 7a7180ab896e6c157e32b534c0016975d21511ff Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 21:20:47 +0300 Subject: [PATCH 1336/1406] update --- lua/platformio/utils/pio.lua | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 37b2f6f0..b04c330e 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -583,7 +583,7 @@ function M.handlePioinitDb(result) boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) - boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') + -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') term.ToggleTerminal(table.remove(M.queue, 1), 'float') elseif result == 'PASS' then @@ -598,8 +598,8 @@ function M.handlePioinitDb(result) vim.notify('PIO init+db: pass ' .. commandPassed, vim.log.levels.INFO) vim.notify('PIO init+db: Done', vim.log.levels.INFO) vim.misc.gitignore_lsp_configs('compile_commands.json') - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen([[.clangd]], _G.metadata.core_dir) + -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() @@ -631,7 +631,7 @@ function M.handlePioinit(result) boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) - boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') + -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') win_id = vim.misc.showMessage('************ Project Initializing ************') trm = term.ToggleTerminal(table.remove(M.queue, 1), 'float') @@ -656,8 +656,8 @@ function M.handlePioinit(result) local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen([[.clangd]], _G.metadata.core_dir) + -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) clangdRestart() vim.misc.closeMessage(win_id) -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') From 75fd3ea3396fddcebb36412d6c246b3a2afa9a09 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 21:34:14 +0300 Subject: [PATCH 1337/1406] update --- lua/platformio/utils/pio.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index b04c330e..6f464d8b 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -598,8 +598,8 @@ function M.handlePioinitDb(result) vim.notify('PIO init+db: pass ' .. commandPassed, vim.log.levels.INFO) vim.notify('PIO init+db: Done', vim.log.levels.INFO) vim.misc.gitignore_lsp_configs('compile_commands.json') - -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen([[.clangd]], _G.metadata.core_dir) local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() @@ -656,8 +656,8 @@ function M.handlePioinit(result) local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() - -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen([[.clangd]], _G.metadata.core_dir) clangdRestart() vim.misc.closeMessage(win_id) -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') From 93b7b08786a7038b75ce5f598ed966cf621660d9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 21:45:31 +0300 Subject: [PATCH 1338/1406] update --- lua/platformio/boilerplate.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 2c8d92d2..9d030970 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -170,9 +170,6 @@ boilerplate['.clangd_config'] = { -- External: -- File: .clangd_index --- Add: --- - "-xc++" --- - "-std=c++17" -- INFO: .clangd -- boilerplate['.clangd'] = { boilerplate['.clangd'] = { @@ -183,6 +180,9 @@ boilerplate['.clangd'] = { -- template = [[ content = [[ CompileFlags: + Add: + - "-xc++" + - "-std=c++17" Remove: - "-Winclude-next-outside-header" - "-fno-fat-lto-objects" From ca087701694ad68383cdcb754fc4dcdce80f868d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 21:52:40 +0300 Subject: [PATCH 1339/1406] update --- lua/platformio/lspConfig/clangd.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 861e9df2..f9ed3841 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -118,8 +118,8 @@ function _G.get_clangd_config() -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) - -- q_driver = '**' --_G.metadata.query_driver .. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" - q_driver = _G.metadata.query_driver --.. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" + q_driver = '**' --_G.metadata.query_driver .. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" + -- q_driver = _G.metadata.query_driver --.. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" end end From 240decc59ed78d19267f867a7aad24546969df7a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 22:05:59 +0300 Subject: [PATCH 1340/1406] update --- lua/platformio/lspConfig/clangd.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index f9ed3841..3527c557 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -118,15 +118,15 @@ function _G.get_clangd_config() -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) - q_driver = '**' --_G.metadata.query_driver .. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" - -- q_driver = _G.metadata.query_driver --.. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" + -- q_driver = '**' --_G.metadata.query_driver .. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" + q_driver = _G.metadata.query_driver --.. ',C:/PROGRA~1/LLVM/bin/*' -- use with "--query-driver=%s" end end -- 3. Format your template string local table_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) - local formatted_str = string.format(table_config or '', q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) - -- local formatted_str = string.format(table_config or '', q_driver, '', vim.misc.normalizePath(new_root_dir)) + -- local formatted_str = string.format(table_config or '', q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) + local formatted_str = string.format(table_config or '', q_driver, '', vim.misc.normalizePath(new_root_dir)) -- 4. Load the config table local cok, clangd_config = pcall(function() return load('return ' .. formatted_str)() end) From d0684fc3c2febd5c7468b54177dc2a41aa96e659 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 23:15:32 +0300 Subject: [PATCH 1341/1406] update --- lua/platformio/lspConfig/clangd.lua | 4 +- lua/platformio/metadata.lua | 34 +---- lua/platformio/utils/misc.lua | 221 +--------------------------- lua/platformio/utils/pio.lua | 53 +------ 4 files changed, 9 insertions(+), 303 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 3527c557..861e9df2 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -125,8 +125,8 @@ function _G.get_clangd_config() -- 3. Format your template string local table_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) - -- local formatted_str = string.format(table_config or '', q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) - local formatted_str = string.format(table_config or '', q_driver, '', vim.misc.normalizePath(new_root_dir)) + local formatted_str = string.format(table_config or '', q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) + -- local formatted_str = string.format(table_config or '', q_driver, '', vim.misc.normalizePath(new_root_dir)) -- 4. Load the config table local cok, clangd_config = pcall(function() return load('return ' .. formatted_str)() end) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index af4cda24..c1044da4 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -82,8 +82,8 @@ local config_path = vim.fs.joinpath(vim.uv.cwd(), '.project_config.json') --INFO: -- 3. Save Logic (Uses sha256 for stability) function M.save_project_config(quiet) - -- 1. Generate the formatted string directly, pretty_print already returns a string! - local ok, pretty_json = pcall(vim.misc.pretty_print, _pio_metadata) + -- 1. Generate the formatted string directly, jsonFormat already returns a string! + local ok, pretty_json = pcall(vim.misc.jsonFormat, _pio_metadata) if not ok or not pretty_json then print('Error formatting metadata') @@ -107,34 +107,6 @@ function M.save_project_config(quiet) end end --- function M.save_project_config(quiet) --- if vim.fn.filereadable('platformio.ini') == 0 then --- return --- end --- -- local json_data = pio.pretty_json(_pio_metadata) --- local ok, json_data = pcall(vim.json.encode, _pio_metadata) --- if not ok then --- print('Error encoding JSON: ' .. json_data) --- return --- end --- local pretty_json = vim.misc.pretty_print(json_data) --- local current_hash = vim.fn.sha256(pretty_json) --- --- -- file:write(pio.jsonFormat(json_data)) --- if current_hash ~= last_saved_hash then --- -- local status = vim.fn.writefile({ json_data }, config_path) --- local status, _ = vim.misc.writeFile(json_data, config_path, {}) --- if status == 0 then --- last_saved_hash = current_hash --- if not quiet then --- vim.notify('Config synced', vim.log.levels.INFO, { title = 'PlatformIO' }) --- end --- else --- vim.notify('Could not open file for writing') --- end --- end --- end - --INFO: -- 4. Load Logic (Populates proxy safely) function M.load_project_config() @@ -154,7 +126,7 @@ function M.load_project_config() end end -- If no file, initialize hash with defaults - last_saved_hash = vim.fn.sha256(vim.misc.pretty_print(_pio_metadata)) + last_saved_hash = vim.fn.sha256(vim.misc.jsonFormat(_pio_metadata)) end -- 5. Helper for ToggleTerm / Commands diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index c6a0fc54..5855db7d 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -3,6 +3,7 @@ local M = {} M.is_windows = jit.os == 'Windows' +local uv = vim.uv or vim.loop M.devNul = M.is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' @@ -10,7 +11,6 @@ M.devNul = M.is_windows and ' 2>./nul' or ' 2>/dev/null' ------------------------------------------------------ --INFO: -local uv = vim.uv or vim.loop -- stylua: ignore function M.showMessage(msg) @@ -74,47 +74,10 @@ function M.closeMessage(status_obj) end end --- function M.showMessage(msg) --- local bufnr = vim.api.nvim_create_buf(false, true) --- local text = ' ' .. msg .. ' ' --- vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, { '', text, '' }) --- --- local width = #text + 2 --- local height = 3 --- --- -- Calculate center of the screen --- local row = math.floor((vim.o.lines - height) / 2) --- local col = math.floor((vim.o.columns - width) / 2) --- --- local opts = { --- relative = 'editor', --- row = row, --- col = col, --- width = width, --- height = height, --- style = 'minimal', --- border = 'double', --- focusable = false, --- zindex = 200, -- High zindex to stay above ToggleTerm --- } --- --- local win_id = vim.api.nvim_open_win(bufnr, false, opts) --- --- -- Apply a solid background so you can't see the terminal text through it --- vim.api.nvim_set_option_value('winhl', 'Normal:NormalFloat,FloatBorder:DiagnosticInfo', { scope = 'local', win = win_id }) --- --- return win_id --- end - --- function M.closeMessage(win_id) --- if win_id and vim.api.nvim_win_is_valid(win_id) then --- vim.api.nvim_win_close(win_id, true) --- end --- end ------------------------------------------------------ --INFO: --- stylua: ignore -function M.delete_file(path) +function M.deleteFile(path) local file = vim.fn.fnamemodify(path, ':t') if vim.fn.filereadable(path) == 1 then local success = vim.fn.delete(path) @@ -237,146 +200,6 @@ function M.jsonFormat(root_data) return table.concat(buffer) end ------------------------------------------------------- ---INFO: --- regex 100ms --- stylua: ignore -function M.pretty_json(data) - -- 1. Get a guaranteed valid JSON string from Neovim's core - local json = vim.json.encode(data) - - -- 2. Use regex to inject newlines and indentation - -- This is much faster than manual recursion in Lua - local indent = ' ' - local level = 0 - - -- Add newlines after { [ , and before } ] - json = json:gsub('([%[%{%],])', '%1\n') - json = json:gsub('([%]}])', '\n%1') - - local lines = {} - for line in json:gmatch('[^\n]+') do - line = line:gsub('^%s+', '') -- trim existing whitespace - - -- Decrease level if line starts with closing bracket - if line:match('^[%]}]') then level = level - 1 end - - table.insert(lines, string.rep(indent, level) .. line) - - -- Increase level if line ends with opening bracket - if line:match('[%[{]$') then level = level + 1 end - end - return table.concat(lines, '\n') -end - ------------------------------------------------------- ---INFO: --- recursion 50ms --- stylua: ignore --- local function pretty_print(data) -- 48ms -function M.pretty_print(data) -- 48ms - local buffer = {} - local insert = table.insert - - -- Table of standard JSON escape sequences - local escapes = { - ['\\'] = '\\\\', - ['"'] = '\\"', - ['\b'] = '\\b', - ['\f'] = '\\f', - ['\n'] = '\\n', - ['\r'] = '\\r', - ['\t'] = '\\t', - } - - local function format_item(item, current_level) - local indent = string.rep(' ', current_level) - local next_indent = string.rep(' ', current_level + 1) - - -- 1. Handle Neovim-specific Nulls and Empty Objects - -- vim.NIL represents a JSON 'null' (distinct from Lua nil) - if item == nil or item == vim.NIL then - insert(buffer, 'null') - return - elseif item == vim.empty_dict then - insert(buffer, '{}') - return - end - - if type(item) == 'table' then - -- 2. Determine if Table should be an Array [] or an Object {} - local is_array = false - local mt = getmetatable(item) - - -- If decoded by Neovim, it likely has a __jsontype marker - if mt and mt.__jsontype == 'array' then is_array = true - -- If not marked, treat as array if it has indexed items or is a plain empty table - elseif #item > 0 or (next(item) == nil and mt == nil) then is_array = true end - - -- 3. Handle Empty Structures Immediately - if next(item) == nil then - insert(buffer, is_array and '[]' or '{}') - return - end - - local opener = is_array and '[' or '{' - local closer = is_array and ']' or '}' - insert(buffer, opener .. '\n') - - -- 4. Key Management & Sorting - -- Sorting is mandatory for consistent SHA256 hashes across different systems - local keys = {} - for k in pairs(item) do insert(keys, k) end - - -- Sort object keys alphabetically - if not is_array then table.sort(keys, function(a, b) return tostring(a) < tostring(b) end) - -- Ensure array indices [1, 2, 3] are processed in order - else table.sort(keys) end - - -- 5. Iterate through items - for i, k in ipairs(keys) do - local v = item[k] - if i > 1 then insert(buffer, ',\n') end -- Standard JSON comma placement - insert(buffer, next_indent) - - -- If it's an object, add the "key": prefix - if not is_array then insert(buffer, '"' .. tostring(k) .. '": ') end - - -- Recurse for nested tables - format_item(v, current_level + 1) - end - - insert(buffer, '\n' .. indent .. closer) - - elseif type(item) == 'string' then - -- 6. String Escaping & Path Normalization - -- A. Apply standard escapes (newline, tab, etc.) - local s = item:gsub('[\\"\b\f\n\r\t]', escapes) - - -- B. Convert unprintable control characters to \u00xx format - s = s:gsub('[%z\1-\31]', function(c) - return string.format('\\u%04x', string.byte(c)) - end) - - -- C. Normalize Windows paths to Unix style - -- We flip double-backslashes (\\) to (/) so SHA256 matches across OSs - s = s:gsub('\\\\', '/') - - insert(buffer, '"' .. s .. '"') - - elseif type(item) == 'boolean' or type(item) == 'number' then - -- 7. Primitives - insert(buffer, tostring(item)) - else - -- 8. Fallback for anything else - insert(buffer, '"' .. tostring(item) .. '"') - end - end - - -- Start recursion at level 0 - format_item(data, 0) - return table.concat(buffer) -end ------------------------------------------------------ --INFO: @@ -386,8 +209,6 @@ end -- stylua: ignore ---@param path string function M.readFile(path) - local uv = vim.uv or vim.loop - -- 1. Check if file exists before opening to avoid "noisy" errors local stat = uv.fs_stat(path) if not stat then return false, 'File does not exist' end @@ -405,42 +226,6 @@ function M.readFile(path) return true, content end ------------------------------------------------------- --- function M.writeFile(path, data, opts) --- local uv = vim.uv or vim.loop --- --- opts = opts or {overwrite = true, mkdir = true} --- --- -- 1. Check if file exists and handle overwrite flag --- local stat = uv.fs_stat(path) --- if stat and opts.overwrite == false then --- return false, 'writeFile: File already exists and overwrite is disabled' --- end --- --- -- 2. Ensure folder exists (mkdir -p logic) --- if opts.mkdir ~= false then --- local parent = vim.fn.fnamemodify(path, ':h') --- if not stat or stat.type ~= 'directory' then --- -- Using vim.fn.mkdir is easier for recursive creation --- vim.fn.mkdir(parent, 'p', '0700') --- end --- end --- --- -- 3. Open file for writing --- local fd, err = uv.fs_open(path, 'w', 438) --- if not fd then return false, 'writeFile: Open error: ' .. (err or 'unknown') end --- --- -- 4. Write data --- local success, write_err = uv.fs_write(fd, data, 0) --- --- -- 5. ALWAYS close --- uv.fs_close(fd) --- --- if not success then return false, 'writeFile: Write error: ' .. write_err end --- --- return true, 'writeFile: complete' --- end - --INFO: -- Example -- local ok, err = writeFiile(path, json) @@ -450,8 +235,6 @@ end ---@param data string ---@param opts table function M.writeFile(path, data, opts) - local uv = vim.uv or vim.loop - -- opts.overwrite: boolean (default true) -- opts.mkdir: boolean (default true) opts = opts or { overwrite = true, mkdir = true } diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 6f464d8b..63e3a348 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -239,25 +239,10 @@ function M.fetch_metadata(callback, env, from, attempts) end -- else end - buildIdedata() - --------------------------------------------------------- -- STEP 3: Auto-Initialize (If files project.checksum and idedata.json are missing) --------------------------------------------------------- - -- if not ok or not current_checksum then - -- vim.notify(msg .. 'Initializing project metadata...', vim.log.levels.WARN) - -- vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env, '-s' }, { text = true }, function(obj) - -- vim.schedule(function() - -- if obj.code == 0 then - -- vim.notify(msg .. 'Initializing project metadata success.', vim.log.levels.ERROR) - -- M.fetch_metadata(callback, active_env, from, attempts - 1) -- Recursive call after files created - -- else - -- vim.notify(msg .. 'Initialization failed. Build project manually.', vim.log.levels.ERROR) - -- end - -- end) - -- end) - -- return - -- end + buildIdedata() --------------------------------------------------------- -- STEP 4: Standard CLI Fallback (The Slow Path) @@ -286,41 +271,6 @@ function M.fetch_metadata(callback, env, from, attempts) -- end) end --- INFO: --- stylua: ignore ---============================================================================= --- function M.pioConfig(callback) --- -- 'pio project config --json' is the only way to get FINAL computed paths --- vim.system({ 'pio', 'project', 'config', '--json' }, { text = true }, function(obj) --- if obj.code ~= 0 then return end --- --- local ok, data = pcall(vim.json.decode, obj.stdout) --- if not ok or type(data) ~= 'table' then return end --- --- local paths = {} --- -- PlatformIO JSON output groups options by section --- for _, section_data in pairs(data) do --- for _, item in ipairs(section_data) do --- if item.option == 'core_dir' then paths.core = item.value end --- if item.option == 'packages_dir' then paths.packages = item.value end --- if item.option == 'platforms_dir' then paths.platforms = item.value end --- end --- end --- --- -- Fill in defaults if not explicitly overridden --- local home = vim.uv.os_homedir() --- paths.core = paths.core or (home .. '/.platformio') --- paths.packages = paths.packages or (paths.core .. '/packages') --- paths.platforms = paths.platforms or (paths.core .. '/platforms') --- --- vim.schedule(function() --- _G.metadata.paths = paths -- Cache the results --- if callback then callback(paths) end --- end) --- end) --- end - - -- INFO: -- ============================================================================= -- Get project configuration @@ -640,6 +590,7 @@ function M.handlePioinit(result) vim.notify('PIO init: pass ' .. commandPassed, vim.log.levels.INFO) vim.notify('PIO init: Done', vim.log.levels.INFO) vim.misc.gitignore_lsp_configs('compile_commands.json') + vim.misc.deleteFile(vim.misc.joinPath(vim.vim.g.platformioRootDir, '.ccl')) -- \27[s : Save current cursor position (the prompt) -- \r : Go to start of line From 60f3577c5386179824a730beaa9efdc9ecd84cc5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 23:19:21 +0300 Subject: [PATCH 1342/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 63e3a348..8a2f5524 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -590,7 +590,7 @@ function M.handlePioinit(result) vim.notify('PIO init: pass ' .. commandPassed, vim.log.levels.INFO) vim.notify('PIO init: Done', vim.log.levels.INFO) vim.misc.gitignore_lsp_configs('compile_commands.json') - vim.misc.deleteFile(vim.misc.joinPath(vim.vim.g.platformioRootDir, '.ccl')) + vim.misc.deleteFile(vim.misc.joinPath(vim.vim.g.platformioRootDir, '.ccls')) -- \27[s : Save current cursor position (the prompt) -- \r : Go to start of line From dcc1cbc770b4a1fa9c32773028d82917d518d293 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 23:26:55 +0300 Subject: [PATCH 1343/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 8a2f5524..f4b5c009 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -590,7 +590,7 @@ function M.handlePioinit(result) vim.notify('PIO init: pass ' .. commandPassed, vim.log.levels.INFO) vim.notify('PIO init: Done', vim.log.levels.INFO) vim.misc.gitignore_lsp_configs('compile_commands.json') - vim.misc.deleteFile(vim.misc.joinPath(vim.vim.g.platformioRootDir, '.ccls')) + vim.misc.deleteFile(vim.fs.joinpath(vim.vim.g.platformioRootDir, '.ccls')) -- \27[s : Save current cursor position (the prompt) -- \r : Go to start of line From c1203dfa56c5cd8b2f9fa13ed962f2ef708c1984 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 23:31:50 +0300 Subject: [PATCH 1344/1406] update --- lua/platformio/utils/misc.lua | 13 ++++--------- lua/platformio/utils/pio.lua | 2 +- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/lua/platformio/utils/misc.lua b/lua/platformio/utils/misc.lua index 5855db7d..2aee7f94 100644 --- a/lua/platformio/utils/misc.lua +++ b/lua/platformio/utils/misc.lua @@ -76,20 +76,15 @@ end ------------------------------------------------------ --INFO: ---- stylua: ignore +-- stylua: ignore function M.deleteFile(path) local file = vim.fn.fnamemodify(path, ':t') if vim.fn.filereadable(path) == 1 then local success = vim.fn.delete(path) - if success == 0 then - vim.notify('PlatformIO: ' .. file .. ' file removed', vim.log.levels.INFO) - else - vim.notify('PlatformIO: Failed to delete ' .. file, vim.log.levels.ERROR) - end - else - vim.notify('PlatformIO: ' .. file .. ' file not found', vim.log.levels.WARN) - end + if success == 0 then vim.notify('PlatformIO: ' .. file .. ' file removed', vim.log.levels.INFO) + else vim.notify('PlatformIO: Failed to delete ' .. file, vim.log.levels.ERROR) end + else vim.notify('PlatformIO: ' .. file .. ' file not found', vim.log.levels.WARN) end end ------------------------------------------------------ diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f4b5c009..59e675f2 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -590,7 +590,6 @@ function M.handlePioinit(result) vim.notify('PIO init: pass ' .. commandPassed, vim.log.levels.INFO) vim.notify('PIO init: Done', vim.log.levels.INFO) vim.misc.gitignore_lsp_configs('compile_commands.json') - vim.misc.deleteFile(vim.fs.joinpath(vim.vim.g.platformioRootDir, '.ccls')) -- \27[s : Save current cursor position (the prompt) -- \r : Go to start of line @@ -614,6 +613,7 @@ function M.handlePioinit(result) -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') end, 'PIO init: ') end) + vim.misc.deleteFile(vim.fs.joinpath(vim.vim.g.platformioRootDir, '.ccls')) M.queue = {} term.stdout_callback = nil trm:close() From 1d3a0b93563388bae4566f3477273cf0d55181c1 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 23:39:40 +0300 Subject: [PATCH 1345/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 59e675f2..edf6f62a 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -613,7 +613,7 @@ function M.handlePioinit(result) -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') end, 'PIO init: ') end) - vim.misc.deleteFile(vim.fs.joinpath(vim.vim.g.platformioRootDir, '.ccls')) + vim.misc.deleteFile(vim.fs.joinpath(vim.g.platformioRootDir, '.ccls')) M.queue = {} term.stdout_callback = nil trm:close() From b10209a2b0d463f706bffc46e04508a8d376ee44 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Fri, 1 May 2026 23:52:26 +0300 Subject: [PATCH 1346/1406] update --- lua/platformio/pio_setup.lua | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index d0e15fd1..3521fffd 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -76,12 +76,12 @@ function M.run_compiledb(target) if obj.code == 0 then -- vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) -- Trigger refresh (LSP restart, etc.) - -- vim.schedule(function () - -- M.pio_refresh(function() - clangdRestart() - vim.notify('PIO platformio.ini change: Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- end, 'PIO platformio.ini change: ') - -- end) + vim.schedule(function () + M.pio_refresh(function() + clangdRestart() + vim.notify('PIO platformio.ini change: Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) + end, 'PIO platformio.ini change: ') + end) else local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) From 6a81f8f9a5cf61745f0d5d6be104b97248adf2e3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 06:15:25 +0300 Subject: [PATCH 1347/1406] update --- lua/platformio/boilerplate.lua | 11 ++--------- lua/platformio/utils/pio.lua | 20 +++++++++++--------- 2 files changed, 13 insertions(+), 18 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 9d030970..54d684d9 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -80,6 +80,7 @@ boilerplate['.clangd_config'] = { "--all-scopes-completion", "--background-index", "--clang-tidy", + "--compile-commands-dir=.", "--compile_args_from=filesystem", "--enable-config", "--completion-parse=always", @@ -485,6 +486,7 @@ function M.boilerplate_gen(framework, src_path, filename) local entry = boilerplate[framework] if not entry then return '' end local file_path = vim.fs.normalize(src_path .. '/' .. filename) + if vim.uv.fs_stat(file_path) then if not entry.rewrite then if entry.read then @@ -496,17 +498,8 @@ function M.boilerplate_gen(framework, src_path, filename) return '' end end - -- if vim.fn.isdirectory(src_path) == 0 then vim.fn.mkdir(src_path, 'p') end - -- - -- local fd = assert(uv.fs_open(file_path, 'w', 420)) - -- if not fd then - -- print('failed to create file: ' .. file_path) - -- return '' - -- end -- local template = type(entry.content) == 'function' and entry:content() or entry.content - -- uv.fs_write(fd, template, 0) - -- uv.fs_close(fd) vim.misc.writeFile(file_path, template, {}) if entry.read then diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index edf6f62a..4d6dacaa 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -521,6 +521,7 @@ local trm ------------------------------------------------------ -- Handle after pioinit execution -- ============================================================================= +-- stylua: ignore function M.handlePioinitDb(result) if result == 'INIT' then local boilerplate = require('platformio.boilerplate') @@ -535,14 +536,14 @@ function M.handlePioinitDb(result) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') - term.ToggleTerminal(table.remove(M.queue, 1), 'float') + if #M.queue > 0 then term.ToggleTerminal(table.remove(M.queue, 1), 'float') end elseif result == 'PASS' then -- if commandPassed == 1 then -- elseif commandPassed == 2 then -- if you sned more than 2 commands you need this -- end vim.notify('PIO init+db: pass ' .. commandPassed, vim.log.levels.INFO) commandPassed = commandPassed + 1 - term.ToggleTerminal(table.remove(M.queue, 1), 'float') + if #M.queue > 0 then term.ToggleTerminal(table.remove(M.queue, 1), 'float') end elseif result == 'DONE' then -- result of the last command vim.schedule(function() vim.notify('PIO init+db: pass ' .. commandPassed, vim.log.levels.INFO) @@ -552,9 +553,7 @@ function M.handlePioinitDb(result) boilerplate_gen([[.clangd]], _G.metadata.core_dir) local pio_refresh = require('platformio.pio_setup').pio_refresh - pio_refresh(function() - clangdRestart() - end, 'PIO init+db: ') + pio_refresh(function() clangdRestart() end, 'PIO init+db: ') end) M.queue = {} term.stdout_callback = nil @@ -569,6 +568,7 @@ end local win_id ---------------------------------------------------- -- Handle after pioinit execution +-- stylua: ignore function M.handlePioinit(result) if result == 'INIT' then local boilerplate = require('platformio.boilerplate') @@ -584,7 +584,7 @@ function M.handlePioinit(result) -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') win_id = vim.misc.showMessage('************ Project Initializing ************') - trm = term.ToggleTerminal(table.remove(M.queue, 1), 'float') + if #M.queue > 0 then trm = term.ToggleTerminal(table.remove(M.queue, 1), 'float')end elseif result == 'DONE' then -- result of the last command vim.schedule(function() vim.notify('PIO init: pass ' .. commandPassed, vim.log.levels.INFO) @@ -607,7 +607,7 @@ function M.handlePioinit(result) local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen([[.clangd]], _G.metadata.core_dir) + -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) clangdRestart() vim.misc.closeMessage(win_id) -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') @@ -630,9 +630,10 @@ end ------------------------------------------------------ -- Handle after piolib execution -- ============================================================================= +-- stylua: ignore function M.handlePiolib(result) if result == 'INIT' then - term.ToggleTerminal(table.remove(M.queue, 1), 'float') + if #M.queue > 0 then term.ToggleTerminal(table.remove(M.queue, 1), 'float')end elseif result == 'DONE' then -- result of the only and the last command vim.notify('PIO lib: pass ' .. commandPassed, vim.log.levels.INFO) vim.notify('PIO lib: Done', vim.log.levels.INFO) @@ -649,9 +650,10 @@ end ------------------------------------------------------ -- ============================================================================= +-- stylua: ignore function M.handlePiodb(target, result) if result == 'INIT' then - term.ToggleTerminal(table.remove(M.queue, 1), 'float') + if #M.queue > 0 then term.ToggleTerminal(table.remove(M.queue, 1), 'float')end elseif result == 'DONE' then -- result of the only and the last command vim.notify('PIO db: pass ' .. commandPassed, vim.log.levels.INFO) vim.notify('PIO db: Done', vim.log.levels.INFO) From 5876a04b1e6959ade081ba55ac11372f59c841c9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 06:45:49 +0300 Subject: [PATCH 1348/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/lspConfig/clangd.lua | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 54d684d9..7df16732 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -80,7 +80,7 @@ boilerplate['.clangd_config'] = { "--all-scopes-completion", "--background-index", "--clang-tidy", - "--compile-commands-dir=.", + "--compile-commands-dir=%s" "--compile_args_from=filesystem", "--enable-config", "--completion-parse=always", diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 861e9df2..54e65ec2 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -125,7 +125,7 @@ function _G.get_clangd_config() -- 3. Format your template string local table_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) - local formatted_str = string.format(table_config or '', q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) + local formatted_str = string.format(table_config or '', vim.misc.normalizePath(new_root_dir), q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) -- local formatted_str = string.format(table_config or '', q_driver, '', vim.misc.normalizePath(new_root_dir)) -- 4. Load the config table From a702420629254d637dc5773961aa85b8204afa6a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 06:49:52 +0300 Subject: [PATCH 1349/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 7df16732..307bc418 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -80,7 +80,7 @@ boilerplate['.clangd_config'] = { "--all-scopes-completion", "--background-index", "--clang-tidy", - "--compile-commands-dir=%s" + "--compile-commands-dir=%s", "--compile_args_from=filesystem", "--enable-config", "--completion-parse=always", From a2c57db41e52b3aeffb01b1ecbc7d82c43a191fb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 07:10:18 +0300 Subject: [PATCH 1350/1406] update --- lua/platformio/boilerplate.lua | 46 ++++++++++++++++++++++++++++- lua/platformio/lspConfig/clangd.lua | 3 +- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 307bc418..863e8945 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -114,10 +114,10 @@ boilerplate['.clangd_config'] = { completeUnimported = true, fallbackFlags = {%s}, clangdFileStatus = true, - compilationDatabasePath = %q, } } ]], + -- compilationDatabasePath = %q, } -- CompileFlags: -- Add: @@ -220,6 +220,50 @@ Diagnostics: - "bugprone-*" - "hicpp-vararg" - "modernize-*" +--- +# This section targets external library files specifically +If: + PathMatch: [.*\.platformio/packages/.*] +CompileFlags: + Add: + - "-xc++" + - "-std=c++17" + Remove: + - "-Winclude-next-outside-header" + - "-fno-fat-lto-objects" + - "-fno%%-fat%%-lto%%-objects" + - "-fno%%-canonical%%-system%%-headers" + - "-misc-definitions-in-headers" + - "-fno-tree-switch-conversion" + - "-mtext-section-literals" + - "-mlong-calls" + - "-mlongcalls" + - "-fstrict-volatile-bitfields" + - "-free*" + - "-fipa-pta*" + - "-march=*" + - "-mabi=*" + - "-mcpu=*" +Diagnostics: + Suppress: + - "pragma_system_header_ignored" + - "misc-definitions-in-headers" + - "pp_including_mainfile_in_preamble" + - "misc-unused-using-decls" + - "unused-includes" + ClangTidy: + Remove: + - "readability-*" + - "cert-err58-cpp" + - "llvmlibc-*" + - "fuchsia-*" + - "hicpp-avoid-c-arrays" + - "cppcoreguidelines-*" + - "llvm-*" + - "google-*" + - "bugprone-*" + - "hicpp-vararg" + - "modernize-*" ]], -- content = function(self) -- local sysroot = '--sysroot=' .. _G.metadata.sysroot diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 54e65ec2..b2e9a598 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -125,7 +125,8 @@ function _G.get_clangd_config() -- 3. Format your template string local table_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) - local formatted_str = string.format(table_config or '', vim.misc.normalizePath(new_root_dir), q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) + -- local formatted_str = string.format(table_config or '', q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) + local formatted_str = string.format(table_config or '', q_driver, f_flags) -- local formatted_str = string.format(table_config or '', q_driver, '', vim.misc.normalizePath(new_root_dir)) -- 4. Load the config table From 92c69483b08acbf0a507db1d9ec26e35891d8da4 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 07:15:31 +0300 Subject: [PATCH 1351/1406] update --- lua/platformio/lspConfig/clangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index b2e9a598..453f7d29 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -126,8 +126,8 @@ function _G.get_clangd_config() -- 3. Format your template string local table_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) -- local formatted_str = string.format(table_config or '', q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) - local formatted_str = string.format(table_config or '', q_driver, f_flags) -- local formatted_str = string.format(table_config or '', q_driver, '', vim.misc.normalizePath(new_root_dir)) + local formatted_str = string.format(table_config or '', q_driver, '') -- 4. Load the config table local cok, clangd_config = pcall(function() return load('return ' .. formatted_str)() end) From 14023db25bf0fa7c4964fca412add358bbe0dbb5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 07:17:24 +0300 Subject: [PATCH 1352/1406] update --- lua/platformio/boilerplate.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 863e8945..883a62f7 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -80,7 +80,6 @@ boilerplate['.clangd_config'] = { "--all-scopes-completion", "--background-index", "--clang-tidy", - "--compile-commands-dir=%s", "--compile_args_from=filesystem", "--enable-config", "--completion-parse=always", From 5dfa3cc1ad52b3ae231a2b334be6d1f2f8640314 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 07:32:16 +0300 Subject: [PATCH 1353/1406] update --- lua/platformio/boilerplate.lua | 13 +++++++++---- lua/platformio/lspConfig/clangd.lua | 2 +- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 883a62f7..9fa0eed1 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -109,10 +109,11 @@ boilerplate['.clangd_config'] = { workspace_required = true, single_file_support = true, init_options = { - usePlaceholders = true, - completeUnimported = true, - fallbackFlags = {%s}, - clangdFileStatus = true, + usePlaceholders = true, + completeUnimported = true, + fallbackFlags = {%s}, + clangdFileStatus = true, + compilationDatabasePath = %q, } } ]], @@ -184,6 +185,8 @@ CompileFlags: - "-xc++" - "-std=c++17" Remove: + - "pp_file_not_found" + - "pp_file_not_found_angled_not_fatal" - "-Winclude-next-outside-header" - "-fno-fat-lto-objects" - "-fno%%-fat%%-lto%%-objects" @@ -228,6 +231,8 @@ CompileFlags: - "-xc++" - "-std=c++17" Remove: + - "pp_file_not_found" + - "pp_file_not_found_angled_not_fatal" - "-Winclude-next-outside-header" - "-fno-fat-lto-objects" - "-fno%%-fat%%-lto%%-objects" diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 453f7d29..8cc5e01e 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -127,7 +127,7 @@ function _G.get_clangd_config() local table_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) -- local formatted_str = string.format(table_config or '', q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) -- local formatted_str = string.format(table_config or '', q_driver, '', vim.misc.normalizePath(new_root_dir)) - local formatted_str = string.format(table_config or '', q_driver, '') + local formatted_str = string.format(table_config or '', q_driver, '', vim.g.platformioRootDir) -- 4. Load the config table local cok, clangd_config = pcall(function() return load('return ' .. formatted_str)() end) From 9685c256d4b511e2c058ab4d446680875dd65aa6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 12:41:33 +0300 Subject: [PATCH 1354/1406] update --- lua/platformio/boilerplate.lua | 129 +++++++++++++++------------------ 1 file changed, 59 insertions(+), 70 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 9fa0eed1..4c2d7085 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -185,89 +185,32 @@ CompileFlags: - "-xc++" - "-std=c++17" Remove: - - "pp_file_not_found" - - "pp_file_not_found_angled_not_fatal" - - "-Winclude-next-outside-header" + # Exact matches - "-fno-fat-lto-objects" - - "-fno%%-fat%%-lto%%-objects" - - "-fno%%-canonical%%-system%%-headers" - - "-misc-definitions-in-headers" + - "-fno-canonical-system-headers" - "-fno-tree-switch-conversion" - "-mtext-section-literals" - "-mlong-calls" - - "-mlongcalls" - "-fstrict-volatile-bitfields" - - "-free*" - - "-fipa-pta*" - - "-march=*" - - "-mabi=*" - - "-mcpu=*" + # REGEX matches (Supported in your version 22.1.1) + - "-march=.*" + - "-mabi=.*" + - "-mcpu=.*" + - "-fipa-pta.*" + - "-free.*" + Diagnostics: Suppress: - "pragma_system_header_ignored" - - "misc-definitions-in-headers" - - "pp_including_mainfile_in_preamble" - - "misc-unused-using-decls" - - "unused-includes" - ClangTidy: - Remove: - - "readability-*" - - "cert-err58-cpp" - - "llvmlibc-*" - - "fuchsia-*" - - "hicpp-avoid-c-arrays" - - "cppcoreguidelines-*" - - "llvm-*" - - "google-*" - - "bugprone-*" - - "hicpp-vararg" - - "modernize-*" ---- -# This section targets external library files specifically -If: - PathMatch: [.*\.platformio/packages/.*] -CompileFlags: - Add: - - "-xc++" - - "-std=c++17" - Remove: - "pp_file_not_found" - - "pp_file_not_found_angled_not_fatal" - - "-Winclude-next-outside-header" - - "-fno-fat-lto-objects" - - "-fno%%-fat%%-lto%%-objects" - - "-fno%%-canonical%%-system%%-headers" - - "-misc-definitions-in-headers" - - "-fno-tree-switch-conversion" - - "-mtext-section-literals" - - "-mlong-calls" - - "-mlongcalls" - - "-fstrict-volatile-bitfields" - - "-free*" - - "-fipa-pta*" - - "-march=*" - - "-mabi=*" - - "-mcpu=*" -Diagnostics: - Suppress: - - "pragma_system_header_ignored" - - "misc-definitions-in-headers" + - "pp_file_not_found_angled_not_fatal" - "pp_including_mainfile_in_preamble" + - "misc-definitions-in-headers" - "misc-unused-using-decls" - "unused-includes" ClangTidy: - Remove: - - "readability-*" - - "cert-err58-cpp" - - "llvmlibc-*" - - "fuchsia-*" - - "hicpp-avoid-c-arrays" - - "cppcoreguidelines-*" - - "llvm-*" - - "google-*" - - "bugprone-*" - - "hicpp-vararg" - - "modernize-*" + Remove: ["readability-*", "modernize-*", "bugprone-*", "cert-err58-cpp"] + ]], -- content = function(self) -- local sysroot = '--sysroot=' .. _G.metadata.sysroot @@ -276,6 +219,52 @@ Diagnostics: -- end, } +-- # This section targets external library files specifically +--- +-- If: +-- PathMatch: [.*\.platformio/packages/.*] +-- CompileFlags: +-- Add: +-- - "-xc++" +-- - "-std=c++17" +-- Remove: +-- - "pp_file_not_found" +-- - "pp_file_not_found_angled_not_fatal" +-- - "-Winclude-next-outside-header" +-- - "-fno-fat-lto-objects" +-- - "-fno%%-fat%%-lto%%-objects" +-- - "-fno%%-canonical%%-system%%-headers" +-- - "-misc-definitions-in-headers" +-- - "-fno-tree-switch-conversion" +-- - "-mtext-section-literals" +-- - "-mlong-calls" +-- - "-mlongcalls" +-- - "-fstrict-volatile-bitfields" +-- - "-free*" +-- - "-fipa-pta*" +-- - "-march=*" +-- - "-mabi=*" +-- - "-mcpu=*" +-- Diagnostics: +-- Suppress: +-- - "pragma_system_header_ignored" +-- - "misc-definitions-in-headers" +-- - "pp_including_mainfile_in_preamble" +-- - "misc-unused-using-decls" +-- - "unused-includes" +-- ClangTidy: +-- Remove: +-- - "readability-*" +-- - "cert-err58-cpp" +-- - "llvmlibc-*" +-- - "fuchsia-*" +-- - "hicpp-avoid-c-arrays" +-- - "cppcoreguidelines-*" +-- - "llvm-*" +-- - "google-*" +-- - "bugprone-*" +-- - "hicpp-vararg" +-- - "modernize-*" -- INFO: .clang-format boilerplate['.clang-format'] = { rewrite = false, From 5ee739783ac921b5fb573f080bca83ac42d02ef6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 12:48:31 +0300 Subject: [PATCH 1355/1406] update --- lua/platformio/boilerplate.lua | 16 ++++------------ lua/platformio/utils/pio.lua | 2 +- 2 files changed, 5 insertions(+), 13 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 4c2d7085..eac425ba 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -181,36 +181,28 @@ boilerplate['.clangd'] = { -- template = [[ content = [[ CompileFlags: - Add: - - "-xc++" - - "-std=c++17" - Remove: - # Exact matches + Remove: + - "-fno-tree-switch-conversion" - "-fno-fat-lto-objects" - "-fno-canonical-system-headers" - - "-fno-tree-switch-conversion" - "-mtext-section-literals" - "-mlong-calls" - "-fstrict-volatile-bitfields" - # REGEX matches (Supported in your version 22.1.1) - "-march=.*" - "-mabi=.*" - "-mcpu=.*" - "-fipa-pta.*" - - "-free.*" Diagnostics: - Suppress: + Suppress: + - "unused-includes" - "pragma_system_header_ignored" - "pp_file_not_found" - "pp_file_not_found_angled_not_fatal" - "pp_including_mainfile_in_preamble" - "misc-definitions-in-headers" - - "misc-unused-using-decls" - - "unused-includes" ClangTidy: Remove: ["readability-*", "modernize-*", "bugprone-*", "cert-err58-cpp"] - ]], -- content = function(self) -- local sysroot = '--sysroot=' .. _G.metadata.sysroot diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 4d6dacaa..cfe7a028 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -607,7 +607,7 @@ function M.handlePioinit(result) local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) + boilerplate_gen([[.clangd]], _G.metadata.core_dir) clangdRestart() vim.misc.closeMessage(win_id) -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') From 95755b5a655db859f24a8573e790d74bc871d696 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 12:51:47 +0300 Subject: [PATCH 1356/1406] update --- lua/platformio/boilerplate.lua | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index eac425ba..7bf1b5f6 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -181,6 +181,9 @@ boilerplate['.clangd'] = { -- template = [[ content = [[ CompileFlags: + Add: + - "-xc++" + - "-std=c++17" Remove: - "-fno-tree-switch-conversion" - "-fno-fat-lto-objects" From 873b64d5517b2cb4fe9b003c5a6719ed5ce18e16 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 12:55:18 +0300 Subject: [PATCH 1357/1406] update --- lua/platformio/boilerplate.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 7bf1b5f6..8714c67b 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -183,7 +183,6 @@ boilerplate['.clangd'] = { CompileFlags: Add: - "-xc++" - - "-std=c++17" Remove: - "-fno-tree-switch-conversion" - "-fno-fat-lto-objects" From 058774721523a75ec6435f8ac51adc49c1e82491 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 12:59:46 +0300 Subject: [PATCH 1358/1406] update --- lua/platformio/boilerplate.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 8714c67b..003694d7 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -181,8 +181,10 @@ boilerplate['.clangd'] = { -- template = [[ content = [[ CompileFlags: + BuiltinHeaders: QueryDriver Add: - "-xc++" + - "-std=c++17" Remove: - "-fno-tree-switch-conversion" - "-fno-fat-lto-objects" From 442695ce743285b96d554bf47741e437995d923c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 13:14:23 +0300 Subject: [PATCH 1359/1406] update --- lua/platformio/boilerplate.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 003694d7..74d94b7f 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -199,11 +199,12 @@ CompileFlags: Diagnostics: Suppress: - - "unused-includes" - - "pragma_system_header_ignored" - "pp_file_not_found" - "pp_file_not_found_angled_not_fatal" + - "pp_included_file_not_found" - "pp_including_mainfile_in_preamble" + - "unused-includes" + - "pragma_system_header_ignored" - "misc-definitions-in-headers" ClangTidy: Remove: ["readability-*", "modernize-*", "bugprone-*", "cert-err58-cpp"] From e34cd71e50b43f03ecc16ce9bdb3d4ed7d4f8c7e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 13:23:29 +0300 Subject: [PATCH 1360/1406] update --- lua/platformio/pio_setup.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 3521fffd..52e8c72e 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -66,7 +66,7 @@ function M.run_compiledb(target) -- }) -- if env and env ~= '' then - vim.notify('PIO platformio.ini change: update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) + vim.notify('PIO platformio.ini change: compiledb update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) -- vim.schedule(function() vim.system({ 'pio', 'run', '-t', 'compiledb', '-s', '-e', env }, { text = true }, function(obj) -- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) @@ -79,7 +79,7 @@ function M.run_compiledb(target) vim.schedule(function () M.pio_refresh(function() clangdRestart() - vim.notify('PIO platformio.ini change: Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) + vim.notify('PIO platformio.ini change: compiledb update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) end, 'PIO platformio.ini change: ') end) else From 091282b590fb56927df68c590060d8d9dce73c87 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 13:29:15 +0300 Subject: [PATCH 1361/1406] update --- lua/platformio/boilerplate.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 74d94b7f..cd75bde5 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -184,7 +184,7 @@ CompileFlags: BuiltinHeaders: QueryDriver Add: - "-xc++" - - "-std=c++17" + - "-std=gnu++17" Remove: - "-fno-tree-switch-conversion" - "-fno-fat-lto-objects" From 0da4f6a18d9fae50507b162fa69f847c09f1655c Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 13:47:17 +0300 Subject: [PATCH 1362/1406] update --- lua/platformio/utils/pio.lua | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index cfe7a028..5fd31ee3 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -194,7 +194,6 @@ function M.fetch_metadata(callback, env, from, attempts) end) end) return true - end --------------------------------------------------------- @@ -566,6 +565,9 @@ function M.handlePioinitDb(result) end local win_id +-- if current_checksum == meta.last_projectChecksum then +local current_checksum = _G.metadata.last_projectChecksum + ---------------------------------------------------- -- Handle after pioinit execution -- stylua: ignore @@ -604,14 +606,16 @@ function M.handlePioinit(result) -- local clean_msg = string.format('\27[G\27[2K\27[33m%s\27[0m', msg) -- vim.api.nvim_chan_send(trm.job_id, clean_msg) - local pio_refresh = require('platformio.pio_setup').pio_refresh - pio_refresh(function() - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen([[.clangd]], _G.metadata.core_dir) - clangdRestart() - vim.misc.closeMessage(win_id) - -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') - end, 'PIO init: ') + if current_checksum == _G.metadata.last_projectChecksum then + local pio_refresh = require('platformio.pio_setup').pio_refresh + pio_refresh(function() + clangdRestart() + -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') + end, 'PIO init: ') + end + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen([[.clangd]], _G.metadata.core_dir) + vim.misc.closeMessage(win_id) end) vim.misc.deleteFile(vim.fs.joinpath(vim.g.platformioRootDir, '.ccls')) M.queue = {} From 54a652f9973939af7efa160705a89d8eaa5b43e2 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 13:49:57 +0300 Subject: [PATCH 1363/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 5fd31ee3..9ff666d1 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -566,7 +566,7 @@ end local win_id -- if current_checksum == meta.last_projectChecksum then -local current_checksum = _G.metadata.last_projectChecksum +local current_checksum = _G.metadata.last_projectChecksum or '' ---------------------------------------------------- -- Handle after pioinit execution From 77db1784cb070a2af5caa41eb07dee0402b1ebdb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 13:52:58 +0300 Subject: [PATCH 1364/1406] update --- lua/platformio/utils/pio.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 9ff666d1..f298e77c 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -566,13 +566,14 @@ end local win_id -- if current_checksum == meta.last_projectChecksum then -local current_checksum = _G.metadata.last_projectChecksum or '' +local current_checksum = '' ---------------------------------------------------- -- Handle after pioinit execution -- stylua: ignore function M.handlePioinit(result) if result == 'INIT' then + current_checksum = _G.metadata.last_projectChecksum local boilerplate = require('platformio.boilerplate') local boilerplate_gen = boilerplate.boilerplate_gen From d6dc2ae8224af928fef360a8feac1aa34e349dd3 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 13:55:26 +0300 Subject: [PATCH 1365/1406] update --- lua/platformio/pio_setup.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 52e8c72e..4640c936 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -78,8 +78,8 @@ function M.run_compiledb(target) -- Trigger refresh (LSP restart, etc.) vim.schedule(function () M.pio_refresh(function() - clangdRestart() vim.notify('PIO platformio.ini change: compiledb update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) + clangdRestart() end, 'PIO platformio.ini change: ') end) else From 6efe250758de03936e1a2b7ea9dde4902ca28944 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 14:00:48 +0300 Subject: [PATCH 1366/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index f298e77c..e9e02da3 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -565,7 +565,6 @@ function M.handlePioinitDb(result) end local win_id --- if current_checksum == meta.last_projectChecksum then local current_checksum = '' ---------------------------------------------------- @@ -607,6 +606,7 @@ function M.handlePioinit(result) -- local clean_msg = string.format('\27[G\27[2K\27[33m%s\27[0m', msg) -- vim.api.nvim_chan_send(trm.job_id, clean_msg) + print('current= '.. current_checksum .. ' meta='.. _G.metadata.last_projectChecksum) if current_checksum == _G.metadata.last_projectChecksum then local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() From 23a899bf830020f217b54072b1d5076321e64801 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 14:19:22 +0300 Subject: [PATCH 1367/1406] update --- lua/platformio/pio_setup.lua | 3 ++- lua/platformio/utils/pio.lua | 24 +++++++++++------------- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 4640c936..538bdde3 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -49,10 +49,11 @@ local last_mtime = 0 function M.run_compiledb(target) -- 1. Prevent overlapping builds if target.isBusy then return end + if _G.metadata.isBusy == true then return end + local env = vim.pio.get_active__env() if not env then return end target.isBusy = true - _G.metadata.isBusy = true -- local pio = require('platformio.utils.pio') diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index e9e02da3..5f4bc1e1 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -565,14 +565,12 @@ function M.handlePioinitDb(result) end local win_id -local current_checksum = '' ---------------------------------------------------- -- Handle after pioinit execution -- stylua: ignore function M.handlePioinit(result) if result == 'INIT' then - current_checksum = _G.metadata.last_projectChecksum local boilerplate = require('platformio.boilerplate') local boilerplate_gen = boilerplate.boilerplate_gen @@ -585,6 +583,7 @@ function M.handlePioinit(result) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') + _G.metadata.isBusy = true win_id = vim.misc.showMessage('************ Project Initializing ************') if #M.queue > 0 then trm = term.ToggleTerminal(table.remove(M.queue, 1), 'float')end elseif result == 'DONE' then -- result of the last command @@ -606,17 +605,15 @@ function M.handlePioinit(result) -- local clean_msg = string.format('\27[G\27[2K\27[33m%s\27[0m', msg) -- vim.api.nvim_chan_send(trm.job_id, clean_msg) - print('current= '.. current_checksum .. ' meta='.. _G.metadata.last_projectChecksum) - if current_checksum == _G.metadata.last_projectChecksum then - local pio_refresh = require('platformio.pio_setup').pio_refresh - pio_refresh(function() - clangdRestart() - -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') - end, 'PIO init: ') - end - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen([[.clangd]], _G.metadata.core_dir) - vim.misc.closeMessage(win_id) + local pio_refresh = require('platformio.pio_setup').pio_refresh + pio_refresh(function() + _G.metadata.isBusy = false + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen([[.clangd]], _G.metadata.core_dir) + vim.misc.closeMessage(win_id) + clangdRestart() + -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') + end, 'PIO init: ') end) vim.misc.deleteFile(vim.fs.joinpath(vim.g.platformioRootDir, '.ccls')) M.queue = {} @@ -624,6 +621,7 @@ function M.handlePioinit(result) trm:close() _G.metadata.isBusy = false elseif result == 'FAIL' then + _G.metadata.isBusy = false vim.misc.closeMessage(win_id) M.queue = {} term.stdout_callback = nil From af1474a6001669c7923869bebacbeb4409385987 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 14:26:24 +0300 Subject: [PATCH 1368/1406] update --- lua/platformio/metadata.lua | 8 +++----- lua/platformio/utils/pio.lua | 4 ++-- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index c1044da4..9e3b35dc 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -81,7 +81,7 @@ local config_path = vim.fs.joinpath(vim.uv.cwd(), '.project_config.json') -- local misc = vim.misc --INFO: -- 3. Save Logic (Uses sha256 for stability) -function M.save_project_config(quiet) +function M.save_project_config(from) -- 1. Generate the formatted string directly, jsonFormat already returns a string! local ok, pretty_json = pcall(vim.misc.jsonFormat, _pio_metadata) @@ -98,11 +98,9 @@ function M.save_project_config(quiet) if status then last_saved_hash = current_hash - if not quiet then - vim.notify('PIO save config: success', vim.log.levels.INFO, { title = 'PlatformIO' }) - end + vim.notify(from .. 'save config: success', vim.log.levels.INFO, { title = 'PlatformIO' }) else - vim.notify('PIO save config: failed==> ' .. (err or 'unknown error'), vim.log.levels.ERROR) + vim.notify(from .. 'save config: failed==> ' .. (err or 'unknown error'), vim.log.levels.ERROR) end end end diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 5f4bc1e1..bc8112b3 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -221,7 +221,7 @@ function M.fetch_metadata(callback, env, from, attempts) if cok and apply_metadata(decoded, current_checksum) then local metadata = require('platformio.metadata') - metadata.save_project_config() + metadata.save_project_config(msg) vim.notify(msg .. 'Metadata synced from cache', vim.log.levels.INFO) -- if callback then vim.schedule(callback) end @@ -229,7 +229,7 @@ function M.fetch_metadata(callback, env, from, attempts) vim.schedule(callback) else -- If it's not a function, just do nothing or print a debug message - print("Debug: callback was " .. type(callback)) + print(msg .." Debug; callback was " .. type(callback)) end return true From f4a71155a530b309a5834e631b2f4cb3f9130c8a Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 14:29:34 +0300 Subject: [PATCH 1369/1406] update --- lua/platformio/metadata.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index 9e3b35dc..bb7f9d83 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -98,9 +98,9 @@ function M.save_project_config(from) if status then last_saved_hash = current_hash - vim.notify(from .. 'save config: success', vim.log.levels.INFO, { title = 'PlatformIO' }) + vim.notify(from .. 'config save success', vim.log.levels.INFO, { title = 'PlatformIO' }) else - vim.notify(from .. 'save config: failed==> ' .. (err or 'unknown error'), vim.log.levels.ERROR) + vim.notify(from .. 'config save failed==> ' .. (err or 'unknown error'), vim.log.levels.ERROR) end end end From c3441bcba4eb97a99a5bc6519ebda806df22692e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 14:40:34 +0300 Subject: [PATCH 1370/1406] update --- lua/platformio/pioinit2.lua | 10 +++++----- lua/platformio/utils/pio.lua | 17 ++++++++++++----- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/lua/platformio/pioinit2.lua b/lua/platformio/pioinit2.lua index 7c8c7680..659b1b55 100644 --- a/lua/platformio/pioinit2.lua +++ b/lua/platformio/pioinit2.lua @@ -47,12 +47,12 @@ local function finalize_setup() local sample_flag = wizard_data.sample == 'Yes' and ' --sample-code' or '' local init_cmd = string.format('pio project init --ide vim --board %s -O "framework=%s"%s', wizard_data.board_id, wizard_data.framework, sample_flag) - -- local db_cmd = string.format('pio run -t compiledb -e %s', wizard_data.board_id) - -- local commands = { init_cmd, db_cmd } - -- local final_cb = pio.handlePioinitDb + local db_cmd = string.format('pio run -t compiledb -e %s', wizard_data.board_id) + local commands = { init_cmd, db_cmd } + local final_cb = pio.handlePioinitDb - local commands = { init_cmd } - local final_cb = pio.handlePioinit + -- local commands = { init_cmd } + -- local final_cb = pio.handlePioinit notify('Starting project setup for ' .. wizard_data.board_id .. '...') pio.run_sequence({ cmnds = commands, cb = final_cb }) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index bc8112b3..d0665ddb 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -517,6 +517,7 @@ M.run_sequence = function(tasks) end local trm +local win_id ------------------------------------------------------ -- Handle after pioinit execution -- ============================================================================= @@ -535,6 +536,8 @@ function M.handlePioinitDb(result) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') + _G.metadata.isBusy = true + win_id = vim.misc.showMessage('************ Project Initializing ************') if #M.queue > 0 then term.ToggleTerminal(table.remove(M.queue, 1), 'float') end elseif result == 'PASS' then -- if commandPassed == 1 then @@ -548,23 +551,27 @@ function M.handlePioinitDb(result) vim.notify('PIO init+db: pass ' .. commandPassed, vim.log.levels.INFO) vim.notify('PIO init+db: Done', vim.log.levels.INFO) vim.misc.gitignore_lsp_configs('compile_commands.json') - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen([[.clangd]], _G.metadata.core_dir) - local pio_refresh = require('platformio.pio_setup').pio_refresh - pio_refresh(function() clangdRestart() end, 'PIO init+db: ') + pio_refresh(function() + _G.metadata.isBusy = false + local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + boilerplate_gen([[.clangd]], _G.metadata.core_dir) + vim.misc.closeMessage(win_id) + clangdRestart() + -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') + end, 'PIO init+db: ') end) M.queue = {} term.stdout_callback = nil _G.metadata.isBusy = false elseif result == 'FAIL' then + vim.misc.closeMessage(win_id) M.queue = {} term.stdout_callback = nil _G.metadata.isBusy = false end end -local win_id ---------------------------------------------------- -- Handle after pioinit execution From 715cdfe34cc453102266d2c1aa696525ea1c3ed5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 14:42:30 +0300 Subject: [PATCH 1371/1406] update --- lua/platformio/utils/pio.lua | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index d0665ddb..5c7886f9 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -563,12 +563,11 @@ function M.handlePioinitDb(result) end) M.queue = {} term.stdout_callback = nil - _G.metadata.isBusy = false elseif result == 'FAIL' then + _G.metadata.isBusy = false vim.misc.closeMessage(win_id) M.queue = {} term.stdout_callback = nil - _G.metadata.isBusy = false end end @@ -626,14 +625,12 @@ function M.handlePioinit(result) M.queue = {} term.stdout_callback = nil trm:close() - _G.metadata.isBusy = false elseif result == 'FAIL' then _G.metadata.isBusy = false vim.misc.closeMessage(win_id) M.queue = {} term.stdout_callback = nil trm:close() - _G.metadata.isBusy = false end end From 74b922552bf896370f5528f80391c09b45e1efab Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 14:45:40 +0300 Subject: [PATCH 1372/1406] update --- lua/platformio/utils/pio.lua | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 5c7886f9..150639da 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -561,13 +561,16 @@ function M.handlePioinitDb(result) -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') end, 'PIO init+db: ') end) + vim.misc.deleteFile(vim.fs.joinpath(vim.g.platformioRootDir, '.ccls')) M.queue = {} term.stdout_callback = nil + trm:close() elseif result == 'FAIL' then _G.metadata.isBusy = false vim.misc.closeMessage(win_id) M.queue = {} term.stdout_callback = nil + trm:close() end end From 60f67c59f8a9f099309bfdf45d9829808094b621 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 14:47:40 +0300 Subject: [PATCH 1373/1406] update --- lua/platformio/utils/pio.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 150639da..98402818 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -538,7 +538,7 @@ function M.handlePioinitDb(result) _G.metadata.isBusy = true win_id = vim.misc.showMessage('************ Project Initializing ************') - if #M.queue > 0 then term.ToggleTerminal(table.remove(M.queue, 1), 'float') end + if #M.queue > 0 then trm = term.ToggleTerminal(table.remove(M.queue, 1), 'float')end elseif result == 'PASS' then -- if commandPassed == 1 then -- elseif commandPassed == 2 then -- if you sned more than 2 commands you need this From 3465edd2ecab395c1b4b1018856aeaac00934617 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 15:01:45 +0300 Subject: [PATCH 1374/1406] update --- lua/platformio/boilerplate.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index cd75bde5..f2df2fae 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -185,6 +185,8 @@ CompileFlags: Add: - "-xc++" - "-std=gnu++17" + - "-x" + - "c++-header" Remove: - "-fno-tree-switch-conversion" - "-fno-fat-lto-objects" From 20964360dd28dcebf68783d51abdf95a4c972eaf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 15:17:14 +0300 Subject: [PATCH 1375/1406] update --- lua/platformio/boilerplate.lua | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index f2df2fae..363175a8 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -180,13 +180,12 @@ boilerplate['.clangd'] = { -- - "-std=gnu++17" -- template = [[ content = [[ +# 1. Global Project Rules CompileFlags: BuiltinHeaders: QueryDriver Add: - "-xc++" - "-std=gnu++17" - - "-x" - - "c++-header" Remove: - "-fno-tree-switch-conversion" - "-fno-fat-lto-objects" @@ -210,6 +209,15 @@ Diagnostics: - "misc-definitions-in-headers" ClangTidy: Remove: ["readability-*", "modernize-*", "bugprone-*", "cert-err58-cpp"] + +--- +# 2. Specific Rule for Headers (The fix for your pragma error) +If: + PathMatch: [.*\.h, .*\.hpp] +CompileFlags: + Add: + - "-x" + - "c++-header" ]], -- content = function(self) -- local sysroot = '--sysroot=' .. _G.metadata.sysroot From 224c0c522caa47e87a76da51a4881ea420b4cb6b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 15:23:16 +0300 Subject: [PATCH 1376/1406] update --- lua/platformio/boilerplate.lua | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 363175a8..fdf739d9 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -180,12 +180,11 @@ boilerplate['.clangd'] = { -- - "-std=gnu++17" -- template = [[ content = [[ -# 1. Global Project Rules CompileFlags: BuiltinHeaders: QueryDriver Add: - - "-xc++" - "-std=gnu++17" + - "-xc++-header" Remove: - "-fno-tree-switch-conversion" - "-fno-fat-lto-objects" @@ -210,14 +209,6 @@ Diagnostics: ClangTidy: Remove: ["readability-*", "modernize-*", "bugprone-*", "cert-err58-cpp"] ---- -# 2. Specific Rule for Headers (The fix for your pragma error) -If: - PathMatch: [.*\.h, .*\.hpp] -CompileFlags: - Add: - - "-x" - - "c++-header" ]], -- content = function(self) -- local sysroot = '--sysroot=' .. _G.metadata.sysroot From 95a97cb0ec597a2100084028fc36aa8a2d2a7434 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 17:33:34 +0300 Subject: [PATCH 1377/1406] update --- lua/platformio/boilerplate.lua | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index fdf739d9..6bcc2c31 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -180,12 +180,10 @@ boilerplate['.clangd'] = { -- - "-std=gnu++17" -- template = [[ content = [[ +--- CompileFlags: - BuiltinHeaders: QueryDriver - Add: - - "-std=gnu++17" - - "-xc++-header" Remove: + - "-Wunknown-warning-option" - "-fno-tree-switch-conversion" - "-fno-fat-lto-objects" - "-fno-canonical-system-headers" @@ -196,7 +194,8 @@ CompileFlags: - "-mabi=.*" - "-mcpu=.*" - "-fipa-pta.*" - + Add: + - "-Wno-pragma-system-header-outside-header" Diagnostics: Suppress: - "pp_file_not_found" @@ -204,11 +203,9 @@ Diagnostics: - "pp_included_file_not_found" - "pp_including_mainfile_in_preamble" - "unused-includes" - - "pragma_system_header_ignored" - "misc-definitions-in-headers" ClangTidy: Remove: ["readability-*", "modernize-*", "bugprone-*", "cert-err58-cpp"] - ]], -- content = function(self) -- local sysroot = '--sysroot=' .. _G.metadata.sysroot From c4644b6118811b238df3f0dba1300ea044ed4a7e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 18:02:20 +0300 Subject: [PATCH 1378/1406] update --- lua/platformio/utils/pio.lua | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/utils/pio.lua index 98402818..e4b1ced7 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/utils/pio.lua @@ -509,6 +509,7 @@ M.run_sequence = function(tasks) callBack = tasks.cb -- 1. Save the callback in a local variable + commandPassed = 1 _G.metadata.isBusy = true @@ -536,7 +537,6 @@ function M.handlePioinitDb(result) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') - _G.metadata.isBusy = true win_id = vim.misc.showMessage('************ Project Initializing ************') if #M.queue > 0 then trm = term.ToggleTerminal(table.remove(M.queue, 1), 'float')end elseif result == 'PASS' then @@ -553,7 +553,6 @@ function M.handlePioinitDb(result) vim.misc.gitignore_lsp_configs('compile_commands.json') local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() - _G.metadata.isBusy = false local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], _G.metadata.core_dir) vim.misc.closeMessage(win_id) @@ -565,6 +564,7 @@ function M.handlePioinitDb(result) M.queue = {} term.stdout_callback = nil trm:close() + _G.metadata.isBusy = false elseif result == 'FAIL' then _G.metadata.isBusy = false vim.misc.closeMessage(win_id) @@ -592,7 +592,6 @@ function M.handlePioinit(result) -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') - _G.metadata.isBusy = true win_id = vim.misc.showMessage('************ Project Initializing ************') if #M.queue > 0 then trm = term.ToggleTerminal(table.remove(M.queue, 1), 'float')end elseif result == 'DONE' then -- result of the last command @@ -616,7 +615,6 @@ function M.handlePioinit(result) local pio_refresh = require('platformio.pio_setup').pio_refresh pio_refresh(function() - _G.metadata.isBusy = false local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], _G.metadata.core_dir) vim.misc.closeMessage(win_id) @@ -628,6 +626,7 @@ function M.handlePioinit(result) M.queue = {} term.stdout_callback = nil trm:close() + _G.metadata.isBusy = false elseif result == 'FAIL' then _G.metadata.isBusy = false vim.misc.closeMessage(win_id) From 0c9732057e6edf45b69ce70eb5d9001256e85f8b Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 18:03:54 +0300 Subject: [PATCH 1379/1406] update --- lua/platformio/boilerplate.lua | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 6bcc2c31..e8f998ef 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -182,6 +182,10 @@ boilerplate['.clangd'] = { content = [[ --- CompileFlags: + Add: + - "-xc++" + - "-std=gnu++17" + - "-Wno-pragma-system-header-outside-header" Remove: - "-Wunknown-warning-option" - "-fno-tree-switch-conversion" @@ -194,8 +198,6 @@ CompileFlags: - "-mabi=.*" - "-mcpu=.*" - "-fipa-pta.*" - Add: - - "-Wno-pragma-system-header-outside-header" Diagnostics: Suppress: - "pp_file_not_found" From 83eb93a47ebc7c50ebe77075866cba1c20a179b6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 18:53:52 +0300 Subject: [PATCH 1380/1406] update --- lua/platformio/metadata.lua | 20 +++------------ lua/platformio/pio_setup.lua | 47 ++++++++++++++++++------------------ 2 files changed, 28 insertions(+), 39 deletions(-) diff --git a/lua/platformio/metadata.lua b/lua/platformio/metadata.lua index bb7f9d83..7b68ba93 100644 --- a/lua/platformio/metadata.lua +++ b/lua/platformio/metadata.lua @@ -80,7 +80,7 @@ local config_path = vim.fs.joinpath(vim.uv.cwd(), '.project_config.json') -- ---@type platformio.utils.misc -- local misc = vim.misc --INFO: --- 3. Save Logic (Uses sha256 for stability) +-- 2. Save Logic (Uses sha256 for stability) function M.save_project_config(from) -- 1. Generate the formatted string directly, jsonFormat already returns a string! local ok, pretty_json = pcall(vim.misc.jsonFormat, _pio_metadata) @@ -106,7 +106,7 @@ function M.save_project_config(from) end --INFO: --- 4. Load Logic (Populates proxy safely) +-- 3. Load Logic (Populates proxy safely) function M.load_project_config() if vim.fn.filereadable(config_path) == 1 then local _, json_data = vim.misc.readFile(config_path) @@ -127,20 +127,8 @@ function M.load_project_config() last_saved_hash = vim.fn.sha256(vim.misc.jsonFormat(_pio_metadata)) end --- 5. Helper for ToggleTerm / Commands -function M.run_command(cmd_str) - -- Mute watcher logic would go here if needed - require('toggleterm').exec(cmd_str) -end - --- 6. Initialization +--INFO: +-- 4. Initialization M.load_project_config() --- Auto-save on exit even if no manual changes were made --- vim.api.nvim_create_autocmd('VimLeavePre', { --- callback = function() --- M.save_project_config(true) --- end, --- }) - return M diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio_setup.lua index 538bdde3..b356d2c7 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio_setup.lua @@ -47,36 +47,18 @@ local last_mtime = 0 --1.run_compiledb after platformio.ini changed --============================================================================= function M.run_compiledb(target) - -- 1. Prevent overlapping builds if target.isBusy then return end if _G.metadata.isBusy == true then return end local env = vim.pio.get_active__env() if not env then return end target.isBusy = true - - - -- local pio = require('platformio.utils.pio') - -- pio.run_sequence({ - -- cmnds = { - -- 'pio run -t compiledb -e ' .. vim.misc.get_active__env(), - -- }, - -- cb = function (result) - -- pio.handlePiodb(target, result) - -- end - -- }) - - -- if env and env ~= '' then vim.notify('PIO platformio.ini change: compiledb update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- vim.schedule(function() vim.system({ 'pio', 'run', '-t', 'compiledb', '-s', '-e', env }, { text = true }, function(obj) - -- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) vim.schedule(function() target.isBusy = false if obj.code == 0 then - -- vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) - -- Trigger refresh (LSP restart, etc.) vim.schedule(function () M.pio_refresh(function() vim.notify('PIO platformio.ini change: compiledb update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) @@ -90,8 +72,6 @@ function M.run_compiledb(target) _G.metadata.isBusy = false end) end) - -- end) - -- end end --INFO: @@ -217,12 +197,33 @@ function M.start_watchers() path = vim.misc.joinPath(project_root, 'platformio.ini'), cb = function(self) if self.isBusy then return end + if _G.metadata.isBusy == true then return end local new_hash = get_hash(self.path) or '' if new_hash and new_hash ~= self.last_hash then self.last_hash = new_hash - vim.schedule(function() - M.run_compiledb(self) -- Smart: Auto-update DB if config changes - end) + -- vim.schedule(function() + local env = vim.pio.get_active__env() + if not env then return end + self.isBusy = true + vim.notify('PIO platformio.ini change: compiledb update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) + vim.system({ 'pio', 'run', '-t', 'compiledb', '-s', '-e', env }, { text = true }, function(obj) + vim.schedule(function() + if obj.code == 0 then + vim.schedule(function () + M.pio_refresh(function() + vim.notify('PIO platformio.ini change: compiledb update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) + clangdRestart() + end, 'PIO platformio.ini change: ') + end) + else + local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' + vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) + end + self.isBusy = false + end) + end) + -- M.run_compiledb(self) -- Smart: Auto-update DB if config changes + -- end) end end, }, From 37fa9169b084bbbc59d1ab5de5092c6d696b9df0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 20:41:49 +0300 Subject: [PATCH 1381/1406] update --- lua/platformio/boilerplate.lua | 4 - lua/platformio/init.lua | 46 +- lua/platformio/{ => pio}/metadata.lua | 0 .../{utils/pio.lua => pio/upkeep.lua} | 6 +- .../{pio_setup.lua => pio/watcher.lua} | 116 ++- lua/platformio/pioCommands.lua | 85 ++- lua/platformio/pioinit.lua | 624 ++++++++++++---- lua/platformio/pioinit2.lua | 480 ------------ lua/platformio/piolib.lua | 2 +- lua/platformio/piomenu.lua | 46 -- lua/platformio/piorun.lua | 49 -- metadata.lua | 134 ++++ pio.lua | 682 ++++++++++++++++++ pio2.lua | 356 --------- pio_setup.lua | 453 +++--------- pioinit.lua | 144 ++++ pioinit2.lua | 160 ---- piomenu.lua | 45 ++ plugin/platformio.lua | 13 +- term2.lua | 330 --------- tmp.lua | 0 tmp1.lua | 0 22 files changed, 1753 insertions(+), 2022 deletions(-) rename lua/platformio/{ => pio}/metadata.lua (100%) rename lua/platformio/{utils/pio.lua => pio/upkeep.lua} (96%) rename lua/platformio/{pio_setup.lua => pio/watcher.lua} (74%) delete mode 100644 lua/platformio/pioinit2.lua delete mode 100644 lua/platformio/piomenu.lua delete mode 100644 lua/platformio/piorun.lua create mode 100644 metadata.lua create mode 100644 pio.lua delete mode 100644 pio2.lua create mode 100644 pioinit.lua delete mode 100644 pioinit2.lua create mode 100644 piomenu.lua delete mode 100644 term2.lua delete mode 100644 tmp.lua delete mode 100644 tmp1.lua diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index e8f998ef..f18bba42 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -2,8 +2,6 @@ M = {} M.core_dir = '' -local uv = vim.loop - local boilerplate = {} -- INFO: main.cpp @@ -59,8 +57,6 @@ lib_ldf_mode = chain ;Library dependencies Finder ldf ]], content = function(self) - -- local pio = require('platformio.utils.pio') - -- return string.format(self.template, require('platformio.utils.pio').get_pio_dir('core')) return string.format(self.template, M.core_dir) end, } diff --git a/lua/platformio/init.lua b/lua/platformio/init.lua index 3f109c48..4a18352e 100644 --- a/lua/platformio/init.lua +++ b/lua/platformio/init.lua @@ -154,6 +154,48 @@ local function validateMenu(menu) return true end +function M.piomenu(config) + local icon = { icon = ' ', color = 'orange' } -- Assign platformio orange icon + local wk_table = { mode = { 'n', 'v' } } + + local function traverseMenu(menu, wkey) + for _, child_node in ipairs(menu) do + if child_node.node == 'menu' then + traverseMenu(child_node.items, wkey .. child_node.shortcut) + table.insert(wk_table, { wkey .. child_node.shortcut, group = child_node.desc, icon = icon }) + elseif child_node.node == 'item' then + table.insert(wk_table, { + wkey .. child_node.shortcut, + ' ' .. child_node.command .. '', + desc = child_node.desc, + icon = icon, + }) + end + end + end + if config.menu_key == nil then + return + end + + local ok, wk = pcall(require, 'which-key') + if not ok then + vim.api.nvim_echo({ { 'which-key plugin not found!', 'ErrorMsg' } }, true, {}) + return + end + + wk.setup({ + preset = 'helix', --'modern', --'classic' + }) + local Config = require('which-key.config') + Config.sort = { 'order', 'group', 'manual', 'mod' } + + table.insert(wk_table, { config.menu_key, group = config.menu_name, icon = icon }) + + traverseMenu(config.menu_bindings, config.menu_key) + + wk.add(wk_table) +end + function M.setup(user_config) if vim.g.platformioRootDir and (next(user_config) ~= nil) then if user_config.lspClangd then @@ -181,10 +223,10 @@ function M.setup(user_config) M.config = vim.tbl_deep_extend('force', M.config, user_config or {}) end - require('platformio.piomenu').piomenu(M.config) + M.piomenu(M.config) vim.schedule(function() - require('platformio.pio_setup').init() + require('platformio.pio.watcher').init() end) end diff --git a/lua/platformio/metadata.lua b/lua/platformio/pio/metadata.lua similarity index 100% rename from lua/platformio/metadata.lua rename to lua/platformio/pio/metadata.lua diff --git a/lua/platformio/utils/pio.lua b/lua/platformio/pio/upkeep.lua similarity index 96% rename from lua/platformio/utils/pio.lua rename to lua/platformio/pio/upkeep.lua index e4b1ced7..b3ababd8 100644 --- a/lua/platformio/utils/pio.lua +++ b/lua/platformio/pio/upkeep.lua @@ -220,7 +220,7 @@ function M.fetch_metadata(callback, env, from, attempts) if cok and apply_metadata(decoded, current_checksum) then - local metadata = require('platformio.metadata') + local metadata = require('platformio.pio.metadata') metadata.save_project_config(msg) vim.notify(msg .. 'Metadata synced from cache', vim.log.levels.INFO) -- if callback then vim.schedule(callback) end @@ -551,7 +551,7 @@ function M.handlePioinitDb(result) vim.notify('PIO init+db: pass ' .. commandPassed, vim.log.levels.INFO) vim.notify('PIO init+db: Done', vim.log.levels.INFO) vim.misc.gitignore_lsp_configs('compile_commands.json') - local pio_refresh = require('platformio.pio_setup').pio_refresh + local pio_refresh = require('platformio.pio.watcher').pio_refresh pio_refresh(function() local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], _G.metadata.core_dir) @@ -613,7 +613,7 @@ function M.handlePioinit(result) -- local clean_msg = string.format('\27[G\27[2K\27[33m%s\27[0m', msg) -- vim.api.nvim_chan_send(trm.job_id, clean_msg) - local pio_refresh = require('platformio.pio_setup').pio_refresh + local pio_refresh = require('platformio.pio.watcher').pio_refresh pio_refresh(function() local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], _G.metadata.core_dir) diff --git a/lua/platformio/pio_setup.lua b/lua/platformio/pio/watcher.lua similarity index 74% rename from lua/platformio/pio_setup.lua rename to lua/platformio/pio/watcher.lua index b356d2c7..9bc7a6a9 100644 --- a/lua/platformio/pio_setup.lua +++ b/lua/platformio/pio/watcher.lua @@ -42,41 +42,41 @@ M.watcher_handles = {} local debounce_timer = uv.new_timer() local last_mtime = 0 +-- --INFO: +-- --stylua: ignore +-- --1.run_compiledb after platformio.ini changed +-- --============================================================================= +-- function M.run_compiledb(target) +-- if target.isBusy then return end +-- if _G.metadata.isBusy == true then return end +-- +-- local env = vim.pio.get_active__env() +-- if not env then return end +-- target.isBusy = true +-- vim.notify('PIO platformio.ini change: compiledb update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) +-- vim.system({ 'pio', 'run', '-t', 'compiledb', '-s', '-e', env }, { text = true }, function(obj) +-- vim.schedule(function() +-- target.isBusy = false +-- +-- if obj.code == 0 then +-- vim.schedule(function () +-- M.pio_refresh(function() +-- vim.notify('PIO platformio.ini change: compiledb update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) +-- clangdRestart() +-- end, 'PIO platformio.ini change: ') +-- end) +-- else +-- local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' +-- vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) +-- end +-- _G.metadata.isBusy = false +-- end) +-- end) +-- end +-- --INFO: --stylua: ignore ---1.run_compiledb after platformio.ini changed ---============================================================================= -function M.run_compiledb(target) - if target.isBusy then return end - if _G.metadata.isBusy == true then return end - - local env = vim.pio.get_active__env() - if not env then return end - target.isBusy = true - vim.notify('PIO platformio.ini change: compiledb update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) - vim.system({ 'pio', 'run', '-t', 'compiledb', '-s', '-e', env }, { text = true }, function(obj) - vim.schedule(function() - target.isBusy = false - - if obj.code == 0 then - vim.schedule(function () - M.pio_refresh(function() - vim.notify('PIO platformio.ini change: compiledb update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) - clangdRestart() - end, 'PIO platformio.ini change: ') - end) - else - local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' - vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) - end - _G.metadata.isBusy = false - end) - end) -end - ---INFO: ---stylua: ignore ---2.stop_watchers +--1.stop_watchers --============================================================================= function M.stop_watchers() if not M.watcher_handles or (type(M.watcher_handles) ~= 'table') then M.watcher_handles = {} return end @@ -92,7 +92,7 @@ end --INFO: --stylua: ignore ---3.watcher cleanup +--2.watcher cleanup --============================================================================= function M.cleanup() M.stop_watchers() @@ -111,7 +111,7 @@ vim.api.nvim_create_autocmd('VimLeavePre', { --INFO: --stylua: ignore ---4. MAIN WATCHER: Efficient Folder Monitoring +--3. MAIN WATCHER: Efficient Folder Monitoring --============================================================================= local function watch_file(target, callback) local folder_path = target.path:match('(.*[/\\])') @@ -181,7 +181,7 @@ end --INFO: --stylua: ignore ---5. start_watches +--4. start_watches --============================================================================= function M.start_watchers() -- Clean up any existing watchers first to prevent duplicates @@ -201,29 +201,27 @@ function M.start_watchers() local new_hash = get_hash(self.path) or '' if new_hash and new_hash ~= self.last_hash then self.last_hash = new_hash - -- vim.schedule(function() - local env = vim.pio.get_active__env() - if not env then return end - self.isBusy = true - vim.notify('PIO platformio.ini change: compiledb update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) - vim.system({ 'pio', 'run', '-t', 'compiledb', '-s', '-e', env }, { text = true }, function(obj) - vim.schedule(function() - if obj.code == 0 then - vim.schedule(function () - M.pio_refresh(function() - vim.notify('PIO platformio.ini change: compiledb update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) - clangdRestart() - end, 'PIO platformio.ini change: ') - end) - else - local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' - vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) - end - self.isBusy = false - end) + local env = vim.pio.get_active__env() + if not env then return end + self.isBusy = true + vim.notify('PIO platformio.ini change: compiledb update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) + vim.system({ 'pio', 'run', '-t', 'compiledb', '-s', '-e', env }, { text = true }, function(obj) + vim.schedule(function() + if obj.code == 0 then + vim.schedule(function () + M.pio_refresh(function() + vim.notify('PIO platformio.ini change: compiledb update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) + clangdRestart() + end, 'PIO platformio.ini change: ') + end) + else + local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' + vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) + end + self.isBusy = false end) - -- M.run_compiledb(self) -- Smart: Auto-update DB if config changes - -- end) + end) + -- M.run_compiledb(self) -- Smart: Auto-update DB if config changes end end, }, @@ -269,7 +267,7 @@ function M.init() vim.notify('PIO start: initialize', vim.log.levels.INFO) -- activate meta save and upload and env switch - local metadata = require('platformio.metadata') + local metadata = require('platformio.pio.metadata') metadata.load_project_config() require('platformio.lspConfig.clangd') diff --git a/lua/platformio/pioCommands.lua b/lua/platformio/pioCommands.lua index 6b6448c3..0ac1a150 100644 --- a/lua/platformio/pioCommands.lua +++ b/lua/platformio/pioCommands.lua @@ -1,35 +1,37 @@ local M = {} -local misc = require('platformio.utils.misc') +-- local misc = require('platformio.utils.misc') local ToggleTerminal = require('platformio.utils.term').ToggleTerminal +local misc = vim.misc -- stylua: ignore +--INFO: PioLSP +------------------------------------------------------ function M.piolsp() require('platformio.lspConfig.tools').clangdRestart() end +-- stylua: ignore +--INFO: Piocmd(h/f) +------------------------------------------------------ function M.piocmd(cmd_table, direction) - if not misc.pio_install_check() then - return - end + if not misc.pio_install_check() then return end misc.cd_pioini() - if cmd_table[1] == '' then - ToggleTerminal('', direction) + if cmd_table[1] == '' then ToggleTerminal('', direction) else local cmd = 'pio ' - for _, v in pairs(cmd_table) do - cmd = cmd .. ' ' .. v - end + for _, v in pairs(cmd_table) do cmd = cmd .. ' ' .. v end ToggleTerminal(cmd, direction) end end +-- stylua: ignore +--INFO: Piodebug +------------------------------------------------------ function M.piodebug(args_table) - if not misc.pio_install_check() then - return - end + if not misc.pio_install_check() then return end misc.cd_pioini() @@ -38,16 +40,16 @@ function M.piodebug(args_table) ToggleTerminal(command, 'float') end +-- stylua: ignore +--INFO: Piomon +------------------------------------------------------ function M.piomon(args_table) - if not misc.pio_install_check() then - return - end + if not misc.pio_install_check() then return end misc.cd_pioini() local command = nil - if #args_table == 0 then - command = 'pio device monitor' + if #args_table == 0 then command = 'pio device monitor' elseif #args_table == 1 then local baud_rate = args_table[1] command = string.format('pio device monitor -b %s', baud_rate) @@ -57,10 +59,53 @@ function M.piomon(args_table) command = string.format('pio device monitor -b %s -p %s', baud_rate, port) end - if command == nil then - vim.notify('Usage: Piomon ', vim.log.levels.ERROR) + if command == nil then vim.notify('Usage: Piomon ', vim.log.levels.ERROR) + else ToggleTerminal(command, 'horizontal') end +end + +-- stylua: ignore +--INFO: Piorun +------------------------------------------------------ +function M.piobuild() + misc.cd_pioini() + local command = 'pio run' -- .. utils.extra + ToggleTerminal(command, 'float') +end + +function M.pioupload() + misc.cd_pioini() + local command = 'pio run --target upload' -- .. utils.extra + ToggleTerminal(command, 'float') +end + +function M.piouploadfs() + misc.cd_pioini() + local command = 'pio run --target uploadfs' -- .. utils.extra + ToggleTerminal(command, 'float') +end + +function M.pioclean() + misc.cd_pioini() + local command = 'pio run --target clean' -- .. utils.extra + ToggleTerminal(command, 'float') +end + +function M.piorun(arg_table) + if not misc.pio_install_check() then + return + end + if arg_table[1] == '' then + M.pioupload() + elseif arg_table[1] == 'upload' then + M.pioupload() + elseif arg_table[1] == 'uploadfs' then + M.piouploadfs() + elseif arg_table[1] == 'build' then + M.piobuild() + elseif arg_table[1] == 'clean' then + M.pioclean() else - ToggleTerminal(command, 'horizontal') + vim.notify('Invalid argument: build, upload, uploadfs or clean', vim.log.levels.WARN) end end diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index dd9b713f..7c7d4407 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -1,144 +1,480 @@ -local M = {} - -local pickers = require('telescope.pickers') -local finders = require('telescope.finders') -local telescope_conf = require('telescope.config').values -local actions = require('telescope.actions') -local action_state = require('telescope.actions.state') -local entry_display = require('telescope.pickers.entry_display') -local make_entry = require('telescope.make_entry') -local misc = require('platformio.utils.misc') -local previewers = require('telescope.previewers') - -local boardentry_maker = function(opts) - local displayer = entry_display.create({ - separator = '▏', - items = { - { width = 35 }, - { width = 20 }, - { width = 15 }, - }, - }) - - local make_display = function(entry) - return displayer({ - entry.value.name, - entry.value.vendor, - entry.value.platform, - }) - end - - return function(entry) - return make_entry.set_default_entry_mt({ - value = { - id = entry.id, - name = entry.name, - vendor = entry.vendor, - platform = entry.platform, - data = entry, - }, - ordinal = entry.name .. ' ' .. entry.vendor .. ' ' .. entry.platform, - display = make_display, - }, opts) - end -end - ---- stylua: ignore -local function pick_framework(board_details) - local opts = {} - pickers - .new(opts, { - prompt_title = 'frameworks', - finder = finders.new_table({ - results = board_details['frameworks'], - }), - attach_mappings = function(prompt_bufnr, _) - actions.select_default:replace(function() - actions.close(prompt_bufnr) - local selection = action_state.get_selected_entry() - - local pio = require('platformio.utils.pio') - pio.selected_framework = selection[1] - pio.run_sequence({ - cmnds = { - 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', - -- 'pio run -t compiledb', - }, - cb = pio.handlePioinit, - }) - end) - return true - end, - sorter = telescope_conf.generic_sorter(opts), - }) - :find() -end - --- stylua: ignore -local function pick_board(json_data) - local opts = {} - pickers.new(opts, { - prompt_title = 'Boards', - finder = finders.new_table({ - results = json_data, - entry_maker = opts.entry_maker or boardentry_maker(opts), - }), - attach_mappings = function(prompt_bufnr, _) - actions.select_default:replace(function() - actions.close(prompt_bufnr) - local selection = action_state.get_selected_entry() - pick_framework(selection['value']['data']) - end) - return true - end, - previewer = previewers.new_buffer_previewer({ - title = 'Board Info', - define_preview = function(self, entry, _) - local json = misc.strsplit(vim.inspect(entry['value']['data']), '\n') - local bufnr = self.state.bufnr - vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) - vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function - vim.defer_fn(function() - local win = self.state.winid - vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) - vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) - vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) - end, 0) - end, - }), - sorter = telescope_conf.generic_sorter(opts), - }):find() -end - -function M.pioinit() - if not misc.pio_install_check() then - return - end - - -- Read stdout - local command = 'pio boards --json-output' - local handle = io.popen(command .. misc.devNul) - if not handle then - return - end - local json_str = handle:read('*a') - handle:close() - - if #json_str == 0 then - -- read stderr - handle = io.popen(command .. ' 2>&1') - if not handle then - return - end - local command_output = handle:read('*a') - handle:close() - vim.notify('Some error occured while executing `' .. command .. "`', command output: \n", vim.log.levels.WARN) - print(command_output) - return - end - - local json_data = vim.json.decode(json_str) - pick_board(json_data) -end - -return M +local pickers = require('telescope.pickers') +local finders = require('telescope.finders') +local actions = require('telescope.actions') +local action_state = require('telescope.actions.state') +local previewers = require('telescope.previewers') +local telescope_conf = require('telescope.config').values +local themes = require('telescope.themes') + +local wizard_data = {} + +-- Visual Notifications +local function notify(msg, level) + vim.notify('PIO Wizard: ' .. msg, level or vim.log.levels.INFO) +end + +-- Reusable Small Menu for Yes/No and Frameworks +local function small_menu(title, results, callback) + pickers + .new( + themes.get_dropdown({ + prompt_title = title, + layout_config = { width = 0.3, height = 0.25 }, + previewer = false, + }), + { + finder = finders.new_table({ results = results }), + sorter = telescope_conf.generic_sorter({}), + attach_mappings = function(prompt_bufnr) + actions.select_default:replace(function() + local selection = action_state.get_selected_entry() + actions.close(prompt_bufnr) + if selection then + callback(selection[1]) + end + end) + return true + end, + } + ) + :find() +end + +-- FINAL STEP: Construction & Sequence Execution +local function finalize_setup() + local pio = require('platformio.pio.upkeep') + + local sample_flag = wizard_data.sample == 'Yes' and ' --sample-code' or '' + local init_cmd = string.format('pio project init --ide vim --board %s -O "framework=%s"%s', wizard_data.board_id, wizard_data.framework, sample_flag) + + local db_cmd = string.format('pio run -t compiledb -e %s', wizard_data.board_id) + local commands = { init_cmd, db_cmd } + local final_cb = pio.handlePioinitDb + + -- local commands = { init_cmd } + -- local final_cb = pio.handlePioinit + + notify('Starting project setup for ' .. wizard_data.board_id .. '...') + pio.run_sequence({ cmnds = commands, cb = final_cb }) +end + +--- SEQUENTIAL STEPS --- + +-- Step 4: CompileDB +-- local function pick_compiledb() +-- small_menu('Generate Compilation Database (LSP)?', { 'Yes', 'No' }, function(choice) +-- wizard_data.use_compiledb = choice +-- finalize_setup() +-- end) +-- end + +-- Step 3: Sample Code +local function pick_sample() + small_menu('Include Sample Code?', { 'Yes', 'No' }, function(choice) + wizard_data.sample = choice + -- pick_compiledb() + finalize_setup() + end) +end + +-- Step 2: Framework +local function pick_framework(board_details) + small_menu('Select Framework', board_details.frameworks, function(choice) + wizard_data.framework = choice + pick_sample() + end) +end + +-- Step 1: Board (Entry Point) +local function pick_board(json_data) + pickers + .new({}, { + prompt_title = 'Select Board', + -- Define the layout behavior + layout_strategy = 'horizontal', + layout_config = { + width = 0.9, -- Overall width of the Telescope window (90% of screen) + preview_width = 0.70, -- 65% of the window goes to "Board Details", leaving 25% for results + }, + finder = finders.new_table({ + results = json_data, + entry_maker = function(entry) + return { + value = entry, + display = entry.name or entry.id, + ordinal = (entry.name or '') .. ' ' .. (entry.id or ''), + } + end, + }), + previewer = previewers.new_buffer_previewer({ + title = 'Board Details', + define_preview = function(self, entry) + local content = vim.split(vim.inspect(entry.value), '\n') + vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, content) + vim.api.nvim_set_option_value('filetype', 'lua', { buf = self.state.bufnr }) + end, + }), + sorter = telescope_conf.generic_sorter({}), + attach_mappings = function(prompt_bufnr) + actions.select_default:replace(function() + local selection = action_state.get_selected_entry() + actions.close(prompt_bufnr) + -- wizard_data.board_id = selection.value.id + -- pick_framework(selection.value) -- Next step + if selection then + wizard_data.board_id = selection.value.id + pick_framework(selection.value) + end + end) + return true + end, + }) + :find() +end + +-- local function pick_board(json_data) +-- pickers +-- .new({}, { +-- prompt_title = 'Select PlatformIO Board', +-- layout_strategy = 'horizontal', +-- layout_config = { width = 0.9, preview_width = 0.6 }, +-- finder = finders.new_table({ +-- results = json_data, +-- entry_maker = function(entry) +-- return { +-- value = entry, +-- display = string.format('%-25s | %s', entry.id, entry.name), +-- ordinal = entry.id .. ' ' .. entry.name, +-- } +-- end, +-- }), +-- previewer = previewers.new_buffer_previewer({ +-- title = 'Board Specifications', +-- define_preview = function(self, entry) +-- local val = entry.value +-- +-- -- Safe conversion for hardware specs +-- local ram = val.ram and (math.floor(val.ram / 1024) .. ' KB') or 'Unknown' +-- local flash = val.rom and (math.floor(val.rom / 1024) .. ' KB') or 'Unknown' +-- local mhz = val.fcpu and (math.floor(val.fcpu / 1000000) .. ' MHz') or 'Unknown' +-- +-- -- Build base lines +-- local lines = { +-- '# ' .. (val.name or val.id), +-- '', +-- '**Basic Info**', +-- '---', +-- '**Board ID:** ' .. val.id, +-- '**Vendor:** ' .. (val.vendor or 'Generic'), +-- '**Platform:** ' .. (val.platform or 'N/A'), +-- '', +-- '**Hardware Specs**', +-- '---', +-- '**MCU:** ' .. (val.mcu or 'N/A'), +-- '**CPU Speed:** ' .. mhz, +-- '**Flash (ROM):** ' .. flash, +-- '**RAM:** ' .. ram, +-- '', +-- '**Available Frameworks**', +-- '---', +-- } +-- +-- -- Correctly append frameworks as separate lines to avoid the newline error +-- if val.frameworks and #val.frameworks > 0 then +-- for _, fw in ipairs(val.frameworks) do +-- table.insert(lines, '- ' .. fw) +-- end +-- else +-- table.insert(lines, '*No frameworks listed*') +-- end +-- +-- vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, lines) +-- vim.api.nvim_set_option_value('filetype', 'markdown', { buf = self.state.bufnr }) +-- end, +-- }), +-- sorter = telescope_conf.generic_sorter({}), +-- attach_mappings = function(prompt_bufnr) +-- actions.select_default:replace(function() +-- local selection = action_state.get_selected_entry() +-- actions.close(prompt_bufnr) +-- if selection then +-- wizard_data.board_id = selection.value.id +-- pick_framework(selection.value) +-- end +-- end) +-- return true +-- end, +-- }) +-- :find() +-- end + +-- local function pick_board(json_data) +-- pickers +-- .new({}, { +-- prompt_title = 'Select PlatformIO Board', +-- layout_strategy = 'horizontal', +-- layout_config = { width = 0.9, preview_width = 0.6 }, +-- finder = finders.new_table({ +-- results = json_data, +-- entry_maker = function(entry) +-- return { +-- value = entry, +-- display = string.format('%-25s | %s', entry.id, entry.name), +-- ordinal = entry.id .. ' ' .. entry.name, +-- } +-- end, +-- }), +-- previewer = previewers.new_buffer_previewer({ +-- title = 'Board Specs', +-- define_preview = function(self, entry) +-- local val = entry.value +-- local lines = { +-- '# ' .. (val.name or val.id), +-- '', +-- '**Micro:** ' .. (val.mcu or 'N/A'), +-- '**Vendor:** ' .. (val.vendor or 'N/A'), +-- '**Clock:** ' .. (val.fcpu or 0) / 1000000 .. ' MHz', +-- '**RAM:** ' .. (val.ram or 0) / 1024 .. ' KB', +-- '', +-- '**Frameworks:** ' .. table.concat(val.frameworks, ', '), +-- } +-- vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, lines) +-- vim.api.nvim_set_option_value('filetype', 'markdown', { buf = self.state.bufnr }) +-- end, +-- }), +-- sorter = telescope_conf.generic_sorter({}), +-- attach_mappings = function(prompt_bufnr) +-- actions.select_default:replace(function() +-- local selection = action_state.get_selected_entry() +-- actions.close(prompt_bufnr) +-- if selection then +-- wizard_data.board_id = selection.value.id +-- pick_framework(selection.value) +-- end +-- end) +-- return true +-- end, +-- }) +-- :find() +-- end + +-- Entry point +local function launch_pio_project_wizard() + wizard_data = {} -- Reset state + notify('Fetching board database...') + + local handle = io.popen('pio boards --json-output') + if not handle then + return + end + local result = handle:read('*a') + handle:close() + + local ok, json_data = pcall(vim.json.decode, result) + if not ok or type(json_data) ~= 'table' then + notify('Failed to parse board data.', vim.log.levels.ERROR) + return + end + + pick_board(json_data) +end + +return { + launch = launch_pio_project_wizard, +} + +-- local pickers = require('telescope.pickers') +-- local finders = require('telescope.finders') +-- local actions = require('telescope.actions') +-- local action_state = require('telescope.actions.state') +-- local previewers = require('telescope.previewers') +-- local telescope_conf = require('telescope.config').values +-- +-- local wizard_data = {} +-- +-- -- Final Step: Command Construction & Execution +-- local function finalize_setup() +-- local pio = require('platformio.utils.pio') +-- +-- -- 1. Construct the basic init command +-- local sample_flag = wizard_data.sample == 'true' and ' --sample-code' or '' +-- local init_cmd = string.format('pio project init --ide vim --board %s -O "framework=%s"%s', wizard_data.board_id, wizard_data.framework, sample_flag) +-- +-- -- 2. Determine commands and callback +-- local commands = { init_cmd } +-- local final_cb = pio.handlePioinit -- Default for 1 command +-- +-- if wizard_data.use_compiledb then +-- table.insert(commands, 'pio run -t compiledb') +-- final_cb = pio.handlePioinitDb -- Switch to Db handler for 2 commands +-- end +-- +-- -- 3. Execute +-- pio.run_sequence({ +-- cmnds = commands, +-- cb = final_cb, +-- }) +-- end +-- +-- local function dialog_opts(title, width) +-- return require('telescope.themes').get_dropdown({ +-- prompt_title = title, +-- layout_config = { +-- width = width or 0.4, -- Adjust width (0.4 = 40% of screen) +-- height = 0.2, -- Small height for few choices +-- }, +-- previewer = false, -- Hide preview for simple choices +-- }) +-- end +-- +-- --- PICKERS (In Order of Execution) --- +-- +-- -- STEP 4: Sample (True/False) +-- local function pick_sample() +-- local opts = dialog_opts('Include Sample Code?', 0.3) +-- pickers +-- .new(opts, { +-- finder = finders.new_table({ results = { 'true', 'false' } }), +-- sorter = telescope_conf.generic_sorter(opts), +-- attach_mappings = function(prompt_bufnr) +-- actions.select_default:replace(function() +-- local selection = action_state.get_selected_entry() +-- actions.close(prompt_bufnr) +-- wizard_data.sample = selection[1] +-- finalize_setup() +-- end) +-- return true +-- end, +-- }) +-- :find() +-- end +-- +-- -- STEP 3: Framework Selection (Small Dialog) +-- local function pick_framework(board_details) +-- -- Use dropdown theme to keep the window small and centered +-- local opts = require('telescope.themes').get_dropdown({ +-- prompt_title = 'Select Framework (' .. board_details.id .. ')', +-- layout_config = { +-- width = 0.25, -- 40% of screen width +-- height = 0.25, -- Small height for few choices +-- }, +-- previewer = false, -- No preview needed for framework names +-- }) +-- +-- pickers +-- .new(opts, { +-- finder = finders.new_table({ +-- results = board_details['frameworks'], +-- }), +-- sorter = telescope_conf.generic_sorter(opts), +-- attach_mappings = function(prompt_bufnr) +-- actions.select_default:replace(function() +-- local selection = action_state.get_selected_entry() +-- actions.close(prompt_bufnr) +-- -- selection is a simple string in this case +-- wizard_data.framework = selection[1] +-- pick_sample() +-- end) +-- return true +-- end, +-- }) +-- :find() +-- end +-- +-- -- STEP 2: Board (with Buffer Previewer) +-- local function pick_board(json_data) +-- pickers +-- .new({}, { +-- prompt_title = 'Select Board', +-- -- Define the layout behavior +-- layout_strategy = 'horizontal', +-- layout_config = { +-- width = 0.9, -- Overall width of the Telescope window (90% of screen) +-- preview_width = 0.70, -- 65% of the window goes to "Board Details", leaving 25% for results +-- }, +-- finder = finders.new_table({ +-- results = json_data, +-- entry_maker = function(entry) +-- return { +-- value = entry, +-- display = entry.name or entry.id, +-- ordinal = (entry.name or '') .. ' ' .. (entry.id or ''), +-- } +-- end, +-- }), +-- previewer = previewers.new_buffer_previewer({ +-- title = 'Board Details', +-- define_preview = function(self, entry) +-- local content = vim.split(vim.inspect(entry.value), '\n') +-- vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, content) +-- vim.api.nvim_set_option_value('filetype', 'lua', { buf = self.state.bufnr }) +-- end, +-- }), +-- sorter = telescope_conf.generic_sorter({}), +-- attach_mappings = function(prompt_bufnr) +-- actions.select_default:replace(function() +-- local selection = action_state.get_selected_entry() +-- actions.close(prompt_bufnr) +-- wizard_data.board_id = selection.value.id +-- pick_framework(selection.value) -- Next step +-- end) +-- return true +-- end, +-- }) +-- :find() +-- end +-- +-- -- STEP 1: IDE (True/False) +-- local function start_pio_wizard(json_data) +-- local opts = require('telescope.themes').get_dropdown({ +-- prompt_title = 'Generate Compilation Database (LSP)?', +-- layout_config = { width = 0.2, height = 0.2 }, +-- previewer = false, +-- }) +-- +-- pickers +-- .new(opts, { +-- finder = finders.new_table({ results = { 'true', 'false' } }), +-- sorter = telescope_conf.generic_sorter(opts), +-- attach_mappings = function(prompt_bufnr) +-- actions.select_default:replace(function() +-- local selection = action_state.get_selected_entry() +-- actions.close(prompt_bufnr) +-- -- Save the boolean for the final step +-- wizard_data.use_compiledb = (selection[1] == 'true') +-- pick_board(json_data) +-- end) +-- return true +-- end, +-- }) +-- :find() +-- end +-- +-- local function launch_pio_project_wizard() +-- print('Fetching board data from PlatformIO...') +-- +-- -- 1. Get board data from PIO CLI in JSON format +-- -- The '--json-output' flag ensures we get structured data +-- local handle = io.popen('pio boards --json-output') +-- if not handle then +-- return +-- end +-- +-- local result = handle:read('*a') +-- handle:close() +-- +-- -- 2. Decode the JSON string into a Lua table +-- local ok, json_data = pcall(vim.json.decode, result) +-- if not ok or not json_data then +-- print('Error: Could not parse PlatformIO board data.') +-- return +-- end +-- +-- -- 3. Start the wizard we built previously +-- start_pio_wizard(json_data) +-- end +-- +-- -- Export the function so it's accessible via require() +-- return { +-- launch = launch_pio_project_wizard, +-- } diff --git a/lua/platformio/pioinit2.lua b/lua/platformio/pioinit2.lua deleted file mode 100644 index 659b1b55..00000000 --- a/lua/platformio/pioinit2.lua +++ /dev/null @@ -1,480 +0,0 @@ -local pickers = require('telescope.pickers') -local finders = require('telescope.finders') -local actions = require('telescope.actions') -local action_state = require('telescope.actions.state') -local previewers = require('telescope.previewers') -local telescope_conf = require('telescope.config').values -local themes = require('telescope.themes') - -local wizard_data = {} - --- Visual Notifications -local function notify(msg, level) - vim.notify('PIO Wizard: ' .. msg, level or vim.log.levels.INFO) -end - --- Reusable Small Menu for Yes/No and Frameworks -local function small_menu(title, results, callback) - pickers - .new( - themes.get_dropdown({ - prompt_title = title, - layout_config = { width = 0.3, height = 0.25 }, - previewer = false, - }), - { - finder = finders.new_table({ results = results }), - sorter = telescope_conf.generic_sorter({}), - attach_mappings = function(prompt_bufnr) - actions.select_default:replace(function() - local selection = action_state.get_selected_entry() - actions.close(prompt_bufnr) - if selection then - callback(selection[1]) - end - end) - return true - end, - } - ) - :find() -end - --- FINAL STEP: Construction & Sequence Execution -local function finalize_setup() - local pio = require('platformio.utils.pio') - - local sample_flag = wizard_data.sample == 'Yes' and ' --sample-code' or '' - local init_cmd = string.format('pio project init --ide vim --board %s -O "framework=%s"%s', wizard_data.board_id, wizard_data.framework, sample_flag) - - local db_cmd = string.format('pio run -t compiledb -e %s', wizard_data.board_id) - local commands = { init_cmd, db_cmd } - local final_cb = pio.handlePioinitDb - - -- local commands = { init_cmd } - -- local final_cb = pio.handlePioinit - - notify('Starting project setup for ' .. wizard_data.board_id .. '...') - pio.run_sequence({ cmnds = commands, cb = final_cb }) -end - ---- SEQUENTIAL STEPS --- - --- Step 4: CompileDB --- local function pick_compiledb() --- small_menu('Generate Compilation Database (LSP)?', { 'Yes', 'No' }, function(choice) --- wizard_data.use_compiledb = choice --- finalize_setup() --- end) --- end - --- Step 3: Sample Code -local function pick_sample() - small_menu('Include Sample Code?', { 'Yes', 'No' }, function(choice) - wizard_data.sample = choice - -- pick_compiledb() - finalize_setup() - end) -end - --- Step 2: Framework -local function pick_framework(board_details) - small_menu('Select Framework', board_details.frameworks, function(choice) - wizard_data.framework = choice - pick_sample() - end) -end - --- Step 1: Board (Entry Point) -local function pick_board(json_data) - pickers - .new({}, { - prompt_title = 'Select Board', - -- Define the layout behavior - layout_strategy = 'horizontal', - layout_config = { - width = 0.9, -- Overall width of the Telescope window (90% of screen) - preview_width = 0.70, -- 65% of the window goes to "Board Details", leaving 25% for results - }, - finder = finders.new_table({ - results = json_data, - entry_maker = function(entry) - return { - value = entry, - display = entry.name or entry.id, - ordinal = (entry.name or '') .. ' ' .. (entry.id or ''), - } - end, - }), - previewer = previewers.new_buffer_previewer({ - title = 'Board Details', - define_preview = function(self, entry) - local content = vim.split(vim.inspect(entry.value), '\n') - vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, content) - vim.api.nvim_set_option_value('filetype', 'lua', { buf = self.state.bufnr }) - end, - }), - sorter = telescope_conf.generic_sorter({}), - attach_mappings = function(prompt_bufnr) - actions.select_default:replace(function() - local selection = action_state.get_selected_entry() - actions.close(prompt_bufnr) - -- wizard_data.board_id = selection.value.id - -- pick_framework(selection.value) -- Next step - if selection then - wizard_data.board_id = selection.value.id - pick_framework(selection.value) - end - end) - return true - end, - }) - :find() -end - --- local function pick_board(json_data) --- pickers --- .new({}, { --- prompt_title = 'Select PlatformIO Board', --- layout_strategy = 'horizontal', --- layout_config = { width = 0.9, preview_width = 0.6 }, --- finder = finders.new_table({ --- results = json_data, --- entry_maker = function(entry) --- return { --- value = entry, --- display = string.format('%-25s | %s', entry.id, entry.name), --- ordinal = entry.id .. ' ' .. entry.name, --- } --- end, --- }), --- previewer = previewers.new_buffer_previewer({ --- title = 'Board Specifications', --- define_preview = function(self, entry) --- local val = entry.value --- --- -- Safe conversion for hardware specs --- local ram = val.ram and (math.floor(val.ram / 1024) .. ' KB') or 'Unknown' --- local flash = val.rom and (math.floor(val.rom / 1024) .. ' KB') or 'Unknown' --- local mhz = val.fcpu and (math.floor(val.fcpu / 1000000) .. ' MHz') or 'Unknown' --- --- -- Build base lines --- local lines = { --- '# ' .. (val.name or val.id), --- '', --- '**Basic Info**', --- '---', --- '**Board ID:** ' .. val.id, --- '**Vendor:** ' .. (val.vendor or 'Generic'), --- '**Platform:** ' .. (val.platform or 'N/A'), --- '', --- '**Hardware Specs**', --- '---', --- '**MCU:** ' .. (val.mcu or 'N/A'), --- '**CPU Speed:** ' .. mhz, --- '**Flash (ROM):** ' .. flash, --- '**RAM:** ' .. ram, --- '', --- '**Available Frameworks**', --- '---', --- } --- --- -- Correctly append frameworks as separate lines to avoid the newline error --- if val.frameworks and #val.frameworks > 0 then --- for _, fw in ipairs(val.frameworks) do --- table.insert(lines, '- ' .. fw) --- end --- else --- table.insert(lines, '*No frameworks listed*') --- end --- --- vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, lines) --- vim.api.nvim_set_option_value('filetype', 'markdown', { buf = self.state.bufnr }) --- end, --- }), --- sorter = telescope_conf.generic_sorter({}), --- attach_mappings = function(prompt_bufnr) --- actions.select_default:replace(function() --- local selection = action_state.get_selected_entry() --- actions.close(prompt_bufnr) --- if selection then --- wizard_data.board_id = selection.value.id --- pick_framework(selection.value) --- end --- end) --- return true --- end, --- }) --- :find() --- end - --- local function pick_board(json_data) --- pickers --- .new({}, { --- prompt_title = 'Select PlatformIO Board', --- layout_strategy = 'horizontal', --- layout_config = { width = 0.9, preview_width = 0.6 }, --- finder = finders.new_table({ --- results = json_data, --- entry_maker = function(entry) --- return { --- value = entry, --- display = string.format('%-25s | %s', entry.id, entry.name), --- ordinal = entry.id .. ' ' .. entry.name, --- } --- end, --- }), --- previewer = previewers.new_buffer_previewer({ --- title = 'Board Specs', --- define_preview = function(self, entry) --- local val = entry.value --- local lines = { --- '# ' .. (val.name or val.id), --- '', --- '**Micro:** ' .. (val.mcu or 'N/A'), --- '**Vendor:** ' .. (val.vendor or 'N/A'), --- '**Clock:** ' .. (val.fcpu or 0) / 1000000 .. ' MHz', --- '**RAM:** ' .. (val.ram or 0) / 1024 .. ' KB', --- '', --- '**Frameworks:** ' .. table.concat(val.frameworks, ', '), --- } --- vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, lines) --- vim.api.nvim_set_option_value('filetype', 'markdown', { buf = self.state.bufnr }) --- end, --- }), --- sorter = telescope_conf.generic_sorter({}), --- attach_mappings = function(prompt_bufnr) --- actions.select_default:replace(function() --- local selection = action_state.get_selected_entry() --- actions.close(prompt_bufnr) --- if selection then --- wizard_data.board_id = selection.value.id --- pick_framework(selection.value) --- end --- end) --- return true --- end, --- }) --- :find() --- end - --- Entry point -local function launch_pio_project_wizard() - wizard_data = {} -- Reset state - notify('Fetching board database...') - - local handle = io.popen('pio boards --json-output') - if not handle then - return - end - local result = handle:read('*a') - handle:close() - - local ok, json_data = pcall(vim.json.decode, result) - if not ok or type(json_data) ~= 'table' then - notify('Failed to parse board data.', vim.log.levels.ERROR) - return - end - - pick_board(json_data) -end - -return { - launch = launch_pio_project_wizard, -} - --- local pickers = require('telescope.pickers') --- local finders = require('telescope.finders') --- local actions = require('telescope.actions') --- local action_state = require('telescope.actions.state') --- local previewers = require('telescope.previewers') --- local telescope_conf = require('telescope.config').values --- --- local wizard_data = {} --- --- -- Final Step: Command Construction & Execution --- local function finalize_setup() --- local pio = require('platformio.utils.pio') --- --- -- 1. Construct the basic init command --- local sample_flag = wizard_data.sample == 'true' and ' --sample-code' or '' --- local init_cmd = string.format('pio project init --ide vim --board %s -O "framework=%s"%s', wizard_data.board_id, wizard_data.framework, sample_flag) --- --- -- 2. Determine commands and callback --- local commands = { init_cmd } --- local final_cb = pio.handlePioinit -- Default for 1 command --- --- if wizard_data.use_compiledb then --- table.insert(commands, 'pio run -t compiledb') --- final_cb = pio.handlePioinitDb -- Switch to Db handler for 2 commands --- end --- --- -- 3. Execute --- pio.run_sequence({ --- cmnds = commands, --- cb = final_cb, --- }) --- end --- --- local function dialog_opts(title, width) --- return require('telescope.themes').get_dropdown({ --- prompt_title = title, --- layout_config = { --- width = width or 0.4, -- Adjust width (0.4 = 40% of screen) --- height = 0.2, -- Small height for few choices --- }, --- previewer = false, -- Hide preview for simple choices --- }) --- end --- --- --- PICKERS (In Order of Execution) --- --- --- -- STEP 4: Sample (True/False) --- local function pick_sample() --- local opts = dialog_opts('Include Sample Code?', 0.3) --- pickers --- .new(opts, { --- finder = finders.new_table({ results = { 'true', 'false' } }), --- sorter = telescope_conf.generic_sorter(opts), --- attach_mappings = function(prompt_bufnr) --- actions.select_default:replace(function() --- local selection = action_state.get_selected_entry() --- actions.close(prompt_bufnr) --- wizard_data.sample = selection[1] --- finalize_setup() --- end) --- return true --- end, --- }) --- :find() --- end --- --- -- STEP 3: Framework Selection (Small Dialog) --- local function pick_framework(board_details) --- -- Use dropdown theme to keep the window small and centered --- local opts = require('telescope.themes').get_dropdown({ --- prompt_title = 'Select Framework (' .. board_details.id .. ')', --- layout_config = { --- width = 0.25, -- 40% of screen width --- height = 0.25, -- Small height for few choices --- }, --- previewer = false, -- No preview needed for framework names --- }) --- --- pickers --- .new(opts, { --- finder = finders.new_table({ --- results = board_details['frameworks'], --- }), --- sorter = telescope_conf.generic_sorter(opts), --- attach_mappings = function(prompt_bufnr) --- actions.select_default:replace(function() --- local selection = action_state.get_selected_entry() --- actions.close(prompt_bufnr) --- -- selection is a simple string in this case --- wizard_data.framework = selection[1] --- pick_sample() --- end) --- return true --- end, --- }) --- :find() --- end --- --- -- STEP 2: Board (with Buffer Previewer) --- local function pick_board(json_data) --- pickers --- .new({}, { --- prompt_title = 'Select Board', --- -- Define the layout behavior --- layout_strategy = 'horizontal', --- layout_config = { --- width = 0.9, -- Overall width of the Telescope window (90% of screen) --- preview_width = 0.70, -- 65% of the window goes to "Board Details", leaving 25% for results --- }, --- finder = finders.new_table({ --- results = json_data, --- entry_maker = function(entry) --- return { --- value = entry, --- display = entry.name or entry.id, --- ordinal = (entry.name or '') .. ' ' .. (entry.id or ''), --- } --- end, --- }), --- previewer = previewers.new_buffer_previewer({ --- title = 'Board Details', --- define_preview = function(self, entry) --- local content = vim.split(vim.inspect(entry.value), '\n') --- vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, content) --- vim.api.nvim_set_option_value('filetype', 'lua', { buf = self.state.bufnr }) --- end, --- }), --- sorter = telescope_conf.generic_sorter({}), --- attach_mappings = function(prompt_bufnr) --- actions.select_default:replace(function() --- local selection = action_state.get_selected_entry() --- actions.close(prompt_bufnr) --- wizard_data.board_id = selection.value.id --- pick_framework(selection.value) -- Next step --- end) --- return true --- end, --- }) --- :find() --- end --- --- -- STEP 1: IDE (True/False) --- local function start_pio_wizard(json_data) --- local opts = require('telescope.themes').get_dropdown({ --- prompt_title = 'Generate Compilation Database (LSP)?', --- layout_config = { width = 0.2, height = 0.2 }, --- previewer = false, --- }) --- --- pickers --- .new(opts, { --- finder = finders.new_table({ results = { 'true', 'false' } }), --- sorter = telescope_conf.generic_sorter(opts), --- attach_mappings = function(prompt_bufnr) --- actions.select_default:replace(function() --- local selection = action_state.get_selected_entry() --- actions.close(prompt_bufnr) --- -- Save the boolean for the final step --- wizard_data.use_compiledb = (selection[1] == 'true') --- pick_board(json_data) --- end) --- return true --- end, --- }) --- :find() --- end --- --- local function launch_pio_project_wizard() --- print('Fetching board data from PlatformIO...') --- --- -- 1. Get board data from PIO CLI in JSON format --- -- The '--json-output' flag ensures we get structured data --- local handle = io.popen('pio boards --json-output') --- if not handle then --- return --- end --- --- local result = handle:read('*a') --- handle:close() --- --- -- 2. Decode the JSON string into a Lua table --- local ok, json_data = pcall(vim.json.decode, result) --- if not ok or not json_data then --- print('Error: Could not parse PlatformIO board data.') --- return --- end --- --- -- 3. Start the wizard we built previously --- start_pio_wizard(json_data) --- end --- --- -- Export the function so it's accessible via require() --- return { --- launch = launch_pio_project_wizard, --- } diff --git a/lua/platformio/piolib.lua b/lua/platformio/piolib.lua index 5dc8cd12..9b7c34b2 100644 --- a/lua/platformio/piolib.lua +++ b/lua/platformio/piolib.lua @@ -64,7 +64,7 @@ local function pick_library(json_data) -- local command = 'pio pkg install --library "' .. pkg_name .. '"' -- command = command .. ' && pio run -t compiledb' - local pio = require('platformio.utils.pio') + local pio = require('platformio.pio.upkeep') pio.run_sequence({ cmnds = {'pio pkg install --library "' .. pkg_name .. '"'}, cb = pio.handlePiolib diff --git a/lua/platformio/piomenu.lua b/lua/platformio/piomenu.lua deleted file mode 100644 index 7657a12a..00000000 --- a/lua/platformio/piomenu.lua +++ /dev/null @@ -1,46 +0,0 @@ -local M = {} - -local icon = { icon = ' ', color = 'orange' } -- Assign platformio orange icon -local wk_table = { mode = { 'n', 'v' } } - -local function traverseMenu(menu, wkey) - for _, child_node in ipairs(menu) do - if child_node.node == 'menu' then - traverseMenu(child_node.items, wkey .. child_node.shortcut) - table.insert(wk_table, { wkey .. child_node.shortcut, group = child_node.desc, icon = icon }) - elseif child_node.node == 'item' then - table.insert(wk_table, { - wkey .. child_node.shortcut, - ' ' .. child_node.command .. '', - desc = child_node.desc, - icon = icon, - }) - end - end -end - -function M.piomenu(config) - if config.menu_key == nil then - return - end - - local ok, wk = pcall(require, 'which-key') - if not ok then - vim.api.nvim_echo({ { 'which-key plugin not found!', 'ErrorMsg' } }, true, {}) - return - end - - wk.setup({ - preset = 'helix', --'modern', --'classic' - }) - local Config = require('which-key.config') - Config.sort = { 'order', 'group', 'manual', 'mod' } - - table.insert(wk_table, { config.menu_key, group = config.menu_name, icon = icon }) - - traverseMenu(config.menu_bindings, config.menu_key) - - wk.add(wk_table) -end - -return M diff --git a/lua/platformio/piorun.lua b/lua/platformio/piorun.lua deleted file mode 100644 index aae85f15..00000000 --- a/lua/platformio/piorun.lua +++ /dev/null @@ -1,49 +0,0 @@ -local M = {} - -local misc = require('platformio.utils.misc') -local ToggleTerminal = require('platformio.utils.term').ToggleTerminal - -function M.piobuild() - misc.cd_pioini() - local command = 'pio run' -- .. utils.extra - ToggleTerminal(command, 'float') -end - -function M.pioupload() - misc.cd_pioini() - local command = 'pio run --target upload' -- .. utils.extra - ToggleTerminal(command, 'float') -end - -function M.piouploadfs() - misc.cd_pioini() - local command = 'pio run --target uploadfs' -- .. utils.extra - ToggleTerminal(command, 'float') -end - -function M.pioclean() - misc.cd_pioini() - local command = 'pio run --target clean' -- .. utils.extra - ToggleTerminal(command, 'float') -end - -function M.piorun(arg_table) - if not misc.pio_install_check() then - return - end - if arg_table[1] == '' then - M.pioupload() - elseif arg_table[1] == 'upload' then - M.pioupload() - elseif arg_table[1] == 'uploadfs' then - M.piouploadfs() - elseif arg_table[1] == 'build' then - M.piobuild() - elseif arg_table[1] == 'clean' then - M.pioclean() - else - vim.notify('Invalid argument: build, upload, uploadfs or clean', vim.log.levels.WARN) - end -end - -return M diff --git a/metadata.lua b/metadata.lua new file mode 100644 index 00000000..7b68ba93 --- /dev/null +++ b/metadata.lua @@ -0,0 +1,134 @@ +local M = {} + +------------------------------------------------------------------------------------------------------- +local last_saved_hash = '' + +--INFO: +-- 1. Internal State & Defaults +local _pio_metadata = { + isBusy = false, + envs = {}, + active_env = '', + default_envs = {}, + core_dir = '', + packages_dir = '', + platforms_dir = '', + query_driver = '', + cc_compiler = '', + includes_build = {}, + includes_compatlib = {}, + includes_toolchain = {}, + cc_path = '', + cc_flags = {}, + cxx_path = '', + cxx_flags = {}, + gdb_path = '', + defines = {}, + triplet = '', + toolchain_root = '', + sysroot = '', + fallbackFlags = {}, + dbTrigger = false, + last_projectChecksum = '', -- Used to track changes +} +-- 2. The Reactive Proxy Wrapper +-- Any write to _G.metadata.key = val triggers this logic +_G.metadata = setmetatable({}, { + __index = _pio_metadata, + __newindex = function(_, key, value) + if _pio_metadata[key] == value then + -- print('Value is identical, returning...') -- DEBUG LINE + return + end -- Performance check + -- print('Newindex attempt for: ' .. tostring(key)) -- DEBUG LINE + _pio_metadata[key] = value + + -- Trigger background actions + vim.schedule(function() + -- M.save_project_config(true) + if key == 'toolchain_root' then + local binPath = value .. '/bin' + local sep = (vim.fn.has('win32') == 1 and ';' or ':') + vim.env.PATH = binPath .. sep .. vim.env.PATH + vim.notify('PIO env: ' .. binPath .. ' added to path', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) + -- vim.notify('Env: ' .. value, vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) + -- pcall(function() + -- if _pio_metadata.dbTrigger then + -- vim.notify('Env: dbTrigger', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) + -- local dbFix = pio.compile_commandsFix + -- local ok, _ = pcall(dbFix) + -- if not ok then + -- print('Env: dbTrigger, fail to call dbFix') + -- end + -- -- dbFix() + -- _pio_metadata.dbTrigger = false + -- else + -- local LspRestart = require('platformio.lspConfigConfig.tools').lsp_restart + -- LspRestart('clangd') + -- vim.notify('Env: LspRestart', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) + -- end + -- end) + elseif key == 'last_projectChecksum' then + elseif key == 'active_env' then + end + end) + end, +}) + +local config_path = vim.fs.joinpath(vim.uv.cwd(), '.project_config.json') +-- -- Add this temporary line in a file where you are coding: +-- ---@type platformio.utils.misc +-- local misc = vim.misc +--INFO: +-- 2. Save Logic (Uses sha256 for stability) +function M.save_project_config(from) + -- 1. Generate the formatted string directly, jsonFormat already returns a string! + local ok, pretty_json = pcall(vim.misc.jsonFormat, _pio_metadata) + + if not ok or not pretty_json then + print('Error formatting metadata') + return + end + + local current_hash = vim.fn.sha256(pretty_json) + + -- 2. Only write if the content actually changed + if current_hash ~= last_saved_hash then + local status, err = vim.misc.writeFile(config_path, pretty_json, {}) + + if status then + last_saved_hash = current_hash + vim.notify(from .. 'config save success', vim.log.levels.INFO, { title = 'PlatformIO' }) + else + vim.notify(from .. 'config save failed==> ' .. (err or 'unknown error'), vim.log.levels.ERROR) + end + end +end + +--INFO: +-- 3. Load Logic (Populates proxy safely) +function M.load_project_config() + if vim.fn.filereadable(config_path) == 1 then + local _, json_data = vim.misc.readFile(config_path) + if json_data then + local ok, table_data = pcall(vim.json.decode, json_data) + if ok and type(table_data) == 'table' then + -- We update _pio_metadata directly to avoid triggering + -- 50+ notifications/restarts during the initial load loop + for k, v in pairs(table_data) do + _G.metadata[k] = v + end + last_saved_hash = vim.fn.sha256(json_data) + return + end + end + end + -- If no file, initialize hash with defaults + last_saved_hash = vim.fn.sha256(vim.misc.jsonFormat(_pio_metadata)) +end + +--INFO: +-- 4. Initialization +M.load_project_config() + +return M diff --git a/pio.lua b/pio.lua new file mode 100644 index 00000000..defa207c --- /dev/null +++ b/pio.lua @@ -0,0 +1,682 @@ +-- ---@class platformio.utils.pio +-- local M = {} +-- +-- -- to fix require loop, this value is set in plugin/platformio +-- local misc = vim.misc +-- +-- -- local sep = package.config:sub(1, 1) -- Dynamic OS separator (\ or /) +-- M.selected_framework = '' +-- M.is_processing = false +-- M.queue = {} +-- +-- local term = require('platformio.utils.term') +-- local clangdRestart = require('platformio.lspConfig.tools').clangdRestart +-- +-- -- INFO: +-- -- ============================================================================= +-- -- UNIVERSAL TOOLCHAIN DETECTION +-- -- ============================================================================= +-- -- stylua: ignore +-- function M.get_sysroot_triplet(cc_compiler) +-- local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') +-- +-- -- Early exit if path is nil or not a directory +-- if not bin_path or vim.fn.isdirectory(bin_path) == 0 then return nil end +-- +-- -- Normalize backslashes to forward slashes for cross-platform consistency +-- bin_path = bin_path:gsub('\\', '/') +-- local files = vim.fn.readdir(bin_path) +-- local triplet = nil +-- +-- -- Loop through files to find the compiler and extract the triplet +-- for _, name in ipairs(files) do +-- -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ +-- local match = name:match('^(.*)%-g[c%+][c%+]') +-- if match then triplet = vim.misc.normalizePath(match) break +-- end +-- end +-- +-- -- Return nil if no compiler was found in the bin directory +-- if not triplet then return nil end +-- +-- -- toolchain_root is the parent of the 'bin' folder +-- local toolchain_root = vim.misc.normalizePath(vim.fn.fnamemodify(bin_path, ':h')) +-- -- sysroot folder is expected to have the same name as the triplet +-- local sysroot = vim.misc.normalizePath(toolchain_root .. '/' .. triplet) +-- local query_driver = vim.misc.normalizePath(bin_path .. '/' .. triplet .. '-*') +-- +-- -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) +-- -- Only return data if the sysroot folder actually exists on disk +-- if vim.fn.isdirectory(sysroot) == 1 then +-- _G.metadata.triplet = triplet +-- _G.metadata.sysroot = sysroot +-- _G.metadata.toolchain_root = toolchain_root +-- _G.metadata.query_driver = query_driver +-- return { +-- triplet = triplet, +-- sysroot = sysroot, +-- toolchain_root = toolchain_root, +-- query_driver = query_driver, +-- } +-- end +-- return nil +-- end +-- +-- --INFO: +-- -- Fast environment detection from platformio.ini file(no external calls) +-- -- stylua: ignore +-- --============================================================================= +-- function M.get_active__env() +-- local path +-- +-- for _, dir in ipairs({ vim.api.nvim_buf_get_name(0):match('(.*[/\\])'), (vim.uv.cwd() .. '/') }) do +-- local tmp = dir .. 'platformio.ini' +-- local filestat = vim.uv.fs_stat(tmp) +-- if filestat and filestat.type == 'file' then +-- path = vim.fs.normalize(tmp) +-- break +-- end +-- end +-- if not path or path == '' then return vim.notify('PIO: platformio.ini not found or no [env] defined.', vim.log.levels.ERROR) end +-- +-- -- Read file content (returns string or nil) +-- local ok, content = vim.misc.readFile(path) +-- if not ok or not content then return vim.notify('PIO: platformio.ini not found in ' .. path, vim.log.levels.WARN) end +-- +-- local default_envs_raw = '' +-- local first_env = nil +-- local valid_envs = {} +-- local in_platformio_block = false +-- +-- -- Iterate lines from the content string +-- for line in vim.gsplit(content, '\n') do +-- -- Section Detection: [section_name] +-- local section = line:match('^%s*%[(.+)%]%s*$') +-- if section then +-- in_platformio_block = (section == 'platformio') +-- local env_name = section:match('^env:(.+)') +-- if env_name then +-- if not first_env then first_env = env_name end +-- valid_envs[env_name] = true +-- end +-- end +-- +-- -- Collect the default_envs string from [platformio] block +-- if in_platformio_block then +-- local def = line:match('^%s*default_envs%s*=%s*(.+)') +-- if def then default_envs_raw = def end +-- end +-- end +-- +-- -- Validation: Find the first default_env that actually exists as a block +-- if default_envs_raw ~= '' then +-- for env_name in default_envs_raw:gmatch('([^%s,]+)') do +-- if valid_envs[env_name] then return env_name end +-- end +-- end +-- +-- -- Fallback to the very first [env:...] block found in the file +-- return first_env +-- end +-- +-- +-- --INFO: +-- -- get pio project metadata info +-- -- stylua: ignore +-- --============================================================================= +-- function M.fetch_metadata(callback, env, from, attempts) +-- local msg = (type(from)=='string' and from ~= '') and from or 'PIO: ' +-- local meta = _G.metadata +-- local active_env = env or meta.active_env +-- if not active_env or active_env == '' then +-- return +-- end +-- +-- -- Set up file paths +-- local build_dir = vim.misc.joinPath(vim.uv.cwd(), '.pio', 'build') +-- local build_env_dir = vim.misc.joinPath(build_dir, active_env) +-- local checksum_file = vim.misc.joinPath(build_dir, 'project.checksum') +-- local idedata_file = vim.misc.joinPath(build_env_dir, 'idedata.json') +-- +-- --INFO: +-- --INTERNAL PROCESSOR: Applies parsed data to _G.metadata +-- --------------------------------------------------------- +-- local function apply_metadata(data, checksum) +-- if not data then return false end +-- +-- local norm = function(p) return vim.misc.normalizePath(p) or '' end +-- +-- -- Helper for flags/defines to keep order and formatting +-- local quote_map = function(list, prefix) +-- local res = {} +-- for _, v in ipairs(list or {}) do +-- local val = prefix and (prefix .. norm(v)) or v +-- table.insert(res, string.format('%s', val)) +-- end +-- return res +-- end +-- +-- -- 1. Base Paths & Compilers +-- meta.cc_path = norm(data.cc_path) +-- meta.cc_compiler = meta.cc_path +-- meta.cxx_path = norm(data.cxx_path) +-- meta.gdb_path = norm(data.gdb_path) +-- +-- -- 2. Flags & Defines +-- meta.cc_flags = quote_map(data.cc_flags) +-- meta.cxx_flags = quote_map(data.cxx_flags) +-- meta.defines = quote_map(data.defines) +-- +-- -- 3. Includes (Build, Toolchain, Compatlib) +-- local inc = data.includes or {} +-- meta.includes_build = quote_map(inc.build, '-I') +-- meta.includes_toolchain = quote_map(inc.toolchain, '-isystem') +-- meta.includes_compatlib = quote_map(inc.compatlib, '-isystem') +-- meta.last_projectChecksum = checksum +-- pcall(M.get_sysroot_triplet, meta.cc_compiler) +-- +-- return true +-- end +-- +-- --INFO: +-- --Generate idedata.json +-- --------------------------------------------------------- +-- local function buildIdedata() +-- vim.notify(msg .. 'Initializing project metadata...', vim.log.levels.INFO) +-- vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env, '-s' }, { text = true }, function(obj) +-- vim.schedule(function() +-- if obj.code == 0 then +-- vim.notify(msg .. 'Initializing project metadata success.', vim.log.levels.INFO) +-- M.fetch_metadata(callback, active_env, from, attempts - 1) -- Recursive call after files created +-- else +-- vim.notify(msg .. 'Initialization failed. Build project manually.', vim.log.levels.ERROR) +-- end +-- end) +-- end) +-- return true +-- end +-- +-- --------------------------------------------------------- +-- -- STEP 1: Fast Checksum Check (project.checksum and idedata.json) +-- --------------------------------------------------------- +-- local ok, current_checksum = vim.misc.readFile(checksum_file) +-- if ok and (type(current_checksum) == 'string' and current_checksum ~= '') then +-- if current_checksum == meta.last_projectChecksum then +-- vim.notify(msg .. 'Metadata synced with cache', vim.log.levels.INFO) +-- -- if callback then callback() end +-- if callback then vim.schedule(callback) end +-- return true +-- end -- Already updated +-- +-- -- STEP 2: Cache Path (idedata.json exists and checksum changed) +-- local idok, content = vim.misc.readFile(idedata_file) +-- if idok and (type(content) == 'string' and content ~= '') then +-- local cok, decoded = pcall(vim.json.decode, content) +-- +-- +-- local formated = vim.misc.jsonFormat(decoded) +-- local file = vim.misc.joinPath(vim.uv.cwd(), 'idedata.json') +-- vim.misc.writeFile(file, formated, {}) +-- +-- +-- if cok and apply_metadata(decoded, current_checksum) then +-- local metadata = require('platformio.pio.metadata') +-- metadata.save_project_config(msg) +-- vim.notify(msg .. 'Metadata synced from cache', vim.log.levels.INFO) +-- -- if callback then vim.schedule(callback) end +-- +-- if type(callback) == "function" then +-- vim.schedule(callback) +-- else +-- -- If it's not a function, just do nothing or print a debug message +-- print(msg .." Debug; callback was " .. type(callback)) +-- end +-- +-- return true +-- end +-- -- else +-- end +-- -- else +-- end +-- --------------------------------------------------------- +-- -- STEP 3: Auto-Initialize (If files project.checksum and idedata.json are missing) +-- --------------------------------------------------------- +-- buildIdedata() +-- +-- --------------------------------------------------------- +-- -- STEP 4: Standard CLI Fallback (The Slow Path) +-- --------------------------------------------------------- +-- -- vim.notify(msg .. 'Metadata sync ...', vim.log.levels.INFO) +-- -- vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(obj) +-- -- vim.schedule(function() +-- -- if obj.code ~= 0 then +-- -- if attempts > 0 then +-- -- vim.defer_fn(function() M.fetch_metadata(attempts - 1, env) end, 500) +-- -- return +-- -- end +-- -- return vim.notify(msg .. 'Metadata Error: ' .. (obj.stderr or 'Unknown'), vim.log.levels.WARN) +-- -- end +-- -- +-- -- local ook, raw_data = pcall(vim.json.decode, obj.stdout or '') +-- -- local _, data = next(raw_data or {}) +-- -- +-- -- if ook and apply_metadata(data, current_checksum) then +-- -- vim.notify(msg .. 'Metadata synced from CLI', vim.log.levels.INFO) +-- -- if callback then vim.schedule(callback) end +-- -- else +-- -- vim.notify(msg .. 'Failed to parse metadata output', vim.log.levels.WARN) +-- -- end +-- -- end) +-- -- end) +-- end +-- +-- -- INFO: +-- -- ============================================================================= +-- -- Get project configuration +-- -- ============================================================================= +-- -- stylua: ignore +-- function M.fetch_config(on_done, from) +-- local msg = (type(from) == 'string' and from ~= '') and from or 'PIO: ' +-- local meta = _G.metadata +-- local home = (os.getenv('HOME') or os.getenv('USERPROFILE') or ''):gsub('[\\/]+$', '') +-- +-- local active_env +-- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) +-- vim.schedule(function() +-- -- 1. Check Execution +-- if obj.code ~= 0 then +-- local errmsg = obj.code == 127 and "'pio' not found" or (obj.stderr or 'Unknown Error') +-- return vim.notify(msg .. 'Config Error: ' .. errmsg, vim.log.levels.ERROR) +-- end +-- +-- -- 2. Decode JSON safely +-- local ok, decoded = pcall(vim.json.decode, obj.stdout or '') +-- if not ok or type(decoded) ~= 'table' then +-- return vim.notify(msg .. 'Failed to decode config JSON', vim.log.levels.ERROR) +-- end +-- +-- local formated = vim.misc.jsonFormat(decoded) +-- local file = vim.misc.joinPath(vim.uv.cwd(), 'config.json') +-- vim.misc.writeFile(file, formated, {}) +-- +-- -- Reset core structure +-- meta.envs = {} +-- meta.default_envs = {} +-- local valid_envs = {} +-- +-- -- 3. Parse Sections +-- for _, section in ipairs(decoded) do +-- local name, data = section[1], section[2] +-- if name == 'platformio' then +-- for _, kv in ipairs(data) do +-- meta[kv[1]] = kv[2] +-- end +-- elseif name:match('^env:') then +-- local env_name = name:match('^env:(.+)') +-- if not active_env then active_env = env_name end +-- valid_envs[env_name] = true +-- meta.envs[env_name] = {} +-- for _, kv in ipairs(data) do +-- meta.envs[env_name][kv[1]] = kv[2] +-- end +-- end +-- end +-- +-- -- 4. Assign active_env +-- -- Validation: Find the first default_env that actually exists as a block +-- for _, env_name in ipairs(meta.default_envs) do +-- if valid_envs[env_name] then +-- active_env = env_name +-- break +-- end +-- end +-- meta.active_env = active_env +-- +-- -- 5. Resolve Paths (INI -> Env -> Default) +-- local path_map = { +-- { key = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, +-- { key = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, +-- { key = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, +-- } +-- +-- for _, item in ipairs(path_map) do +-- local val = meta[item.key] +-- -- Fallback chain +-- if not val or val == '' then +-- val = os.getenv(item.env) or (home .. item.sub) +-- end +-- -- Expand variables and Normalize +-- if type(val) == 'string' then +-- val = val:gsub('%%${platformio.core_dir}', meta.core_dir or '') +-- meta[item.key] = vim.misc.normalizePath(val) +-- end +-- end +-- +-- -- if active_env then +-- -- vim.notify(msg .. 'active_env= ' .. active_env, vim.log.levels.INFO) +-- -- end +-- -- 6. Trigger next step +-- if meta.active_env ~= '' then +-- vim.notify(msg .. 'Config sync successful', vim.log.levels.INFO) +-- else +-- vim.notify(msg .. 'No [env:] found. Please add a board.', vim.log.levels.ERROR) +-- end +-- +-- if on_done then +-- vim.schedule(function() on_done(active_env) end) +-- end +-- end) +-- end) +-- end +-- +-- -- INFO: +-- -- Fix compile_commands.json file with absoulute paths +-- -- stylua: ignore +-- -- ============================================================================= +-- function M.compile_commandsFix() --M.dbPathsFix() +-- local filename = vim.fs.joinpath(vim.uv.cwd(), 'compile_commands.json') +-- local content = vim.fn.readfile(filename) +-- if #content == 0 then return end +-- +-- local start_time = vim.loop.hrtime() +-- local ok, data = pcall(vim.json.decode, table.concat(content, '\n')) +-- if not ok or type(data) ~= 'table' then return end +-- +-- -- 1. Build Path Map (Scan toolchain) +-- local path_map = {} +-- local pio_binaries = _G.metadata.query_driver or '/bin/*' +-- -- local pio_binaries = (_G.metadata.toolchain_root or "") .. '/bin/*' +-- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do +-- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') +-- path_map[name] = full_path +-- end +-- +-- -- 2. Update Entries +-- local modified = false +-- local prntFlags = true +-- for _, entry in ipairs(data) do +-- -- Standard normalization +-- if entry.directory then entry.directory = misc.normalizePath(entry.directory) end +-- if entry.file then entry.file = misc.normalizePath(entry.file) end +-- if entry.arguments then entry.arguments = misc.normalizeFlags(entry.arguments) end +-- if entry.output then entry.output = misc.normalizePath(entry.output) end +-- +-- if entry.command then +-- -- Extract compiler and everything after it +-- local compiler, args = entry.command:match("^%s*(%S+)(.*)") +-- if compiler then +-- local is_absolute = compiler:sub(1, 1) == '/' or compiler:match('^%a:') +-- +-- if not is_absolute then +-- local short_name = compiler:match('([^/\\\\]+)$'):gsub('%.exe$', '') +-- +-- if path_map[short_name] then +-- -- Use normalizePath on the new path +-- local full_compiler_path = misc.normalizePath(path_map[short_name]) +-- +-- -- Quote the path if it contains spaces +-- if full_compiler_path:find(" ") then +-- full_compiler_path = '"' .. full_compiler_path .. '"' +-- end +-- if prntFlags then +-- -- print(string.format('ful_compiler_path = %s flags=%s', full_compiler_path, args)) +-- prntFlags = false +-- end +-- entry.command = full_compiler_path .. args +-- modified = true +-- end +-- end +-- end +-- end +-- end +-- -- -- 3. Save with Formatting +-- if modified then +-- local jok, formatted = pcall(vim.misc.jsonFormat, data) +-- -- local jok, formatted = pcall(M.pretty_print, data) +-- if not jok then +-- print('Formatting failed: ' .. formatted) +-- return +-- end +-- +-- local wk, err = vim.misc.writeFile(filename, formatted, { overwrite = true, mkdir = true }) +-- if not wk then print(err) end +-- +-- local end_time = vim.loop.hrtime() +-- local duration = (end_time - start_time) / 1e6 +-- vim.notify(string.format('compiledb: paths fixed in %.2fms', duration), vim.log.levels.INFO) +-- clangdRestart() +-- end +-- _G.metadata.isBusy = false +-- end +-- +-- +-- -- INFO: +-- --configuration for running sequential commands on ToggleTerminal +-- -- stylua: ignore +-- -- ============================================================================= +-- -- ============================================================================= +-- local callBack = nil +-- local pio_buffer = '' -- Persistent stream buffer +-- +-- -- INFO: ToggleTerminal commands stdout filter +-- -- stylua: ignore +-- -- ============================================================================= +-- function M.stdoutcallback(_, _, data) +-- if not data then return end +-- +-- -- 1. Combine the last partial line with the new first line +-- local lines_to_process = pio_buffer .. data[1] +-- +-- -- 2. If there are newlines, we have complete lines to check +-- if #data > 1 then +-- -- Join all complete parts (everything except the very last partial line) +-- for i = 2, #data - 1 do lines_to_process = lines_to_process .. data[i] end +-- +-- -- 3. Search for the status in the complete chunk +-- local status = lines_to_process:match('_CMMNDS_:(%a+)') +-- if status and callBack then vim.schedule(function() callBack(status) end) end +-- -- save the trailing part for the next chunk +-- pio_buffer = data[#data] +-- else +-- -- Only one element in data means no newline yet; just update the partial buffer +-- pio_buffer = lines_to_process +-- end +-- +-- -- 4. Safety Trim (Prevents memory leaks if no newline ever comes) +-- if #pio_buffer > 5000 then pio_buffer = pio_buffer:sub(-2500) end +-- end +-- +-- local commandPassed = 0 +-- +-- +-- -- INFO: commands sequencer +-- -- stylua: ignore +-- -- ============================================================================= +-- M.run_sequence = function(tasks) +-- M.queue = {} +-- local commands = tasks.cmnds +-- +-- local done = ' && echo _CMMNDS_":"DONE' +-- local pass = ' && echo _CMMNDS_":"PASS' +-- local fail = ' || echo _CMMNDS_":"FAIL' +-- -- +-- for i, cmd in ipairs(commands) do +-- local full_cmd = '' +-- if i == #commands then full_cmd = cmd .. done .. fail +-- else full_cmd = cmd .. pass .. fail end +-- table.insert(M.queue, full_cmd) +-- end +-- +-- +-- callBack = tasks.cb -- 1. Save the callback in a local variable +-- +-- commandPassed = 1 +-- _G.metadata.isBusy = true +-- +-- term.stdout_callback = M.stdoutcallback +-- vim.schedule(function() if callBack then callBack('INIT') end end) +-- end +-- +-- local trm +-- local win_id +-- ------------------------------------------------------ +-- -- Handle after pioinit execution +-- -- ============================================================================= +-- -- stylua: ignore +-- function M.handlePioinitDb(result) +-- if result == 'INIT' then +-- local boilerplate = require('platformio.boilerplate') +-- local boilerplate_gen = boilerplate.boilerplate_gen +-- +-- boilerplate.core_dir = _G.metadata.core_dir +-- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) +-- +-- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) +-- +-- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +-- -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) +-- -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') +-- +-- win_id = vim.misc.showMessage('************ Project Initializing ************') +-- if #M.queue > 0 then trm = term.ToggleTerminal(table.remove(M.queue, 1), 'float')end +-- elseif result == 'PASS' then +-- -- if commandPassed == 1 then +-- -- elseif commandPassed == 2 then -- if you sned more than 2 commands you need this +-- -- end +-- vim.notify('PIO init+db: pass ' .. commandPassed, vim.log.levels.INFO) +-- commandPassed = commandPassed + 1 +-- if #M.queue > 0 then term.ToggleTerminal(table.remove(M.queue, 1), 'float') end +-- elseif result == 'DONE' then -- result of the last command +-- vim.schedule(function() +-- vim.notify('PIO init+db: pass ' .. commandPassed, vim.log.levels.INFO) +-- vim.notify('PIO init+db: Done', vim.log.levels.INFO) +-- vim.misc.gitignore_lsp_configs('compile_commands.json') +-- local pio_refresh = require('platformio.pio.watcher').pio_refresh +-- pio_refresh(function() +-- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +-- boilerplate_gen([[.clangd]], _G.metadata.core_dir) +-- vim.misc.closeMessage(win_id) +-- clangdRestart() +-- -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') +-- end, 'PIO init+db: ') +-- end) +-- vim.misc.deleteFile(vim.fs.joinpath(vim.g.platformioRootDir, '.ccls')) +-- M.queue = {} +-- term.stdout_callback = nil +-- trm:close() +-- _G.metadata.isBusy = false +-- elseif result == 'FAIL' then +-- _G.metadata.isBusy = false +-- vim.misc.closeMessage(win_id) +-- M.queue = {} +-- term.stdout_callback = nil +-- trm:close() +-- end +-- end +-- +-- +-- ---------------------------------------------------- +-- -- Handle after pioinit execution +-- -- stylua: ignore +-- function M.handlePioinit(result) +-- if result == 'INIT' then +-- local boilerplate = require('platformio.boilerplate') +-- local boilerplate_gen = boilerplate.boilerplate_gen +-- +-- boilerplate.core_dir = _G.metadata.core_dir +-- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) +-- +-- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) +-- +-- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +-- -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) +-- -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') +-- +-- win_id = vim.misc.showMessage('************ Project Initializing ************') +-- if #M.queue > 0 then trm = term.ToggleTerminal(table.remove(M.queue, 1), 'float')end +-- elseif result == 'DONE' then -- result of the last command +-- vim.schedule(function() +-- vim.notify('PIO init: pass ' .. commandPassed, vim.log.levels.INFO) +-- vim.notify('PIO init: Done', vim.log.levels.INFO) +-- vim.misc.gitignore_lsp_configs('compile_commands.json') +-- +-- -- \27[s : Save current cursor position (the prompt) +-- -- \r : Go to start of line +-- -- \27[A : Move cursor UP one line (to space above prompt) +-- -- \27[K : Clear that line +-- -- \27[33m : Color Yellow (optional) +-- -- %s : Your message +-- -- \27[0m : Reset color +-- -- \27[u : Restore cursor back to the prompt +-- -- IMPORTANT: No \n at the end, so it doesn't execute +-- -- local msg = '************ Please wait for project Initialization to finish ************' +-- -- local clean_msg = string.format('\27[G\27[2K\27[33m%s\27[0m', msg) +-- -- vim.api.nvim_chan_send(trm.job_id, clean_msg) +-- +-- local pio_refresh = require('platformio.pio.watcher').pio_refresh +-- pio_refresh(function() +-- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +-- boilerplate_gen([[.clangd]], _G.metadata.core_dir) +-- vim.misc.closeMessage(win_id) +-- clangdRestart() +-- -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') +-- end, 'PIO init: ') +-- end) +-- vim.misc.deleteFile(vim.fs.joinpath(vim.g.platformioRootDir, '.ccls')) +-- M.queue = {} +-- term.stdout_callback = nil +-- trm:close() +-- _G.metadata.isBusy = false +-- elseif result == 'FAIL' then +-- _G.metadata.isBusy = false +-- vim.misc.closeMessage(win_id) +-- M.queue = {} +-- term.stdout_callback = nil +-- trm:close() +-- end +-- end +-- +-- ------------------------------------------------------ +-- -- Handle after piolib execution +-- -- ============================================================================= +-- -- stylua: ignore +-- function M.handlePiolib(result) +-- if result == 'INIT' then +-- if #M.queue > 0 then term.ToggleTerminal(table.remove(M.queue, 1), 'float')end +-- elseif result == 'DONE' then -- result of the only and the last command +-- vim.notify('PIO lib: pass ' .. commandPassed, vim.log.levels.INFO) +-- vim.notify('PIO lib: Done', vim.log.levels.INFO) +-- commandPassed = commandPassed + 1 +-- M.queue = {} +-- term.stdout_callback = nil +-- _G.metadata.isBusy = false +-- elseif result == 'FAIL' then +-- M.queue = {} +-- term.stdout_callback = nil +-- _G.metadata.isBusy = false +-- end +-- end +-- +-- ------------------------------------------------------ +-- -- ============================================================================= +-- -- stylua: ignore +-- function M.handlePiodb(target, result) +-- if result == 'INIT' then +-- if #M.queue > 0 then term.ToggleTerminal(table.remove(M.queue, 1), 'float')end +-- elseif result == 'DONE' then -- result of the only and the last command +-- vim.notify('PIO db: pass ' .. commandPassed, vim.log.levels.INFO) +-- vim.notify('PIO db: Done', vim.log.levels.INFO) +-- commandPassed = commandPassed + 1 +-- target.isBusy = false +-- M.queue = {} +-- term.stdout_callback = nil +-- _G.metadata.isBusy = false +-- elseif result == 'FAIL' then +-- target.isBusy = false +-- M.queue = {} +-- term.stdout_callback = nil +-- _G.metadata.isBusy = false +-- end +-- end +-- +-- return M diff --git a/pio2.lua b/pio2.lua deleted file mode 100644 index 81af31aa..00000000 --- a/pio2.lua +++ /dev/null @@ -1,356 +0,0 @@ -local M = {} - -M.selected_framework = '' - -local misc = require('platformio.utils.misc') -local lsp_restart = require('platformio.lspConfig.tools').lsp_restart - -local term = require('platformio.utils.term') --- term.on_stdout_handler = nil - -M.is_processing = false ------------------------------------------------------- --- stylua: ignore -function M.compile_commandsFix() - local filename = vim.uv.cwd() .. '/compile_commands.json' - if vim.fn.filereadable(filename) == 0 then return end - - -- Atomic read using built-in Vim function - local content = table.concat(vim.fn.readfile(filename), "\n") - local ok, data = pcall(vim.json.decode, content) - if not ok or type(data) ~= 'table' then return end - - -- 1. Build Path Map (Scan toolchain) - local path_map = {} - local toolchain_bin = (_G.metadata and _G.metadata.toolchain or "") .. '/bin/*' - for _, full_path in ipairs(vim.fn.glob(toolchain_bin, false, true)) do - local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') - path_map[name] = full_path - end - - -- 2. Update Entries efficiently with string matching - local modified = false - for _, entry in ipairs(data) do - local cmd = entry.command or "" - local first_token = cmd:match("^%S+") -- Grab only the compiler driver - - -- Fix if it's a relative path (doesn't start with / or Drive letter) - if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then - local short_name = first_token:gsub('%.exe$', '') - if path_map[short_name] then - -- Replace only the first token to preserve arguments - entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) - modified = true - end - end - end - - -- 3. Save with Python formatting - if modified then - local json_str = vim.json.encode(data) - local formatted = vim.fn.system('python -m json.tool', json_str) - - if vim.v.shell_error == 0 then - -- Atomic write back to disk - vim.fn.writefile(vim.split(formatted, "\n"), filename) - vim.notify('compiledb: paths fixed', vim.log.levels.INFO) - else - vim.notify('PIO Fix: Python formatting failed', vim.log.levels.ERROR) - end - end -end - --- function M.compile_commandsFix() --- local filename = vim.uv.cwd() .. '/compile_commands.json' --- local content = vim.fn.readfile(filename) --- if #content == 0 then return end --- --- local ok, data = pcall(vim.json.decode, table.concat(content, "\n")) --- if not ok or type(data) ~= 'table' then return end --- --- -- 1. Build Path Map (Scan toolchain) --- local path_map = {} --- --- local pio_binaries = _G.metadata.query_driver or "/bin/*" --- -- local pio_binaries = (_G.metadata.toolchain or "") .. '/bin/*' --- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do --- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') --- path_map[name] = full_path --- end --- --- -- 2. Update Entries --- local modified = false --- for _, entry in ipairs(data) do --- local cmd = entry.command or "" --- local first_token = cmd:match("^%S+") -- Get first word before space --- --- if first_token and not (first_token:sub(1,1) == '/' or first_token:match('^%a:')) then --- local short_name = first_token:gsub('%.exe$', '') --- if path_map[short_name] then --- -- Swap first token with full path safely --- entry.command = path_map[short_name] .. cmd:sub(#first_token + 1) --- modified = true --- end --- end --- end --- --- -- 3. Save with Formatting --- if modified then --- local json_str = vim.json.encode(data) --- -- Use python to format, then write file --- local formatted = vim.fn.system('python -m json.tool', json_str) --- if vim.v.shell_error == 0 then --- vim.fn.writefile(vim.split(formatted, "\n"), filename) --- vim.notify('compiledb: paths fixed', vim.log.levels.INFO) --- end --- end --- end - --- function M.compile_commandsFix() --- local filename = vim.uv.cwd() .. '/compile_commands.json' --- local file = io.open(filename, 'r') --- if not file then return end --- --- -- read compile_commands.json file to content --- local content = file:read('*a') --- file:close() --- if not content or content == '' then return end --- --- -- JSON decoding content to data --- local ok, data = pcall(vim.json.decode, content) --- if not ok or type(data) ~= 'table' then --- vim.notify('PIO Fix: Invalid JSON in ' .. filename, vim.log.levels.ERROR) --- return --- end --- --- -- print('PioFix0') --- -- PHASE 1: Scan Disk to build a Map of Name -> Absolute Path --- local path_map = {} --- local pio_home = _G.metadata.core_dir --os.getenv('PLATFORMIO_CORE_DIR') --or os.getenv('USERPROFILE') --- if pio_home then --- -- Recursively find all binaries in PIO packages --- local pio_packages = _G.metadata.toolchain .. '/bin/*' --M.get_pio_dir('packages') .. '/*/bin/*' --- local found_binaries = vim.fn.glob(pio_packages, false, true) --- --- for _, full_path in ipairs(found_binaries) do --- -- Extract filename (e.g., riscv32-esp-elf-gcc) --- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') --- path_map[name] = full_path --- -- print('PioFix1: driver_path=' .. full_path .. ' name=' .. name) --- end --- end --- --- -- PHASE 2: Update JSON using the Map --- local modified = 0 --- for _, entry in ipairs(data) do --- if type(entry.command) == 'string' then --- local cmd_parts = vim.split(entry.command, ' ') --- local first_token = cmd_parts[1] --- if first_token then --- -- Check if it's already a short name (not an absolute path) --- local is_abs = first_token:sub(1, 1) == '/' or first_token:match('^%a:[/\\]') --- if not is_abs then --- local short_name = first_token:gsub('%.exe$', '') --- -- print('PioFix2: short_name=' .. short_name) --- -- Direct Query: Does this name exist in our discovered list? --- if path_map[short_name] then --- cmd_parts[1] = path_map[short_name] --- -- print('PioFix3: full_name=' .. cmd_parts[1]) --- entry.command = table.concat(cmd_parts, ' ') --- modified = modified + 1 --- end --- end --- end --- end --- end --- --- -- PHASE 3: Save and Refresh --- -- Safe JSON encoding --- if modified > 0 then --- local out_file = io.open(filename, 'w') --- if out_file then --- local encode_ok, json_str = pcall(vim.json.encode, data, { indent = ' ' }) --- if encode_ok and json_str then --- -- 1. Format the string using python's json.tool --- -- The second argument to vim.fn.system() is the "stdin" passed to the command --- local formatted_json = vim.fn.system('python -m json.tool', json_str) --- --- -- out_file:write(json_str) --- out_file:write(formatted_json) --- out_file:close() --- vim.notify('compiledb: fixed', vim.log.levels.INFO) --- -- lsp_restart('clangd') --- end --- end --- end --- end - ------------------------------------------------------- --- INFO: ToggleTerminal commands sequencer - -M.queue = {} -local pio_buffer = '' -- Persistent stream buffer - ------------------------------------------------------- --- INFO: ToggleTerminal commands stdout filter --- stylua: ignore -function M.stdoutFilter(_, _, data) - if #M.queue == 0 then return end - - -- 1. attach partial buffer from previous data last line to 1st line - pio_buffer = pio_buffer .. data[1] - -- 2. If the chunk has more than one element, we've encountered newlines - if #data > 1 then - -- 3. Process any "middle" lines which are guaranteed to be complete - for i = 2, #data - 1 do pio_buffer = pio_buffer .. data[i] end - - for status in pio_buffer:gmatch('_DONE_:(%a+)') do - if status then - if status == 'PASS' then - -- 4. Store the last element as the new partial buffer for the next call - pio_buffer = data[#data] - M.process_queue() - -- local task = table.remove(M.queue, 1) - -- if task then vim.schedule(task) end - -- elseif status == 'LAST' then - -- _G.metadata.isBusy = false - -- M.queue = {} -- Clear queue on any other status - -- pio_buffer = '' - -- vim.schedule(function() vim.notify('PIO Sequence: Finished', 4) end) - elseif status == 'FAIL' then - M.queue = {} -- Clear queue on any other status (failure) - pio_buffer = '' - vim.schedule(function() vim.notify('PIO Sequence: Aborted', 4) end) - end - break - end - end - end - if #pio_buffer > 10000 then pio_buffer = pio_buffer:sub(-5000) end -end - --- _G.metadata.isBusy = true -term.on_stdout_handler = M.stdoutFilter -local pio_terminal = term.ToggleTerminal('', 'float') ------------------------------------------------------- --- INFO: ToggleTerminal commands Sequencer ---- stylua: ignore -M.run_sequence = function(tasks) - -- Reset local state for new run - M.queue = {} - pio_buffer = '' - local full_cmd = '' - - local pass = 'echo _DONE_":"PASS' - -- local last = 'echo _DONE_":"LAST' - local fail = 'echo _DONE_":"FAIL' - - for _, row in ipairs(tasks) do - -- Build the wrapped command string - local wrapped_cmd = string.format('%s && %s || %s', row.cmd, pass, fail) - table.insert(M.queue, { - cmd = wrapped_cmd, - cb = row.cb, - }) - end - - -- for _, task in ipairs(tasks) do - -- table.insert(M.queue, task.cb) - -- local part = string.format('%s && %s', task.cmd, pass) - -- if full_cmd == '' then - -- full_cmd = part - -- else - -- full_cmd = full_cmd .. ' && ' .. part - -- end -- Chain multiple commands - -- end - -- full_cmd = full_cmd .. ' && ' .. last .. ' || ' .. failure - -- local term = require('platformio.utils.term').ToggleTerminal - -- _G.metadata.isBusy = true - -- term(full_cmd, 'float') -end - --- 2. Shell Runner: Sends text to the live shell -function M.run_shell_job(cmd, on_exit_callback) - -- Ensure terminal is open and process is alive - if not pio_terminal then - return - end - if not pio_terminal:is_open() then - pio_terminal:open() - end - - -- Wrap the command: - -- 1. Run the actual command - -- 2. Run the callback logic (optional) - -- 3. Print the sentinel so the Lua listener knows we're done - -- local full_cmd = string.format('%s && echo %s', cmd, sentinel) - - -- Store callback for the listener if needed - M.current_cb = on_exit_callback - - -- Send the text + Enter key - pio_terminal:send(cmd) -end --- 3. Queue Controller -function M.process_queue() - local task = table.remove(M.queue, 1) - - if not task then - M.is_processing = false - if M.current_cb then - M.current_cb() - end -- Final callback - return - end - - M.is_processing = true - - if task.cmd then - M.run_shell_job(task.cmd, task.cb) - elseif type(task.cb) == 'function' then - vim.schedule(function() - task.cb() - -- Lua tasks need to manually move the queue - M.process_queue() - end) - end -end ------------------------------------------------------- --- Handle after 'pio run -t compiledb' execution -function M.handleDb() - vim.notify('compiledb: compile_commands.json generated/updated', vim.log.levels.INFO) - misc.gitignore_lsp_configs('compile_commands.json') - local pio_manager = require('platformio.pio_setup').pio_manager - pio_manager.refresh(function() - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - boilerplate_gen([[.clangd]], _G.metadata.core_dir) - M.compile_commandsFix() - lsp_restart('clangd') - end) -end - ------------------------------------------------------- --- Handle after poioinit execution ---- stylua: ignore -function M.handlePioinit() - -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - -- boilerplate_gen([[.clangd_cmd]], vim.g.platformioRootDir) - -- vim.schedule(function() - -- local pio_manager = require('platformio.pio_setup').pio_manager - -- pio_manager.refresh(function() - -- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen - -- boilerplate_gen(M.selected_framework, vim.uv.cwd() .. '/src', 'main.cpp') - vim.notify('Pioinit: Success', vim.log.levels.INFO) - -- end) - -- end) -end --- Handle after poioinit execution --- stylua: ignore -function M.handlePiolib() - vim.notify('Piolib: Success', vim.log.levels.INFO) -end --- INFO: end commands sequencer ------------------------------------------------------- - -return M diff --git a/pio_setup.lua b/pio_setup.lua index 2819875f..eda8f081 100644 --- a/pio_setup.lua +++ b/pio_setup.lua @@ -1,226 +1,12 @@ -- M = {} -- --- -- local lsp_restart = require('platformio.lspConfig.tools').lsp_restart +-- local clangdRestart = require('platformio.lspConfig.tools').clangdRestart -- local boilerplate = require('platformio.boilerplate') -- local boilerplate_gen = boilerplate.boilerplate_gen -- --- --- --- -- local debounce_timer = vim.uv.new_timer() --- -- ============================================================================= --- -- stylua: ignore --- function M.pio_refresh(callback, from) --- local msg = (type(from)=='string' and from ~= '') and from or 'PIO: ' --- vim.notify(msg ..'Config sync ...', vim.log.levels.INFO) --- -- -- INFO:------------------------------------------------- --- -- -- get pio project metadata info --- -- -- stylua: ignore --- -- local function fetch_metadata(attempts, env) --- -- local meta = _G.metadata --- -- local active_env = env or meta.active_env --- -- if not active_env or active_env == '' then --- -- return --- -- end --- -- --- -- -- Set up file paths --- -- local build_dir = vim.misc.joinPath(vim.uv.cwd(), '.pio', 'build') --- -- local build_env_dir = vim.misc.joinPath(build_dir, active_env) --- -- local checksum_file = vim.misc.joinPath(build_dir, 'project.checksum') --- -- local idedata_file = vim.misc.joinPath(build_env_dir, 'idedata.json') --- -- --- -- --------------------------------------------------------- --- -- -- INTERNAL PROCESSOR: Applies parsed data to _G.metadata --- -- local function apply_metadata(data, checksum) --- -- if not data then return false end --- -- --- -- local norm = function(p) return vim.misc.normalizePath(p) or '' end --- -- --- -- -- Helper for flags/defines to keep order and formatting --- -- local quote_map = function(list, prefix) --- -- local res = {} --- -- for _, v in ipairs(list or {}) do --- -- local val = prefix and (prefix .. norm(v)) or v --- -- table.insert(res, string.format('%s', val)) --- -- end --- -- return res --- -- end --- -- --- -- -- 1. Base Paths & Compilers --- -- meta.cc_path = norm(data.cc_path) --- -- meta.cc_compiler = meta.cc_path --- -- meta.cxx_path = norm(data.cxx_path) --- -- meta.gdb_path = norm(data.gdb_path) --- -- --- -- -- 2. Flags & Defines --- -- meta.cc_flags = quote_map(data.cc_flags) --- -- meta.cxx_flags = quote_map(data.cxx_flags) --- -- meta.defines = quote_map(data.defines) --- -- --- -- -- 3. Includes (Build, Toolchain, Compatlib) --- -- local inc = data.includes or {} --- -- meta.includes_build = quote_map(inc.build, '-I') --- -- meta.includes_toolchain = quote_map(inc.toolchain, '-isystem') --- -- meta.includes_compatlib = quote_map(inc.compatlib, '-isystem') --- -- meta.last_projectChecksum = checksum --- -- pcall(M.get_sysroot_triplet, meta.cc_compiler) --- -- --- -- -- if callback then vim.schedule(callback) end --- -- return true --- -- end --- -- --- -- --------------------------------------------------------- --- -- -- STEP 1: Fast Checksum Check --- -- --------------------------------------------------------- --- -- local ok, current_checksum = vim.misc.readFile(checksum_file) --- -- if ok and (type(current_checksum) == 'string' and current_checksum ~= '') then --- -- if current_checksum == meta.last_projectChecksum then --- -- vim.notify(msg .. 'Metadata synced with cache', vim.log.levels.INFO) --- -- -- if callback then callback() end --- -- if callback then vim.schedule(callback) end --- -- return true --- -- end -- Already updated --- -- --- -- -- STEP 2: Cache Path (idedata.json exists and checksum changed) --- -- local idok, content = vim.misc.readFile(idedata_file) --- -- if idok and (type(content) == 'string' and content ~= '') then --- -- local cok, decoded = pcall(vim.json.decode, content) --- -- if cok and apply_metadata(decoded, current_checksum) then --- -- local metadata = require('platformio.metadata') --- -- metadata.save_project_config() --- -- vim.notify(msg .. 'Metadata synced from cache', vim.log.levels.INFO) --- -- if callback then vim.schedule(callback) end --- -- return true --- -- end --- -- end --- -- end --- -- --- -- --------------------------------------------------------- --- -- -- STEP 3: Auto-Initialize (If files are missing) --- -- --------------------------------------------------------- --- -- -- if not current_checksum then --- -- -- vim.notify(msg .. 'Initializing project metadata...', vim.log.levels.WARN) --- -- -- vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env }, { text = true }, function(obj) --- -- -- vim.schedule(function() --- -- -- if obj.code == 0 thenl --- -- -- fetch_metadata(attempts, active_env) -- Recursive call after files created --- -- -- else --- -- -- vim.notify(msg .. 'Initialization failed. Build project manually.', vim.log.levels.ERROR) --- -- -- end --- -- -- end) --- -- -- end) --- -- -- return --- -- -- end --- -- --- -- --------------------------------------------------------- --- -- -- STEP 4: Standard CLI Fallback (The Slow Path) --- -- --------------------------------------------------------- --- -- vim.notify(msg .. 'Metadata sync ...', vim.log.levels.INFO) --- -- vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(obj) --- -- vim.schedule(function() --- -- if obj.code ~= 0 then --- -- if attempts > 0 then --- -- vim.defer_fn(function() fetch_metadata(attempts - 1, env) end, 500) --- -- return --- -- end --- -- return vim.notify(msg .. 'Metadata Error: ' .. (obj.stderr or 'Unknown'), vim.log.levels.WARN) --- -- end --- -- --- -- local ook, raw_data = pcall(vim.json.decode, obj.stdout or '') --- -- local _, data = next(raw_data or {}) --- -- --- -- if ook and apply_metadata(data, current_checksum) then --- -- vim.notify(msg .. 'Metadata synced from CLI', vim.log.levels.INFO) --- -- if callback then vim.schedule(callback) end --- -- else --- -- vim.notify(msg .. 'Failed to parse metadata output', vim.log.levels.WARN) --- -- end --- -- end) --- -- end) --- -- end --- ------------------------------------------------------------------------------------------------------------- --- --- -- INFO:------------------------------------------------- --- -- get pio project config info --- --------------------------------------------------------- --- -- stylua: ignore --- -- local function fetch_config() --- -- local meta = _G.metadata --- -- local home = (os.getenv('HOME') or os.getenv('USERPROFILE') or ""):gsub('[\\/]+$', '') --- -- --- -- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) --- -- vim.schedule(function() --- -- -- 1. Check Execution --- -- if obj.code ~= 0 then --- -- local errmsg = obj.code == 127 and "'pio' not found" or (obj.stderr or "Unknown Error") --- -- return vim.notify(msg .. "Config Error: " .. errmsg, vim.log.levels.ERROR) --- -- end --- -- --- -- -- 2. Decode JSON safely --- -- local ok, decoded = pcall(vim.json.decode, obj.stdout or "") --- -- if not ok or type(decoded) ~= "table" then --- -- return vim.notify(msg .. "Failed to decode config JSON", vim.log.levels.ERROR) --- -- end --- -- --- -- local formated = vim.misc.jsonFormat(decoded) --- -- local file = vim.misc.joinPath(vim.uv.cwd(), 'config.json') --- -- vim.misc.writeFile(file, formated, {}) --- -- --- -- -- Reset core structure --- -- meta.envs = {} --- -- meta.default_envs = {} --- -- --- -- -- 3. Parse Sections --- -- for _, section in ipairs(decoded) do --- -- local name, data = section[1], section[2] --- -- if name == 'platformio' then for _, kv in ipairs(data) do meta[kv[1]] = kv[2] end --- -- elseif name:match('^env:') then --- -- local env_name = name:match('^env:(.+)') --- -- meta.envs[env_name] = {} --- -- for _, kv in ipairs(data) do meta.envs[env_name][kv[1]] = kv[2] end --- -- end --- -- end --- -- --- -- -- 4. Assign active_env --- -- meta.active_env = meta.default_envs[1] or next(meta.envs) or "" --- -- --- -- -- 5. Resolve Paths (INI -> Env -> Default) --- -- local path_map = { --- -- { key = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, --- -- { key = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, --- -- { key = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, --- -- } --- -- --- -- for _, item in ipairs(path_map) do --- -- local val = meta[item.key] --- -- -- Fallback chain --- -- if not val or val == "" then val = os.getenv(item.env) or (home .. item.sub) end --- -- -- Expand variables and Normalize --- -- if type(val) == "string" then --- -- val = val:gsub('%%${platformio.core_dir}', meta.core_dir or "") --- -- meta[item.key] = vim.misc.normalizePath(val) --- -- end --- -- end --- -- --- -- -- 6. Trigger next step --- -- if meta.active_env ~= "" then --- -- vim.notify(msg .. 'Config sync successful', vim.log.levels.INFO) --- -- fetch_metadata(1, meta.active_env) --- -- else --- -- vim.notify(msg .. 'No [env:] found. Please add a board.', vim.log.levels.ERROR) --- -- end --- -- end) --- -- end) --- -- end --- local active_env = vim.pio.fetch_config(from) --- if active_env then --- vim.pio.fetch_metadata(callback, active_env, from, 1) --- end --- -- fetch_config() --- end --- -- -- ============================================================================= -- -- INFO: --- -- 1. Helper: Unified hashing for change detection +-- -- Unified hashing for change detection -- local function get_hash(path) -- if vim.fn.filereadable(path) == 0 then -- return nil @@ -231,67 +17,67 @@ -- return (ok and type(data) == 'string' and data ~= '') and vim.fn.sha256(data) or '' -- end -- --- -- ============================================================================= --- -- stylua: ignore +-- -- --INFO: --- -- 1.run_compiledb --- function M.run_compiledb(target) --- -- 1. Prevent overlapping builds --- if target.isBusy then return end --- target.isBusy = true --- _G.metadata.isBusy = true --- --- --- -- local pio = require('platformio.utils.pio') --- -- pio.run_sequence({ --- -- cmnds = { --- -- 'pio run -t compiledb -e ' .. vim.misc.get_active__env(), --- -- }, --- -- cb = function (result) --- -- pio.handlePiodb(target, result) --- -- end --- -- }) --- --- local env = vim.misc.get_active__env() --- -- if env and env ~= '' then --- vim.notify('PIO platformio.ini change: update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) --- -- vim.schedule(function() --- vim.system({ 'pio', 'run', '-t', 'compiledb', '-s', '-e', env }, { text = true }, function(obj) --- -- vim.system({ 'pio', 'run', '-t', 'compiledb' }, { detach = true, text = true }, function(obj) --- vim.schedule(function() --- target.isBusy = false --- --- if obj.code == 0 then --- -- vim.notify('DB Updated Successfully', vim.log.levels.INFO, { title = 'PlatformIO' }) --- -- Trigger refresh (LSP restart, etc.) --- -- vim.schedule(function () --- -- M.pio_refresh(function() --- vim.notify('PIO platformio.ini change: Update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) --- -- end, 'PIO platformio.ini change: ') --- -- end) --- else --- local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' --- vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) --- end --- _G.metadata.isBusy = false --- end) --- end) --- -- end) --- -- end +-- --stylua: ignore +-- --============================================================================= +-- function M.pio_refresh(callback, from) +-- local msg = (type(from)=='string' and from ~= '') and from or 'PIO: ' +-- vim.notify(msg ..'Config sync ...', vim.log.levels.INFO) +-- +-- local function on_done(active_env) +-- if active_env then vim.notify(msg .. 'active_env= ' .. active_env, vim.log.levels.INFO) end +-- if active_env then vim.pio.fetch_metadata(callback, active_env, from, 1) end +-- end +-- vim.pio.fetch_config(on_done, from) -- end -- --- -- ============================================================================= -- --INFO: +-- --============================================================================= +-- -- watchers setup +-- --============================================================================= -- -- Ensure this is at the TOP of your file, outside any functions -- local uv = vim.uv or vim.loop -- M.watcher_handles = {} -- local debounce_timer = uv.new_timer() -- local last_mtime = 0 -- --- -- ============================================================================= --- -- stylua: ignore +-- -- --INFO: +-- -- --stylua: ignore +-- -- --1.run_compiledb after platformio.ini changed +-- -- --============================================================================= +-- -- function M.run_compiledb(target) +-- -- if target.isBusy then return end +-- -- if _G.metadata.isBusy == true then return end +-- -- +-- -- local env = vim.pio.get_active__env() +-- -- if not env then return end +-- -- target.isBusy = true +-- -- vim.notify('PIO platformio.ini change: compiledb update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) +-- -- vim.system({ 'pio', 'run', '-t', 'compiledb', '-s', '-e', env }, { text = true }, function(obj) +-- -- vim.schedule(function() +-- -- target.isBusy = false +-- -- +-- -- if obj.code == 0 then +-- -- vim.schedule(function () +-- -- M.pio_refresh(function() +-- -- vim.notify('PIO platformio.ini change: compiledb update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) +-- -- clangdRestart() +-- -- end, 'PIO platformio.ini change: ') +-- -- end) +-- -- else +-- -- local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' +-- -- vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) +-- -- end +-- -- _G.metadata.isBusy = false +-- -- end) +-- -- end) +-- -- end +-- -- -- --INFO: --- -- 2.stop_watchers +-- --stylua: ignore +-- --1.stop_watchers +-- --============================================================================= -- function M.stop_watchers() -- if not M.watcher_handles or (type(M.watcher_handles) ~= 'table') then M.watcher_handles = {} return end -- @@ -304,10 +90,10 @@ -- M.watcher_handles = {} -- end -- --- -- ============================================================================= --- -- stylua: ignore -- --INFO: --- -- 3.watcher cleanup +-- --stylua: ignore +-- --2.watcher cleanup +-- --============================================================================= -- function M.cleanup() -- M.stop_watchers() -- if debounce_timer and not debounce_timer:is_closing() then @@ -315,8 +101,7 @@ -- debounce_timer:close() -- end -- end --- -- ============================================================================= --- --INFO: +-- -- -- Force cleanup when leaving Neovim to prevent :qa lag -- vim.api.nvim_create_autocmd('VimLeavePre', { -- callback = function() @@ -324,8 +109,10 @@ -- end, -- }) -- --- -- stylua: ignore --- -- 3. MAIN WATCHER: Efficient Folder Monitoring +-- --INFO: +-- --stylua: ignore +-- --3. MAIN WATCHER: Efficient Folder Monitoring +-- --============================================================================= -- local function watch_file(target, callback) -- local folder_path = target.path:match('(.*[/\\])') -- local target_filename = target.path:match('[^/\\]+$') @@ -339,11 +126,11 @@ -- -- Early Exit Filters -- if target.isBusy or (filename and filename ~= target_filename) then return end -- --- local f = io.open(target.path, "r") --- if f then f:close() --- else return end -- Not readable (protected, locked, or missing) +-- -- local f = io.open(target.path, "r") +-- -- if f then f:close() +-- -- else return end -- Not readable (protected, locked, or missing) -- --- -- if not uv.fs_access(target.path, 'R') then return end +-- if not uv.fs_access(target.path, 'R') then return end -- -- -- Protected Execution -- local ok, result = pcall(function() @@ -391,67 +178,11 @@ -- table.insert(M.watcher_handles, handle) -- return handle -- end --- -- ============================================================================= --- -- stylua: ignore --- --INFO: --- -- 4. watch_file --- -- stylua: ignore --- -- local function watch_file(target, callback) --- -- local handle = uv.new_fs_poll() --- -- if not handle then return end --- -- --- -- -- handle:start(target.path, 1000, function(err, stat) --- -- -- if err or not stat then return end --- -- -- --- -- -- if debounce_timer then --- -- -- debounce_timer:stop() --- -- -- -- Define the logic in a local variable so it can "call itself" for retries --- -- -- local function attempt_callback() --- -- -- if target.isBusy then --- -- -- -- Retry in 1000ms if still busy --- -- -- debounce_timer:start(1500, 0, vim.schedule_wrap(attempt_callback)) --- -- -- return --- -- -- end --- -- -- --- -- -- local filestat = uv.fs_stat(target.path) --- -- -- if filestat and filestat.type == 'file' then callback(target) end --- -- -- end --- -- -- -- Initial start --- -- -- debounce_timer:start(1500, 0, vim.schedule_wrap(attempt_callback)) --- -- -- end --- -- -- end) --- -- --- -- -- Poll every 1000ms. This is light on CPU and ignores "save noise". --- -- -- handle:start(target.path, 1000, function(err, stat) --- -- -- -- if err or not stat or (target and target.isBusy) then return end --- -- -- if err or not stat then return end --- -- -- --- -- -- -- 2. Debounce: Reset the timer on every event --- -- -- -- Only after 500ms of "silence" will the actual callback run --- -- -- if debounce_timer then --- -- -- -- Stop any existing timer to "debounce" --- -- -- if debounce_timer:is_active() then debounce_timer:stop() end --- -- -- debounce_timer:start(500, 0, vim.schedule_wrap(function() --- -- -- -- vim.schedule(function () --- -- -- local filestat = uv.fs_stat(target.path) --- -- -- if filestat and filestat.type == 'file' then --- -- -- callback(target) --- -- -- end --- -- -- -- if vim.loop.fs_stat(target.path) then callback(target) end --- -- -- -- end) --- -- -- end)) --- -- -- end --- -- -- end) --- -- --- -- table.insert(M.watcher_handles, handle) --- -- return handle --- -- end --- -- --- -- ============================================================================= --- -- stylua: ignore -- --INFO: --- -- 5. start_watches +-- --stylua: ignore +-- --4. start_watches +-- --============================================================================= -- function M.start_watchers() -- -- Clean up any existing watchers first to prevent duplicates -- if next(M.watcher_handles) then M.stop_watchers() end @@ -466,12 +197,31 @@ -- path = vim.misc.joinPath(project_root, 'platformio.ini'), -- cb = function(self) -- if self.isBusy then return end +-- if _G.metadata.isBusy == true then return end -- local new_hash = get_hash(self.path) or '' -- if new_hash and new_hash ~= self.last_hash then -- self.last_hash = new_hash --- vim.schedule(function() --- M.run_compiledb(self) -- Smart: Auto-update DB if config changes +-- local env = vim.pio.get_active__env() +-- if not env then return end +-- self.isBusy = true +-- vim.notify('PIO platformio.ini change: compiledb update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) +-- vim.system({ 'pio', 'run', '-t', 'compiledb', '-s', '-e', env }, { text = true }, function(obj) +-- vim.schedule(function() +-- if obj.code == 0 then +-- vim.schedule(function () +-- M.pio_refresh(function() +-- vim.notify('PIO platformio.ini change: compiledb update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) +-- clangdRestart() +-- end, 'PIO platformio.ini change: ') +-- end) +-- else +-- local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' +-- vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) +-- end +-- self.isBusy = false +-- end) -- end) +-- -- M.run_compiledb(self) -- Smart: Auto-update DB if config changes -- end -- end, -- }, @@ -488,35 +238,18 @@ -- return -- end -- --- -- local attempts = 0 --- -- local function run_when_ready() --- -- if _G.metadata.isBusy and attempts < 50 then -- Timeout after 5 seconds --- -- attempts = attempts + 1 --- -- vim.defer_fn(run_when_ready, 100) --- -- return --- -- end --- -- self.isBusy = true --- -- vim.defer_fn(function() --- -- M.pio_refresh(function() --- -- self.isBusy = false --- -- vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) --- -- end, 'PIO checksum: ') --- -- end, 500) --- -- end --- -- run_when_ready() --- -- self.isBusy = true -- vim.defer_fn(function () -- M.pio_refresh(function() -- self.isBusy = false -- vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) +-- clangdRestart() -- end, 'PIO checksum: ') -- end, 500) -- end -- end -- }, -- } --- -- targets[1].last_hash = get_hash(targets[1].path) or '' -- -- for _, target in ipairs(targets) do -- --[[ wrap the callback in a small anonymous function, @@ -525,16 +258,16 @@ -- end -- end -- --- -- ============================================================================= --- -- stylua: ignore -- --INFO: 6. Exported setup function +-- --stylua: ignore +-- --============================================================================= -- function M.init() -- local config = require('platformio').config -- if config.lspClangd.enabled == true then -- vim.notify('PIO start: initialize', vim.log.levels.INFO) -- -- -- activate meta save and upload and env switch --- local metadata = require('platformio.metadata') +-- local metadata = require('platformio.pio.metadata') -- metadata.load_project_config() -- -- require('platformio.lspConfig.clangd') @@ -551,7 +284,7 @@ -- ---------------------------------------------------------------------------------------- -- --INFO: create clangd required files -- ----------------------------------------------------------------------------------------- --- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) +-- -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) -- -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') -- -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) -- boilerplate.core_dir = _G.metadata.core_dir diff --git a/pioinit.lua b/pioinit.lua new file mode 100644 index 00000000..ff838273 --- /dev/null +++ b/pioinit.lua @@ -0,0 +1,144 @@ +-- local M = {} +-- +-- local pickers = require('telescope.pickers') +-- local finders = require('telescope.finders') +-- local telescope_conf = require('telescope.config').values +-- local actions = require('telescope.actions') +-- local action_state = require('telescope.actions.state') +-- local entry_display = require('telescope.pickers.entry_display') +-- local make_entry = require('telescope.make_entry') +-- local misc = require('platformio.utils.misc') +-- local previewers = require('telescope.previewers') +-- +-- local boardentry_maker = function(opts) +-- local displayer = entry_display.create({ +-- separator = '▏', +-- items = { +-- { width = 35 }, +-- { width = 20 }, +-- { width = 15 }, +-- }, +-- }) +-- +-- local make_display = function(entry) +-- return displayer({ +-- entry.value.name, +-- entry.value.vendor, +-- entry.value.platform, +-- }) +-- end +-- +-- return function(entry) +-- return make_entry.set_default_entry_mt({ +-- value = { +-- id = entry.id, +-- name = entry.name, +-- vendor = entry.vendor, +-- platform = entry.platform, +-- data = entry, +-- }, +-- ordinal = entry.name .. ' ' .. entry.vendor .. ' ' .. entry.platform, +-- display = make_display, +-- }, opts) +-- end +-- end +-- +-- --- stylua: ignore +-- local function pick_framework(board_details) +-- local opts = {} +-- pickers +-- .new(opts, { +-- prompt_title = 'frameworks', +-- finder = finders.new_table({ +-- results = board_details['frameworks'], +-- }), +-- attach_mappings = function(prompt_bufnr, _) +-- actions.select_default:replace(function() +-- actions.close(prompt_bufnr) +-- local selection = action_state.get_selected_entry() +-- +-- local pio = require('platformio..pio.upkeep') +-- pio.selected_framework = selection[1] +-- pio.run_sequence({ +-- cmnds = { +-- 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', +-- -- 'pio run -t compiledb', +-- }, +-- cb = pio.handlePioinit, +-- }) +-- end) +-- return true +-- end, +-- sorter = telescope_conf.generic_sorter(opts), +-- }) +-- :find() +-- end +-- +-- -- stylua: ignore +-- local function pick_board(json_data) +-- local opts = {} +-- pickers.new(opts, { +-- prompt_title = 'Boards', +-- finder = finders.new_table({ +-- results = json_data, +-- entry_maker = opts.entry_maker or boardentry_maker(opts), +-- }), +-- attach_mappings = function(prompt_bufnr, _) +-- actions.select_default:replace(function() +-- actions.close(prompt_bufnr) +-- local selection = action_state.get_selected_entry() +-- pick_framework(selection['value']['data']) +-- end) +-- return true +-- end, +-- previewer = previewers.new_buffer_previewer({ +-- title = 'Board Info', +-- define_preview = function(self, entry, _) +-- local json = misc.strsplit(vim.inspect(entry['value']['data']), '\n') +-- local bufnr = self.state.bufnr +-- vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) +-- vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function +-- vim.defer_fn(function() +-- local win = self.state.winid +-- vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) +-- vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) +-- vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) +-- end, 0) +-- end, +-- }), +-- sorter = telescope_conf.generic_sorter(opts), +-- }):find() +-- end +-- +-- function M.pioinit() +-- if not misc.pio_install_check() then +-- return +-- end +-- +-- -- Read stdout +-- local command = 'pio boards --json-output' +-- local handle = io.popen(command .. misc.devNul) +-- if not handle then +-- return +-- end +-- local json_str = handle:read('*a') +-- handle:close() +-- +-- if #json_str == 0 then +-- -- read stderr +-- handle = io.popen(command .. ' 2>&1') +-- if not handle then +-- return +-- end +-- local command_output = handle:read('*a') +-- handle:close() +-- vim.notify('Some error occured while executing `' .. command .. "`', command output: \n", vim.log.levels.WARN) +-- print(command_output) +-- return +-- end +-- +-- local json_data = vim.json.decode(json_str) +-- pick_board(json_data) +-- end +-- +-- return M diff --git a/pioinit2.lua b/pioinit2.lua deleted file mode 100644 index 66af0990..00000000 --- a/pioinit2.lua +++ /dev/null @@ -1,160 +0,0 @@ -local pickers = require('telescope.pickers') -local finders = require('telescope.finders') -local actions = require('telescope.actions') -local action_state = require('telescope.actions.state') -local previewers = require('telescope.previewers') -local telescope_conf = require('telescope.config').values - -local wizard_data = {} - --- Final Step: Command Construction & Execution -local function finalize_setup() - local pio = require('platformio.utils.pio') - - -- 1. Determine IDE flag: --ide vim enables LSP support for Neovim - local ide_flag = wizard_data.use_ide and ' --ide vim' or '' - - -- 2. Determine Sample flag: --sample-code generates boilerplate - local sample_flag = wizard_data.sample == 'true' and ' --sample-code' or '' - - -- 3. Construct the full init command - local init_cmd = string.format('pio project init --board %s %s -O "framework=%s"%s', wizard_data.board_id, ide_flag, wizard_data.framework, sample_flag) - - print('Executing: ' .. init_cmd) - - pio.run_sequence({ - cmnds = { - init_cmd, - 'pio run -t compiledb', -- Essential to generate compile_commands.json for LSP - }, - cb = pio.handlePioinit, - }) -end - --- --- PICKERS (In Order of Execution) --- - --- STEP 4: Sample (True/False) -local function pick_sample() - pickers - .new({}, { - prompt_title = 'Include Sample Code?', - finder = finders.new_table({ results = { 'true', 'false' } }), - sorter = telescope_conf.generic_sorter({}), - attach_mappings = function(prompt_bufnr) - actions.select_default:replace(function() - local selection = action_state.get_selected_entry() - actions.close(prompt_bufnr) - wizard_data.sample = selection[1] -- Capture result - finalize_setup() - end) - return true - end, - }) - :find() -end - --- STEP 3: Framework (From Board Data) -local function pick_framework(board_details) - pickers - .new({}, { - prompt_title = 'Select Framework (' .. board_details.id .. ')', - finder = finders.new_table({ results = board_details['frameworks'] }), - sorter = telescope_conf.generic_sorter({}), - attach_mappings = function(prompt_bufnr) - actions.select_default:replace(function() - local selection = action_state.get_selected_entry() - actions.close(prompt_bufnr) - wizard_data.framework = selection[1] - pick_sample() -- Next step - end) - return true - end, - }) - :find() -end - --- STEP 2: Board (with Buffer Previewer) -local function pick_board(json_data) - pickers - .new({}, { - prompt_title = 'Select Board', - finder = finders.new_table({ - results = json_data, - entry_maker = function(entry) - return { - value = entry, - display = entry.name or entry.id, - ordinal = (entry.name or '') .. ' ' .. (entry.id or ''), - } - end, - }), - previewer = previewers.new_buffer_previewer({ - title = 'Board Details', - define_preview = function(self, entry) - local content = vim.split(vim.inspect(entry.value), '\n') - vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, content) - vim.api.nvim_set_option_value('filetype', 'lua', { buf = self.state.bufnr }) - end, - }), - sorter = telescope_conf.generic_sorter({}), - attach_mappings = function(prompt_bufnr) - actions.select_default:replace(function() - local selection = action_state.get_selected_entry() - actions.close(prompt_bufnr) - wizard_data.board_id = selection.value.id - pick_framework(selection.value) -- Next step - end) - return true - end, - }) - :find() -end - --- STEP 1: IDE (True/False) -local function start_pio_wizard(json_data) - pickers - .new({}, { - prompt_title = 'Setup for Neovim IDE?', - finder = finders.new_table({ results = { 'true', 'false' } }), - sorter = telescope_conf.generic_sorter({}), - attach_mappings = function(prompt_bufnr) - actions.select_default:replace(function() - local selection = action_state.get_selected_entry() - actions.close(prompt_bufnr) - wizard_data.use_ide = (selection[1] == 'true') - pick_board(json_data) -- Next step - end) - return true - end, - }) - :find() -end - -local function launch_pio_project_wizard() - print('Fetching board data from PlatformIO...') - - -- 1. Get board data from PIO CLI in JSON format - -- The '--json-output' flag ensures we get structured data - local handle = io.popen('pio boards --json-output') - if not handle then - return - end - - local result = handle:read('*a') - handle:close() - - -- 2. Decode the JSON string into a Lua table - local ok, json_data = pcall(vim.json.decode, result) - if not ok or not json_data then - print('Error: Could not parse PlatformIO board data.') - return - end - - -- 3. Start the wizard we built previously - start_pio_wizard(json_data) -end - --- Export the function so it's accessible via require() -return { - launch = launch_pio_project_wizard, -} diff --git a/piomenu.lua b/piomenu.lua new file mode 100644 index 00000000..8895dba0 --- /dev/null +++ b/piomenu.lua @@ -0,0 +1,45 @@ +-- local M = {} +-- +-- function M.piomenu(config) +-- local icon = { icon = ' ', color = 'orange' } -- Assign platformio orange icon +-- local wk_table = { mode = { 'n', 'v' } } +-- +-- local function traverseMenu(menu, wkey) +-- for _, child_node in ipairs(menu) do +-- if child_node.node == 'menu' then +-- traverseMenu(child_node.items, wkey .. child_node.shortcut) +-- table.insert(wk_table, { wkey .. child_node.shortcut, group = child_node.desc, icon = icon }) +-- elseif child_node.node == 'item' then +-- table.insert(wk_table, { +-- wkey .. child_node.shortcut, +-- ' ' .. child_node.command .. '', +-- desc = child_node.desc, +-- icon = icon, +-- }) +-- end +-- end +-- end +-- if config.menu_key == nil then +-- return +-- end +-- +-- local ok, wk = pcall(require, 'which-key') +-- if not ok then +-- vim.api.nvim_echo({ { 'which-key plugin not found!', 'ErrorMsg' } }, true, {}) +-- return +-- end +-- +-- wk.setup({ +-- preset = 'helix', --'modern', --'classic' +-- }) +-- local Config = require('which-key.config') +-- Config.sort = { 'order', 'group', 'manual', 'mod' } +-- +-- table.insert(wk_table, { config.menu_key, group = config.menu_name, icon = icon }) +-- +-- traverseMenu(config.menu_bindings, config.menu_key) +-- +-- wk.add(wk_table) +-- end +-- +-- return M diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 710e57b2..9e9a6d08 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -44,7 +44,7 @@ -- end, -- }) vim.misc = require('platformio.utils.misc') -vim.pio = require('platformio.utils.pio') +vim.pio = require('platformio.pio.upkeep') -- INFO: fix paths in compile_commands.json vim.api.nvim_create_user_command('PioFixPaths', function() @@ -82,7 +82,7 @@ end, {}) -- Piorun vim.api.nvim_create_user_command('Piorun', function(opts) local args = opts.args - require('platformio.piorun').piorun({ args }) + require('platformio.piocommands').piorun({ args }) end, { nargs = '?', complete = function(_, _, _) @@ -152,6 +152,7 @@ end, {}) ------------------------------------------------------ -- require('telescope').load_extension('ui-select') +-- stylua: ignore -- INFO: List ToggleTerminals vim.api.nvim_create_user_command('PioTermList', function() local telescope = require('telescope') @@ -219,12 +220,8 @@ vim.api.nvim_create_user_command('PioTermList', function() local win_open = win_type == '' or win_type == 'popup' if chosen.term.window and (win_open and vim.api.nvim_win_get_buf(chosen.term.window) == chosen.term.bufnr) then vim.api.nvim_set_current_win(chosen.term.window) - else - chosen.term:open() - end + else chosen.term:open() end vim.api.nvim_echo({ { 'Switched to PIO terminal: ' .. chosen.termtype, 'Normal' } }, true, {}) - else - vim.api.nvim_echo({ { 'No PIO terminal window selected.', 'Normal' } }, true, {}) - end + else vim.api.nvim_echo({ { 'No PIO terminal window selected.', 'Normal' } }, true, {}) end end) end, {}) diff --git a/term2.lua b/term2.lua deleted file mode 100644 index 4dd7e8e4..00000000 --- a/term2.lua +++ /dev/null @@ -1,330 +0,0 @@ -local M = {} - -local is_windows = jit.os == 'Windows' -M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' --- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' --- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' - -local config = require('platformio').config - -M.on_stdout_handler = nil - ------------------------------------------------------- -function M.strsplit(inputstr, del) - local t = {} - if type(inputstr) == 'string' and inputstr and inputstr ~= '' then - for str in string.gmatch(inputstr, '([^' .. del .. ']+)') do - table.insert(t, str) - end - end - return t -end - -function M.check_prefix(str, prefix) - return str:sub(1, #prefix) == prefix -end - ------------------------------------------------------- - --- INFO: get current OS enter -function M.enter() - local shell = vim.o.shell - if is_windows then - return vim.fn.executable('pwsh') and '\r' or '\r\n' - elseif shell:find('nu') then - return '\r' - else - return '\n' - end -end - --- INFO: get previous window -local function getPreviousWindow(orig_window) - local prev = { - orig_window = orig_window, - term = nil, --active terminal - cli = nil, --cli terminal - mon = nil, --mon terminal - float = false, --is active terminal direction float - } - local terms = require('toggleterm.terminal').get_all(true) - if #terms ~= 0 then - for i = 1, #terms do - if terms[i].display_name and terms[i].display_name ~= '' and terms[i].display_name:find('pio', 1) then - local name_splt = M.strsplit(terms[i].display_name, ':') - if name_splt[1] == 'piocli' then - prev.cli = terms[i] - if terms[i].window == orig_window then - ---@diagnostic disable-next-line: cast-local-type - prev.orig_window = tonumber(name_splt[2]) -- set orig_window to the previous terminal onrig_window - prev.term = terms[i] - end - if terms[i].direction == 'float' then - prev.float = true - end - elseif name_splt[1] == 'piomon' then - prev.mon = terms[i] - if terms[i].window == orig_window then - ---@diagnostic disable-next-line: cast-local-type - prev.orig_window = tonumber(name_splt[2]) -- set orig_window to the previous terminal onrig_window - prev.term = terms[i] - end - if terms[i].direction == 'float' then - prev.float = true - end - end - end - end - end - return prev -end - ------------------------------------------------------- --- INFO: Send command -local function send(term, cmd) - vim.fn.chansend(term.job_id, cmd .. M.enter()) - if vim.api.nvim_buf_is_loaded(term.bufnr) and vim.api.nvim_buf_is_valid(term.bufnr) then - if term.window and vim.api.nvim_win_is_valid(term.window) then --vim.ui.term_has_open_win(term) then - vim.api.nvim_set_current_win(term.window) -- terminal focus - vim.api.nvim_buf_call(term.bufnr, function() - local mode = vim.api.nvim_get_mode().mode - if mode == 'n' or mode == 'nt' then - vim.cmd('normal! G') -- normal command to Goto bottom of buffer (scroll) - end - end) - end - end -end - ------------------------------------------------------- --- INFO: PioTermClose -local function PioTermClose(t) - local orig_window = tonumber(M.strsplit(t.display_name, ':')[2]) - -- close terminal window - vim.api.nvim_win_close(t.window, true) - - -- go back to previous window - if orig_window and vim.api.nvim_win_is_valid(orig_window) then - vim.api.nvim_set_current_win(orig_window) - else - vim.api.nvim_set_current_win(0) - end -end - ------------------------------------------------------- --- INFO: ToggleTerminal -function M.ToggleTerminal(command, direction) - local status_ok, _ = pcall(require, 'toggleterm') - if not status_ok then - vim.api.nvim_echo({ { 'toggleterm not found!', 'ErrorMsg' } }, true, {}) - return - end - - local title = '' - local pioOpts = {} - - -- INFO: set orig_window to current window, or if available get current toggleterm previous window - local prev = getPreviousWindow(vim.api.nvim_get_current_win()) - local orig_window = prev.orig_window - - if string.find(command, ' monitor') then - if prev.mon then -- INFO: if previous monitor terminal already opened ==> reopen - prev.mon.display_name = 'piomon:' .. orig_window - local win_type = vim.fn.win_gettype(prev.mon.window) - local win_open = win_type == '' or win_type == 'popup' - if prev.mon.window and (win_open and vim.api.nvim_win_get_buf(prev.mon.window) == prev.mon.bufnr) then - vim.api.nvim_set_current_win(prev.mon.window) - else - prev.mon:open() - end - return - end - title = 'Pio Monitor: [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' - pioOpts.display_name = 'piomon:' .. orig_window - pioOpts.id = 98 - pioOpts.on_stdout = nil -- INFO: on_stdout - else -- INFO: if previous cli terminal already opened ==> reopen - if prev.cli then - prev.cli.display_name = 'piocli:' .. orig_window - local win_type = vim.fn.win_gettype(prev.cli.window) - local win_open = win_type == '' or win_type == 'popup' - if prev.cli.window and (win_open and vim.api.nvim_win_get_buf(prev.cli.window) == prev.cli.bufnr) then - vim.api.nvim_set_current_win(prev.cli.window) - else - prev.cli:open() - end - vim.defer_fn(function() - if command and command ~= '' then - send(prev.cli, command) - end - end, 50) -- 50ms delay, adjust as needed - return - end - title = 'Pio CLI> [In normal mode press: q or :q to hide; :q! to quit; :PioTermList to list terminals]' - pioOpts.display_name = 'piocli:' .. orig_window - pioOpts.id = 99 - - -- INFO: on_stdout - pioOpts.on_stdout = function(t, job, data) - -- Only run if pio.lua has successfully "plugged in" the handler - if M.on_stdout_handler then - M.on_stdout_handler(t, job, data) - end - end - end - pioOpts.direction = direction - ------------------------------------------------------ - - -- INFO: termConfig table start - local termConfig = { - hidden = true, -- Start hidden, we'll open it explicitly - hide_numbers = true, - float_opts = { - winblend = 0, - width = function() - return math.ceil(vim.o.columns * 0.85) - end, - height = function() - return math.ceil(vim.o.lines * 0.85) - end, - -- shell = vim.o.shell, - shell = vim.o.shell, - highlights = { - border = 'FloatBorder', - background = 'NormalFloat', - }, - }, - close_on_exit = false, --closeOnexit, - - -- INFO: on_open() - on_open = function(t) - -- Get properties of the 'Normal' highlight group (background of main editor) - -- local hl = vim.api.nvim_get_hl(0, { name = 'PmenuSel' }) - -- local hl = { bg = '#e4cf0e', fg = '#0012d9' } - local hl = { bg = '#80a3d4', fg = '#000000' } - - if hl then - vim.api.nvim_set_hl(0, 'MyWinBar', { bg = hl.bg, fg = hl.fg }) - - local winBartitle = '%#MyWinBar#' .. title .. '%*' - vim.api.nvim_set_option_value('winbar', winBartitle, { scope = 'local', win = t.window }) - - -- Following necessary to solve that some time winbar not showing - vim.schedule(function() - vim.api.nvim_set_option_value('winbar', winBartitle, { scope = 'local', win = t.window }) - end) - end - vim.keymap.set('t', '', [[k]], { buffer = t.bufnr }) - vim.keymap.set('n', '', [[a]], { buffer = t.bufnr }) - - vim.keymap.set('n', 'q', function() - PioTermClose(t) - end, { desc = 'PioTermClose', buffer = t.bufnr }) - - if config.debug then - local name_splt = M.strsplit(t.display_name, ':') - vim.api.nvim_echo({ - { 'ToggleTerm ', 'MoreMsg' }, - { '(Term name: ' .. name_splt[1] .. ')', 'MoreMsg' }, - { '(Prev win ID: ' .. name_splt[2] .. ')', 'MoreMsg' }, - { '(Term Win ID: ' .. t.window .. ')', 'MoreMsg' }, - { '(Term Buffer#: ' .. t.bufnr .. ')', 'MoreMsg' }, - { '(Term id: ' .. t.id .. ')', 'MoreMsg' }, - { '(Job ID: ' .. t.job_id .. ')', 'MoreMsg' }, - }, true, {}) - end - end, - - -- INFO: on_close() - on_close = function(t) - orig_window = tonumber(M.strsplit(t.display_name, ':')[2]) - ---@diagnostic disable-next-line: param-type-mismatch - if orig_window and vim.api.nvim_win_is_valid(orig_window) then - vim.api.nvim_set_current_win(orig_window) - else - vim.api.nvim_set_current_win(0) - end - end, - - -- -- INFO: on_exit() - -- on_exit = function(_) - -- exit_callback() - -- end, - - -- INFO: on_stdout - -- on_stdout = stdout_callback, - -- on_stdout = pio.stdoutFilter, - - -- INFO: on_create() { - on_create = function(t) - local platformio = vim.api.nvim_create_augroup(M.strsplit(t.display_name, ':')[1], { clear = true }) - - -- INFO: CmdlineLeave - vim.api.nvim_create_autocmd('CmdlineLeave', { - group = platformio, - -- pattern = ':', - buffer = t.bufnr, - callback = function() - if vim.v.event and not vim.v.event.abort and vim.v.event.cmdtype == ':' then - local quit = vim.fn.getcmdline() == 'q' - local quitbang = vim.fn.getcmdline() == 'q!' - if quitbang or quit then - local name_splt = M.strsplit(t.display_name, ':') - if quitbang then - if name_splt[1] == 'piomon' then -- monitor terminal - local exit = vim.api.nvim_replace_termcodes('exit', true, true, true) - send(t, exit) - else -- cli terminal - send(t, 'exit') - end - end - - orig_window = tonumber(name_splt[2]) - vim.schedule(function() - -- go back to previous window - if orig_window and vim.api.nvim_win_is_valid(orig_window) then - vim.api.nvim_set_current_win(orig_window) - else - vim.api.nvim_set_current_win(0) - end - end) - end - end - end, - }) - - -- INFO: BufUnload - vim.api.nvim_create_autocmd('BufUnload', { - group = platformio, - desc = 'toggleterm buffer unloaded', - buffer = t.bufnr, - callback = function(args) - vim.keymap.del('t', '', { buffer = args.buf }) - vim.keymap.del('n', '', { buffer = args.buf }) - - -- clear autommmand when quit - vim.api.nvim_clear_autocmds({ group = M.strsplit(t.display_name, ':')[1] }) - end, - }) - end, - } - -- INFO: termConfig table end - - termConfig = vim.tbl_deep_extend('force', termConfig, pioOpts or {}) - - -- INFO: create new terminal - local terminal = require('toggleterm.terminal').Terminal:new(termConfig) - if prev.term and prev.float then - prev.term:close() - end - terminal:toggle() - -- vim.defer_fn(function() - -- if command and command ~= '' then - -- send(terminal, command) - -- end - -- end, 50) -- 50ms delay, adjust as needed sgget - return terminal -end - -return M ----------------------------------------------------------------------------------------- diff --git a/tmp.lua b/tmp.lua deleted file mode 100644 index e69de29b..00000000 diff --git a/tmp1.lua b/tmp1.lua deleted file mode 100644 index e69de29b..00000000 From f5082d8c5b206160309e5d47c8c8e95a1a9aaad0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 20:52:44 +0300 Subject: [PATCH 1382/1406] update --- lua/platformio/pioinit.lua | 326 +------------------------------------ plugin/platformio.lua | 26 +-- 2 files changed, 15 insertions(+), 337 deletions(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index 7c7d4407..de712134 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -132,134 +132,8 @@ local function pick_board(json_data) :find() end --- local function pick_board(json_data) --- pickers --- .new({}, { --- prompt_title = 'Select PlatformIO Board', --- layout_strategy = 'horizontal', --- layout_config = { width = 0.9, preview_width = 0.6 }, --- finder = finders.new_table({ --- results = json_data, --- entry_maker = function(entry) --- return { --- value = entry, --- display = string.format('%-25s | %s', entry.id, entry.name), --- ordinal = entry.id .. ' ' .. entry.name, --- } --- end, --- }), --- previewer = previewers.new_buffer_previewer({ --- title = 'Board Specifications', --- define_preview = function(self, entry) --- local val = entry.value --- --- -- Safe conversion for hardware specs --- local ram = val.ram and (math.floor(val.ram / 1024) .. ' KB') or 'Unknown' --- local flash = val.rom and (math.floor(val.rom / 1024) .. ' KB') or 'Unknown' --- local mhz = val.fcpu and (math.floor(val.fcpu / 1000000) .. ' MHz') or 'Unknown' --- --- -- Build base lines --- local lines = { --- '# ' .. (val.name or val.id), --- '', --- '**Basic Info**', --- '---', --- '**Board ID:** ' .. val.id, --- '**Vendor:** ' .. (val.vendor or 'Generic'), --- '**Platform:** ' .. (val.platform or 'N/A'), --- '', --- '**Hardware Specs**', --- '---', --- '**MCU:** ' .. (val.mcu or 'N/A'), --- '**CPU Speed:** ' .. mhz, --- '**Flash (ROM):** ' .. flash, --- '**RAM:** ' .. ram, --- '', --- '**Available Frameworks**', --- '---', --- } --- --- -- Correctly append frameworks as separate lines to avoid the newline error --- if val.frameworks and #val.frameworks > 0 then --- for _, fw in ipairs(val.frameworks) do --- table.insert(lines, '- ' .. fw) --- end --- else --- table.insert(lines, '*No frameworks listed*') --- end --- --- vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, lines) --- vim.api.nvim_set_option_value('filetype', 'markdown', { buf = self.state.bufnr }) --- end, --- }), --- sorter = telescope_conf.generic_sorter({}), --- attach_mappings = function(prompt_bufnr) --- actions.select_default:replace(function() --- local selection = action_state.get_selected_entry() --- actions.close(prompt_bufnr) --- if selection then --- wizard_data.board_id = selection.value.id --- pick_framework(selection.value) --- end --- end) --- return true --- end, --- }) --- :find() --- end - --- local function pick_board(json_data) --- pickers --- .new({}, { --- prompt_title = 'Select PlatformIO Board', --- layout_strategy = 'horizontal', --- layout_config = { width = 0.9, preview_width = 0.6 }, --- finder = finders.new_table({ --- results = json_data, --- entry_maker = function(entry) --- return { --- value = entry, --- display = string.format('%-25s | %s', entry.id, entry.name), --- ordinal = entry.id .. ' ' .. entry.name, --- } --- end, --- }), --- previewer = previewers.new_buffer_previewer({ --- title = 'Board Specs', --- define_preview = function(self, entry) --- local val = entry.value --- local lines = { --- '# ' .. (val.name or val.id), --- '', --- '**Micro:** ' .. (val.mcu or 'N/A'), --- '**Vendor:** ' .. (val.vendor or 'N/A'), --- '**Clock:** ' .. (val.fcpu or 0) / 1000000 .. ' MHz', --- '**RAM:** ' .. (val.ram or 0) / 1024 .. ' KB', --- '', --- '**Frameworks:** ' .. table.concat(val.frameworks, ', '), --- } --- vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, lines) --- vim.api.nvim_set_option_value('filetype', 'markdown', { buf = self.state.bufnr }) --- end, --- }), --- sorter = telescope_conf.generic_sorter({}), --- attach_mappings = function(prompt_bufnr) --- actions.select_default:replace(function() --- local selection = action_state.get_selected_entry() --- actions.close(prompt_bufnr) --- if selection then --- wizard_data.board_id = selection.value.id --- pick_framework(selection.value) --- end --- end) --- return true --- end, --- }) --- :find() --- end - -- Entry point -local function launch_pio_project_wizard() +local function launch_project_init() wizard_data = {} -- Reset state notify('Fetching board database...') @@ -280,201 +154,5 @@ local function launch_pio_project_wizard() end return { - launch = launch_pio_project_wizard, + pioinit = launch_project_init, } - --- local pickers = require('telescope.pickers') --- local finders = require('telescope.finders') --- local actions = require('telescope.actions') --- local action_state = require('telescope.actions.state') --- local previewers = require('telescope.previewers') --- local telescope_conf = require('telescope.config').values --- --- local wizard_data = {} --- --- -- Final Step: Command Construction & Execution --- local function finalize_setup() --- local pio = require('platformio.utils.pio') --- --- -- 1. Construct the basic init command --- local sample_flag = wizard_data.sample == 'true' and ' --sample-code' or '' --- local init_cmd = string.format('pio project init --ide vim --board %s -O "framework=%s"%s', wizard_data.board_id, wizard_data.framework, sample_flag) --- --- -- 2. Determine commands and callback --- local commands = { init_cmd } --- local final_cb = pio.handlePioinit -- Default for 1 command --- --- if wizard_data.use_compiledb then --- table.insert(commands, 'pio run -t compiledb') --- final_cb = pio.handlePioinitDb -- Switch to Db handler for 2 commands --- end --- --- -- 3. Execute --- pio.run_sequence({ --- cmnds = commands, --- cb = final_cb, --- }) --- end --- --- local function dialog_opts(title, width) --- return require('telescope.themes').get_dropdown({ --- prompt_title = title, --- layout_config = { --- width = width or 0.4, -- Adjust width (0.4 = 40% of screen) --- height = 0.2, -- Small height for few choices --- }, --- previewer = false, -- Hide preview for simple choices --- }) --- end --- --- --- PICKERS (In Order of Execution) --- --- --- -- STEP 4: Sample (True/False) --- local function pick_sample() --- local opts = dialog_opts('Include Sample Code?', 0.3) --- pickers --- .new(opts, { --- finder = finders.new_table({ results = { 'true', 'false' } }), --- sorter = telescope_conf.generic_sorter(opts), --- attach_mappings = function(prompt_bufnr) --- actions.select_default:replace(function() --- local selection = action_state.get_selected_entry() --- actions.close(prompt_bufnr) --- wizard_data.sample = selection[1] --- finalize_setup() --- end) --- return true --- end, --- }) --- :find() --- end --- --- -- STEP 3: Framework Selection (Small Dialog) --- local function pick_framework(board_details) --- -- Use dropdown theme to keep the window small and centered --- local opts = require('telescope.themes').get_dropdown({ --- prompt_title = 'Select Framework (' .. board_details.id .. ')', --- layout_config = { --- width = 0.25, -- 40% of screen width --- height = 0.25, -- Small height for few choices --- }, --- previewer = false, -- No preview needed for framework names --- }) --- --- pickers --- .new(opts, { --- finder = finders.new_table({ --- results = board_details['frameworks'], --- }), --- sorter = telescope_conf.generic_sorter(opts), --- attach_mappings = function(prompt_bufnr) --- actions.select_default:replace(function() --- local selection = action_state.get_selected_entry() --- actions.close(prompt_bufnr) --- -- selection is a simple string in this case --- wizard_data.framework = selection[1] --- pick_sample() --- end) --- return true --- end, --- }) --- :find() --- end --- --- -- STEP 2: Board (with Buffer Previewer) --- local function pick_board(json_data) --- pickers --- .new({}, { --- prompt_title = 'Select Board', --- -- Define the layout behavior --- layout_strategy = 'horizontal', --- layout_config = { --- width = 0.9, -- Overall width of the Telescope window (90% of screen) --- preview_width = 0.70, -- 65% of the window goes to "Board Details", leaving 25% for results --- }, --- finder = finders.new_table({ --- results = json_data, --- entry_maker = function(entry) --- return { --- value = entry, --- display = entry.name or entry.id, --- ordinal = (entry.name or '') .. ' ' .. (entry.id or ''), --- } --- end, --- }), --- previewer = previewers.new_buffer_previewer({ --- title = 'Board Details', --- define_preview = function(self, entry) --- local content = vim.split(vim.inspect(entry.value), '\n') --- vim.api.nvim_buf_set_lines(self.state.bufnr, 0, -1, false, content) --- vim.api.nvim_set_option_value('filetype', 'lua', { buf = self.state.bufnr }) --- end, --- }), --- sorter = telescope_conf.generic_sorter({}), --- attach_mappings = function(prompt_bufnr) --- actions.select_default:replace(function() --- local selection = action_state.get_selected_entry() --- actions.close(prompt_bufnr) --- wizard_data.board_id = selection.value.id --- pick_framework(selection.value) -- Next step --- end) --- return true --- end, --- }) --- :find() --- end --- --- -- STEP 1: IDE (True/False) --- local function start_pio_wizard(json_data) --- local opts = require('telescope.themes').get_dropdown({ --- prompt_title = 'Generate Compilation Database (LSP)?', --- layout_config = { width = 0.2, height = 0.2 }, --- previewer = false, --- }) --- --- pickers --- .new(opts, { --- finder = finders.new_table({ results = { 'true', 'false' } }), --- sorter = telescope_conf.generic_sorter(opts), --- attach_mappings = function(prompt_bufnr) --- actions.select_default:replace(function() --- local selection = action_state.get_selected_entry() --- actions.close(prompt_bufnr) --- -- Save the boolean for the final step --- wizard_data.use_compiledb = (selection[1] == 'true') --- pick_board(json_data) --- end) --- return true --- end, --- }) --- :find() --- end --- --- local function launch_pio_project_wizard() --- print('Fetching board data from PlatformIO...') --- --- -- 1. Get board data from PIO CLI in JSON format --- -- The '--json-output' flag ensures we get structured data --- local handle = io.popen('pio boards --json-output') --- if not handle then --- return --- end --- --- local result = handle:read('*a') --- handle:close() --- --- -- 2. Decode the JSON string into a Lua table --- local ok, json_data = pcall(vim.json.decode, result) --- if not ok or not json_data then --- print('Error: Could not parse PlatformIO board data.') --- return --- end --- --- -- 3. Start the wizard we built previously --- start_pio_wizard(json_data) --- end --- --- -- Export the function so it's accessible via require() --- return { --- launch = launch_pio_project_wizard, --- } diff --git a/plugin/platformio.lua b/plugin/platformio.lua index 9e9a6d08..c03ec85e 100644 --- a/plugin/platformio.lua +++ b/plugin/platformio.lua @@ -51,19 +51,19 @@ vim.api.nvim_create_user_command('PioFixPaths', function() vim.pio.compile_commandsFix() end, {}) --- Pioinit2 -local pio_wiz = require('platformio.pioinit2') - --- Create a keybinding to trigger the wizard -vim.keymap.set('n', 'pi', function() - pio_wiz.launch() -end, { desc = 'Run PIO Project Wizard' }) - --- Alternatively, create a user command -vim.api.nvim_create_user_command('PioWizard', function() - pio_wiz.launch() -end, {}) - +-- -- Pioinit2 +-- local pio_wiz = require('platformio.pioinit2') +-- +-- -- Create a keybinding to trigger the wizard +-- vim.keymap.set('n', 'pi', function() +-- pio_wiz.launch() +-- end, { desc = 'Run PIO Project Wizard' }) +-- +-- -- Alternatively, create a user command +-- vim.api.nvim_create_user_command('PioWizard', function() +-- pio_wiz.launch() +-- end, {}) +-- ------------------------------------------------------ local piolsserial = require('platformio.piolsserial') From a16ba888b3211fb943619c86804fed834ee1e7cd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 21:04:36 +0300 Subject: [PATCH 1383/1406] update --- metadata.lua | 134 ---- mini_nvimPlatformio.lua => mini_nvimPIO.lua | 0 pio.lua | 682 -------------------- pio_setup.lua | 303 --------- pioinit.lua | 144 ----- piomenu.lua | 45 -- 6 files changed, 1308 deletions(-) delete mode 100644 metadata.lua rename mini_nvimPlatformio.lua => mini_nvimPIO.lua (100%) delete mode 100644 pio.lua delete mode 100644 pio_setup.lua delete mode 100644 pioinit.lua delete mode 100644 piomenu.lua diff --git a/metadata.lua b/metadata.lua deleted file mode 100644 index 7b68ba93..00000000 --- a/metadata.lua +++ /dev/null @@ -1,134 +0,0 @@ -local M = {} - -------------------------------------------------------------------------------------------------------- -local last_saved_hash = '' - ---INFO: --- 1. Internal State & Defaults -local _pio_metadata = { - isBusy = false, - envs = {}, - active_env = '', - default_envs = {}, - core_dir = '', - packages_dir = '', - platforms_dir = '', - query_driver = '', - cc_compiler = '', - includes_build = {}, - includes_compatlib = {}, - includes_toolchain = {}, - cc_path = '', - cc_flags = {}, - cxx_path = '', - cxx_flags = {}, - gdb_path = '', - defines = {}, - triplet = '', - toolchain_root = '', - sysroot = '', - fallbackFlags = {}, - dbTrigger = false, - last_projectChecksum = '', -- Used to track changes -} --- 2. The Reactive Proxy Wrapper --- Any write to _G.metadata.key = val triggers this logic -_G.metadata = setmetatable({}, { - __index = _pio_metadata, - __newindex = function(_, key, value) - if _pio_metadata[key] == value then - -- print('Value is identical, returning...') -- DEBUG LINE - return - end -- Performance check - -- print('Newindex attempt for: ' .. tostring(key)) -- DEBUG LINE - _pio_metadata[key] = value - - -- Trigger background actions - vim.schedule(function() - -- M.save_project_config(true) - if key == 'toolchain_root' then - local binPath = value .. '/bin' - local sep = (vim.fn.has('win32') == 1 and ';' or ':') - vim.env.PATH = binPath .. sep .. vim.env.PATH - vim.notify('PIO env: ' .. binPath .. ' added to path', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) - -- vim.notify('Env: ' .. value, vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) - -- pcall(function() - -- if _pio_metadata.dbTrigger then - -- vim.notify('Env: dbTrigger', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) - -- local dbFix = pio.compile_commandsFix - -- local ok, _ = pcall(dbFix) - -- if not ok then - -- print('Env: dbTrigger, fail to call dbFix') - -- end - -- -- dbFix() - -- _pio_metadata.dbTrigger = false - -- else - -- local LspRestart = require('platformio.lspConfigConfig.tools').lsp_restart - -- LspRestart('clangd') - -- vim.notify('Env: LspRestart', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) - -- end - -- end) - elseif key == 'last_projectChecksum' then - elseif key == 'active_env' then - end - end) - end, -}) - -local config_path = vim.fs.joinpath(vim.uv.cwd(), '.project_config.json') --- -- Add this temporary line in a file where you are coding: --- ---@type platformio.utils.misc --- local misc = vim.misc ---INFO: --- 2. Save Logic (Uses sha256 for stability) -function M.save_project_config(from) - -- 1. Generate the formatted string directly, jsonFormat already returns a string! - local ok, pretty_json = pcall(vim.misc.jsonFormat, _pio_metadata) - - if not ok or not pretty_json then - print('Error formatting metadata') - return - end - - local current_hash = vim.fn.sha256(pretty_json) - - -- 2. Only write if the content actually changed - if current_hash ~= last_saved_hash then - local status, err = vim.misc.writeFile(config_path, pretty_json, {}) - - if status then - last_saved_hash = current_hash - vim.notify(from .. 'config save success', vim.log.levels.INFO, { title = 'PlatformIO' }) - else - vim.notify(from .. 'config save failed==> ' .. (err or 'unknown error'), vim.log.levels.ERROR) - end - end -end - ---INFO: --- 3. Load Logic (Populates proxy safely) -function M.load_project_config() - if vim.fn.filereadable(config_path) == 1 then - local _, json_data = vim.misc.readFile(config_path) - if json_data then - local ok, table_data = pcall(vim.json.decode, json_data) - if ok and type(table_data) == 'table' then - -- We update _pio_metadata directly to avoid triggering - -- 50+ notifications/restarts during the initial load loop - for k, v in pairs(table_data) do - _G.metadata[k] = v - end - last_saved_hash = vim.fn.sha256(json_data) - return - end - end - end - -- If no file, initialize hash with defaults - last_saved_hash = vim.fn.sha256(vim.misc.jsonFormat(_pio_metadata)) -end - ---INFO: --- 4. Initialization -M.load_project_config() - -return M diff --git a/mini_nvimPlatformio.lua b/mini_nvimPIO.lua similarity index 100% rename from mini_nvimPlatformio.lua rename to mini_nvimPIO.lua diff --git a/pio.lua b/pio.lua deleted file mode 100644 index defa207c..00000000 --- a/pio.lua +++ /dev/null @@ -1,682 +0,0 @@ --- ---@class platformio.utils.pio --- local M = {} --- --- -- to fix require loop, this value is set in plugin/platformio --- local misc = vim.misc --- --- -- local sep = package.config:sub(1, 1) -- Dynamic OS separator (\ or /) --- M.selected_framework = '' --- M.is_processing = false --- M.queue = {} --- --- local term = require('platformio.utils.term') --- local clangdRestart = require('platformio.lspConfig.tools').clangdRestart --- --- -- INFO: --- -- ============================================================================= --- -- UNIVERSAL TOOLCHAIN DETECTION --- -- ============================================================================= --- -- stylua: ignore --- function M.get_sysroot_triplet(cc_compiler) --- local bin_path = vim.fn.fnamemodify(cc_compiler, ':h') --- --- -- Early exit if path is nil or not a directory --- if not bin_path or vim.fn.isdirectory(bin_path) == 0 then return nil end --- --- -- Normalize backslashes to forward slashes for cross-platform consistency --- bin_path = bin_path:gsub('\\', '/') --- local files = vim.fn.readdir(bin_path) --- local triplet = nil --- --- -- Loop through files to find the compiler and extract the triplet --- for _, name in ipairs(files) do --- -- Pattern: ^(.*) matches triplet, %- matches dash, g[c%+][c%+] matches gcc/g++ --- local match = name:match('^(.*)%-g[c%+][c%+]') --- if match then triplet = vim.misc.normalizePath(match) break --- end --- end --- --- -- Return nil if no compiler was found in the bin directory --- if not triplet then return nil end --- --- -- toolchain_root is the parent of the 'bin' folder --- local toolchain_root = vim.misc.normalizePath(vim.fn.fnamemodify(bin_path, ':h')) --- -- sysroot folder is expected to have the same name as the triplet --- local sysroot = vim.misc.normalizePath(toolchain_root .. '/' .. triplet) --- local query_driver = vim.misc.normalizePath(bin_path .. '/' .. triplet .. '-*') --- --- -- vim.notify('triplet= ' .. triplet, vim.log.levels.INFO) --- -- Only return data if the sysroot folder actually exists on disk --- if vim.fn.isdirectory(sysroot) == 1 then --- _G.metadata.triplet = triplet --- _G.metadata.sysroot = sysroot --- _G.metadata.toolchain_root = toolchain_root --- _G.metadata.query_driver = query_driver --- return { --- triplet = triplet, --- sysroot = sysroot, --- toolchain_root = toolchain_root, --- query_driver = query_driver, --- } --- end --- return nil --- end --- --- --INFO: --- -- Fast environment detection from platformio.ini file(no external calls) --- -- stylua: ignore --- --============================================================================= --- function M.get_active__env() --- local path --- --- for _, dir in ipairs({ vim.api.nvim_buf_get_name(0):match('(.*[/\\])'), (vim.uv.cwd() .. '/') }) do --- local tmp = dir .. 'platformio.ini' --- local filestat = vim.uv.fs_stat(tmp) --- if filestat and filestat.type == 'file' then --- path = vim.fs.normalize(tmp) --- break --- end --- end --- if not path or path == '' then return vim.notify('PIO: platformio.ini not found or no [env] defined.', vim.log.levels.ERROR) end --- --- -- Read file content (returns string or nil) --- local ok, content = vim.misc.readFile(path) --- if not ok or not content then return vim.notify('PIO: platformio.ini not found in ' .. path, vim.log.levels.WARN) end --- --- local default_envs_raw = '' --- local first_env = nil --- local valid_envs = {} --- local in_platformio_block = false --- --- -- Iterate lines from the content string --- for line in vim.gsplit(content, '\n') do --- -- Section Detection: [section_name] --- local section = line:match('^%s*%[(.+)%]%s*$') --- if section then --- in_platformio_block = (section == 'platformio') --- local env_name = section:match('^env:(.+)') --- if env_name then --- if not first_env then first_env = env_name end --- valid_envs[env_name] = true --- end --- end --- --- -- Collect the default_envs string from [platformio] block --- if in_platformio_block then --- local def = line:match('^%s*default_envs%s*=%s*(.+)') --- if def then default_envs_raw = def end --- end --- end --- --- -- Validation: Find the first default_env that actually exists as a block --- if default_envs_raw ~= '' then --- for env_name in default_envs_raw:gmatch('([^%s,]+)') do --- if valid_envs[env_name] then return env_name end --- end --- end --- --- -- Fallback to the very first [env:...] block found in the file --- return first_env --- end --- --- --- --INFO: --- -- get pio project metadata info --- -- stylua: ignore --- --============================================================================= --- function M.fetch_metadata(callback, env, from, attempts) --- local msg = (type(from)=='string' and from ~= '') and from or 'PIO: ' --- local meta = _G.metadata --- local active_env = env or meta.active_env --- if not active_env or active_env == '' then --- return --- end --- --- -- Set up file paths --- local build_dir = vim.misc.joinPath(vim.uv.cwd(), '.pio', 'build') --- local build_env_dir = vim.misc.joinPath(build_dir, active_env) --- local checksum_file = vim.misc.joinPath(build_dir, 'project.checksum') --- local idedata_file = vim.misc.joinPath(build_env_dir, 'idedata.json') --- --- --INFO: --- --INTERNAL PROCESSOR: Applies parsed data to _G.metadata --- --------------------------------------------------------- --- local function apply_metadata(data, checksum) --- if not data then return false end --- --- local norm = function(p) return vim.misc.normalizePath(p) or '' end --- --- -- Helper for flags/defines to keep order and formatting --- local quote_map = function(list, prefix) --- local res = {} --- for _, v in ipairs(list or {}) do --- local val = prefix and (prefix .. norm(v)) or v --- table.insert(res, string.format('%s', val)) --- end --- return res --- end --- --- -- 1. Base Paths & Compilers --- meta.cc_path = norm(data.cc_path) --- meta.cc_compiler = meta.cc_path --- meta.cxx_path = norm(data.cxx_path) --- meta.gdb_path = norm(data.gdb_path) --- --- -- 2. Flags & Defines --- meta.cc_flags = quote_map(data.cc_flags) --- meta.cxx_flags = quote_map(data.cxx_flags) --- meta.defines = quote_map(data.defines) --- --- -- 3. Includes (Build, Toolchain, Compatlib) --- local inc = data.includes or {} --- meta.includes_build = quote_map(inc.build, '-I') --- meta.includes_toolchain = quote_map(inc.toolchain, '-isystem') --- meta.includes_compatlib = quote_map(inc.compatlib, '-isystem') --- meta.last_projectChecksum = checksum --- pcall(M.get_sysroot_triplet, meta.cc_compiler) --- --- return true --- end --- --- --INFO: --- --Generate idedata.json --- --------------------------------------------------------- --- local function buildIdedata() --- vim.notify(msg .. 'Initializing project metadata...', vim.log.levels.INFO) --- vim.system({ 'pio', 'run', '-t', 'idedata', '-e', active_env, '-s' }, { text = true }, function(obj) --- vim.schedule(function() --- if obj.code == 0 then --- vim.notify(msg .. 'Initializing project metadata success.', vim.log.levels.INFO) --- M.fetch_metadata(callback, active_env, from, attempts - 1) -- Recursive call after files created --- else --- vim.notify(msg .. 'Initialization failed. Build project manually.', vim.log.levels.ERROR) --- end --- end) --- end) --- return true --- end --- --- --------------------------------------------------------- --- -- STEP 1: Fast Checksum Check (project.checksum and idedata.json) --- --------------------------------------------------------- --- local ok, current_checksum = vim.misc.readFile(checksum_file) --- if ok and (type(current_checksum) == 'string' and current_checksum ~= '') then --- if current_checksum == meta.last_projectChecksum then --- vim.notify(msg .. 'Metadata synced with cache', vim.log.levels.INFO) --- -- if callback then callback() end --- if callback then vim.schedule(callback) end --- return true --- end -- Already updated --- --- -- STEP 2: Cache Path (idedata.json exists and checksum changed) --- local idok, content = vim.misc.readFile(idedata_file) --- if idok and (type(content) == 'string' and content ~= '') then --- local cok, decoded = pcall(vim.json.decode, content) --- --- --- local formated = vim.misc.jsonFormat(decoded) --- local file = vim.misc.joinPath(vim.uv.cwd(), 'idedata.json') --- vim.misc.writeFile(file, formated, {}) --- --- --- if cok and apply_metadata(decoded, current_checksum) then --- local metadata = require('platformio.pio.metadata') --- metadata.save_project_config(msg) --- vim.notify(msg .. 'Metadata synced from cache', vim.log.levels.INFO) --- -- if callback then vim.schedule(callback) end --- --- if type(callback) == "function" then --- vim.schedule(callback) --- else --- -- If it's not a function, just do nothing or print a debug message --- print(msg .." Debug; callback was " .. type(callback)) --- end --- --- return true --- end --- -- else --- end --- -- else --- end --- --------------------------------------------------------- --- -- STEP 3: Auto-Initialize (If files project.checksum and idedata.json are missing) --- --------------------------------------------------------- --- buildIdedata() --- --- --------------------------------------------------------- --- -- STEP 4: Standard CLI Fallback (The Slow Path) --- --------------------------------------------------------- --- -- vim.notify(msg .. 'Metadata sync ...', vim.log.levels.INFO) --- -- vim.system({ 'pio', 'project', 'metadata', '-e', active_env, '--json-output' }, { text = true }, function(obj) --- -- vim.schedule(function() --- -- if obj.code ~= 0 then --- -- if attempts > 0 then --- -- vim.defer_fn(function() M.fetch_metadata(attempts - 1, env) end, 500) --- -- return --- -- end --- -- return vim.notify(msg .. 'Metadata Error: ' .. (obj.stderr or 'Unknown'), vim.log.levels.WARN) --- -- end --- -- --- -- local ook, raw_data = pcall(vim.json.decode, obj.stdout or '') --- -- local _, data = next(raw_data or {}) --- -- --- -- if ook and apply_metadata(data, current_checksum) then --- -- vim.notify(msg .. 'Metadata synced from CLI', vim.log.levels.INFO) --- -- if callback then vim.schedule(callback) end --- -- else --- -- vim.notify(msg .. 'Failed to parse metadata output', vim.log.levels.WARN) --- -- end --- -- end) --- -- end) --- end --- --- -- INFO: --- -- ============================================================================= --- -- Get project configuration --- -- ============================================================================= --- -- stylua: ignore --- function M.fetch_config(on_done, from) --- local msg = (type(from) == 'string' and from ~= '') and from or 'PIO: ' --- local meta = _G.metadata --- local home = (os.getenv('HOME') or os.getenv('USERPROFILE') or ''):gsub('[\\/]+$', '') --- --- local active_env --- vim.system({ 'pio', 'project', 'config', '--json-output' }, { text = true }, function(obj) --- vim.schedule(function() --- -- 1. Check Execution --- if obj.code ~= 0 then --- local errmsg = obj.code == 127 and "'pio' not found" or (obj.stderr or 'Unknown Error') --- return vim.notify(msg .. 'Config Error: ' .. errmsg, vim.log.levels.ERROR) --- end --- --- -- 2. Decode JSON safely --- local ok, decoded = pcall(vim.json.decode, obj.stdout or '') --- if not ok or type(decoded) ~= 'table' then --- return vim.notify(msg .. 'Failed to decode config JSON', vim.log.levels.ERROR) --- end --- --- local formated = vim.misc.jsonFormat(decoded) --- local file = vim.misc.joinPath(vim.uv.cwd(), 'config.json') --- vim.misc.writeFile(file, formated, {}) --- --- -- Reset core structure --- meta.envs = {} --- meta.default_envs = {} --- local valid_envs = {} --- --- -- 3. Parse Sections --- for _, section in ipairs(decoded) do --- local name, data = section[1], section[2] --- if name == 'platformio' then --- for _, kv in ipairs(data) do --- meta[kv[1]] = kv[2] --- end --- elseif name:match('^env:') then --- local env_name = name:match('^env:(.+)') --- if not active_env then active_env = env_name end --- valid_envs[env_name] = true --- meta.envs[env_name] = {} --- for _, kv in ipairs(data) do --- meta.envs[env_name][kv[1]] = kv[2] --- end --- end --- end --- --- -- 4. Assign active_env --- -- Validation: Find the first default_env that actually exists as a block --- for _, env_name in ipairs(meta.default_envs) do --- if valid_envs[env_name] then --- active_env = env_name --- break --- end --- end --- meta.active_env = active_env --- --- -- 5. Resolve Paths (INI -> Env -> Default) --- local path_map = { --- { key = 'core_dir', env = 'PLATFORMIO_CORE_DIR', sub = '/.platformio' }, --- { key = 'packages_dir', env = 'PLATFORMIO_PACKAGES_DIR', sub = '/.platformio/packages' }, --- { key = 'platforms_dir', env = 'PLATFORMIO_PLATFORMS_DIR', sub = '/.platformio/platforms' }, --- } --- --- for _, item in ipairs(path_map) do --- local val = meta[item.key] --- -- Fallback chain --- if not val or val == '' then --- val = os.getenv(item.env) or (home .. item.sub) --- end --- -- Expand variables and Normalize --- if type(val) == 'string' then --- val = val:gsub('%%${platformio.core_dir}', meta.core_dir or '') --- meta[item.key] = vim.misc.normalizePath(val) --- end --- end --- --- -- if active_env then --- -- vim.notify(msg .. 'active_env= ' .. active_env, vim.log.levels.INFO) --- -- end --- -- 6. Trigger next step --- if meta.active_env ~= '' then --- vim.notify(msg .. 'Config sync successful', vim.log.levels.INFO) --- else --- vim.notify(msg .. 'No [env:] found. Please add a board.', vim.log.levels.ERROR) --- end --- --- if on_done then --- vim.schedule(function() on_done(active_env) end) --- end --- end) --- end) --- end --- --- -- INFO: --- -- Fix compile_commands.json file with absoulute paths --- -- stylua: ignore --- -- ============================================================================= --- function M.compile_commandsFix() --M.dbPathsFix() --- local filename = vim.fs.joinpath(vim.uv.cwd(), 'compile_commands.json') --- local content = vim.fn.readfile(filename) --- if #content == 0 then return end --- --- local start_time = vim.loop.hrtime() --- local ok, data = pcall(vim.json.decode, table.concat(content, '\n')) --- if not ok or type(data) ~= 'table' then return end --- --- -- 1. Build Path Map (Scan toolchain) --- local path_map = {} --- local pio_binaries = _G.metadata.query_driver or '/bin/*' --- -- local pio_binaries = (_G.metadata.toolchain_root or "") .. '/bin/*' --- for _, full_path in ipairs(vim.fn.glob(pio_binaries, false, true)) do --- local name = full_path:match('([^/\\\\]+)$'):gsub('%.exe$', '') --- path_map[name] = full_path --- end --- --- -- 2. Update Entries --- local modified = false --- local prntFlags = true --- for _, entry in ipairs(data) do --- -- Standard normalization --- if entry.directory then entry.directory = misc.normalizePath(entry.directory) end --- if entry.file then entry.file = misc.normalizePath(entry.file) end --- if entry.arguments then entry.arguments = misc.normalizeFlags(entry.arguments) end --- if entry.output then entry.output = misc.normalizePath(entry.output) end --- --- if entry.command then --- -- Extract compiler and everything after it --- local compiler, args = entry.command:match("^%s*(%S+)(.*)") --- if compiler then --- local is_absolute = compiler:sub(1, 1) == '/' or compiler:match('^%a:') --- --- if not is_absolute then --- local short_name = compiler:match('([^/\\\\]+)$'):gsub('%.exe$', '') --- --- if path_map[short_name] then --- -- Use normalizePath on the new path --- local full_compiler_path = misc.normalizePath(path_map[short_name]) --- --- -- Quote the path if it contains spaces --- if full_compiler_path:find(" ") then --- full_compiler_path = '"' .. full_compiler_path .. '"' --- end --- if prntFlags then --- -- print(string.format('ful_compiler_path = %s flags=%s', full_compiler_path, args)) --- prntFlags = false --- end --- entry.command = full_compiler_path .. args --- modified = true --- end --- end --- end --- end --- end --- -- -- 3. Save with Formatting --- if modified then --- local jok, formatted = pcall(vim.misc.jsonFormat, data) --- -- local jok, formatted = pcall(M.pretty_print, data) --- if not jok then --- print('Formatting failed: ' .. formatted) --- return --- end --- --- local wk, err = vim.misc.writeFile(filename, formatted, { overwrite = true, mkdir = true }) --- if not wk then print(err) end --- --- local end_time = vim.loop.hrtime() --- local duration = (end_time - start_time) / 1e6 --- vim.notify(string.format('compiledb: paths fixed in %.2fms', duration), vim.log.levels.INFO) --- clangdRestart() --- end --- _G.metadata.isBusy = false --- end --- --- --- -- INFO: --- --configuration for running sequential commands on ToggleTerminal --- -- stylua: ignore --- -- ============================================================================= --- -- ============================================================================= --- local callBack = nil --- local pio_buffer = '' -- Persistent stream buffer --- --- -- INFO: ToggleTerminal commands stdout filter --- -- stylua: ignore --- -- ============================================================================= --- function M.stdoutcallback(_, _, data) --- if not data then return end --- --- -- 1. Combine the last partial line with the new first line --- local lines_to_process = pio_buffer .. data[1] --- --- -- 2. If there are newlines, we have complete lines to check --- if #data > 1 then --- -- Join all complete parts (everything except the very last partial line) --- for i = 2, #data - 1 do lines_to_process = lines_to_process .. data[i] end --- --- -- 3. Search for the status in the complete chunk --- local status = lines_to_process:match('_CMMNDS_:(%a+)') --- if status and callBack then vim.schedule(function() callBack(status) end) end --- -- save the trailing part for the next chunk --- pio_buffer = data[#data] --- else --- -- Only one element in data means no newline yet; just update the partial buffer --- pio_buffer = lines_to_process --- end --- --- -- 4. Safety Trim (Prevents memory leaks if no newline ever comes) --- if #pio_buffer > 5000 then pio_buffer = pio_buffer:sub(-2500) end --- end --- --- local commandPassed = 0 --- --- --- -- INFO: commands sequencer --- -- stylua: ignore --- -- ============================================================================= --- M.run_sequence = function(tasks) --- M.queue = {} --- local commands = tasks.cmnds --- --- local done = ' && echo _CMMNDS_":"DONE' --- local pass = ' && echo _CMMNDS_":"PASS' --- local fail = ' || echo _CMMNDS_":"FAIL' --- -- --- for i, cmd in ipairs(commands) do --- local full_cmd = '' --- if i == #commands then full_cmd = cmd .. done .. fail --- else full_cmd = cmd .. pass .. fail end --- table.insert(M.queue, full_cmd) --- end --- --- --- callBack = tasks.cb -- 1. Save the callback in a local variable --- --- commandPassed = 1 --- _G.metadata.isBusy = true --- --- term.stdout_callback = M.stdoutcallback --- vim.schedule(function() if callBack then callBack('INIT') end end) --- end --- --- local trm --- local win_id --- ------------------------------------------------------ --- -- Handle after pioinit execution --- -- ============================================================================= --- -- stylua: ignore --- function M.handlePioinitDb(result) --- if result == 'INIT' then --- local boilerplate = require('platformio.boilerplate') --- local boilerplate_gen = boilerplate.boilerplate_gen --- --- boilerplate.core_dir = _G.metadata.core_dir --- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) --- --- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) --- --- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) --- -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --- -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') --- --- win_id = vim.misc.showMessage('************ Project Initializing ************') --- if #M.queue > 0 then trm = term.ToggleTerminal(table.remove(M.queue, 1), 'float')end --- elseif result == 'PASS' then --- -- if commandPassed == 1 then --- -- elseif commandPassed == 2 then -- if you sned more than 2 commands you need this --- -- end --- vim.notify('PIO init+db: pass ' .. commandPassed, vim.log.levels.INFO) --- commandPassed = commandPassed + 1 --- if #M.queue > 0 then term.ToggleTerminal(table.remove(M.queue, 1), 'float') end --- elseif result == 'DONE' then -- result of the last command --- vim.schedule(function() --- vim.notify('PIO init+db: pass ' .. commandPassed, vim.log.levels.INFO) --- vim.notify('PIO init+db: Done', vim.log.levels.INFO) --- vim.misc.gitignore_lsp_configs('compile_commands.json') --- local pio_refresh = require('platformio.pio.watcher').pio_refresh --- pio_refresh(function() --- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen --- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --- vim.misc.closeMessage(win_id) --- clangdRestart() --- -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') --- end, 'PIO init+db: ') --- end) --- vim.misc.deleteFile(vim.fs.joinpath(vim.g.platformioRootDir, '.ccls')) --- M.queue = {} --- term.stdout_callback = nil --- trm:close() --- _G.metadata.isBusy = false --- elseif result == 'FAIL' then --- _G.metadata.isBusy = false --- vim.misc.closeMessage(win_id) --- M.queue = {} --- term.stdout_callback = nil --- trm:close() --- end --- end --- --- --- ---------------------------------------------------- --- -- Handle after pioinit execution --- -- stylua: ignore --- function M.handlePioinit(result) --- if result == 'INIT' then --- local boilerplate = require('platformio.boilerplate') --- local boilerplate_gen = boilerplate.boilerplate_gen --- --- boilerplate.core_dir = _G.metadata.core_dir --- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) --- --- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) --- --- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) --- -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --- -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') --- --- win_id = vim.misc.showMessage('************ Project Initializing ************') --- if #M.queue > 0 then trm = term.ToggleTerminal(table.remove(M.queue, 1), 'float')end --- elseif result == 'DONE' then -- result of the last command --- vim.schedule(function() --- vim.notify('PIO init: pass ' .. commandPassed, vim.log.levels.INFO) --- vim.notify('PIO init: Done', vim.log.levels.INFO) --- vim.misc.gitignore_lsp_configs('compile_commands.json') --- --- -- \27[s : Save current cursor position (the prompt) --- -- \r : Go to start of line --- -- \27[A : Move cursor UP one line (to space above prompt) --- -- \27[K : Clear that line --- -- \27[33m : Color Yellow (optional) --- -- %s : Your message --- -- \27[0m : Reset color --- -- \27[u : Restore cursor back to the prompt --- -- IMPORTANT: No \n at the end, so it doesn't execute --- -- local msg = '************ Please wait for project Initialization to finish ************' --- -- local clean_msg = string.format('\27[G\27[2K\27[33m%s\27[0m', msg) --- -- vim.api.nvim_chan_send(trm.job_id, clean_msg) --- --- local pio_refresh = require('platformio.pio.watcher').pio_refresh --- pio_refresh(function() --- local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen --- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --- vim.misc.closeMessage(win_id) --- clangdRestart() --- -- term.ToggleTerminal('echo "************ project Initialization success ************"', 'float') --- end, 'PIO init: ') --- end) --- vim.misc.deleteFile(vim.fs.joinpath(vim.g.platformioRootDir, '.ccls')) --- M.queue = {} --- term.stdout_callback = nil --- trm:close() --- _G.metadata.isBusy = false --- elseif result == 'FAIL' then --- _G.metadata.isBusy = false --- vim.misc.closeMessage(win_id) --- M.queue = {} --- term.stdout_callback = nil --- trm:close() --- end --- end --- --- ------------------------------------------------------ --- -- Handle after piolib execution --- -- ============================================================================= --- -- stylua: ignore --- function M.handlePiolib(result) --- if result == 'INIT' then --- if #M.queue > 0 then term.ToggleTerminal(table.remove(M.queue, 1), 'float')end --- elseif result == 'DONE' then -- result of the only and the last command --- vim.notify('PIO lib: pass ' .. commandPassed, vim.log.levels.INFO) --- vim.notify('PIO lib: Done', vim.log.levels.INFO) --- commandPassed = commandPassed + 1 --- M.queue = {} --- term.stdout_callback = nil --- _G.metadata.isBusy = false --- elseif result == 'FAIL' then --- M.queue = {} --- term.stdout_callback = nil --- _G.metadata.isBusy = false --- end --- end --- --- ------------------------------------------------------ --- -- ============================================================================= --- -- stylua: ignore --- function M.handlePiodb(target, result) --- if result == 'INIT' then --- if #M.queue > 0 then term.ToggleTerminal(table.remove(M.queue, 1), 'float')end --- elseif result == 'DONE' then -- result of the only and the last command --- vim.notify('PIO db: pass ' .. commandPassed, vim.log.levels.INFO) --- vim.notify('PIO db: Done', vim.log.levels.INFO) --- commandPassed = commandPassed + 1 --- target.isBusy = false --- M.queue = {} --- term.stdout_callback = nil --- _G.metadata.isBusy = false --- elseif result == 'FAIL' then --- target.isBusy = false --- M.queue = {} --- term.stdout_callback = nil --- _G.metadata.isBusy = false --- end --- end --- --- return M diff --git a/pio_setup.lua b/pio_setup.lua deleted file mode 100644 index eda8f081..00000000 --- a/pio_setup.lua +++ /dev/null @@ -1,303 +0,0 @@ --- M = {} --- --- local clangdRestart = require('platformio.lspConfig.tools').clangdRestart --- local boilerplate = require('platformio.boilerplate') --- local boilerplate_gen = boilerplate.boilerplate_gen --- --- -- ============================================================================= --- -- INFO: --- -- Unified hashing for change detection --- local function get_hash(path) --- if vim.fn.filereadable(path) == 0 then --- return nil --- end --- -- local ok, data = pcall(vim.fn.readfile, path) -- readfile is safer than io.open --- -- return ok and vim.fn.sha256(table.concat(data, '\n')) or nil --- local ok, data = vim.misc.readFile(path) -- readfile is safer than io.open --- return (ok and type(data) == 'string' and data ~= '') and vim.fn.sha256(data) or '' --- end --- --- --- --INFO: --- --stylua: ignore --- --============================================================================= --- function M.pio_refresh(callback, from) --- local msg = (type(from)=='string' and from ~= '') and from or 'PIO: ' --- vim.notify(msg ..'Config sync ...', vim.log.levels.INFO) --- --- local function on_done(active_env) --- if active_env then vim.notify(msg .. 'active_env= ' .. active_env, vim.log.levels.INFO) end --- if active_env then vim.pio.fetch_metadata(callback, active_env, from, 1) end --- end --- vim.pio.fetch_config(on_done, from) --- end --- --- --INFO: --- --============================================================================= --- -- watchers setup --- --============================================================================= --- -- Ensure this is at the TOP of your file, outside any functions --- local uv = vim.uv or vim.loop --- M.watcher_handles = {} --- local debounce_timer = uv.new_timer() --- local last_mtime = 0 --- --- -- --INFO: --- -- --stylua: ignore --- -- --1.run_compiledb after platformio.ini changed --- -- --============================================================================= --- -- function M.run_compiledb(target) --- -- if target.isBusy then return end --- -- if _G.metadata.isBusy == true then return end --- -- --- -- local env = vim.pio.get_active__env() --- -- if not env then return end --- -- target.isBusy = true --- -- vim.notify('PIO platformio.ini change: compiledb update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) --- -- vim.system({ 'pio', 'run', '-t', 'compiledb', '-s', '-e', env }, { text = true }, function(obj) --- -- vim.schedule(function() --- -- target.isBusy = false --- -- --- -- if obj.code == 0 then --- -- vim.schedule(function () --- -- M.pio_refresh(function() --- -- vim.notify('PIO platformio.ini change: compiledb update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) --- -- clangdRestart() --- -- end, 'PIO platformio.ini change: ') --- -- end) --- -- else --- -- local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' --- -- vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) --- -- end --- -- _G.metadata.isBusy = false --- -- end) --- -- end) --- -- end --- -- --- --INFO: --- --stylua: ignore --- --1.stop_watchers --- --============================================================================= --- function M.stop_watchers() --- if not M.watcher_handles or (type(M.watcher_handles) ~= 'table') then M.watcher_handles = {} return end --- --- for _, handle in ipairs(M.watcher_handles) do --- if handle and not handle:is_closing() then --- handle:stop() --- handle:close() -- CRITICAL: This allows Neovim to quit instantly --- end --- end --- M.watcher_handles = {} --- end --- --- --INFO: --- --stylua: ignore --- --2.watcher cleanup --- --============================================================================= --- function M.cleanup() --- M.stop_watchers() --- if debounce_timer and not debounce_timer:is_closing() then --- debounce_timer:stop() --- debounce_timer:close() --- end --- end --- --- -- Force cleanup when leaving Neovim to prevent :qa lag --- vim.api.nvim_create_autocmd('VimLeavePre', { --- callback = function() --- M.cleanup() --- end, --- }) --- --- --INFO: --- --stylua: ignore --- --3. MAIN WATCHER: Efficient Folder Monitoring --- --============================================================================= --- local function watch_file(target, callback) --- local folder_path = target.path:match('(.*[/\\])') --- local target_filename = target.path:match('[^/\\]+$') --- --- local handle = uv.new_fs_event() --- if not handle then return end --- --- handle:start(folder_path, {}, function(err, filename) --- if err then return end --- --- -- Early Exit Filters --- if target.isBusy or (filename and filename ~= target_filename) then return end --- --- -- local f = io.open(target.path, "r") --- -- if f then f:close() --- -- else return end -- Not readable (protected, locked, or missing) --- --- if not uv.fs_access(target.path, 'R') then return end --- --- -- Protected Execution --- local ok, result = pcall(function() --- local stat = uv.fs_stat(target.path) --- if not stat or stat.mtime.sec <= last_mtime then return end --- --- vim.schedule(function() --- if debounce_timer then --- debounce_timer:stop() --- local retries = 0 --- local max_retries = 15 -- 15 seconds max wait --- --- local function attempt_callback() --- -- Check if busy (checks both local M and global _G) --- if target.isBusy then --or (_G.metadata and _G.metadata.isBusy) then --- if retries < max_retries then --- retries = retries + 1 --- debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) --- return --- end --- vim.notify('PIO: Sync timed out (busy)', vim.log.levels.ERROR) --- return --- end --- --- -- Final validation & run --- local final_stat = uv.fs_stat(target.path) --- if final_stat and final_stat.mtime.sec > last_mtime then --- last_mtime = final_stat.mtime.sec --- callback(target) --- end --- end --- --- debounce_timer:start(1000, 0, vim.schedule_wrap(attempt_callback)) --- end --- end) --- end) --- --- if not ok then --- vim.schedule(function() --- vim.notify('PIO Watcher Error: ' .. tostring(result), vim.log.levels.ERROR) --- end) --- end --- end) --- --- table.insert(M.watcher_handles, handle) --- return handle --- end --- --- --INFO: --- --stylua: ignore --- --4. start_watches --- --============================================================================= --- function M.start_watchers() --- -- Clean up any existing watchers first to prevent duplicates --- if next(M.watcher_handles) then M.stop_watchers() end --- --- local project_root = vim.uv.cwd() -- Use dynamic CWD instead of hardcoded path --- --- local targets = { --- { -- watcher for platformio.ini --- name = 'ini', --- isBusy = false, --- last_hash = '', --- path = vim.misc.joinPath(project_root, 'platformio.ini'), --- cb = function(self) --- if self.isBusy then return end --- if _G.metadata.isBusy == true then return end --- local new_hash = get_hash(self.path) or '' --- if new_hash and new_hash ~= self.last_hash then --- self.last_hash = new_hash --- local env = vim.pio.get_active__env() --- if not env then return end --- self.isBusy = true --- vim.notify('PIO platformio.ini change: compiledb update ...', vim.log.levels.INFO, { title = 'PlatformIO' }) --- vim.system({ 'pio', 'run', '-t', 'compiledb', '-s', '-e', env }, { text = true }, function(obj) --- vim.schedule(function() --- if obj.code == 0 then --- vim.schedule(function () --- M.pio_refresh(function() --- vim.notify('PIO platformio.ini change: compiledb update Success', vim.log.levels.INFO, { title = 'PlatformIO' }) --- clangdRestart() --- end, 'PIO platformio.ini change: ') --- end) --- else --- local err = (obj.stderr and obj.stderr ~= '') and obj.stderr or 'Check PIO logs' --- vim.notify('PIO Build Failed: ' .. err, vim.log.levels.ERROR, { title = 'PlatformIO' }) --- end --- self.isBusy = false --- end) --- end) --- -- M.run_compiledb(self) -- Smart: Auto-update DB if config changes --- end --- end, --- }, --- { -- watcher for ./.pio/build/projct.checksum --- name = 'checksum', --- isBusy = false, --- path = vim.misc.joinPath(project_root, '.pio', 'build', 'project.checksum'), --checksum_path --- cb = function(self) --- if self.isBusy then return end --- local ok, current_checksum = vim.misc.readFile(self.path) --- -- Check if we should exit early --- if ok and type(current_checksum) == 'string' and current_checksum ~= '' then --- if current_checksum == _G.metadata.last_projectChecksum then --- return --- end --- --- self.isBusy = true --- vim.defer_fn(function () --- M.pio_refresh(function() --- self.isBusy = false --- vim.notify('PIO checksum: Metadata synced', vim.log.levels.INFO) --- clangdRestart() --- end, 'PIO checksum: ') --- end, 500) --- end --- end --- }, --- } --- --- for _, target in ipairs(targets) do --- --[[ wrap the callback in a small anonymous function, --- so it passes the target (self) back into it.]] --- watch_file(target, target.cb) --- end --- end --- --- --INFO: 6. Exported setup function --- --stylua: ignore --- --============================================================================= --- function M.init() --- local config = require('platformio').config --- if config.lspClangd.enabled == true then --- vim.notify('PIO start: initialize', vim.log.levels.INFO) --- --- -- activate meta save and upload and env switch --- local metadata = require('platformio.pio.metadata') --- metadata.load_project_config() --- --- require('platformio.lspConfig.clangd') --- if config.lspClangd.attach.enabled then --- require('platformio.lspConfig.attach') --- end --- --- -- Always start the watcher so it can catch a future 'pio init' --- M.start_watchers() --- --- -- boilerplate_gen([[platformio.ini]], vim.g.platformioRootDir) --- -- If the file already exists, do an initial sync --- if vim.fn.filereadable(vim.uv.cwd() .. '/platformio.ini') == 1 then --- ---------------------------------------------------------------------------------------- --- --INFO: create clangd required files --- ----------------------------------------------------------------------------------------- --- -- boilerplate_gen([[.clangd]], vim.g.platformioRootDir) --- -- boilerplate_gen([[.clangd]], vim.fs.joinpath(vim.env.XDG_CONFIG_HOME, 'clangd'), 'config.yaml') --- -- boilerplate_gen([[.clangd]], _G.metadata.core_dir) --- boilerplate.core_dir = _G.metadata.core_dir --- boilerplate_gen([[.clang-format]], vim.g.platformioRootDir) --- --------------------------------------------------------------------------------- --- -- M.run_compiledb() -- Smart: Auto-update DB if config changes --- M.pio_refresh(function() --- -- vim.schedule(function() --- -- lsp_restart('clangd') --- -- end) --- end, 'PIO start: ') --- end --- end --- end --- --- return M diff --git a/pioinit.lua b/pioinit.lua deleted file mode 100644 index ff838273..00000000 --- a/pioinit.lua +++ /dev/null @@ -1,144 +0,0 @@ --- local M = {} --- --- local pickers = require('telescope.pickers') --- local finders = require('telescope.finders') --- local telescope_conf = require('telescope.config').values --- local actions = require('telescope.actions') --- local action_state = require('telescope.actions.state') --- local entry_display = require('telescope.pickers.entry_display') --- local make_entry = require('telescope.make_entry') --- local misc = require('platformio.utils.misc') --- local previewers = require('telescope.previewers') --- --- local boardentry_maker = function(opts) --- local displayer = entry_display.create({ --- separator = '▏', --- items = { --- { width = 35 }, --- { width = 20 }, --- { width = 15 }, --- }, --- }) --- --- local make_display = function(entry) --- return displayer({ --- entry.value.name, --- entry.value.vendor, --- entry.value.platform, --- }) --- end --- --- return function(entry) --- return make_entry.set_default_entry_mt({ --- value = { --- id = entry.id, --- name = entry.name, --- vendor = entry.vendor, --- platform = entry.platform, --- data = entry, --- }, --- ordinal = entry.name .. ' ' .. entry.vendor .. ' ' .. entry.platform, --- display = make_display, --- }, opts) --- end --- end --- --- --- stylua: ignore --- local function pick_framework(board_details) --- local opts = {} --- pickers --- .new(opts, { --- prompt_title = 'frameworks', --- finder = finders.new_table({ --- results = board_details['frameworks'], --- }), --- attach_mappings = function(prompt_bufnr, _) --- actions.select_default:replace(function() --- actions.close(prompt_bufnr) --- local selection = action_state.get_selected_entry() --- --- local pio = require('platformio..pio.upkeep') --- pio.selected_framework = selection[1] --- pio.run_sequence({ --- cmnds = { --- 'pio project init --board ' .. board_details['id'] .. ' -O "framework=' .. pio.selected_framework .. '"', --- -- 'pio run -t compiledb', --- }, --- cb = pio.handlePioinit, --- }) --- end) --- return true --- end, --- sorter = telescope_conf.generic_sorter(opts), --- }) --- :find() --- end --- --- -- stylua: ignore --- local function pick_board(json_data) --- local opts = {} --- pickers.new(opts, { --- prompt_title = 'Boards', --- finder = finders.new_table({ --- results = json_data, --- entry_maker = opts.entry_maker or boardentry_maker(opts), --- }), --- attach_mappings = function(prompt_bufnr, _) --- actions.select_default:replace(function() --- actions.close(prompt_bufnr) --- local selection = action_state.get_selected_entry() --- pick_framework(selection['value']['data']) --- end) --- return true --- end, --- previewer = previewers.new_buffer_previewer({ --- title = 'Board Info', --- define_preview = function(self, entry, _) --- local json = misc.strsplit(vim.inspect(entry['value']['data']), '\n') --- local bufnr = self.state.bufnr --- vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, json) --- vim.api.nvim_set_option_value('filetype', 'lua', { buf = bufnr }) --fix deprecated function --- vim.defer_fn(function() --- local win = self.state.winid --- vim.api.nvim_set_option_value('wrap', true, { scope = 'local', win = win }) --- vim.api.nvim_set_option_value('linebreak', true, { scope = 'local', win = win }) --- vim.api.nvim_set_option_value('wrapmargin', 2, { buf = bufnr }) --- end, 0) --- end, --- }), --- sorter = telescope_conf.generic_sorter(opts), --- }):find() --- end --- --- function M.pioinit() --- if not misc.pio_install_check() then --- return --- end --- --- -- Read stdout --- local command = 'pio boards --json-output' --- local handle = io.popen(command .. misc.devNul) --- if not handle then --- return --- end --- local json_str = handle:read('*a') --- handle:close() --- --- if #json_str == 0 then --- -- read stderr --- handle = io.popen(command .. ' 2>&1') --- if not handle then --- return --- end --- local command_output = handle:read('*a') --- handle:close() --- vim.notify('Some error occured while executing `' .. command .. "`', command output: \n", vim.log.levels.WARN) --- print(command_output) --- return --- end --- --- local json_data = vim.json.decode(json_str) --- pick_board(json_data) --- end --- --- return M diff --git a/piomenu.lua b/piomenu.lua deleted file mode 100644 index 8895dba0..00000000 --- a/piomenu.lua +++ /dev/null @@ -1,45 +0,0 @@ --- local M = {} --- --- function M.piomenu(config) --- local icon = { icon = ' ', color = 'orange' } -- Assign platformio orange icon --- local wk_table = { mode = { 'n', 'v' } } --- --- local function traverseMenu(menu, wkey) --- for _, child_node in ipairs(menu) do --- if child_node.node == 'menu' then --- traverseMenu(child_node.items, wkey .. child_node.shortcut) --- table.insert(wk_table, { wkey .. child_node.shortcut, group = child_node.desc, icon = icon }) --- elseif child_node.node == 'item' then --- table.insert(wk_table, { --- wkey .. child_node.shortcut, --- ' ' .. child_node.command .. '', --- desc = child_node.desc, --- icon = icon, --- }) --- end --- end --- end --- if config.menu_key == nil then --- return --- end --- --- local ok, wk = pcall(require, 'which-key') --- if not ok then --- vim.api.nvim_echo({ { 'which-key plugin not found!', 'ErrorMsg' } }, true, {}) --- return --- end --- --- wk.setup({ --- preset = 'helix', --'modern', --'classic' --- }) --- local Config = require('which-key.config') --- Config.sort = { 'order', 'group', 'manual', 'mod' } --- --- table.insert(wk_table, { config.menu_key, group = config.menu_name, icon = icon }) --- --- traverseMenu(config.menu_bindings, config.menu_key) --- --- wk.add(wk_table) --- end --- --- return M From 1d3a850b6bf959fe6b207d281e0181ec40f85c8d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 21:48:02 +0300 Subject: [PATCH 1384/1406] update --- mini_nvimPIO.lua | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/mini_nvimPIO.lua b/mini_nvimPIO.lua index 25388fcd..a67f3e08 100644 --- a/mini_nvimPIO.lua +++ b/mini_nvimPIO.lua @@ -155,6 +155,7 @@ keymap('n', '', '', { desc = 'Move focus to the upper window' }) ---------------------------------------------------------------------------------------- -- INFO: Set mini lazy config ---------------------------------------------------------------------------------------- +-- stylua: ignore ---[[ local function setup_xdg_paths() -- local isWindows = vim.fn.has('win32') == 1 @@ -169,29 +170,33 @@ local function setup_xdg_paths() -- 1. XDG_CONFIG_HOME (Settings/Configs) if not vim.env.XDG_CONFIG_HOME then - local path = isWindows and (vim.env.LOCALAPPDATA or (home .. '/AppData/Local')) or isMac and (home .. '/Library/Preferences') or (home .. '/.config') + local path = isWindows and (vim.env.LOCALAPPDATA or (home .. '/AppData/Local')) + or isMac and (home .. '/Library/Preferences') + or (home .. '/.config') vim.env.XDG_CONFIG_HOME = normalize(vim.fs.joinpath(path, app_name)) end -- 2. XDG_DATA_HOME (Large data/Databases) if not vim.env.XDG_DATA_HOME then local path = isWindows and (vim.env.LOCALAPPDATA or (home .. '/AppData/Local')) - or isMac and (home .. '/Library/Application Support') - or (home .. '/.local/share') + or isMac and (home .. '/Library/Application Support') + or (home .. '/.local/share') vim.env.XDG_DATA_HOME = normalize(vim.fs.joinpath(path, app_name)) end -- 3. XDG_STATE_HOME (Logs/History/Persistent State) if not vim.env.XDG_STATE_HOME then local path = isWindows and (vim.env.LOCALAPPDATA or (home .. '/AppData/Local')) - or isMac and (home .. '/Library/Application Support') - or (home .. '/.local/state') + or isMac and (home .. '/Library/Application Support') + or (home .. '/.local/state') vim.env.XDG_STATE_HOME = normalize(vim.fs.joinpath(path, app_name)) end -- 4. XDG_CACHE_HOME (Temporary/Disposable data) if not vim.env.XDG_CACHE_HOME then - local path = isWindows and (vim.env.TEMP or (home .. '/AppData/Local/Temp')) or isMac and (home .. '/Library/Caches') or (home .. '/.cache') + local path = isWindows and (vim.env.TEMP or (home .. '/AppData/Local/Temp')) + or isMac and (home .. '/Library/Caches') + or (home .. '/.cache') vim.env.XDG_CACHE_HOME = normalize(vim.fs.joinpath(path, app_name)) end end From 6f3b00695e4a7f96028d92c34c181fc479051d5e Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 22:00:15 +0300 Subject: [PATCH 1385/1406] update --- lua/platformio/boilerplate.lua | 1 + lua/platformio/lspConfig/clangd.lua | 9 +++++++-- lua/platformio/pio/upkeep.lua | 14 ++++++-------- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index f18bba42..2f80eee3 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -76,6 +76,7 @@ boilerplate['.clangd_config'] = { "--all-scopes-completion", "--background-index", "--clang-tidy", + "--config-file=%s" "--compile_args_from=filesystem", "--enable-config", "--completion-parse=always", diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 8cc5e01e..b04c258a 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -107,6 +107,7 @@ function _G.get_clangd_config() -- 1. Safe defaults (Standard clangd behavior) local f_flags, q_driver = '', '--query-driver=**' + local clangdFile = vim.misc.joinPath(vim.uv.cwd(), '.clangd') -- 2. Run your toolchain detection if _G.metadata and _G.metadata.cc_compiler and _G.metadata.cc_compiler ~= '' then @@ -125,13 +126,17 @@ function _G.get_clangd_config() -- 3. Format your template string local table_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) - -- local formatted_str = string.format(table_config or '', q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) + local formatted_str = string.format(table_config or '', clangdFile, q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) -- local formatted_str = string.format(table_config or '', q_driver, '', vim.misc.normalizePath(new_root_dir)) - local formatted_str = string.format(table_config or '', q_driver, '', vim.g.platformioRootDir) + -- local formatted_str = string.format(table_config or '', q_driver, '', vim.g.platformioRootDir) -- 4. Load the config table local cok, clangd_config = pcall(function() return load('return ' .. formatted_str)() end) + local formated = vim.misc.jsonFormat(clangd_config) + local file = vim.misc.joinPath(vim.uv.cwd(), 'clangd_config.json') + vim.misc.writeFile(file, formated, {}) + if cok and clangd_config then -- print(vim.inspect(clangd_config)) return clangd_config diff --git a/lua/platformio/pio/upkeep.lua b/lua/platformio/pio/upkeep.lua index b3ababd8..e8c99449 100644 --- a/lua/platformio/pio/upkeep.lua +++ b/lua/platformio/pio/upkeep.lua @@ -213,11 +213,9 @@ function M.fetch_metadata(callback, env, from, attempts) if idok and (type(content) == 'string' and content ~= '') then local cok, decoded = pcall(vim.json.decode, content) - - local formated = vim.misc.jsonFormat(decoded) - local file = vim.misc.joinPath(vim.uv.cwd(), 'idedata.json') - vim.misc.writeFile(file, formated, {}) - + -- local formated = vim.misc.jsonFormat(decoded) + -- local file = vim.misc.joinPath(vim.uv.cwd(), 'idedata.json') + -- vim.misc.writeFile(file, formated, {}) if cok and apply_metadata(decoded, current_checksum) then local metadata = require('platformio.pio.metadata') @@ -295,9 +293,9 @@ function M.fetch_config(on_done, from) return vim.notify(msg .. 'Failed to decode config JSON', vim.log.levels.ERROR) end - local formated = vim.misc.jsonFormat(decoded) - local file = vim.misc.joinPath(vim.uv.cwd(), 'config.json') - vim.misc.writeFile(file, formated, {}) + -- local formated = vim.misc.jsonFormat(decoded) + -- local file = vim.misc.joinPath(vim.uv.cwd(), 'config.json') + -- vim.misc.writeFile(file, formated, {}) -- Reset core structure meta.envs = {} From 68bef6b455f5671ab1b3bd912ded7b43da1acb45 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 22:09:03 +0300 Subject: [PATCH 1386/1406] update --- lua/platformio/lspConfig/clangd.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index b04c258a..b42c9e0a 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -129,6 +129,7 @@ function _G.get_clangd_config() local formatted_str = string.format(table_config or '', clangdFile, q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) -- local formatted_str = string.format(table_config or '', q_driver, '', vim.misc.normalizePath(new_root_dir)) -- local formatted_str = string.format(table_config or '', q_driver, '', vim.g.platformioRootDir) + print(formatted_str) -- 4. Load the config table local cok, clangd_config = pcall(function() return load('return ' .. formatted_str)() end) From e9764b551fe22a5727dd220b3562448873363dd6 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 22:21:22 +0300 Subject: [PATCH 1387/1406] update --- lua/platformio/boilerplate.lua | 2 +- lua/platformio/lspConfig/clangd.lua | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 2f80eee3..0016ed72 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -61,6 +61,7 @@ lib_ldf_mode = chain ;Library dependencies Finder ldf end, } +-- "--config-file=%s" -- ============================================================================= -- DYNAMIC CLANGD CONFIGURATION TEMPLATE -- ============================================================================= @@ -76,7 +77,6 @@ boilerplate['.clangd_config'] = { "--all-scopes-completion", "--background-index", "--clang-tidy", - "--config-file=%s" "--compile_args_from=filesystem", "--enable-config", "--completion-parse=always", diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index b42c9e0a..4e58ed43 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -126,7 +126,8 @@ function _G.get_clangd_config() -- 3. Format your template string local table_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) - local formatted_str = string.format(table_config or '', clangdFile, q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) + -- local formatted_str = string.format(table_config or '', clangdFile, q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) + local formatted_str = string.format(table_config or '', q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) -- local formatted_str = string.format(table_config or '', q_driver, '', vim.misc.normalizePath(new_root_dir)) -- local formatted_str = string.format(table_config or '', q_driver, '', vim.g.platformioRootDir) print(formatted_str) From c81c82f45f8dc0adf08b800bd854bcd499d2eed5 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 22:25:14 +0300 Subject: [PATCH 1388/1406] update --- lua/platformio/lspConfig/clangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 4e58ed43..ca2e9902 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -114,7 +114,7 @@ function _G.get_clangd_config() if _G.metadata.triplet and _G.metadata.triplet ~= '' then -- local include_flags = table.concat(_G.metadata.fallbackFlags, ", ") local includes_toolchain = table.concat(_G.metadata.includes_toolchain, ", ") - f_flags = [["-std=c++17", "-xc++"]] + f_flags = string.format([["-std=c++17", "-xc++"]]) -- f_flags = string.format([["-std=c++17", "-xc++", "-D__cplusplus=201703L", "--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, includes_toolchain) -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) From 76b7c03b10c74f1d2abf8e52cb5a33ae677401cd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 22:29:53 +0300 Subject: [PATCH 1389/1406] update --- lua/platformio/lspConfig/clangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index ca2e9902..7cc6f83b 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -114,7 +114,7 @@ function _G.get_clangd_config() if _G.metadata.triplet and _G.metadata.triplet ~= '' then -- local include_flags = table.concat(_G.metadata.fallbackFlags, ", ") local includes_toolchain = table.concat(_G.metadata.includes_toolchain, ", ") - f_flags = string.format([["-std=c++17", "-xc++"]]) + f_flags = '"-std=c++17", "-xc++"' -- f_flags = string.format([["-std=c++17", "-xc++", "-D__cplusplus=201703L", "--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, includes_toolchain) -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) From f702879a8112e0aff16d296ce4c2746f684083bf Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 22:35:25 +0300 Subject: [PATCH 1390/1406] update --- lua/platformio/lspConfig/clangd.lua | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 7cc6f83b..1489d8a4 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -107,15 +107,14 @@ function _G.get_clangd_config() -- 1. Safe defaults (Standard clangd behavior) local f_flags, q_driver = '', '--query-driver=**' - local clangdFile = vim.misc.joinPath(vim.uv.cwd(), '.clangd') -- 2. Run your toolchain detection if _G.metadata and _G.metadata.cc_compiler and _G.metadata.cc_compiler ~= '' then if _G.metadata.triplet and _G.metadata.triplet ~= '' then -- local include_flags = table.concat(_G.metadata.fallbackFlags, ", ") local includes_toolchain = table.concat(_G.metadata.includes_toolchain, ", ") - f_flags = '"-std=c++17", "-xc++"' - -- f_flags = string.format([["-std=c++17", "-xc++", "-D__cplusplus=201703L", "--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, includes_toolchain) + -- f_flags = '"-std=c++17", "-xc++"' + f_flags = string.format([["-std=c++17", "-xc++", "-D__cplusplus=201703L", "--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, includes_toolchain) -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) @@ -126,7 +125,6 @@ function _G.get_clangd_config() -- 3. Format your template string local table_config = boilerplate_gen([[.clangd_config]], vim.g.platformioRootDir) - -- local formatted_str = string.format(table_config or '', clangdFile, q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) local formatted_str = string.format(table_config or '', q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) -- local formatted_str = string.format(table_config or '', q_driver, '', vim.misc.normalizePath(new_root_dir)) -- local formatted_str = string.format(table_config or '', q_driver, '', vim.g.platformioRootDir) From 83ae855eab4162ec3554a949f2f814a9e115afeb Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 22:38:38 +0300 Subject: [PATCH 1391/1406] update --- lua/platformio/boilerplate.lua | 4 ++-- lua/platformio/lspConfig/clangd.lua | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 0016ed72..98d966c2 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -175,13 +175,13 @@ boilerplate['.clangd'] = { read = false, -- - "-std=c++17" -- - "-std=gnu++17" + -- - "-xc++" + -- - "-std=gnu++17" -- template = [[ content = [[ --- CompileFlags: Add: - - "-xc++" - - "-std=gnu++17" - "-Wno-pragma-system-header-outside-header" Remove: - "-Wunknown-warning-option" diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 1489d8a4..3ff576b8 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -106,7 +106,7 @@ function _G.get_clangd_config() if not new_root_dir then return end -- 1. Safe defaults (Standard clangd behavior) - local f_flags, q_driver = '', '--query-driver=**' + local f_flags, q_driver = [["-std=c++17", "-xc++"]], '--query-driver=**' -- 2. Run your toolchain detection if _G.metadata and _G.metadata.cc_compiler and _G.metadata.cc_compiler ~= '' then From 1072350a1edf4912a668e207352e4a5477853d11 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 22:39:27 +0300 Subject: [PATCH 1392/1406] update --- lua/platformio/lspConfig/clangd.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 3ff576b8..189a957c 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -128,7 +128,6 @@ function _G.get_clangd_config() local formatted_str = string.format(table_config or '', q_driver, f_flags, vim.misc.normalizePath(new_root_dir)) -- local formatted_str = string.format(table_config or '', q_driver, '', vim.misc.normalizePath(new_root_dir)) -- local formatted_str = string.format(table_config or '', q_driver, '', vim.g.platformioRootDir) - print(formatted_str) -- 4. Load the config table local cok, clangd_config = pcall(function() return load('return ' .. formatted_str)() end) From abebdaf4d40ac56ca22763bd9e0deb4b3e8c1e7f Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 22:55:44 +0300 Subject: [PATCH 1393/1406] update --- lua/platformio/lspConfig/clangd.lua | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 189a957c..305957b2 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -112,9 +112,18 @@ function _G.get_clangd_config() if _G.metadata and _G.metadata.cc_compiler and _G.metadata.cc_compiler ~= '' then if _G.metadata.triplet and _G.metadata.triplet ~= '' then -- local include_flags = table.concat(_G.metadata.fallbackFlags, ", ") - local includes_toolchain = table.concat(_G.metadata.includes_toolchain, ", ") + -- local includes_toolchain = table.concat(_G.metadata.includes_toolchain, ", ") + + local include_flags = table.concat(vim.tbl_map(function(item) + return '"' .. item .. '"' + end, _G.metadata.fallbackFlags), ", ") + + local includes_toolchain = table.concat(vim.tbl_map(function(item) + return '"' .. item .. '"' + end, _G.metadata.includes_toolchain), ", ") + -- f_flags = '"-std=c++17", "-xc++"' - f_flags = string.format([["-std=c++17", "-xc++", "-D__cplusplus=201703L", "--target=%s", "--sysroot=%s", %s]], _G.metadata.triplet, _G.metadata.sysroot, includes_toolchain) + f_flags = string.format([["-std=c++17", "-xc++", "-D__cplusplus=201703L", "--target=%s", "--sysroot=%s", %s, %s]], _G.metadata.triplet, _G.metadata.sysroot, includes_toolchain, include_flags) -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) From ac8579bdfc23722ce74910d6d32208741aa7ecdd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 23:00:22 +0300 Subject: [PATCH 1394/1406] update --- lua/platformio/lspConfig/clangd.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 305957b2..7ee73855 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -123,7 +123,7 @@ function _G.get_clangd_config() end, _G.metadata.includes_toolchain), ", ") -- f_flags = '"-std=c++17", "-xc++"' - f_flags = string.format([["-std=c++17", "-xc++", "-D__cplusplus=201703L", "--target=%s", "--sysroot=%s", %s, %s]], _G.metadata.triplet, _G.metadata.sysroot, includes_toolchain, include_flags) + f_flags = string.format([["-std=gnu++17", "-xc++", "-D__cplusplus=201703L", "--target=%s", "--sysroot=%s", %s, %s]], _G.metadata.triplet, _G.metadata.sysroot, includes_toolchain, include_flags) -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) From a9ace64fd18a81261e8c0d779270596a5fa851d8 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 23:05:55 +0300 Subject: [PATCH 1395/1406] update --- lua/platformio/boilerplate.lua | 4 ++++ lua/platformio/lspConfig/clangd.lua | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 98d966c2..d2118685 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -88,6 +88,10 @@ boilerplate['.clangd_config'] = { "--pretty", "--ranking-model=decision_forest", "--sync", + "-std=gnu++17", + "-Wno-pragma-system-header-outside-header", + "-Wno-unknown-warning-option", + "-Wno-unused-includes" -- Equivalent to unused-includes suppression "--offset-encoding=utf-16", "--query-driver=%s" }, diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 7ee73855..4bfeebba 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -122,8 +122,8 @@ function _G.get_clangd_config() return '"' .. item .. '"' end, _G.metadata.includes_toolchain), ", ") - -- f_flags = '"-std=c++17", "-xc++"' - f_flags = string.format([["-std=gnu++17", "-xc++", "-D__cplusplus=201703L", "--target=%s", "--sysroot=%s", %s, %s]], _G.metadata.triplet, _G.metadata.sysroot, includes_toolchain, include_flags) + f_flags = '' + -- f_flags = string.format([["-std=gnu++17", "-xc++", "-D__cplusplus=201703L", "--target=%s", "--sysroot=%s", %s, %s]], _G.metadata.triplet, _G.metadata.sysroot, includes_toolchain, include_flags) -- f_flags = string.format('"--sysroot=%s"', _G.metadata.sysroot) -- f_flags = string.format([["--sysroot=%s", %s]], _G.metadata.sysroot, include_flags) From f471940d92098361ca963b933eb9a81ead0f8452 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 23:06:53 +0300 Subject: [PATCH 1396/1406] update --- lua/platformio/boilerplate.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index d2118685..42016438 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -88,6 +88,7 @@ boilerplate['.clangd_config'] = { "--pretty", "--ranking-model=decision_forest", "--sync", + "-xc++", "-std=gnu++17", "-Wno-pragma-system-header-outside-header", "-Wno-unknown-warning-option", From efa7dc2cfb1e847697a24a13c68d3763c8d0900d Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 23:22:30 +0300 Subject: [PATCH 1397/1406] update --- lua/platformio/boilerplate.lua | 9 ++++----- lua/platformio/lspConfig/clangd.lua | 17 +++++++---------- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 42016438..2c6805d4 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -88,11 +88,6 @@ boilerplate['.clangd_config'] = { "--pretty", "--ranking-model=decision_forest", "--sync", - "-xc++", - "-std=gnu++17", - "-Wno-pragma-system-header-outside-header", - "-Wno-unknown-warning-option", - "-Wno-unused-includes" -- Equivalent to unused-includes suppression "--offset-encoding=utf-16", "--query-driver=%s" }, @@ -187,7 +182,11 @@ boilerplate['.clangd'] = { --- CompileFlags: Add: + - "-xc++" + - "-std=gnu++17" - "-Wno-pragma-system-header-outside-header" + - "-Wno-unknown-warning-option" + - "-Wno-unused-includes" Remove: - "-Wunknown-warning-option" - "-fno-tree-switch-conversion" diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/platformio/lspConfig/clangd.lua index 4bfeebba..999697e6 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/platformio/lspConfig/clangd.lua @@ -111,16 +111,13 @@ function _G.get_clangd_config() -- 2. Run your toolchain detection if _G.metadata and _G.metadata.cc_compiler and _G.metadata.cc_compiler ~= '' then if _G.metadata.triplet and _G.metadata.triplet ~= '' then - -- local include_flags = table.concat(_G.metadata.fallbackFlags, ", ") - -- local includes_toolchain = table.concat(_G.metadata.includes_toolchain, ", ") - - local include_flags = table.concat(vim.tbl_map(function(item) - return '"' .. item .. '"' - end, _G.metadata.fallbackFlags), ", ") - - local includes_toolchain = table.concat(vim.tbl_map(function(item) - return '"' .. item .. '"' - end, _G.metadata.includes_toolchain), ", ") + -- local include_flags = table.concat(vim.tbl_map(function(item) + -- return '"' .. item .. '"' + -- end, _G.metadata.fallbackFlags), ", ") + -- + -- local includes_toolchain = table.concat(vim.tbl_map(function(item) + -- return '"' .. item .. '"' + -- end, _G.metadata.includes_toolchain), ", ") f_flags = '' -- f_flags = string.format([["-std=gnu++17", "-xc++", "-D__cplusplus=201703L", "--target=%s", "--sysroot=%s", %s, %s]], _G.metadata.triplet, _G.metadata.sysroot, includes_toolchain, include_flags) From 3ccf9bd4051f1be4d509e199fbd2051b3e42e181 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 23:27:09 +0300 Subject: [PATCH 1398/1406] update --- lua/platformio/pioinit.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua/platformio/pioinit.lua b/lua/platformio/pioinit.lua index de712134..f04d5432 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/platformio/pioinit.lua @@ -10,7 +10,7 @@ local wizard_data = {} -- Visual Notifications local function notify(msg, level) - vim.notify('PIO Wizard: ' .. msg, level or vim.log.levels.INFO) + vim.notify('PIO init+db: ' .. msg, level or vim.log.levels.INFO) end -- Reusable Small Menu for Yes/No and Frameworks From 40e0510dd28b7b09f7cafd09b2400328858eeaa9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 23:37:29 +0300 Subject: [PATCH 1399/1406] update --- lua/platformio/boilerplate.lua | 57 ++-------------------------------- 1 file changed, 3 insertions(+), 54 deletions(-) diff --git a/lua/platformio/boilerplate.lua b/lua/platformio/boilerplate.lua index 2c6805d4..bf8b01ed 100644 --- a/lua/platformio/boilerplate.lua +++ b/lua/platformio/boilerplate.lua @@ -33,7 +33,7 @@ platforms_dir = ${platformio.core_dir}/platforms packages_dir = ${platformio.core_dir}/packages ;libdeps_dir = ./external_libs -default_envs = +default_envs = ;default_envs = uno, nodemcu ;-------------------------------------------------------------------------- @@ -42,7 +42,7 @@ framework = arduino upload_speed = 115200 monitor_speed = 9600 -monitor_rts = 1 ; 1 combination to reset esp32c6 (Table 32.3-2. CDC-ACM Settings with RTS and DTR) +monitor_rts = 1 ; 1 combination to reset esp32c6 (Table 32.3-2. CDC-ACM Settings with RTS and DTR) monitor_dtr = 0 ; 0 // pio dev mon --rts=0 --dtr=0 then pio dev mon --rts=1 dtr=0 extra_scripts = @@ -114,7 +114,6 @@ boilerplate['.clangd_config'] = { } } ]], - -- compilationDatabasePath = %q, } -- CompileFlags: -- Add: @@ -169,14 +168,10 @@ boilerplate['.clangd_config'] = { -- File: .clangd_index -- INFO: .clangd --- boilerplate['.clangd'] = { +-- boilerplate['.clangd'] boilerplate['.clangd'] = { rewrite = false, read = false, - -- - "-std=c++17" - -- - "-std=gnu++17" - -- - "-xc++" - -- - "-std=gnu++17" -- template = [[ content = [[ --- @@ -217,52 +212,6 @@ Diagnostics: -- end, } --- # This section targets external library files specifically ---- --- If: --- PathMatch: [.*\.platformio/packages/.*] --- CompileFlags: --- Add: --- - "-xc++" --- - "-std=c++17" --- Remove: --- - "pp_file_not_found" --- - "pp_file_not_found_angled_not_fatal" --- - "-Winclude-next-outside-header" --- - "-fno-fat-lto-objects" --- - "-fno%%-fat%%-lto%%-objects" --- - "-fno%%-canonical%%-system%%-headers" --- - "-misc-definitions-in-headers" --- - "-fno-tree-switch-conversion" --- - "-mtext-section-literals" --- - "-mlong-calls" --- - "-mlongcalls" --- - "-fstrict-volatile-bitfields" --- - "-free*" --- - "-fipa-pta*" --- - "-march=*" --- - "-mabi=*" --- - "-mcpu=*" --- Diagnostics: --- Suppress: --- - "pragma_system_header_ignored" --- - "misc-definitions-in-headers" --- - "pp_including_mainfile_in_preamble" --- - "misc-unused-using-decls" --- - "unused-includes" --- ClangTidy: --- Remove: --- - "readability-*" --- - "cert-err58-cpp" --- - "llvmlibc-*" --- - "fuchsia-*" --- - "hicpp-avoid-c-arrays" --- - "cppcoreguidelines-*" --- - "llvm-*" --- - "google-*" --- - "bugprone-*" --- - "hicpp-vararg" --- - "modernize-*" -- INFO: .clang-format boilerplate['.clang-format'] = { rewrite = false, From 95bb17c158fd57d44235dc6eaec0114fee6d07af Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 23:49:22 +0300 Subject: [PATCH 1400/1406] update --- lua/{platformio => nvimpio}/boilerplate.lua | 0 lua/{platformio => nvimpio}/init.lua | 2 +- .../lspConfig/attach.lua | 4 ++-- .../lspConfig/clangd.lua | 4 ++-- .../lspConfig/keymaps.lua | 0 .../lspConfig/tools.lua | 0 lua/{platformio => nvimpio}/pio/metadata.lua | 2 +- lua/{platformio => nvimpio}/pio/upkeep.lua | 18 +++++++++--------- lua/{platformio => nvimpio}/pio/watcher.lua | 10 +++++----- lua/{platformio => nvimpio}/pioCommands.lua | 6 +++--- lua/{platformio => nvimpio}/pioinit.lua | 2 +- lua/{platformio => nvimpio}/piolib.lua | 6 +++--- lua/{platformio => nvimpio}/piolsserial.lua | 2 +- lua/{platformio => nvimpio}/utils/misc.lua | 0 lua/{platformio => nvimpio}/utils/term.lua | 0 plugin/{platformio.lua => nvimpio.lua} | 0 16 files changed, 28 insertions(+), 28 deletions(-) rename lua/{platformio => nvimpio}/boilerplate.lua (100%) rename lua/{platformio => nvimpio}/init.lua (99%) rename lua/{platformio => nvimpio}/lspConfig/attach.lua (95%) rename lua/{platformio => nvimpio}/lspConfig/clangd.lua (95%) rename lua/{platformio => nvimpio}/lspConfig/keymaps.lua (100%) rename lua/{platformio => nvimpio}/lspConfig/tools.lua (100%) rename lua/{platformio => nvimpio}/pio/metadata.lua (95%) rename lua/{platformio => nvimpio}/pio/upkeep.lua (95%) rename lua/{platformio => nvimpio}/pio/watcher.lua (94%) rename lua/{platformio => nvimpio}/pioCommands.lua (90%) rename lua/{platformio => nvimpio}/pioinit.lua (95%) rename lua/{platformio => nvimpio}/piolib.lua (97%) rename lua/{platformio => nvimpio}/piolsserial.lua (95%) rename lua/{platformio => nvimpio}/utils/misc.lua (100%) rename lua/{platformio => nvimpio}/utils/term.lua (100%) rename plugin/{platformio.lua => nvimpio.lua} (100%) diff --git a/lua/platformio/boilerplate.lua b/lua/nvimpio/boilerplate.lua similarity index 100% rename from lua/platformio/boilerplate.lua rename to lua/nvimpio/boilerplate.lua diff --git a/lua/platformio/init.lua b/lua/nvimpio/init.lua similarity index 99% rename from lua/platformio/init.lua rename to lua/nvimpio/init.lua index 4a18352e..e06c0eb1 100644 --- a/lua/platformio/init.lua +++ b/lua/nvimpio/init.lua @@ -226,7 +226,7 @@ function M.setup(user_config) M.piomenu(M.config) vim.schedule(function() - require('platformio.pio.watcher').init() + require('nvimpio.pio.watcher').init() end) end diff --git a/lua/platformio/lspConfig/attach.lua b/lua/nvimpio/lspConfig/attach.lua similarity index 95% rename from lua/platformio/lspConfig/attach.lua rename to lua/nvimpio/lspConfig/attach.lua index b2f7e76f..361a24a3 100644 --- a/lua/platformio/lspConfig/attach.lua +++ b/lua/nvimpio/lspConfig/attach.lua @@ -1,4 +1,4 @@ --- local piolsp = require('platformio.piolsp') --.piolsp +-- local piolsp = require('nvimpio.piolsp') --.piolsp -- INFO: LspAttach autocommand start vim.api.nvim_create_autocmd('LspAttach', { group = vim.api.nvim_create_augroup('platformio-lsp-attach', { clear = true }), @@ -93,7 +93,7 @@ vim.api.nvim_create_autocmd('LspAttach', { ------------------------------------------------------------------ local config = require('platformio').config if config.lspClangd.attach.keymaps then - local lspkeymaps = require('platformio.lspConfig.keymaps') + local lspkeymaps = require('nvimpio.lspConfig.keymaps') lspkeymaps.lspKeymaps(client, bufnr) end end diff --git a/lua/platformio/lspConfig/clangd.lua b/lua/nvimpio/lspConfig/clangd.lua similarity index 95% rename from lua/platformio/lspConfig/clangd.lua rename to lua/nvimpio/lspConfig/clangd.lua index 999697e6..9c167fad 100644 --- a/lua/platformio/lspConfig/clangd.lua +++ b/lua/nvimpio/lspConfig/clangd.lua @@ -1,4 +1,4 @@ -local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen +local boilerplate_gen = require('nvimpio.boilerplate').boilerplate_gen local ok, result ok, result = pcall(require, 'fidget') if ok then @@ -273,5 +273,5 @@ local pyrefly = { vim.lsp.config('pyrefly', pyrefly) -- restart lsp --- require('platformio.lspConfig.tools').lsp_restart('clangd') +-- require('nvimpio.lspConfig.tools').lsp_restart('clangd') ---------------------------------------------------------------------------------- diff --git a/lua/platformio/lspConfig/keymaps.lua b/lua/nvimpio/lspConfig/keymaps.lua similarity index 100% rename from lua/platformio/lspConfig/keymaps.lua rename to lua/nvimpio/lspConfig/keymaps.lua diff --git a/lua/platformio/lspConfig/tools.lua b/lua/nvimpio/lspConfig/tools.lua similarity index 100% rename from lua/platformio/lspConfig/tools.lua rename to lua/nvimpio/lspConfig/tools.lua diff --git a/lua/platformio/pio/metadata.lua b/lua/nvimpio/pio/metadata.lua similarity index 95% rename from lua/platformio/pio/metadata.lua rename to lua/nvimpio/pio/metadata.lua index 7b68ba93..a2526e5a 100644 --- a/lua/platformio/pio/metadata.lua +++ b/lua/nvimpio/pio/metadata.lua @@ -63,7 +63,7 @@ _G.metadata = setmetatable({}, { -- -- dbFix() -- _pio_metadata.dbTrigger = false -- else - -- local LspRestart = require('platformio.lspConfigConfig.tools').lsp_restart + -- local LspRestart = require('nvimpio.lspConfigConfig.tools').lsp_restart -- LspRestart('clangd') -- vim.notify('Env: LspRestart', vim.log.levels.INFO, { title = 'PlatformIO', render = 'compact' }) -- end diff --git a/lua/platformio/pio/upkeep.lua b/lua/nvimpio/pio/upkeep.lua similarity index 95% rename from lua/platformio/pio/upkeep.lua rename to lua/nvimpio/pio/upkeep.lua index e8c99449..12713916 100644 --- a/lua/platformio/pio/upkeep.lua +++ b/lua/nvimpio/pio/upkeep.lua @@ -9,8 +9,8 @@ M.selected_framework = '' M.is_processing = false M.queue = {} -local term = require('platformio.utils.term') -local clangdRestart = require('platformio.lspConfig.tools').clangdRestart +local term = require('nvimpio.utils.term') +local clangdRestart = require('nvimpio.lspConfig.tools').clangdRestart -- INFO: -- ============================================================================= @@ -218,7 +218,7 @@ function M.fetch_metadata(callback, env, from, attempts) -- vim.misc.writeFile(file, formated, {}) if cok and apply_metadata(decoded, current_checksum) then - local metadata = require('platformio.pio.metadata') + local metadata = require('nvimpio.pio.metadata') metadata.save_project_config(msg) vim.notify(msg .. 'Metadata synced from cache', vim.log.levels.INFO) -- if callback then vim.schedule(callback) end @@ -523,7 +523,7 @@ local win_id -- stylua: ignore function M.handlePioinitDb(result) if result == 'INIT' then - local boilerplate = require('platformio.boilerplate') + local boilerplate = require('nvimpio.boilerplate') local boilerplate_gen = boilerplate.boilerplate_gen boilerplate.core_dir = _G.metadata.core_dir @@ -549,9 +549,9 @@ function M.handlePioinitDb(result) vim.notify('PIO init+db: pass ' .. commandPassed, vim.log.levels.INFO) vim.notify('PIO init+db: Done', vim.log.levels.INFO) vim.misc.gitignore_lsp_configs('compile_commands.json') - local pio_refresh = require('platformio.pio.watcher').pio_refresh + local pio_refresh = require('nvimpio.pio.watcher').pio_refresh pio_refresh(function() - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + local boilerplate_gen = require('nvimpio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], _G.metadata.core_dir) vim.misc.closeMessage(win_id) clangdRestart() @@ -578,7 +578,7 @@ end -- stylua: ignore function M.handlePioinit(result) if result == 'INIT' then - local boilerplate = require('platformio.boilerplate') + local boilerplate = require('nvimpio.boilerplate') local boilerplate_gen = boilerplate.boilerplate_gen boilerplate.core_dir = _G.metadata.core_dir @@ -611,9 +611,9 @@ function M.handlePioinit(result) -- local clean_msg = string.format('\27[G\27[2K\27[33m%s\27[0m', msg) -- vim.api.nvim_chan_send(trm.job_id, clean_msg) - local pio_refresh = require('platformio.pio.watcher').pio_refresh + local pio_refresh = require('nvimpio.pio.watcher').pio_refresh pio_refresh(function() - local boilerplate_gen = require('platformio.boilerplate').boilerplate_gen + local boilerplate_gen = require('nvimpio.boilerplate').boilerplate_gen boilerplate_gen([[.clangd]], _G.metadata.core_dir) vim.misc.closeMessage(win_id) clangdRestart() diff --git a/lua/platformio/pio/watcher.lua b/lua/nvimpio/pio/watcher.lua similarity index 94% rename from lua/platformio/pio/watcher.lua rename to lua/nvimpio/pio/watcher.lua index 9bc7a6a9..ee80e47d 100644 --- a/lua/platformio/pio/watcher.lua +++ b/lua/nvimpio/pio/watcher.lua @@ -1,7 +1,7 @@ M = {} -local clangdRestart = require('platformio.lspConfig.tools').clangdRestart -local boilerplate = require('platformio.boilerplate') +local clangdRestart = require('nvimpio.lspConfig.tools').clangdRestart +local boilerplate = require('nvimpio.boilerplate') local boilerplate_gen = boilerplate.boilerplate_gen -- ============================================================================= @@ -267,12 +267,12 @@ function M.init() vim.notify('PIO start: initialize', vim.log.levels.INFO) -- activate meta save and upload and env switch - local metadata = require('platformio.pio.metadata') + local metadata = require('nvimpio.pio.metadata') metadata.load_project_config() - require('platformio.lspConfig.clangd') + require('nvimpio.lspConfig.clangd') if config.lspClangd.attach.enabled then - require('platformio.lspConfig.attach') + require('nvimpio.lspConfig.attach') end -- Always start the watcher so it can catch a future 'pio init' diff --git a/lua/platformio/pioCommands.lua b/lua/nvimpio/pioCommands.lua similarity index 90% rename from lua/platformio/pioCommands.lua rename to lua/nvimpio/pioCommands.lua index 0ac1a150..835b715f 100644 --- a/lua/platformio/pioCommands.lua +++ b/lua/nvimpio/pioCommands.lua @@ -1,14 +1,14 @@ local M = {} --- local misc = require('platformio.utils.misc') -local ToggleTerminal = require('platformio.utils.term').ToggleTerminal +-- local misc = require('nvimpio.utils.misc') +local ToggleTerminal = require('nvimpio.utils.term').ToggleTerminal local misc = vim.misc -- stylua: ignore --INFO: PioLSP ------------------------------------------------------ function M.piolsp() - require('platformio.lspConfig.tools').clangdRestart() + require('nvimpio.lspConfig.tools').clangdRestart() end -- stylua: ignore diff --git a/lua/platformio/pioinit.lua b/lua/nvimpio/pioinit.lua similarity index 95% rename from lua/platformio/pioinit.lua rename to lua/nvimpio/pioinit.lua index f04d5432..f399709b 100644 --- a/lua/platformio/pioinit.lua +++ b/lua/nvimpio/pioinit.lua @@ -42,7 +42,7 @@ end -- FINAL STEP: Construction & Sequence Execution local function finalize_setup() - local pio = require('platformio.pio.upkeep') + local pio = require('nvimpio.pio.upkeep') local sample_flag = wizard_data.sample == 'Yes' and ' --sample-code' or '' local init_cmd = string.format('pio project init --ide vim --board %s -O "framework=%s"%s', wizard_data.board_id, wizard_data.framework, sample_flag) diff --git a/lua/platformio/piolib.lua b/lua/nvimpio/piolib.lua similarity index 97% rename from lua/platformio/piolib.lua rename to lua/nvimpio/piolib.lua index 9b7c34b2..e7b4c8ae 100644 --- a/lua/platformio/piolib.lua +++ b/lua/nvimpio/piolib.lua @@ -8,7 +8,7 @@ local make_entry = require('telescope.make_entry') local conf = require('telescope.config').values local actions = require('telescope.actions') local action_state = require('telescope.actions.state') -local misc = require('platformio.utils.misc') +local misc = require('nvimpio.utils.misc') local previewers = require('telescope.previewers') local libentry_maker = function(opts) @@ -64,7 +64,7 @@ local function pick_library(json_data) -- local command = 'pio pkg install --library "' .. pkg_name .. '"' -- command = command .. ' && pio run -t compiledb' - local pio = require('platformio.pio.upkeep') + local pio = require('nvimpio.pio.upkeep') pio.run_sequence({ cmnds = {'pio pkg install --library "' .. pkg_name .. '"'}, cb = pio.handlePiolib @@ -138,7 +138,7 @@ end -- local selection = action_state.get_selected_entry() -- local pkg_name = selection['value']['owner'] .. '/' .. selection['value']['name'] -- --- local pio = require('platformio.utils.pio') +-- local pio = require('nvimpio.utils.pio') -- pio.run_sequence({ -- cmnds = {'pio pkg install --library "' .. pkg_name .. '"'}, -- cb = function () vim.notify('Piolib: Done', vim.log.levels.INFO) end diff --git a/lua/platformio/piolsserial.lua b/lua/nvimpio/piolsserial.lua similarity index 95% rename from lua/platformio/piolsserial.lua rename to lua/nvimpio/piolsserial.lua index afc04a4b..29b01b40 100644 --- a/lua/platformio/piolsserial.lua +++ b/lua/nvimpio/piolsserial.lua @@ -1,5 +1,5 @@ local M = {} -local misc = require('platformio.utils.misc') +local misc = require('nvimpio.utils.misc') M.tty_list = {} diff --git a/lua/platformio/utils/misc.lua b/lua/nvimpio/utils/misc.lua similarity index 100% rename from lua/platformio/utils/misc.lua rename to lua/nvimpio/utils/misc.lua diff --git a/lua/platformio/utils/term.lua b/lua/nvimpio/utils/term.lua similarity index 100% rename from lua/platformio/utils/term.lua rename to lua/nvimpio/utils/term.lua diff --git a/plugin/platformio.lua b/plugin/nvimpio.lua similarity index 100% rename from plugin/platformio.lua rename to plugin/nvimpio.lua From 765cf88b7d8a778c2bb7353ad2d63d00ed175226 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 23:51:36 +0300 Subject: [PATCH 1401/1406] update --- plugin/nvimpio.lua | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/plugin/nvimpio.lua b/plugin/nvimpio.lua index c03ec85e..70422084 100644 --- a/plugin/nvimpio.lua +++ b/plugin/nvimpio.lua @@ -13,13 +13,13 @@ -- __index = function(t, k) -- -- Lazy load the misc module if requested -- if k == 'misc' then --- t.misc = require('platformio.utils.misc') +-- t.misc = require('nvimpio.utils.misc') -- return t.misc -- end -- -- -- Alias vim.pio to the pio module for convenience -- if k == 'pio' then --- t.pio = require('platformio.utils.pio') +-- t.pio = require('nvimpio.utils.pio') -- return t.pio -- end -- end, @@ -32,19 +32,19 @@ -- setmetatable(vim, { -- __index = function(t, k) -- if k == 'misc' then --- local m = require('platformio.utils.misc') +-- local m = require('nvimpio.utils.misc') -- rawset(t, k, m) -- Physically add 'misc' to 'vim' -- return m -- end -- if k == 'pio' then --- local p = require('platformio.utils.pio') +-- local p = require('nvimpio.utils.pio') -- rawset(t, k, p) -- Physically add 'pio' to 'vim' -- return p -- end -- end, -- }) -vim.misc = require('platformio.utils.misc') -vim.pio = require('platformio.pio.upkeep') +vim.misc = require('nvimpio.utils.misc') +vim.pio = require('nvimpio.pio.upkeep') -- INFO: fix paths in compile_commands.json vim.api.nvim_create_user_command('PioFixPaths', function() @@ -52,7 +52,7 @@ vim.api.nvim_create_user_command('PioFixPaths', function() end, {}) -- -- Pioinit2 --- local pio_wiz = require('platformio.pioinit2') +-- local pio_wiz = require('nvimpio.pioinit2') -- -- -- Create a keybinding to trigger the wizard -- vim.keymap.set('n', 'pi', function() @@ -65,24 +65,24 @@ end, {}) -- end, {}) -- ------------------------------------------------------ -local piolsserial = require('platformio.piolsserial') +local piolsserial = require('nvimpio.piolsserial') -- Pioinit vim.api.nvim_create_user_command('Pioinit', function() - require('platformio.pioinit').pioinit() + require('nvimpio.pioinit').pioinit() end, { force = true }) -- Piolsp vim.api.nvim_create_user_command('PioLSP', function() vim.schedule(function() - require('platformio.pioCommands').piolsp() + require('nvimpio.pioCommands').piolsp() end) end, {}) -- Piorun vim.api.nvim_create_user_command('Piorun', function(opts) local args = opts.args - require('platformio.piocommands').piorun({ args }) + require('nvimpio.piocommands').piorun({ args }) end, { nargs = '?', complete = function(_, _, _) @@ -94,7 +94,7 @@ end, { -- piolsserial.sync_ttylist() vim.api.nvim_create_user_command('Piomon', function(opts) local args = opts.fargs - require('platformio.pioCommands').piomon(args) + require('nvimpio.pioCommands').piomon(args) end, { nargs = '*', @@ -117,13 +117,13 @@ end, { -- Piolsserial vim.api.nvim_create_user_command('Piolsserial', function() - require('platformio.piolsserial').print_tty_list() + require('nvimpio.piolsserial').print_tty_list() end, {}) -- Piolib vim.api.nvim_create_user_command('Piolib', function(opts) local args = vim.split(opts.args, ' ') - require('platformio.piolib').piolib(args) + require('nvimpio.piolib').piolib(args) end, { nargs = '+', }) @@ -131,7 +131,7 @@ end, { -- Piocmdh Piocmd horizontal terminal vim.api.nvim_create_user_command('Piocmdh', function(opts) local cmd_table = vim.split(opts.args, ' ') - require('platformio.pioCommands').piocmd(cmd_table, 'horizontal') + require('nvimpio.pioCommands').piocmd(cmd_table, 'horizontal') end, { nargs = '*', }) @@ -139,14 +139,14 @@ end, { -- Piocmdf Piocmd float terminal vim.api.nvim_create_user_command('Piocmdf', function(opts) local cmd_table = vim.split(opts.args, ' ') - require('platformio.pioCommands').piocmd(cmd_table, 'float') + require('nvimpio.pioCommands').piocmd(cmd_table, 'float') end, { nargs = '*', }) -- Piodebug vim.api.nvim_create_user_command('Piodebug', function() - require('platformio.pioCommands').piodebug() + require('nvimpio.pioCommands').piodebug() end, {}) ------------------------------------------------------ From 60a49791da3cc1399018f90a1282619a5df51f70 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sat, 2 May 2026 23:54:35 +0300 Subject: [PATCH 1402/1406] update --- lua/nvimpio/lspConfig/attach.lua | 2 +- lua/nvimpio/pio/watcher.lua | 2 +- lua/nvimpio/utils/term.lua | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/nvimpio/lspConfig/attach.lua b/lua/nvimpio/lspConfig/attach.lua index 361a24a3..4cc87a84 100644 --- a/lua/nvimpio/lspConfig/attach.lua +++ b/lua/nvimpio/lspConfig/attach.lua @@ -91,7 +91,7 @@ vim.api.nvim_create_autocmd('LspAttach', { end ------------------------------------------------------------------ - local config = require('platformio').config + local config = require('nvimpio').config if config.lspClangd.attach.keymaps then local lspkeymaps = require('nvimpio.lspConfig.keymaps') lspkeymaps.lspKeymaps(client, bufnr) diff --git a/lua/nvimpio/pio/watcher.lua b/lua/nvimpio/pio/watcher.lua index ee80e47d..a90dbd50 100644 --- a/lua/nvimpio/pio/watcher.lua +++ b/lua/nvimpio/pio/watcher.lua @@ -262,7 +262,7 @@ end --stylua: ignore --============================================================================= function M.init() - local config = require('platformio').config + local config = require('nvimpio').config if config.lspClangd.enabled == true then vim.notify('PIO start: initialize', vim.log.levels.INFO) diff --git a/lua/nvimpio/utils/term.lua b/lua/nvimpio/utils/term.lua index c8cb46c3..c62c9f59 100644 --- a/lua/nvimpio/utils/term.lua +++ b/lua/nvimpio/utils/term.lua @@ -5,7 +5,7 @@ M.devNul = is_windows and ' 2>./nul' or ' 2>/dev/null' -- M.extra = 'printf \'\\\\n\\\\033[0;33mPlease Press ENTER to continue \\\\033[0m\'; read' -- M.extra = ' && echo . && echo . && echo Please Press ENTER to continue' -local config = require('platformio').config +local config = require('nvimpio').config -- to fix require loop, toggleterm is using stdout_callback function in 'platformio.utils.pio' -- M.stdout_callback will be assigned by 'platformio.utils.pio' From 6be0fdfb9ab190403defd657de1722293a9744c9 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 3 May 2026 00:07:17 +0300 Subject: [PATCH 1403/1406] update --- lua/nvimpio/pioinit.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lua/nvimpio/pioinit.lua b/lua/nvimpio/pioinit.lua index f399709b..76896134 100644 --- a/lua/nvimpio/pioinit.lua +++ b/lua/nvimpio/pioinit.lua @@ -5,6 +5,7 @@ local action_state = require('telescope.actions.state') local previewers = require('telescope.previewers') local telescope_conf = require('telescope.config').values local themes = require('telescope.themes') +local pio = require('nvimpio.pio.upkeep') local wizard_data = {} @@ -42,7 +43,7 @@ end -- FINAL STEP: Construction & Sequence Execution local function finalize_setup() - local pio = require('nvimpio.pio.upkeep') + -- local pio = require('nvimpio.pio.upkeep') local sample_flag = wizard_data.sample == 'Yes' and ' --sample-code' or '' local init_cmd = string.format('pio project init --ide vim --board %s -O "framework=%s"%s', wizard_data.board_id, wizard_data.framework, sample_flag) From 3955695a9fbfa54c1d96443aa7e9d8be1c1b34c0 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Sun, 3 May 2026 00:19:18 +0300 Subject: [PATCH 1404/1406] update --- mini_nvimPIO.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mini_nvimPIO.lua b/mini_nvimPIO.lua index a67f3e08..243bedee 100644 --- a/mini_nvimPIO.lua +++ b/mini_nvimPIO.lua @@ -622,8 +622,8 @@ local pioConfig = { -- menu_name = "PlatformIO", -- replace this menu name to your convenience -- debug = false, } -local pok, platformio = pcall(require, 'platformio') +local pok, nvimpio = pcall(require, 'nvimpio') if pok then -- print("here" .. vim.inspect(pioConfig)) - platformio.setup(pioConfig) + nvimpio.setup(pioConfig) end From 884cffa7028aea40f7bc390237b9296e39f2c573 Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 7 May 2026 16:40:11 +0300 Subject: [PATCH 1405/1406] update --- lua/nvimpio/pio/upkeep.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/nvimpio/pio/upkeep.lua b/lua/nvimpio/pio/upkeep.lua index 12713916..8490be01 100644 --- a/lua/nvimpio/pio/upkeep.lua +++ b/lua/nvimpio/pio/upkeep.lua @@ -509,6 +509,7 @@ M.run_sequence = function(tasks) callBack = tasks.cb -- 1. Save the callback in a local variable commandPassed = 1 + require('nvimpio.pio.metadata') _G.metadata.isBusy = true term.stdout_callback = M.stdoutcallback From a69d3c7ef264e893f2caa287eb8eb516da4200dd Mon Sep 17 00:00:00 2001 From: batoaqaa Date: Thu, 7 May 2026 16:44:29 +0300 Subject: [PATCH 1406/1406] update --- lua/nvimpio/init.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/lua/nvimpio/init.lua b/lua/nvimpio/init.lua index e06c0eb1..2ad90702 100644 --- a/lua/nvimpio/init.lua +++ b/lua/nvimpio/init.lua @@ -225,6 +225,7 @@ function M.setup(user_config) M.piomenu(M.config) + vim.g.platformioRootDir = vim.uv.cwd() vim.schedule(function() require('nvimpio.pio.watcher').init() end)