What would be the difference between these two commands?

autocmd FileType python nnoremap <buffer> <localleader>d ihello!


autocmd FileType python nnoremap <localleader>d ihello!

One references <buffer> and one does not. To me they act the same in my testing of the two in different splits and then different windows, so was wondering why <buffer> needed to be included at all, but perhaps I'm not understanding why it's really needed.


1 Answer 1


I've already answered this question you've asked two days ago here

Without <buffer>, if you open a python file after an html one, either you'll see <option-space> from html still working, or you'll override <option-space> with a new one (if you have another mapping dedicated to python), even in the previous html buffer. Without <buffer>, mappings and abbreviations are global: shared between all buffers

To fully appreciate what happens, try the following

autocmd FileType python iab for for :<left>
autocmd FileType vim    iab for for<cr>endfor<up>

And then,

" open a python buffer
e foo.py
" type for + space
" -> should be ok

" open a vim buffer
sp foo.vim
" type for + space
" -> should be OK

" go back to the python buffer
sb foo.py " sb != sp
" type for + space
" -> you should see the vimscript snippet instead of the python one

" open a new python buffer
sp bar.py
" type for + space
" -> it works again!

" if you go back to foo.vim, 
sb foo.vim " sb != sp
" -> this time, this is the python snippet..

Non-<buffer> definitions are global, and Filetype event is triggered once per buffer.

=> the right way to do it is to use buffer-specific mappings, abbreviations, commands, variables... for things that are specific to a filetype.

And last thing, these things are not defined at a semantic level: while the even is Filetype, the definition is buffer-related, not filetype-related, as seen in this other Q/A of yours https://vi.stackexchange.com/a/25865/626.

  • thanks for this, that's a great answer. I appreciate your time writing it up!
    – David542
    Commented Jun 12, 2020 at 4:18
  • Here is going through your exercise with both global (right) and using <buffer> (left) -- imgur.com/a/VIkPgYI
    – David542
    Commented Jun 12, 2020 at 4:28

Your Answer

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

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