Use rev-parse to get abbrev length for status buffer
[vim-fugitive.git] / plugin / fugitive.vim
blob86e657673c82482cfcb1be24432dfbdacf1ac95b
1 " fugitive.vim - A Git wrapper so awesome, it should be illegal
2 " Maintainer:   Tim Pope <http://tpo.pe/>
3 " Version:      3.7
4 " GetLatestVimScripts: 2975 1 :AutoInstall: fugitive.vim
6 if exists('g:loaded_fugitive')
7   finish
8 endif
9 let g:loaded_fugitive = 1
11 let s:bad_git_dir = '/$\|^fugitive:'
13 " FugitiveGitDir() returns the detected Git dir for the given buffer number,
14 " or the current buffer if no argument is passed.  This will be an empty
15 " string if no Git dir was found.  Use !empty(FugitiveGitDir()) to check if
16 " Fugitive is active in the current buffer.  Do not rely on this for direct
17 " filesystem access; use FugitiveFind('.git/whatever') instead.
18 function! FugitiveGitDir(...) abort
19   if v:version < 704
20     return ''
21   elseif !a:0 || type(a:1) == type(0) && a:1 < 0 || a:1 is# get(v:, 'true', -1)
22     if exists('g:fugitive_event')
23       return g:fugitive_event
24     endif
25     let dir = get(b:, 'git_dir', '')
26     if empty(dir) && (empty(bufname('')) && &filetype !=# 'netrw' || &buftype =~# '^\%(nofile\|acwrite\|quickfix\|terminal\|prompt\)$')
27       return FugitiveExtractGitDir(getcwd())
28     elseif (!exists('b:git_dir') || b:git_dir =~# s:bad_git_dir) && &buftype =~# '^\%(nowrite\)\=$'
29       let b:git_dir = FugitiveExtractGitDir(bufnr(''))
30       return b:git_dir
31     endif
32     return dir =~# s:bad_git_dir ? '' : dir
33   elseif type(a:1) == type(0) && a:1 isnot# 0
34     if a:1 == bufnr('') && (!exists('b:git_dir') || b:git_dir =~# s:bad_git_dir) && &buftype =~# '^\%(nowrite\)\=$'
35       let b:git_dir = FugitiveExtractGitDir(a:1)
36     endif
37     let dir = getbufvar(a:1, 'git_dir')
38     return dir =~# s:bad_git_dir ? '' : dir
39   elseif type(a:1) == type('')
40     return substitute(s:Slash(a:1), '/$', '', '')
41   elseif type(a:1) == type({})
42     return get(a:1, 'fugitive_dir', get(a:1, 'git_dir', ''))
43   else
44     return ''
45   endif
46 endfunction
48 " FugitiveReal() takes a fugitive:// URL and returns the corresponding path in
49 " the work tree.  This may be useful to get a cleaner path for inclusion in
50 " the statusline, for example.  Note that the file and its parent directories
51 " are not guaranteed to exist.
53 " This is intended as an abstract API to be used on any "virtual" path.  For a
54 " buffer named foo://bar, check for a function named FooReal(), and if it
55 " exists, call FooReal("foo://bar").
56 function! FugitiveReal(...) abort
57   let file = a:0 ? a:1 : @%
58   if type(file) ==# type({})
59     let dir = FugitiveGitDir(file)
60     let tree = s:Tree(dir)
61     return s:VimSlash(empty(tree) ? dir : tree)
62   elseif file =~# '^\a\a\+:' || a:0 > 1
63     return call('fugitive#Real', [file] + a:000[1:-1])
64   elseif file =~# '^/\|^\a:\|^$'
65     return file
66   else
67     return fnamemodify(file, ':p' . (file =~# '[\/]$' ? '' : ':s?[\/]$??'))
68   endif
69 endfunction
71 " FugitiveFind() takes a Fugitive object and returns the appropriate Vim
72 " buffer name.  You can use this to generate Fugitive URLs ("HEAD:README") or
73 " to get the absolute path to a file in the Git dir (".git/HEAD"), the common
74 " dir (".git/config"), or the work tree (":(top)Makefile").
76 " An optional second argument provides the Git dir, or the buffer number of a
77 " buffer with a Git dir.  The default is the current buffer.
78 function! FugitiveFind(...) abort
79   if a:0 && (type(a:1) ==# type({}) || type(a:1) ==# type(0))
80     return call('fugitive#Find', a:000[1:-1] + [FugitiveGitDir(a:1)])
81   else
82     return fugitive#Find(a:0 ? a:1 : bufnr(''), FugitiveGitDir(a:0 > 1 ? a:2 : -1))
83   endif
84 endfunction
86 " FugitiveParse() takes a fugitive:// URL and returns a 2 element list
87 " containing an object name ("commit:file") and the Git dir.  It's effectively
88 " the inverse of FugitiveFind().
89 function! FugitiveParse(...) abort
90   let path = s:Slash(a:0 ? a:1 : @%)
91   if path !~# '^fugitive://'
92     return ['', '']
93   endif
94   let [rev, dir] = fugitive#Parse(path)
95   if !empty(dir)
96     return [rev, dir]
97   endif
98   throw 'fugitive: invalid Fugitive URL ' . path
99 endfunction
101 " FugitiveGitVersion() queries the version of Git in use.  Pass up to 3
102 " arguments to return a Boolean of whether a certain minimum version is
103 " available (FugitiveGitVersion(2,3,4) checks for 2.3.4 or higher) or no
104 " arguments to get a raw string.
105 function! FugitiveGitVersion(...) abort
106   return call('fugitive#GitVersion', a:000)
107 endfunction
109 " FugitiveResult() returns an object encapsulating the result of the most
110 " recent :Git command.  Will be empty if no result is available.  During a
111 " User FugitiveChanged event, this is guaranteed to correspond to the :Git
112 " command that triggered the event, or be empty if :Git was not the trigger.
113 " Pass in the name of a temp buffer to get the result object for that command
114 " instead.  Contains the following keys:
116 " * "args": List of command arguments, starting with the subcommand.  Will be
117 "   empty for usages like :Git --help.
118 " * "git_dir": Git dir of the relevant repository.
119 " * "exit_status": The integer exit code of the process.
120 " * "flags": Flags passed directly to Git, like -c and --help.
121 " * "file": Path to file containing command output.  Not guaranteed to exist,
122 "   so verify with filereadable() before trying to access it.
123 function! FugitiveResult(...) abort
124   return call('fugitive#Result', a:000)
125 endfunction
127 " FugitiveExecute() runs Git with a list of arguments and returns a dictionary
128 " with the following keys:
130 " * "exit_status": The integer exit code of the process.
131 " * "stdout": The stdout produced by the process, as a list of lines.
132 " * "stderr": The stdout produced by the process, as a list of lines.
134 " An optional second argument provides the Git dir, or the buffer number of a
135 " buffer with a Git dir.  The default is the current buffer.
137 " An optional final argument is a callback Funcref, for asynchronous
138 " execution.
139 function! FugitiveExecute(args, ...) abort
140   return call('fugitive#Execute', [a:args] + a:000)
141 endfunction
143 " FugitiveShellCommand() turns an array of arguments into a Git command string
144 " which can be executed with functions like system() and commands like :!.
145 " Integer arguments will be treated as buffer numbers, and the appropriate
146 " relative path inserted in their place.
148 " An optional second argument provides the Git dir, or the buffer number of a
149 " buffer with a Git dir.  The default is the current buffer.
150 function! FugitiveShellCommand(...) abort
151   return call('fugitive#ShellCommand', a:000)
152 endfunction
154 " FugitiveConfig() get returns an opaque structure that can be passed to other
155 " FugitiveConfig functions in lieu of a Git directory.  This can be faster
156 " when performing multiple config queries.  Do not rely on the internal
157 " structure of the return value as it is not guaranteed.  If you want a full
158 " dictionary of every config value, use FugitiveConfigGetRegexp('.*').
160 " An optional argument provides the Git dir, or the buffer number of a
161 " buffer with a Git dir.  The default is the current buffer.  Pass a blank
162 " string to limit to the global config.
163 function! FugitiveConfig(...) abort
164   return call('fugitive#Config', a:000)
165 endfunction
167 " FugitiveConfigGet() retrieves a Git configuration value.  An optional second
168 " argument can be either the object returned by FugitiveConfig(), or a Git
169 " dir or buffer number to be passed along to FugitiveConfig().
170 function! FugitiveConfigGet(name, ...) abort
171   return get(call('FugitiveConfigGetAll', [a:name] + (a:0 ? [a:1] : [])), -1, get(a:, 2, ''))
172 endfunction
174 " FugitiveConfigGetAll() is like FugitiveConfigGet() but returns a list of
175 " all values.
176 function! FugitiveConfigGetAll(name, ...) abort
177   return call('fugitive#ConfigGetAll', [a:name] + a:000)
178 endfunction
180 " FugitiveConfigGetRegexp() retrieves a dictionary of all configuration values
181 " with a key matching the given pattern.  Like git config --get-regexp, but
182 " using a Vim regexp.  Second argument has same semantics as
183 " FugitiveConfigGet().
184 function! FugitiveConfigGetRegexp(pattern, ...) abort
185   return call('fugitive#ConfigGetRegexp', [a:pattern] + a:000)
186 endfunction
188 " FugitiveRemoteUrl() retrieves the remote URL for the given remote name,
189 " defaulting to the current branch's remote or "origin" if no argument is
190 " given.  Similar to `git remote get-url`, but also attempts to resolve HTTP
191 " redirects and SSH host aliases.
193 " An optional second argument provides the Git dir, or the buffer number of a
194 " buffer with a Git dir.  The default is the current buffer.
195 function! FugitiveRemoteUrl(...) abort
196   return call('fugitive#RemoteUrl', a:000)
197 endfunction
199 " FugitiveRemote() returns a data structure parsed from the remote URL.
200 " For example, for remote URL "https://me@example.com:1234/repo.git", the
201 " returned dictionary will contain the following:
203 " * "scheme": "https"
204 " * "authority": "user@example.com:1234"
205 " * "path": "/repo.git" (for SSH URLs this may be a relative path)
206 " * "pathname": "/repo.git" (always coerced to absolute path)
207 " * "host": "example.com:1234"
208 " * "hostname": "example.com"
209 " * "port": "1234"
210 " * "user": "me"
211 " * "path": "/repo.git"
212 " * "url": "https://me@example.com:1234/repo.git"
213 function! FugitiveRemote(...) abort
214   return call('fugitive#Remote', a:000)
215 endfunction
217 " FugitiveDidChange() triggers a FugitiveChanged event and reloads the summary
218 " buffer for the current or given buffer number's repository.  You can also
219 " give the result of a FugitiveExecute() and that context will be made
220 " available inside the FugitiveChanged() event.
222 " Passing the special argument 0 (the number zero) softly expires summary
223 " buffers for all repositories.  This can be used after a call to system()
224 " with unclear implications.
225 function! FugitiveDidChange(...) abort
226   return call('fugitive#DidChange', a:000)
227 endfunction
229 " FugitiveHead() retrieves the name of the current branch. If the current HEAD
230 " is detached, FugitiveHead() will return the empty string, unless the
231 " optional argument is given, in which case the hash of the current commit
232 " will be truncated to the given number of characters.
234 " An optional second argument provides the Git dir, or the buffer number of a
235 " buffer with a Git dir.  The default is the current buffer.
236 function! FugitiveHead(...) abort
237   if a:0 && (type(a:1) ==# type({}) || type(a:1) ==# type('') && a:1 !~# '^\d\+$')
238     let dir = FugitiveGitDir(a:1)
239     let arg = get(a:, 2, 0)
240   elseif a:0 > 1
241     let dir = FugitiveGitDir(a:2)
242     let arg = a:1
243   else
244     let dir = FugitiveGitDir()
245     let arg = get(a:, 1, 0)
246   endif
247   if empty(dir)
248     return ''
249   endif
250   return fugitive#Head(arg, dir)
251 endfunction
253 function! FugitivePath(...) abort
254   if a:0 > 2 && type(a:1) ==# type({})
255     return fugitive#Path(a:2, a:3, FugitiveGitDir(a:1))
256   elseif a:0 && type(a:1) ==# type({})
257     return FugitiveReal(a:0 > 1 ? a:2 : @%)
258   elseif a:0 > 1
259     return fugitive#Path(a:1, a:2, FugitiveGitDir(a:0 > 2 ? a:3 : -1))
260   else
261     return FugitiveReal(a:0 ? a:1 : @%)
262   endif
263 endfunction
265 function! FugitiveStatusline(...) abort
266   if empty(FugitiveGitDir(bufnr('')))
267     return ''
268   endif
269   return fugitive#Statusline()
270 endfunction
272 let s:resolved_git_dirs = {}
273 function! FugitiveActualDir(...) abort
274   let dir = call('FugitiveGitDir', a:000)
275   if empty(dir)
276     return ''
277   endif
278   if !has_key(s:resolved_git_dirs, dir)
279     let s:resolved_git_dirs[dir] = s:ResolveGitDir(dir)
280   endif
281   return empty(s:resolved_git_dirs[dir]) ? dir : s:resolved_git_dirs[dir]
282 endfunction
284 let s:commondirs = {}
285 function! FugitiveCommonDir(...) abort
286   let dir = call('FugitiveActualDir', a:000)
287   if empty(dir)
288     return ''
289   endif
290   if has_key(s:commondirs, dir)
291     return s:commondirs[dir]
292   endif
293   if getfsize(dir . '/HEAD') >= 10
294     let cdir = get(s:ReadFile(dir . '/commondir', 1), 0, '')
295     if cdir =~# '^/\|^\a:/'
296       let s:commondirs[dir] = s:Slash(FugitiveVimPath(cdir))
297     elseif len(cdir)
298       let s:commondirs[dir] = simplify(dir . '/' . cdir)
299     else
300       let s:commondirs[dir] = dir
301     endif
302   else
303     let s:commondirs[dir] = dir
304   endif
305   return s:commondirs[dir]
306 endfunction
308 function! FugitiveWorkTree(...) abort
309   let tree = s:Tree(FugitiveGitDir(a:0 ? a:1 : -1))
310   if tree isnot# 0 || a:0 > 1
311     return tree
312   else
313     return ''
314   endif
315 endfunction
317 function! FugitiveIsGitDir(...) abort
318   if !a:0 || type(a:1) !=# type('')
319     return !empty(call('FugitiveGitDir', a:000))
320   endif
321   let path = substitute(a:1, '[\/]$', '', '') . '/'
322   return len(path) && getfsize(path.'HEAD') > 10 && (
323         \ isdirectory(path.'objects') && isdirectory(path.'refs') ||
324         \ getftype(path.'commondir') ==# 'file')
325 endfunction
327 function! s:ReadFile(path, line_count) abort
328   if v:version < 800 && !filereadable(a:path)
329     return []
330   endif
331   try
332     return readfile(a:path, 'b', a:line_count)
333   catch
334     return []
335   endtry
336 endfunction
338 let s:worktree_for_dir = {}
339 let s:dir_for_worktree = {}
340 function! s:Tree(path) abort
341   if a:path =~# '/\.git$'
342     return len(a:path) ==# 5 ? '/' : a:path[0:-6]
343   elseif a:path ==# ''
344     return ''
345   endif
346   let dir = FugitiveActualDir(a:path)
347   if !has_key(s:worktree_for_dir, dir)
348     let s:worktree_for_dir[dir] = ''
349     let ext_wtc_pat = 'v:val =~# "^\\s*worktreeConfig *= *\\%(true\\|yes\\|on\\|1\\) *$"'
350     let config = s:ReadFile(dir . '/config', 50)
351     if len(config)
352       let ext_wtc_config = filter(copy(config), ext_wtc_pat)
353       if len(ext_wtc_config) == 1 && filereadable(dir . '/config.worktree')
354          let config += s:ReadFile(dir . '/config.worktree', 50)
355       endif
356     else
357       let worktree = fnamemodify(FugitiveVimPath(get(s:ReadFile(dir . '/gitdir', 1), '0', '')), ':h')
358       if worktree ==# '.'
359         unlet! worktree
360       endif
361       if len(filter(s:ReadFile(FugitiveCommonDir(dir) . '/config', 50), ext_wtc_pat))
362         let config = s:ReadFile(dir . '/config.worktree', 50)
363       endif
364     endif
365     if len(config)
366       let wt_config = filter(copy(config), 'v:val =~# "^\\s*worktree *="')
367       if len(wt_config)
368         let worktree = FugitiveVimPath(matchstr(wt_config[0], '= *\zs.*'))
369       elseif !exists('worktree')
370         call filter(config,'v:val =~# "^\\s*bare *= *true *$"')
371         if empty(config)
372           let s:worktree_for_dir[dir] = 0
373         endif
374       endif
375     endif
376     if exists('worktree')
377       let s:worktree_for_dir[dir] = s:Slash(resolve(worktree))
378       let s:dir_for_worktree[s:worktree_for_dir[dir]] = dir
379     endif
380   endif
381   if s:worktree_for_dir[dir] =~# '^\.'
382     return simplify(dir . '/' . s:worktree_for_dir[dir])
383   else
384     return s:worktree_for_dir[dir]
385   endif
386 endfunction
388 function! s:CeilingDirectories() abort
389   if !exists('s:ceiling_directories')
390     let s:ceiling_directories = []
391     let resolve = 1
392     for dir in split($GIT_CEILING_DIRECTORIES, has('win32') ? ';' : ':', 1)
393       if empty(dir)
394         let resolve = 0
395       elseif resolve
396         call add(s:ceiling_directories, s:Slash(resolve(dir)))
397       else
398         call add(s:ceiling_directories, s:Slash(dir))
399       endif
400     endfor
401   endif
402   return s:ceiling_directories + get(g:, 'ceiling_directories', [s:Slash(fnamemodify(expand('~'), ':h'))])
403 endfunction
405 function! s:ResolveGitDir(git_dir) abort
406   let type = getftype(a:git_dir)
407   if type ==# 'dir' && FugitiveIsGitDir(a:git_dir)
408     return a:git_dir
409   elseif type ==# 'link' && FugitiveIsGitDir(a:git_dir)
410     return resolve(a:git_dir)
411   elseif type !=# ''
412     let line = get(s:ReadFile(a:git_dir, 1), 0, '')
413     let file_dir = s:Slash(FugitiveVimPath(matchstr(line, '^gitdir: \zs.*')))
414     if file_dir !~# '^/\|^\a:\|^$' && a:git_dir =~# '/\.git$' && FugitiveIsGitDir(a:git_dir[0:-5] . file_dir)
415       return simplify(a:git_dir[0:-5] . file_dir)
416     elseif file_dir =~# '^/\|^\a:' && FugitiveIsGitDir(file_dir)
417       return file_dir
418     endif
419   endif
420   return ''
421 endfunction
423 function! FugitiveExtractGitDir(path) abort
424   if type(a:path) ==# type({})
425     return get(a:path, 'fugitive_dir', get(a:path, 'git_dir', ''))
426   elseif type(a:path) == type(0)
427     let path = s:Slash(a:path > 0 ? bufname(a:path) : bufname(''))
428     if getbufvar(a:path, '&filetype') ==# 'netrw'
429       let path = s:Slash(getbufvar(a:path, 'netrw_curdir', path))
430     endif
431   else
432     let path = s:Slash(a:path)
433   endif
434   if path =~# '^fugitive://'
435     return fugitive#Parse(path)[1]
436   elseif empty(path)
437     return ''
438   endif
439   let pre = substitute(matchstr(path, '^\a\a\+\ze:'), '^.', '\u&', '')
440   if len(pre) && exists('*' . pre . 'Real')
441     let path = {pre}Real(path)
442   endif
443   let root = s:Slash(fnamemodify(path, ':p:h'))
444   let previous = ""
445   let env_git_dir = len($GIT_DIR) ? s:Slash(simplify(fnamemodify(FugitiveVimPath($GIT_DIR), ':p:s?[\/]$??'))) : ''
446   call s:Tree(env_git_dir)
447   let ceiling_directories = s:CeilingDirectories()
448   while root !=# previous && root !~# '^$\|^//[^/]*$'
449     if index(ceiling_directories, root) >= 0
450       break
451     endif
452     if root ==# $GIT_WORK_TREE && FugitiveIsGitDir(env_git_dir)
453       return env_git_dir
454     elseif has_key(s:dir_for_worktree, root)
455       return s:dir_for_worktree[root]
456     endif
457     let dir = substitute(root, '[\/]$', '', '') . '/.git'
458     let resolved = s:ResolveGitDir(dir)
459     if !empty(resolved)
460       let s:resolved_git_dirs[dir] = resolved
461       return dir is# resolved || s:Tree(resolved) is# 0 ? dir : resolved
462     elseif FugitiveIsGitDir(root)
463       let s:resolved_git_dirs[root] = root
464       return root
465     endif
466     let previous = root
467     let root = fnamemodify(root, ':h')
468   endwhile
469   return ''
470 endfunction
472 function! FugitiveDetect(...) abort
473   if v:version < 704
474     return ''
475   endif
476   if exists('b:git_dir') && b:git_dir =~# '^$\|' . s:bad_git_dir
477     unlet b:git_dir
478   endif
479   if !exists('b:git_dir')
480     let b:git_dir = FugitiveExtractGitDir(a:0 ? a:1 : bufnr(''))
481   endif
482   return ''
483 endfunction
485 function! FugitiveGitPath(path) abort
486   return s:Slash(a:path)
487 endfunction
489 if exists('+shellslash')
491   function! s:Slash(path) abort
492     return tr(a:path, '\', '/')
493   endfunction
495   function! s:VimSlash(path) abort
496     return tr(a:path, '\/', &shellslash ? '//' : '\\')
497   endfunction
499   function FugitiveVimPath(path) abort
500     return tr(a:path, '\/', &shellslash ? '//' : '\\')
501   endfunction
503 else
505   function! s:Slash(path) abort
506     return a:path
507   endfunction
509   function! s:VimSlash(path) abort
510     return a:path
511   endfunction
513   if has('win32unix') && filereadable('/git-bash.exe')
514     function! FugitiveVimPath(path) abort
515       return substitute(a:path, '^\(\a\):', '/\l\1', '')
516     endfunction
517   else
518     function! FugitiveVimPath(path) abort
519       return a:path
520     endfunction
521   endif
523 endif
525 function! s:ProjectionistDetect() abort
526   let file = s:Slash(get(g:, 'projectionist_file', ''))
527   let dir = FugitiveExtractGitDir(file)
528   let base = matchstr(file, '^fugitive://.\{-\}//\x\+')
529   if empty(base)
530     let base = s:Tree(dir)
531   endif
532   if !empty(base)
533     if exists('+shellslash') && !&shellslash
534       let base = tr(base, '/', '\')
535     endif
536     let file = FugitiveFind('.git/info/projections.json', dir)
537     if filereadable(file)
538       call projectionist#append(base, file)
539     endif
540   endif
541 endfunction
543 let s:addr_other = has('patch-8.1.560') || has('nvim-0.5.0') ? '-addr=other' : ''
544 let s:addr_tabs  = has('patch-7.4.542') ? '-addr=tabs' : ''
545 let s:addr_wins  = has('patch-7.4.542') ? '-addr=windows' : ''
547 if exists(':G') != 2
548   command! -bang -nargs=? -range=-1 -complete=customlist,fugitive#Complete G   exe fugitive#Command(<line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)
549 endif
550 command! -bang -nargs=? -range=-1 -complete=customlist,fugitive#Complete Git exe fugitive#Command(<line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)
552 if exists(':Gstatus') != 2 && get(g:, 'fugitive_legacy_commands', 0)
553   exe 'command! -bang -bar     -range=-1' s:addr_other 'Gstatus exe fugitive#Command(<line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
554         \ '|echohl WarningMSG|echomsg ":Gstatus is deprecated in favor of :Git (with no arguments)"|echohl NONE'
555 endif
557 for s:cmd in ['Commit', 'Revert', 'Merge', 'Rebase', 'Pull', 'Push', 'Fetch', 'Blame']
558   if exists(':G' . tolower(s:cmd)) != 2 && get(g:, 'fugitive_legacy_commands', 0)
559     exe 'command! -bang -nargs=? -range=-1 -complete=customlist,fugitive#' . s:cmd . 'Complete G' . tolower(s:cmd)
560           \ 'echohl WarningMSG|echomsg ":G' . tolower(s:cmd) . ' is deprecated in favor of :Git ' . tolower(s:cmd) . '"|echohl NONE|'
561           \ 'exe fugitive#Command(<line1>, <count>, +"<range>", <bang>0, "<mods>", "' . tolower(s:cmd) . ' " . <q-args>)'
562   endif
563 endfor
564 unlet s:cmd
566 exe "command! -bar -bang -nargs=? -complete=customlist,fugitive#CdComplete Gcd  exe fugitive#Cd(<q-args>, 0)"
567 exe "command! -bar -bang -nargs=? -complete=customlist,fugitive#CdComplete Glcd exe fugitive#Cd(<q-args>, 1)"
569 exe 'command! -bang -nargs=? -range=-1' s:addr_wins '-complete=customlist,fugitive#GrepComplete Ggrep  exe fugitive#GrepCommand(<line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
570 exe 'command! -bang -nargs=? -range=-1' s:addr_wins '-complete=customlist,fugitive#GrepComplete Glgrep exe fugitive#GrepCommand(0, <count> > 0 ? <count> : 0, +"<range>", <bang>0, "<mods>", <q-args>)'
572 exe 'command! -bang -nargs=? -range=-1 -complete=customlist,fugitive#LogComplete Gclog :exe fugitive#LogCommand(<line1>,<count>,+"<range>",<bang>0,"<mods>",<q-args>, "c")'
573 exe 'command! -bang -nargs=? -range=-1 -complete=customlist,fugitive#LogComplete GcLog :exe fugitive#LogCommand(<line1>,<count>,+"<range>",<bang>0,"<mods>",<q-args>, "c")'
574 exe 'command! -bang -nargs=? -range=-1 -complete=customlist,fugitive#LogComplete Gllog :exe fugitive#LogCommand(<line1>,<count>,+"<range>",<bang>0,"<mods>",<q-args>, "l")'
575 exe 'command! -bang -nargs=? -range=-1 -complete=customlist,fugitive#LogComplete GlLog :exe fugitive#LogCommand(<line1>,<count>,+"<range>",<bang>0,"<mods>",<q-args>, "l")'
577 exe 'command! -bar -bang -nargs=*                          -complete=customlist,fugitive#EditComplete   Ge       exe fugitive#Open("edit<bang>", 0, "<mods>", <q-args>)'
578 exe 'command! -bar -bang -nargs=*                          -complete=customlist,fugitive#EditComplete   Gedit    exe fugitive#Open("edit<bang>", 0, "<mods>", <q-args>)'
579 exe 'command! -bar -bang -nargs=*                          -complete=customlist,fugitive#EditComplete   Gpedit   exe fugitive#Open("pedit", <bang>0, "<mods>", <q-args>)'
580 exe 'command! -bar -bang -nargs=* -range=-1' s:addr_other '-complete=customlist,fugitive#EditComplete   Gsplit   exe fugitive#Open((<count> > 0 ? <count> : "").(<count> ? "split" : "edit"), <bang>0, "<mods>", <q-args>)'
581 exe 'command! -bar -bang -nargs=* -range=-1' s:addr_other '-complete=customlist,fugitive#EditComplete   Gvsplit  exe fugitive#Open((<count> > 0 ? <count> : "").(<count> ? "vsplit" : "edit!"), <bang>0, "<mods>", <q-args>)'
582 exe 'command! -bar -bang -nargs=* -range=-1' s:addr_tabs  '-complete=customlist,fugitive#EditComplete   Gtabedit exe fugitive#Open((<count> >= 0 ? <count> : "")."tabedit", <bang>0, "<mods>", <q-args>)'
583 exe 'command! -bar -bang -nargs=*                          -complete=customlist,fugitive#EditComplete   Gdrop    exe fugitive#DropCommand(<line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
585 if exists(':Gr') != 2
586   exe 'command! -bar -bang -nargs=* -range=-1                -complete=customlist,fugitive#ReadComplete   Gr     exe fugitive#ReadCommand(<line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
587 endif
588 exe 'command! -bar -bang -nargs=* -range=-1                -complete=customlist,fugitive#ReadComplete   Gread    exe fugitive#ReadCommand(<line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
590 exe 'command! -bar -bang -nargs=* -complete=customlist,fugitive#EditComplete Gdiffsplit  exe fugitive#Diffsplit(1, <bang>0, "<mods>", <q-args>)'
591 exe 'command! -bar -bang -nargs=* -complete=customlist,fugitive#EditComplete Ghdiffsplit exe fugitive#Diffsplit(0, <bang>0, "<mods>", <q-args>)'
592 exe 'command! -bar -bang -nargs=* -complete=customlist,fugitive#EditComplete Gvdiffsplit exe fugitive#Diffsplit(0, <bang>0, "vertical <mods>", <q-args>)'
594 exe 'command! -bar -bang -nargs=* -complete=customlist,fugitive#EditComplete Gw     exe fugitive#WriteCommand(<line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
595 exe 'command! -bar -bang -nargs=* -complete=customlist,fugitive#EditComplete Gwrite exe fugitive#WriteCommand(<line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
596 exe 'command! -bar -bang -nargs=* -complete=customlist,fugitive#EditComplete Gwq    exe fugitive#WqCommand(   <line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
598 exe 'command! -bar -bang -nargs=0 GRemove exe fugitive#RemoveCommand(<line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
599 exe 'command! -bar -bang -nargs=0 GUnlink exe fugitive#UnlinkCommand(<line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
600 exe 'command! -bar -bang -nargs=0 GDelete exe fugitive#DeleteCommand(<line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
601 exe 'command! -bar -bang -nargs=1 -complete=customlist,fugitive#CompleteObject GMove   exe fugitive#MoveCommand(  <line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
602 exe 'command! -bar -bang -nargs=1 -complete=customlist,fugitive#RenameComplete GRename exe fugitive#RenameCommand(<line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
603 if exists(':Gremove') != 2 && get(g:, 'fugitive_legacy_commands', 0)
604   exe 'command! -bar -bang -nargs=0 Gremove exe fugitive#RemoveCommand(<line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
605         \ '|echohl WarningMSG|echomsg ":Gremove is deprecated in favor of :GRemove"|echohl NONE'
606 elseif exists(':Gremove') != 2 && !exists('g:fugitive_legacy_commands')
607   exe 'command! -bar -bang -nargs=0 Gremove echoerr ":Gremove has been removed in favor of :GRemove"'
608 endif
609 if exists(':Gdelete') != 2 && get(g:, 'fugitive_legacy_commands', 0)
610   exe 'command! -bar -bang -nargs=0 Gdelete exe fugitive#DeleteCommand(<line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
611         \ '|echohl WarningMSG|echomsg ":Gdelete is deprecated in favor of :GDelete"|echohl NONE'
612 elseif exists(':Gdelete') != 2 && !exists('g:fugitive_legacy_commands')
613   exe 'command! -bar -bang -nargs=0 Gdelete echoerr ":Gdelete has been removed in favor of :GDelete"'
614 endif
615 if exists(':Gmove') != 2 && get(g:, 'fugitive_legacy_commands', 0)
616   exe 'command! -bar -bang -nargs=1 -complete=customlist,fugitive#CompleteObject Gmove   exe fugitive#MoveCommand(  <line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
617         \ '|echohl WarningMSG|echomsg ":Gmove is deprecated in favor of :GMove"|echohl NONE'
618 elseif exists(':Gmove') != 2 && !exists('g:fugitive_legacy_commands')
619   exe 'command! -bar -bang -nargs=? -complete=customlist,fugitive#CompleteObject Gmove'
620         \ 'echoerr ":Gmove has been removed in favor of :GMove"'
621 endif
622 if exists(':Grename') != 2 && get(g:, 'fugitive_legacy_commands', 0)
623   exe 'command! -bar -bang -nargs=1 -complete=customlist,fugitive#RenameComplete Grename exe fugitive#RenameCommand(<line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
624         \ '|echohl WarningMSG|echomsg ":Grename is deprecated in favor of :GRename"|echohl NONE'
625 elseif exists(':Grename') != 2 && !exists('g:fugitive_legacy_commands')
626   exe 'command! -bar -bang -nargs=? -complete=customlist,fugitive#RenameComplete Grename'
627         \ 'echoerr ":Grename has been removed in favor of :GRename"'
628 endif
630 exe 'command! -bar -bang -range=-1 -nargs=* -complete=customlist,fugitive#CompleteObject GBrowse exe fugitive#BrowseCommand(<line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
631 if exists(':Gbrowse') != 2 && get(g:, 'fugitive_legacy_commands', 0)
632   exe 'command! -bar -bang -range=-1 -nargs=* -complete=customlist,fugitive#CompleteObject Gbrowse exe fugitive#BrowseCommand(<line1>, <count>, +"<range>", <bang>0, "<mods>", <q-args>)'
633         \ '|if <bang>1|redraw!|endif|echohl WarningMSG|echomsg ":Gbrowse is deprecated in favor of :GBrowse"|echohl NONE'
634 elseif exists(':Gbrowse') != 2 && !exists('g:fugitive_legacy_commands')
635   exe 'command! -bar -bang -range=-1 -nargs=* -complete=customlist,fugitive#CompleteObject Gbrowse'
636         \ 'echoerr ":Gbrowse has been removed in favor of :GBrowse"'
637 endif
639 if v:version < 704
640   finish
641 endif
643 let g:io_fugitive = {
644       \ 'simplify': function('fugitive#simplify'),
645       \ 'resolve': function('fugitive#resolve'),
646       \ 'getftime': function('fugitive#getftime'),
647       \ 'getfsize': function('fugitive#getfsize'),
648       \ 'getftype': function('fugitive#getftype'),
649       \ 'filereadable': function('fugitive#filereadable'),
650       \ 'filewritable': function('fugitive#filewritable'),
651       \ 'isdirectory': function('fugitive#isdirectory'),
652       \ 'getfperm': function('fugitive#getfperm'),
653       \ 'setfperm': function('fugitive#setfperm'),
654       \ 'readfile': function('fugitive#readfile'),
655       \ 'writefile': function('fugitive#writefile'),
656       \ 'glob': function('fugitive#glob'),
657       \ 'delete': function('fugitive#delete'),
658       \ 'Real': function('FugitiveReal')}
660 augroup fugitive
661   autocmd!
663   autocmd BufNewFile,BufReadPost *
664         \ if exists('b:git_dir') && b:git_dir =~# '^$\|' . s:bad_git_dir |
665         \   unlet b:git_dir |
666         \ endif
667   autocmd FileType           netrw
668         \ if exists('b:git_dir') && b:git_dir =~# '^$\|' . s:bad_git_dir |
669         \   unlet b:git_dir |
670         \ endif
671   autocmd BufFilePost            *  unlet! b:git_dir
673   autocmd FileType git
674         \ call fugitive#MapCfile()
675   autocmd FileType gitcommit
676         \ call fugitive#MapCfile('fugitive#MessageCfile()')
677   autocmd FileType git,gitcommit
678         \ if &foldtext ==# 'foldtext()' |
679         \    setlocal foldtext=fugitive#Foldtext() |
680         \ endif
681   autocmd FileType fugitive
682         \ call fugitive#MapCfile('fugitive#PorcelainCfile()')
683   autocmd FileType gitrebase
684         \ let &l:include = '^\%(pick\|squash\|edit\|reword\|fixup\|drop\|[pserfd]\)\>' |
685         \ if &l:includeexpr !~# 'Fugitive' |
686         \   let &l:includeexpr = 'v:fname =~# ''^\x\{4,\}$'' && len(FugitiveGitDir()) ? FugitiveFind(v:fname) : ' .
687         \     (len(&l:includeexpr) ? &l:includeexpr : 'v:fname') |
688         \ endif |
689         \ let b:undo_ftplugin = get(b:, 'undo_ftplugin', 'exe') . '|setl inex= inc='
691   autocmd BufReadCmd index{,.lock} nested
692         \ if FugitiveIsGitDir(expand('<amatch>:p:h')) |
693         \   let b:git_dir = s:Slash(expand('<amatch>:p:h')) |
694         \   exe fugitive#BufReadStatus(v:cmdbang) |
695         \   echohl WarningMSG |
696         \   echo "fugitive: Direct editing of .git/" . expand('%:t') . " is deprecated" |
697         \   echohl NONE |
698         \ elseif filereadable(expand('<amatch>')) |
699         \   silent doautocmd BufReadPre |
700         \   keepalt noautocmd read <amatch> |
701         \   silent 1delete_ |
702         \   silent doautocmd BufReadPost |
703         \ else |
704         \   silent doautocmd BufNewFile |
705         \ endif
707   autocmd BufReadCmd   fugitive://*          nested exe fugitive#BufReadCmd() |
708         \ if &path =~# '^\.\%(,\|$\)' |
709         \   let &l:path = substitute(&path, '^\.,\=', '', '') |
710         \ endif
711   autocmd BufWriteCmd  fugitive://*          nested exe fugitive#BufWriteCmd()
712   autocmd FileReadCmd  fugitive://*          nested exe fugitive#FileReadCmd()
713   autocmd FileWriteCmd fugitive://*          nested exe fugitive#FileWriteCmd()
714   if exists('##SourceCmd')
715     autocmd SourceCmd     fugitive://*       nested exe fugitive#SourceCmd()
716   endif
718   autocmd User Flags call Hoist('buffer', function('FugitiveStatusline'))
720   autocmd User ProjectionistDetect call s:ProjectionistDetect()
721 augroup END
723 nmap <script><silent> <Plug>fugitive:y<C-G> :<C-U>call setreg(v:register, fugitive#Object(@%))<CR>
724 nmap <script> <Plug>fugitive: <Nop>
726 if get(g:, 'fugitive_no_maps')
727   finish
728 endif
730 function! s:Map(mode, lhs, rhs, flags) abort
731   let flags = a:flags . (a:rhs =~# '<Plug>' ? '' : '<script>') . '<nowait>'
732   let head = a:lhs
733   let tail = ''
734   let keys = get(g:, a:mode.'remap', {})
735   if len(keys) && type(keys) == type({})
736     while !empty(head)
737       if has_key(keys, head)
738         let head = keys[head]
739         if empty(head)
740           return
741         endif
742         break
743       endif
744       let tail = matchstr(head, '<[^<>]*>$\|.$') . tail
745       let head = substitute(head, '<[^<>]*>$\|.$', '', '')
746     endwhile
747   endif
748   if empty(mapcheck(head.tail, a:mode))
749     exe a:mode.'map' flags head.tail a:rhs
750   endif
751 endfunction
753 call s:Map('c', '<C-R><C-G>', 'fnameescape(fugitive#Object(@%))', '<expr>')
754 call s:Map('n', 'y<C-G>', ':<C-U>call setreg(v:register, fugitive#Object(@%))<CR>', '<silent>')