Skip to content

Commit

Permalink
feat: Add support for jsonpath
Browse files Browse the repository at this point in the history
  • Loading branch information
Myzel394 committed Jul 11, 2024
1 parent 4d22028 commit 5b11ed0
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
6 changes: 6 additions & 0 deletions lua/jsonfly/utils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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
37 changes: 36 additions & 1 deletion lua/telescope/_extensions/jsonfly.lua
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
--
---@class Commands
---@field add_key string[] - Add the currently entered key to the JSON. Must be of type [string, string] <mode, key>; Example: {"n", "a"} -> When in normal mode, press "a" to add the key; Example: {"i", "<C-a>"} -> When in insert mode, press <C-a> to add the key; Default: {"i", "<C-a>"}
---@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] <mode, key, (path: string, bufnr: number) -> void> - Example: {"n", "<C-j>", function(path) vim.fn.setreg("+", path) end} -> When in normal mode, press <C-j> to copy the JSONPath to the clipboard; Default: {"i", "<C-j>", a function that will copy the JSONPath to the clipboard}
---
---@class Highlights
---@field number string - Highlight group for numbers, Default: "@number.json"
Expand Down Expand Up @@ -60,7 +61,16 @@ local DEFAULT_CONFIG = {
backend = "lsp",
use_cache = 500,
commands = {
add_key = {"i", "<C-a>"}
add_key = {"i", "<C-a>"},
copy_jsonpath = {
"i",
"<C-j>",
---@param path string
---@param prompt_bufnr number
function(path, prompt_bufnr)
vim.fn.setreg("+", path)
end
}
}
}

Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit 5b11ed0

Please sign in to comment.