用于GitHub链接的Vim功能

192 阅读1分钟

更新(1/31/2018)。我将这段代码提取到一个vim插件中,并对其进行了一些改进:https://github.com/pgr0ss/vim-github-url

我在Vim中写了很多代码,根据编程语言的不同,大多停留在编辑器内。

然而,我有一个常见的工作流程,我想把我正在看的东西的链接发给别人。我曾经打开GitHub或GitHub Enterprise,浏览到文件和行,然后复制/粘贴URL给别人。这很麻烦,所以我决定用一个Vim函数(存在于vimrc 文件中)将其自动化。

这就是这个函数。

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()

现在,我可以选择一个代码块并运行:GitHubURL ,它将打印出类似于github.com/braintreeps…的内容

它应该对GitHub和GitHub Enterprise都有效。