Retrieve git branch only on new buffers
dblume

dblume commited on 2024-03-15 00:10:25
Showing 2 changed files, with 10 additions and 4 deletions.


Before this commit, git rev-parse would've been called for every key
press (if the statusline had added the git part).
... ...
@@ -72,7 +72,7 @@ set tags=tags;/
72 72
 
73 73
 set history=500
74 74
 
75
-function! StatuslineGit()
75
+function! GitBranch()
76 76
   let l:branchname = system("git -C " . expand('%:p:h') . " rev-parse --abbrev-ref HEAD 2>/dev/null | tr -d '\n'")
77 77
   return strlen(l:branchname) > 0 ? '  │ '.l:branchname : ''
78 78
 endfunction
... ...
@@ -104,7 +104,7 @@ endfunction
104 104
 
105 105
 set statusline=\ %{Current_mode()}
106 106
 set statusline+=%{&paste?'\ \ ·\ PASTE':''}
107
-"set statusline+=%{StatuslineGit()}
107
+set statusline+=%{b:git_branch}
108 108
 set statusline+=\ │\ %f
109 109
 set statusline+=%m
110 110
 set statusline+=\ %r
... ...
@@ -279,6 +279,9 @@ if has("autocmd")
279 279
   \ if &ft != "p4changelist" && &ft != "gitcommit" && line("'\"") > 0 && line ("'\"") <= line("$") |
280 280
   \   exe "normal! g'\"" |
281 281
   \ endif
282
+
283
+  autocmd BufNewFile,BufReadPost * let b:git_branch = GitBranch()
284
+  autocmd BufEnter * let b:git_branch = GitBranch()
282 285
 endif
283 286
 
284 287
 " This requires vim to be compiled with +python
... ...
@@ -94,7 +94,7 @@ set tags=tags;/
94 94
 set history=500
95 95
 set laststatus=2
96 96
 
97
-function! StatuslineGit()
97
+function! GitBranch()
98 98
   let l:branchname = system("git -C " . expand('%:p:h') . " rev-parse --abbrev-ref HEAD 2>/dev/null | tr -d '\n'")
99 99
   return strlen(l:branchname) > 0 ? '  │ '.l:branchname : ''
100 100
 endfunction
... ...
@@ -126,7 +126,7 @@ endfunction
126 126
 
127 127
 set statusline=\ %{Current_mode()}
128 128
 set statusline+=%{&paste?'\ \ ·\ PASTE':''}
129
-"set statusline+=%{StatuslineGit()}
129
+set statusline+=%{b:git_branch}
130 130
 set statusline+=\ │\ %f
131 131
 set statusline+=%m
132 132
 set statusline+=\ %r
... ...
@@ -308,6 +308,9 @@ if has("autocmd")
308 308
   \ if &ft != "p4changelist" && &ft != "gitcommit" && line("'\"") > 0 && line ("'\"") <= line("$") |
309 309
   \   exe "normal! g'\"" |
310 310
   \ endif
311
+
312
+  autocmd BufNewFile,BufReadPost * let b:git_branch = GitBranch()
313
+  autocmd BufEnter * let b:git_branch = GitBranch()
311 314
 endif
312 315
 
313 316
 " This requires vim to be compiled with +python
314 317