Vim Function for GitHub Links

Update (1/31/2018): I extracted this code to a vim plugin and made a few improvements to it: https://github.com/pgr0ss/vim-github-url

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
endfunction
command! -range GitHubURL <line1>,<line2>call GitHubURL()

Now, I can select a block of code and run :GitHubURL and it will print something like https://github.com/braintreeps/vim_dotfiles/blob/f6c550529b16b48f9ac99d5dd60c354373aa3fa1/vimrc#L275-L284

It should work for both GitHub and GitHub Enterprise.