1

I'd like to combine two events: FileType and TextChangedI. According to this awesome book I can do that, by adding a comma between both events like this:

:autocmd BufWritePre,BufRead *.html :normal gg=G

But if I try that with FileType and TextChangedI like that:

autocmd TextChangedI,FileType c echom "Test"

than I don't get any output if I change something in a c file. How can I achieve that?

4
  • 1
    TextChangedI matches against the filename, and FileType against the filetype, you can't really combine those two. <buffer> is a special pattern which matches against the current buffer. Jan 23 at 20:49
  • oh ok. Thank you for the information! Do you have an idea for a workaround for this "combination"? One idea would be that the user has to provide something like a whitelist and the plugin iterates everytime through that list, but it might has a pretty bad performance...
    – TornaxO7
    Jan 23 at 21:04
  • I would just define two autocmds and put the actual code in a function. Jan 23 at 21:26
  • We do prefer multiple questions to be split up; I’ve been personally lenient with this when the questions are intricately connected (splitting is not always easy!), but that doesn’t seem to be the case here. I believe your questions are (1) why doesn’t this combined autocommand work (and how do i fix it), and (2) what’s this <buffer> stuff? I’ve removed the second question. You should feel free to post it separately!
    – D. Ben Knoble
    Jan 23 at 23:41
3

As Martin mentions in the comments, the two events match on different things. It would be simpler to make a function and use two autocommands (the combined form works best when both match on the same types of things):

function DoIt() abort
endfunction

augroup my_c_stuff
  autocmd!
  autocmd FileType c call DoIt()
  autocmd TextChangedI *.c call DoIt()
augroup END

An even better solution would be to put the function, call, and text-changed autocommand into an ftplugin:

" ~/.vim/after/ftplugin/c.vim
function DoIt() abort
endfunction

call DoIt()

augroup my_c_stuff
  autocmd! * <buffer>
  autocmd TextChangedI <buffer> call DoIt<()
augroup END
" don’t forget b:undo_ftplugin!
2
  • What do you mean with " don’t forget b:undo_ftplugin!?
    – TornaxO7
    Jan 28 at 14:19
  • @TornaxO7 see the help on the subject. It’s a variable containing a string of code that runs to “destruct” all the filetype-specific code when a buffer’s filetype changes. If you change filetypes, you don’t want the old stuff lingering around!
    – D. Ben Knoble
    Jan 28 at 15:58

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.