4

I have an autocommand function in my .vimrc that resets the cursor to where it was before I last closed the file. This function looks like this:

function! ResCur()
  if line("'\"") <= line("$")
    normal! g`"      
    return 1
  endif
endfunction                                                             
autocmd BufWinEnter * call ResCur()

I started using vim-template which recognizes a %HERE% variable in the templates that sets the cursor location. My custom function overrides this capability. Is there a way to change my autocommand to only reset the cursor when a template is not loaded so the %HERE% variable still works when a template is loaded? If part of the solution involves using a different template plugin, I would be happy to hear that as well.

2 Answers 2

7

Since this should only work for existing files, you'll want to use BufRead instead of BufWinEnter. vim-template won't trigger BufRead.

If you really need BufWinEnter to be used to process modelines before calling your function, you can use BufRead to set a buffer variable:

autocmd BufRead * let b:not_new = 1

And check if the variable exists before moving the cursor.

4

Looking at the vim-template source, it checks for the existence of %HERE% when jumping, you could do the same:

function! ResCur()
  if search("%HERE%", "n")
    return
  endif

  if line("'\"") <= line("$")
    normal! g`"      
    return 1
  endif
endfunction                                                             
autocmd BufWinEnter * call ResCur()

The n flag means do not move the cursor on search and the function return the line number, you can check its existence before moving.

This should be fine (I've not tested though, as I don't have the plugin installed).

3
  • I attempted this and it wasn't reliable. The best programmatic way I found was using histget('search' -1) == '%HERE%' then histdel(search, -1) if found. But that seemed like overkill since BufRead appeared to be adequate.
    – Tommy A
    Jun 28, 2016 at 16:41
  • Make sense, it was just a wild guess without having the plugin :3
    – nobe4
    Jun 28, 2016 at 16:42
  • 1
    It was definitely a good guess! The problem is the plugin uses BufNewFile which runs before BufWinEnter. If BufWinEnter is really needed, a second autocmd can't be avoided.
    – Tommy A
    Jun 28, 2016 at 16:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.