Skip to content

Instantly share code, notes, and snippets.

@LaptopDev
Created July 23, 2025 03:58
Show Gist options
  • Save LaptopDev/57894187941fba1936ef3309de5b37df to your computer and use it in GitHub Desktop.
Save LaptopDev/57894187941fba1936ef3309de5b37df to your computer and use it in GitHub Desktop.
Open URL/File under cursor in normal mode w/o selection - Neovim
local function trim_edges(s)
return (s or ""):gsub("^%s+", ""):gsub("%s+$", "")
:gsub('^[\'"()<>%[%],]+', ""):gsub('[\'"()<>%[%],]+$', "")
end
local function stat(p) return vim.loop.fs_stat(p) end
function OpenThing()
local candidates = {
vim.fn.expand("<cfile>"),
vim.fn.expand("<cWORD>"),
}
for _, raw in ipairs(candidates) do
local text = trim_edges(raw or "")
if text ~= "" then
-- URL?
local url = text:match("https?://[^%s>%\"')]+")
if url then
vim.fn.jobstart({ "xdg-open", url }, { detach = true })
return
end
-- file[:ln[:col]]
local file, ln, col = text:match("^([^:]+):?(%d*):?(%d*)$")
file = trim_edges(file)
if file ~= "" and stat(file) then
vim.cmd("edit " .. vim.fn.fnameescape(file))
if ln ~= "" then
vim.api.nvim_win_set_cursor(0, { tonumber(ln), (tonumber(col) or 1) - 1 })
end
return
end
end
end
vim.notify("No URL or file under cursor", vim.log.levels.INFO)
end
vim.keymap.set("n", "<Leader>o", OpenThing, { noremap = true, silent = true, desc = "Open URL/file under cursor" })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment