TransWikia.com

Execute autocommand only if buffer contains a pattern

Vi and Vim Asked on December 30, 2021

Concrete example:

When using React with Styled Components, I want to load the CSS snippets file. I could achieve this with:

autocmd FileType javascript,typescript :UltiSnipsAddFiletypes css

However, I’d like to execute the command above only if styled-components is included in the current buffer.

Is this possible?

One Answer

Put the check in a function so it’s not a mess:

function react#add_snips() abort
  if search('styled-components', 'nw') != 0
    UltiSnipsAddFiletypes css
  endif
endfunction

(This can go in ~/.vim/autoload/react.vim)

And then call the function:

augroup react
  autocmd!
  autocmd Filetype javascript,typescript call react#add_snips
augroup END

Alternatively, place the call portion in both ~/.vim/after/ftplugin/javascript.vim and ~/.vim/after/ftplugin/typescript.vim.

Answered by D. Ben Knoble on December 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP