Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify the last-position-jump vimscript to not do it for git commit messages

Tags:

vim

Here's the script for convenience:

" Uncomment the following to have Vim jump to the last position when                                                       
" reopening a file
if has("autocmd")
  au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$")
    \| exe "normal! g'\"" | endif
endif

The feature is excellent but not when used with certain cases where Vim is invoked as editor: For instance often I write a two line git commit message so the next time I commit it's gonna drop me on the second line and I have to adjust for this.

Similarly many other systems allow you to specify Vim to be used as an editor as part of some process that involves editing a file.

How can we detect this and modify our last-position-jump script? Git's actually kind of special because it uses the .git/COMMIT_EDITMSG file which stays the same across commits which is why this is happening. With a temp file it wouldn't occur on files that Vim hasn't seen before.

This probably makes the task nearly trivial (augment the script with a check if current file == COMMIT_EDITMSG...)

But, a really perfect answer is if we can detect whether Vim is invoked from the command line or if it was opened by a script. Is there a way to tell? I know unix programs can determine if they are running in a term/pseudoterm or not, though either way they do end up receiving input from the terminal.

like image 920
Steven Lu Avatar asked Feb 16 '23 10:02

Steven Lu


2 Answers

If you don't want to modify the global rule (like in FDinoff's answer) with all sorts of exceptions, you can also undo the jump by putting the following into ~/.vim/after/ftplugin/gitcommit.vim:

:autocmd BufWinEnter <buffer> normal! gg0

Though I haven't experienced any problems with the above command, even on buffer switches, a more robust version makes the autocmd fire once:

augroup DisableLastPositionJump
    autocmd! BufWinEnter <buffer> execute 'normal! gg0' | autocmd! DisableLastPositionJump BufWinEnter <buffer>
augroup END
like image 171
Ingo Karkat Avatar answered May 21 '23 07:05

Ingo Karkat


Git commit messages have the filetype gitcommit.

Just add a check to see if the file is not of the gitcommit filetype for deciding when to jump to the last position.

if has("autocmd")
  au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$") && &filetype != "gitcommit"
    \| exe "normal! g'\"" | endif
endif
like image 39
FDinoff Avatar answered May 21 '23 05:05

FDinoff