Vim Function for GitHub Links

I write a lot of code in Vim, and depending on the programming language, mostly stay inside the editor.

However, I have a common workflow where I want to send a link of what I'm looking at to someone. I used to open GitHub or GitHub Enterprise, browse to the file and line, and then copy/paste the URL to someone. This is onerous, so I decided to automate it with a Vim function (that lives in the vimrc file).

Here's the function:

function! GitHubURL() range
  let branch = systemlist("git name-rev --name-only HEAD")[0]
  let remote = systemlist("git config branch." . branch . ".remote")[0]
  let repo = systemlist("git config --get remote." . remote . ".url | sed 's/\.git$//' | sed 's_^git@\\(.*\\):_https://\\1/_' | sed 's_^git://_https://_'")[0]
  let revision = systemlist("git rev-parse HEAD")[0]
  let path = systemlist("git ls-files --full-name " . @%)[0]
  let url = repo . "/blob/" . revision . "/" . path . "#L" . a:firstline . "-L" . a:lastline
  echomsg url
command! -range GitHubURL <line1>,<line2>call GitHubURL()

Now, I can select a block of code and run :GitHubURL and it will print something like

It should work for both GitHub and GitHub Enterprise.

Paul Gross

Paul Gross

I'm a lead software developer in Seattle working for Braintree Payments.

Read More