diff --git a/lua/jsonfly/utils.lua b/lua/jsonfly/utils.lua index 5256498..e121fbb 100644 --- a/lua/jsonfly/utils.lua +++ b/lua/jsonfly/utils.lua @@ -205,4 +205,10 @@ function M:extract_key_description(text) return keys end +---@param name string +---@return boolean +function M:is_module_available(name) + return pcall(function() require(name) end) == true +end + return M diff --git a/lua/telescope/_extensions/jsonfly.lua b/lua/telescope/_extensions/jsonfly.lua index 089484b..56c8e82 100644 --- a/lua/telescope/_extensions/jsonfly.lua +++ b/lua/telescope/_extensions/jsonfly.lua @@ -17,6 +17,7 @@ -- ---@class Commands ---@field add_key string[] - Add the currently entered key to the JSON. Must be of type [string, string] ; Example: {"n", "a"} -> When in normal mode, press "a" to add the key; Example: {"i", ""} -> When in insert mode, press to add the key; Default: {"i", ""} +---@field copy_jsonpath [string, string, function] - Copy the JSONPath of the currently selected key. jsonpath must be installed. Must be of type [string, string, function] void> - Example: {"n", "", function(path) vim.fn.setreg("+", path) end} -> When in normal mode, press to copy the JSONPath to the clipboard; Default: {"i", "", a function that will copy the JSONPath to the clipboard} --- ---@class Highlights ---@field number string - Highlight group for numbers, Default: "@number.json" @@ -60,7 +61,16 @@ local DEFAULT_CONFIG = { backend = "lsp", use_cache = 500, commands = { - add_key = {"i", ""} + add_key = {"i", ""}, + copy_jsonpath = { + "i", + "", + ---@param path string + ---@param prompt_bufnr number + function(path, prompt_bufnr) + vim.fn.setreg("+", path) + end + } } } @@ -105,6 +115,31 @@ local function show_picker(entries, buffer, xopts) end ) + if global_config.commands.copy_jsonpath and utils:is_module_available("jsonpath") then + map( + global_config.commands.copy_jsonpath[1], + global_config.commands.copy_jsonpath[2], + function(prompt_bufnr) + local jsonpath = require("jsonpath") + + local current_picker = action_state.get_current_picker(prompt_bufnr) + local selection = current_picker:get_selection() + + local path = jsonpath.get(vim.treesitter.get_node({ + bufnr = buffer, + pos = { + selection.lnum - 1, + selection.index, + } + }), buffer) + + if path then + global_config.commands.copy_jsonpath[3](path, prompt_bufnr) + end + end + ) + end + return true end, finder = finders.new_table {