sontungexpt/url-open

github github
utility
stars 109
issues 1
subscribers 2
forks 12
CREATED

UPDATED


url-open

Open URLs and local paths from Neovim without netrw. Put the cursor on a link and press gx (or a mapping of your own). url-open hands the link to vim.ui.open, so your system's default handler does the rest.

Easy to use, easy to configure, easy to extend.

Preview

Detect & highlight Open under cursor
preview1 preview2

https://github.com/user-attachments/assets/f57a29f2-2f32-4250-869a-de24b4311aad

Features

  • 🔗 Highlights as you type — see what the cursor would open before you press the key
  • 🌐 Deep URL detection — schemes, <...> autolinks, Markdown links, and nested parentheses in any file
  • 📦 Package-aware — GitHub, npm, Homebrew, Cargo, RubyGems, Docker, PyPI, Go, Composer, NuGet, Java, Kotlin, and Nix flake refs/packages
  • 📁 Local paths — ~/file, absolute, Windows drive/UNC, env-var, and relative paths
  • 🎯 Cursor control — exact match or the familiar next-link-on-the-row behavior
  • ⌨️ Native gx — created by default; disable it and bind your own if you prefer
  • 🧩 Custom parsers — add your own ticket, issue, or docs links in one table entry
  • ⚡ Lazy by design — parser modules are loaded only when they are needed

Requirements

  • Neovim >= 0.10

Installation

-- lazy.nvim
{
    "sontungexpt/url-open",
    event = "VeryLazy",
    opts = {},         -- passed to require("url-open").setup()
}
-- vim.pack (Neovim 0.12+)
-- Note: unlike lazy.nvim, vim.pack does not call setup() for you.
vim.pack.add({
    { src = "https://github.com/sontungexpt/url-open" },
})
require("url-open").setup({})

No configuration is required — opts = {} enables all built-in parsers and creates a native gx mapping. You can also call open_url_under_cursor() directly.

Setup

The smallest working config:

require("url-open").setup({})

Press gx on a highlighted link to open it. See Native keymap if you want to replace the mapping.

Default config

The complete defaults are below. You do not need to copy this table — include only the keys you want to change. matches_buffer_name is an internal helper, shown here to document the real file gates.

