-1

I'd like to make it so that in my current project, when I write the file :w, if the file is *.cpp then also automatically run the substitution

:%s@^\(  \)\+@\=repeat("\t", strlen(submatch(0)) / &ts)

To replace spaces with tabs.

I want it to affect only my current directory/project.

So I thought about using set exrc and adding an autocmd

autocmd BufWrite *.cpp :%s@^\(  \)\+@\=repeat("\t", strlen(submatch(0)) / &ts)

but set exrc should be used with set secure and set secure disables autocmd.

Is there another solution where I won't have to disable set secure?

minseong
  • 2,313
  • 1
  • 19
  • 38
  • 1
    Can't you define the autocommand in your vimrc and in the command itself add a check on the filepath before running the substitution? (Also don't forget the augroup) – statox Mar 18 '21 at 14:21
  • 1
    You could use a local vimrc plugin , which unlike .exrc applies to subdirectories as well. But, honestly, I'd use editorconfig for that purpose. BTW, why don't you use :setlocal noexpandtab + :retab? – Luc Hermitte Mar 18 '21 at 14:23
  • @LucHermitte I guess I could add an exrc :setlocal noexpandtab – minseong Mar 18 '21 at 14:27

1 Answers1

1

To avoid using a local vimrc or the exrc option or things like that I would use a ftplugin (:h ftplugin) with a condition on the filepath.

Create the file ~/.vim/after/ftplugin/cpp.vim and in it use the following condition:

if (expand('%') =~ 'foo')
    setlocal noexpandtab
endif

This way you will set the noexpandtab option only if the file path matches foo. Depending on your directory structure you might want a different match (maybe adding / or the complete path). If you are not familiar with expand() see :h expand().

In the condition you'll need to use buffer local settings only: setlocal works well for noexpandtab and if you still want to use an autocommand check :h autocmd-buflocal.

Also as Luc pointed out in the comments I think it's easier to use editorconfig or to configure a linter (there are dozens different ways to do that) rather than relying on your own autocommand.

statox
  • 49,782
  • 19
  • 148
  • 225