Skip to content

Commit

Permalink
fix: improve repo path extraction under cursor
Browse files Browse the repository at this point in the history
  • Loading branch information
tetzng committed Feb 11, 2025
1 parent 8a1d0db commit 6926e1a
Showing 1 changed file with 28 additions and 9 deletions.
37 changes: 28 additions & 9 deletions lua/open-github-url.lua
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,38 @@ function M.open_url(url)
end

function M.get_repo_path_under_cursor()
local current_line_text = vim.fn.getline(".")
local url_pattern = [[\v('|")(\w|-|_|.)+/(\w|-|_|.)+('|")]]
local vim_regex = vim.regex(url_pattern)
local from_idx, to_idx = vim_regex:match_str(current_line_text)
if from_idx == nil or to_idx == nil then
return nil
local col = vim.fn.col(".")
local line = vim.fn.getline(".")

local left = col
while left > 1 do
local c = line:sub(left - 1, left - 1)
if c == "'" or c == '"' then
break
end
left = left - 1
end

local right = col
while right <= #line do
local c = line:sub(right, right)
if c == "'" or c == '"' then
break
end
right = right + 1
end

local candidate = line:sub(left, right - 1)

if candidate:match("^[%w._-]+/[%w._-]+$") then
return candidate
end
return string.sub(current_line_text, from_idx + 2, to_idx - 1)
return nil
end

function M.open_github_url_under_cursor()
local repo_path = M.get_repo_path_under_cursor()
if repo_path ~= "" then
if repo_path and repo_path ~= "" then
M.open_url("https://github.com/" .. repo_path)
end
end
Expand All @@ -34,7 +53,7 @@ local function setup_commands()
local cmd = vim.api.nvim_create_user_command
cmd("OpenUrl", function(opts) M.open_url(opts.fargs[1]) end, { nargs = 1 })
cmd("OpenGitHubUrlUnderCursor", function() M.open_github_url_under_cursor() end, {})
cmd("GetRepoPathUnderCursor", function() M.get_repo_path_under_cursor() end, {})
cmd("GetRepoPathUnderCursor", function() print(M.get_repo_path_under_cursor() or "") end, {})
end

function M.setup()
Expand Down

0 comments on commit 6926e1a

Please sign in to comment.