Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim restores cursor position; exclude special files

Tags:

vim

The following code is inside my .vimrc and generally restores the last cursor position of a file I opened with vim:

autocmd BufReadPost *
  \ if line("'\"") > 1 && line("'\"") <= line("$") |
  \   exe "normal! g`\"" |
  \ endif

I really like this feature and want to leave it turned on, except for one file: When commiting with git, vim gets fired up and I can edit the commit message with it. However the commit message file exists before vim starts (and is prefilled), so vim sees it as an existing file and restores the last cursor position (which is usually not where I would like to start to type).

So is there a possibility to modify the above script to exclude the COMMIT_EDITMSG file?

like image 951
poke Avatar asked Mar 06 '10 18:03

poke


3 Answers

After reading through the manual on auto commands, I noticed that it seems not possible to define the pattern they match to in such a way that they exclude a special pattern. And I also wasn't able to use some variable that contains the current filename, so that I simply expand the existing if to exclude the file.

However, based on the comment by Pavel Shved (about the gg moving to the top of the file) I thought that in the same way it should be possible to simply overwrite the effect of the position restoring, by simply moving it to the top later again. So I came up with this:

autocmd BufReadPost COMMIT_EDITMSG
  \ exe "normal! gg"

Placing this after the previous autocmd BufReadPost simply chains the event execution, so vim, after executing the first and restoring the position, reads this and matches it on the excluded filename and uses the gg to move the cursor to the top, basically overwriting the effect of the original autocmd.

And that works just fine :)

like image 88
poke Avatar answered Nov 12 '22 08:11

poke


I understand you have already come up with a solution but I had the same question and came up with an alternative that doesn't require chaining.

function! PositionCursorFromViminfo()
  if !(bufname("%") =~ '\(COMMIT_EDITMSG\)') && line("'\"") > 1 && line("'\"") <= line("$")
    exe "normal! g`\""
  endif
endfunction
:au BufReadPost * call PositionCursorFromViminfo()
like image 29
Robert Wahler Avatar answered Nov 12 '22 08:11

Robert Wahler


You should probably investigate mksession. You can set up VimEnter/VimLeave auto commands to "do the right thing" when you have specified files on the command line (as when git invokes vim). There are numerous scripts for this floating around, see http://vim.wikia.com/wiki/Working_with_multiple_sessions for example.

like image 1
ergosys Avatar answered Nov 12 '22 06:11

ergosys