Neovim opening GitHub repos URLs
I have a very useful mapping in my Neovim: gx
, which opens the URL under the
cursor in the browser. I even wrote a blog post on it: Neovim Opening URLs
This blog post is a bit outdated,especially with the newly introduced way of
setting up mappings through vim.keymap.set
, but still works like a charm.
But there was one missing thing - open GitHub repos of Neovim plugins. For example, when you’re browsing your Packer configuration, plugins looks like this:
use {
"nvim-telescope/telescope.nvim",
requires = {
{ "nvim-lua/popup.nvim" },
{ "nvim-lua/plenary.nvim" },
{ "nvim-telescope/telescope-github.nvim" },
{ "kosayoda/nvim-lightbulb" },
{ "antoinemadec/FixCursorHold.nvim" }
}
}
I’ve refactored my old solution to do this:
local function url_repo()
local cursorword = vim.fn.expand "<cfile>"
if string.find(cursorword, "^[a-zA-Z0-9.-_]*/[a-zA-Z0-9.-_]*$") then
cursorword = "https://github.com/" .. cursorword
end
return cursorword or ""
end
local open_command = "xdg-open"
if vim.fn.has "mac" == 1 then
open_command = "open"
end
vim.keymap.set("n", "gx", function()
vim.fn.jobstart({ open_command, url_repo() }, { detach = true })
end, attach_opts)
Here’s the logic:
- Set the command to open URL based on the OS
- Get the word under the cursor(
:h expand
) - Check if the work looks like
<github_user/reponame>
- If yes, add
https://github.com/
to the word under the cursor - Set keymap to open the link through the
vim.fn.jobstart
Overall, I’m pretty happy with how it works:
Comments