3

After typing tds I would like to see it replaced with the current time stamp in Markdown files, but eg. NOT while editing C source code.

The following mostly works (stripped for brevity) except that the the abbreviation tds is available in every buffer (mode) not just a markdown mode buffer.

augroup TXT | au!
autocmd BufRead,BufNewFile *.asciidoc,*.md,README,TODO,CHANGELOG,NOTES,ABOUT
\ setlocal autoindent expandtab tabstop=8 softtabstop=2 shiftwidth=2 |
\ :iab <buffer> <expr> tds strftime("%F %b %T")
augroup END

How can I define an abbreviation to be available in certain buffer modes only?

  • 1
    I expect the | is the issue—it’s being executed globally, rather than attached to the autocommand. Try separating it, or using the (after/) ftplugin directory, which is better anyway. – D. Ben Knoble Feb 5 at 14:04
  • That's been the issue, it works now as expected! – JohnDoe Feb 5 at 14:59
  • Great, I've written an answer – D. Ben Knoble Feb 5 at 15:04
3

When creating an autocommand, the :au part interprets | as a command separator. Just like for mappings, you need to escape it:

au setlocal autoindent expandtab tabstop=8 softtabstop=2 shiftwidth=2 \| inoreabbrev <buffer> <expr> tds strftime("%F %b %T")

Or, use two autocommands:

au setlocal autoindent expandtab tabstop=8 softtabstop=2 shiftwidth=2
au inoreabbrev <buffer> <expr> tds strftime("%F %b %T")

Or, my preferred solution, put it in ~/.vim/after/ftplugin/markdown.vim:

setlocal autoindent expandtab tabstop=8 softtabstop=2 shiftwidth=2
inoreabbrev <buffer> <expr> tds strftime("%F %b %T")
| improve this answer | |
1

What you want is to run the abbreviation command only for that buffer.

autocmd FileType markdown iab <buffer> tds strftime("%F %b %T")

I've also made it into a FileType event autocommand, instead of a BufRead,BufNewFile. So it changes this stuff when filetype is set. I think it's more suitable, but in most cases won't make a lot of difference.

I got most of this from https://learnvimscriptthehardway.stevelosh.com/chapters/12.html#filetype-events.

| improve this answer | |
  • Been on this link before. Doesn't work for me, abbreviation is available in every buffer. Using Neovim fwiw. – JohnDoe Feb 5 at 13:59
  • Note this should be inoreabbrev <buffer> – D. Ben Knoble Feb 5 at 14:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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