require("url-open").setup({
    -- When true, a link opens only if the cursor is directly on it.
    -- When false, the cursor picks the link under it, then the next one
    -- to the right, then the last one on the row.
    exact_cursor_match = false,

    -- Create a native `gx` keymap that opens the link under the cursor.
    -- Enabled by default; set to `false` if you prefer your own mapping.
    native_mapping = true,

    -- Highlight groups. Both are defined with `default = true`, so your
    -- colorscheme wins. Set `enabled = false` to hide that style.
    highlight = {
        link   = { enabled = true, hl_group = "UrlOpenLink" },
        active = { enabled = true, hl_group = "UrlOpenLinkActive" },
    },

    -- Buffers where detection and highlighting are skipped.
    excluded = {
        filetypes = { "NvimTree", "neo-tree", "oil", "TelescopePrompt", "notify" },
        buftypes  = { "terminal", "prompt" },
        buffer = nil, -- or function(bufnr) return true end to skip a buffer
    },

    -- Built-in parsers. All are enabled by default.
    parsers = {
        -- Any file: schemes, autolinks, Markdown links
        urls = {
            path = "url-open.parsers.urls",
            enabled = true,
            priority = 1,
        },

        -- Any file: local filesystem paths
        path = {
            path = "url-open.parsers.path",
            enabled = true,
            priority = 2,
        },

        -- Neovim / Zsh config folders and any .zshrc
        github = {
            path = "url-open.parsers.github",
            enabled = function(bufnr)
                -- Escape magic characters and accept either slash style.
                local function path_pattern(path)
                    return (vim.pesc(path):gsub("[/\\]", "[/\\]"))
                end

                local home = vim.trim(vim.env.HOME or vim.env.USERPROFILE or "")
                local xdg = vim.trim(vim.env.XDG_CONFIG_HOME or (home ~= "" and home .. "/.config" or ""))
                local zsh = vim.trim(vim.env.ZDOTDIR or (xdg ~= "" and xdg .. "/zsh" or ""))
                local localdata = vim.trim(vim.env.LOCALAPPDATA or (home ~= "" and home .. "/AppData/Local" or ""))

                local patterns = {
                    -- Any file named `.zshrc`: $HOME, $ZDOTDIR, symlink targets, dotfiles repos.
                    "[/\\]%.zshrc$",
                }

                if xdg ~= "" then
                    patterns[#patterns + 1] = "^" .. path_pattern(xdg) .. "[/\\]nvim[/\\]"
                end
                if localdata ~= "" then
                    patterns[#patterns + 1] = "^" .. path_pattern(localdata) .. "[/\\]nvim[/\\]"
                end
                if zsh ~= "" then
                    patterns[#patterns + 1] = "^" .. path_pattern(zsh) .. "[/\\]"
                end

                return matches_buffer_name(bufnr, patterns)
            end,
            priority = 3,
        },

        npm = {
            path = "url-open.parsers.npm",
            enabled = function(bufnr) return matches_buffer_name(bufnr, "package%.json$") end,
            priority = 4,
        },

        brew = {
            path = "url-open.parsers.brew",
            enabled = function(bufnr) return matches_buffer_name(bufnr, "Brewfile$") end,
            priority = 5,
        },

        cargo = {
            path = "url-open.parsers.cargo",
            enabled = function(bufnr) return matches_buffer_name(bufnr, "Cargo%.toml$") end,
            priority = 6,
        },

        rubygems = {
            path = "url-open.parsers.rubygems",
            enabled = function(bufnr)
                return matches_buffer_name(bufnr, { "Gemfile$", "gems%.rb$" })
            end,
            priority = 7,
        },

        docker = {
            path = "url-open.parsers.docker",
            enabled = function(bufnr)
                return matches_buffer_name(bufnr, { "Dockerfile$", "Containerfile$" })
            end,
            priority = 8,
        },

        pypi = {
            path = "url-open.parsers.pypi",
            enabled = function(bufnr)
                return matches_buffer_name(bufnr, { "requirements.*%.txt$", "pyproject%.toml$", "Pipfile$" })
            end,
            priority = 9,
        },

        go = {
            path = "url-open.parsers.go",
            enabled = function(bufnr) return matches_buffer_name(bufnr, "go%.mod$") end,
            priority = 10,
        },

        composer = {
            path = "url-open.parsers.composer",
            enabled = function(bufnr) return matches_buffer_name(bufnr, "composer%.json$") end,
            priority = 11,
        },

        nuget = {
            path = "url-open.parsers.nuget",
            enabled = function(bufnr)
                return matches_buffer_name(bufnr, { "%.csproj$", "%.fsproj$", "%.vbproj$", "packages%.config$" })
            end,
            priority = 12,
        },

        java = {
            path = "url-open.parsers.java",
            enabled = function(bufnr)
                return matches_buffer_name(bufnr, { "pom%.xml$", "build%.gradle$" })
            end,
            priority = 13,
        },

        kotlin = {
            path = "url-open.parsers.kotlin",
            enabled = function(bufnr)
                return matches_buffer_name(bufnr, { "build%.gradle%.kts$", "%.gradle%.kts$" })
            end,
            priority = 14,
        },

        nix = {
            path = "url-open.parsers.nix",
            enabled = function(bufnr)
                return matches_buffer_name(bufnr, { "%.nix$", "flake%.lock$" })
            end,
            priority = 16,
        },
    },
})

Updating config: include only the keys you want to change. Nested tables are merged; lists are replaced, not appended. Calling setup() again layers changes on top of the current config.

Detection

Any file

Text Opens
https://example.com/docs https://example.com/docs
<https://example.com> https://example.com
[docs](https://example.com) https://example.com
ftp://host/file, file:///tmp/a, ssh://host the URL as written

Only explicit URLs are detected. Bare text like www.example.com is not treated as a URL.

Local paths

The path parser works in any file and hands its matches to vim.ui.open, so the path opens with your system's default handler.

Text Opens
~/path/to/file, ~\path\to\file the path with ~ expanded to the home directory
~root/notes.txt the named user's home directory (vim.fn.expand)
/tmp/file, ./file, ../file the path as written
C:\Users\me\file, C:/Users/me/file, C:file the Windows path as written
\\server\share\file, //server/share/file the UNC path as written
$HOME/file, ${HOME}/file, %USERPROFILE%\file the path with the environment variable expanded
dir/sub/file.txt, src/init.lua the relative path as written

Quoted paths may contain spaces: "~/My Documents/report.pdf" and `~/My Documents/report.pdf` both work. A bare relative path such as foo/bar is intentionally skipped to avoid matching package references and URL fragments; use a file extension or another separator to make it explicit.

Built-in parsers

Parser Where it works Opens
urls any file explicit schemes, autolinks, Markdown links
path any file local filesystem paths (home, absolute, Windows, UNC, env-var, relative)
github Neovim / Zsh config folders, .zshrc https://github.com/owner/repo
npm package.json npm package pages
brew Brewfile Homebrew formula pages
cargo Cargo.toml crates.io crate pages
rubygems Gemfile, gems.rb RubyGems gem pages
docker Dockerfile, Containerfile Docker Hub images
pypi requirements*.txt, pyproject.toml, Pipfile PyPI projects
go go.mod pkg.go.dev modules
composer composer.json Packagist packages
nuget *.csproj, *.fsproj, *.vbproj, packages.config NuGet packages
java pom.xml, build.gradle Maven Central artifacts
kotlin build.gradle.kts, *.gradle.kts Maven Central artifacts
nix *.nix, flake.lock GitHub/GitLab/SourceHut flake refs, nixpkgs#package, and flake.lock GitHub nodes

The github parser only runs inside the Neovim config folder (XDG_CONFIG_HOME/nvim, or %LOCALAPPDATA%\nvim on Windows), the Zsh config folder (ZDOTDIR), or any file named .zshrc. Other parsers only run on the files listed above.

A plain-text reference with an example of every supported format is in docs/supported-formats.txt.

Cursor matching

Enabled by default, the cursor picks the link under it, then the next link to the right, then the last link on the row. This is close to the usual gx behavior.

For a stricter rule, open a link only when the cursor is directly on it:

require("url-open").setup({
    exact_cursor_match = true,
})

Native keymap

url-open creates a native gx keymap by default (native_mapping = true), so pressing gx in normal mode opens the URL or path under the cursor.

If you prefer your own mapping, disable it:

require("url-open").setup({
    native_mapping = false,
})

vim.keymap.set("n", "gx", function()
    require("url-open").open_url_under_cursor()
end, { desc = "Open URL under cursor" })

The active highlight always shows the link that will open.

Highlights

Two highlight groups are used:

Group Meaning Default style
UrlOpenLink every detected link underline, colorscheme foreground
UrlOpenLinkActive the link the cursor would open soft blue-gray (#9DB6C8, cterm 110) with #7893A8 underline

They are defined with default = true, so your colorscheme wins. To style them yourself:

vim.api.nvim_set_hl(0, "UrlOpenLink", { fg = "#7aa2f7", underline = true })
vim.api.nvim_set_hl(0, "UrlOpenLinkActive", { fg = "#ff9e64", bold = true, underline = true })

To use different group names:

require("url-open").setup({
    highlight = {
        link   = { hl_group = "MyUrl" },
        active = { hl_group = "MyUrlActive" },
    },
})

Set enabled = false on link or active to hide that highlight. Detection and opening still work.

Parsers

Every parser is a key in parsers. Disable a built-in with false:

require("url-open").setup({
    parsers = {
        github = false,
        docker = false,
    },
})

Parser-specific options live under that parser's config. These are free-form and unused by url-open itself — they are only passed through to your parser via parser.config, so a custom parser can read its own options there:

require("url-open").setup({
    parsers = {
        npm = {
            config = {
                -- My own custom npm parser could read `excluded_names` here.
            },
        },
    },
})

Parser option lists are used as given. They are not merged with defaults.

Skipped buffers

Explorers, prompts, terminals, and notifications are skipped by default. To replace the lists:

require("url-open").setup({
    excluded = {
        filetypes = { "NvimTree", "neo-tree", "oil", "TelescopePrompt", "notify" },
        buftypes  = { "terminal", "prompt" },
        buffer = function(bufnr)
            return false -- return true to skip this buffer
        end,
    },
})

Custom parsers

A parser is a plain Lua table. Register it under a key in parsers:

require("url-open").setup({
    parsers = {
        myparser = { ... your parser fields ... },
    },
})

You can define it inline, or keep it in its own file and point path at it (the module is required only when the parser first runs).

Choosing pattern vs parse

Approach Best for How it works
pattern (+ resolve) Simple one-link-per-match formats (ticket IDs, issue refs, package names) url-open finds every regex match in the line, then your resolve turns each match into a link
parse One line → several links, custom ranges, or context-aware logic (e.g. only inside a dependencies section) You get the whole line and return every Link yourself

If both are set, both run and their results are combined.

Parser fields

The canonical type declarations live in lua/url-open/_type.lua.

Control fields (name, enabled, priority, config, path, conflicts) belong in the parsers entry. Implementation fields (pattern, resolve, parse) can be inline there or exported by a lazy parser module.

Field Type Purpose
name? string Parser name. Defaults to the parser's key in parsers; used by conflicts.
enabled? boolean | fun(bufnr: integer): boolean|nil Runs only when true, or when the function returns true for the buffer. Absent means off.
priority? number | fun(a: ParserSpec, b: ParserSpec, bufnr: integer): boolean Lower runs first and wins overlapping matches. Defaults to 999.
config? table<string, any> Free-form options passed to your parser (unused by url-open itself).
path? string Lazy require path to a parser module. The module is loaded on first use.
conflicts? string[] Parser names that cannot run with this parser; higher priority wins.
pattern? string | string[] | fun(parser: Parser, line: string, bufnr: integer, row: integer): string|string[]|nil Lua pattern(s) to search each line with.
resolve? fun(parser: Parser, match: PatternMatch, bufnr: integer, row: integer): Link|nil Turns one pattern match into a Link. Return nil to ignore it.
parse? fun(parser: Parser, line: string, bufnr: integer, row: integer): Link[]|nil Full control: return every link found in line.

Match (PatternMatch) and link (Link) shapes

resolve receives the whole match text and every pattern capture:

--- match
{
    col_start = 0,
    col_end = 8,
    value = "PROJ-123",
    pattern = "%f[%w][A-Z]+%-%d+%f[%W]",
    captures = { n = 1, [1] = "PROJ-123" },
}

captures is always present; captures.n is 0 when the pattern has no captures. Empty captures () are position numbers, normal captures are strings, and unmatched optional captures are nil; use captures.n as the exact count.

Your parse or resolve must return a link:

--- link
{ col_start = 0, col_end = 8, url = "https://example.com/123", hl_group = "UrlOpenLink", row = 0 }
  • col_start / col_end: 0-based byte columns (inclusive start, exclusive end).
  • url: passed to vim.ui.open. Must not be empty.
  • hl_group?: highlight group; defaults to the configured link group.
  • row?: 0-based row override; defaults to the row being parsed.

Example 1: inline pattern + resolve (ticket ID)

Open PROJ-123 as a Jira ticket:

require("url-open").setup({
    parsers = {
        jira = {
            priority = 50,
            pattern = "%f[%w][A-Z]+%-%d+%f[%W]",
            resolve = function(_, match)
                return {
                    col_start = match.col_start,
                    col_end   = match.col_end,
                    url       = "https://jira.example.com/browse/" .. match.value,
                }
            end,
        },
    },
})

Return nil from resolve to ignore a match.

Example 2: inline parse (several links per line)

parse gives you the whole line and returns every link:

require("url-open").setup({
    parsers = {
        myparser = {
            parse = function(_, line, bufnr, row)
                local links = {}
                -- your logic: scan `line`, build link tables
                return links
            end,
        },
    },
})

Example 3: parser module (separate file)

For a larger parser, return the table from its own file:

-- lua/parsers/jira.lua
return {
    pattern = "%f[%w][A-Z]+%-%d+%f[%W]",
    resolve = function(_, match)
        return {
            col_start = match.col_start,
            col_end   = match.col_end,
            url       = "https://jira.example.com/browse/" .. match.value,
        }
    end,
}

Then reference it by module path:

require("url-open").setup({
    parsers = {
        jira = { path = "parsers.jira", priority = 50 },
    },
})

Per-buffer gating with enabled

Use enabled as a function to run a parser only in certain buffers:

require("url-open").setup({
    parsers = {
        cargo = {
            enabled = function(bufnr)
                return vim.fn.expand("%:e") == "toml"
                    and vim.fn.expand("%:t") == "Cargo.toml"
            end,
            path = "url-open.parsers.cargo",
        },
    },
})

Conflicting parsers

Use conflicts in the parser config to skip other parsers in the same buffer:

require("url-open").setup({
    parsers = {
        my_java = {
            path = "parsers.my_java",
            priority = 13,
            conflicts = { "kotlin" },
        },
    },
})

Conflicts are matched by effective parser name: name if set, otherwise the key in parsers. The higher-priority parser wins; a parser that conflicts with an already accepted parser is skipped no matter which side declared the conflict. Equal priorities keep config iteration order. Control fields stay in the config, never in lazy modules.

Lua API

local url_open = require("url-open")

url_open.setup(opts)                 -- configure + start highlighting
url_open.open_url_under_cursor()     -- open the link chosen by the cursor
url_open.enable_highlighting()       -- start highlighting again
url_open.disable_highlighting()      -- stop highlighting and clear marks

No user commands are registered. A native gx mapping is created by default; see Native keymap to replace or disable it.

Troubleshooting

  • With exact_cursor_match = true, put the cursor directly on a highlighted link. Otherwise the active highlight shows what will open.
  • Check that the buffer is not in excluded.filetypes, excluded.buftypes, or your excluded.buffer function.
  • Config changes are applied by setup(). With lazy.nvim, edit opts and restart Neovim.
  • After disabling highlights, call require("url-open").enable_highlighting().
  • url-open uses vim.ui.open only. It has no fallback opener.

Contributing

Because I follow minimalism, I only support the features I actually use.

If you need more, open an issue or pull request with a clear example of the link you want opened.

Migration from v1

url-open v2 is a rewrite of the parser system. Most config keys changed — copying the v1 config table will not work. Here is how to port your setup.

Installation

v1 (lazy load with a command):

{
    "sontungexpt/url-open",
    event = "VeryLazy",
    cmd = "URLOpenUnderCursor",
    config = function()
        local status_ok, url_open = pcall(require, "url-open")
        if not status_ok then return end
        url_open.setup({})
    end,
},

v2 (lazy load, no command):

{
    "sontungexpt/url-open",
    event = "VeryLazy",
    opts = {},
},

Keymap

v2 registers no commands, but it does create a native gx mapping by default (native_mapping = true), so the v1 :URLOpenUnderCursor mapping is no longer needed. To use your own mapping instead, disable the native one:

require("url-open").setup({ native_mapping = false })

vim.keymap.set("n", "gx", function()
    require("url-open").open_url_under_cursor()
end, { desc = "Open URL under cursor" })

Configuration

v1 option v2 replacement Notes
open_app Removed v2 uses vim.ui.open only; no browser selection
open_only_when_cursor_on_url exact_cursor_match Same meaning, renamed
highlight_url.all_urls highlight.link enabled/hl_group instead of fg/bg/underline
highlight_url.cursor_move highlight.active enabled/hl_group instead of fg/bg/underline
deep_pattern Built into urls parser Always on
extra_patterns Custom parsers See Custom parsers
:URLOpenHighlightAll / :URLOpenHighlightAllClear Removed Automatic highlighting handles this

v1 config:

require("url-open").setup({
    open_app = "default",
    open_only_when_cursor_on_url = false,
    highlight_url = {
        all_urls = { enabled = false, fg = "#21d5ff", underline = true },
        cursor_move = { enabled = true, fg = "#199eff", underline = true },
    },
    deep_pattern = false,
    extra_patterns = { ... },
})

v2 equivalent:

require("url-open").setup({
    exact_cursor_match = false,
    highlight = {
        link   = { enabled = true, hl_group = "UrlOpenLink" },
        active = { enabled = true, hl_group = "UrlOpenLinkActive" },
    },
})

Highlight groups are defined with default = true, so your colorscheme wins. To style them yourself:

vim.api.nvim_set_hl(0, "UrlOpenLink", { fg = "#7aa2f7", underline = true })
vim.api.nvim_set_hl(0, "UrlOpenLinkActive", { fg = "#ff9e64", bold = true, underline = true })

Custom parsers (replaces extra_patterns)

v1's extra_patterns used pattern + prefix/suffix to build URLs. In v2, write a custom parser:

-- v1 extra_patterns (npm package):
-- { pattern = '["]([%w@%-%._/]+)["]:%s*"[^"]*%d[%d%.]*", prefix = "https://www.npmjs.com/package/" }

-- v2 equivalent:
require("url-open").setup({
    parsers = {
        npm = {
            enabled = function(bufnr)
                return vim.fn.expand("%:t") == "package.json"
            end,
            pattern = "[\"']([%w@%-%._/]+)[\"']",
            resolve = function(_, match)
                return {
                    col_start = match.col_start,
                    col_end   = match.col_end,
                    url       = "https://www.npmjs.com/package/" .. match.value,
                }
            end,
        },
    },
})

License

This project is licensed under the MIT License — see the LICENSE file for details.