Skip to content

Instantly share code, notes, and snippets.

@lonetwin
Last active December 29, 2015 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lonetwin/7660784 to your computer and use it in GitHub Desktop.
Save lonetwin/7660784 to your computer and use it in GitHub Desktop.
Vim function to echo the currently edited file's github url
function ShowGitHubURL()
" Function to echo the github URL for the currently open file at the
" current line number. This is useful if for example, you want to quickly
" share the URL for the file you're working on via, email / IRC etc.
"
" This can also be easily extended to open the browser with the displayed
" URL using tips such as http://vim.wikia.com/wiki/VimTip306
"
" You may add a mapping like this to bind this function to a keystroke:
" map <Leader>gh :call ShowGitHubURL()<CR>
"
" XXX KNOWN ISSUE: file needs to be opened from the 'top' level of the
" source tree ie: '%' should expand to the filename under the root of the
" repositories source tree. I don't know (yet) how to fix this.
" Suggestions/Patches welcome.
let gh_base = 'github.com'
let gh_url = system("git remote -v show")
if strridx(gh_url, gh_base) == -1
echom "Not within a github repo or github origin not found"
return
endif
" Build the repo's github url
let remote = split(gh_url)[0]
let gh_url = split(gh_url, '@')[2]
let gh_url = split(gh_url)[0]
let gh_url = substitute(gh_url, ':', '/', '')
let gh_url = substitute(gh_url, '.git$', '', '')
let gh_url = 'https://'.gh_url
" Add the current branch
let branch = system("git remote show ".remote."| grep 'HEAD branch'")
let branch = split(branch)[-1]
let gh_url = gh_url."/blob/".branch
" Add the current filename and line number
let gh_url = gh_url . "/" . expand("%") . "#L" . line(".")
echom gh_url
endfunction
@lonetwin
Copy link
Author

Things I know:

  • This probably is bad vimscript. I just hacked it together. I've never bothered actually learning vimscript. Might someday
  • The use of grep at L31 makes this *nix only (unless you have grep.exe in cygwin setup). Well, it isn't strictly necessary, you may modify it appropriately to avoid the use of grep (while maintaining the original assumption -- that the github remote might not be named origin
  • Despite the last point, I realize that I made the assumption that git remote -v show will show the github origin as the first remote ...ah well, that's because too lazy.

If you improve on this, please do let me know. I really do find this useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment