The following command will substitute all tabs in a file with four blank spaces:

%s/\t/    /g

In order to run this command whenever I open a new file I included it in my .vimrc by adding:

autocmd BufNewFile  *   exec "%s/\t/    /g"

However this didn't work. Does anyone know why?

  • 4
    New files don't contain any tabs, because they are empty. Are you looking for BufRead? – Rich May 24 '18 at 9:02
  • 6
    Also, you might be interested in the :retab command. – Rich May 24 '18 at 9:04
  • 4
    This is a very dangerous command. It will alter every file you open automatically. And if the file is readonly or nomodifiable it will probably throw a bunch of errors, also the use of gdefault has to be considered. I would not recommend this setting! Better would be to set your tabstop setting appropriately and have Vim display tabs as 4 spaces. – Christian Brabandt May 24 '18 at 9:50
  • Possible duplicate of How to replace tabs with spaces? – Tumbler41 May 24 '18 at 15:36
autocmd BufRead  *   exec "%s/\t/    /g"
  • 4
    you don't need the exe. BTW: are you sure you want to alter existing files automatically? – Christian Brabandt May 24 '18 at 9:39
  • 1
    I am sure i want to alter existing files automatically. – scrapy May 25 '18 at 6:40

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.