Question

I'm a Vim user who (due to my Python background) has grown accustomed to spaces instead of tabs. I'm working on a PHP project with another developer who uses Windows IDEs and really wants to use tabs. There really doesn't seem to be any hard and fast style guide for PHP that prefers a specific style, so I'm kind of stuck needing to deal with the tabs.

Is there some way, either through Git or Vim, that I can work with tabbed code and convert it to spaces while I'm editing it? Then perhaps on git add/commit it could be converted back to tabs?

Was it helpful?

Solution

The one really important thing is that the tracked content be standardized. You and the other developer are just going to have to agree on something there. Whichever of you wants to do something besides the agreed-upon standard is may end up with mixed results. It's not always possible to cleanly convert back and forth.

I would really recommend just dealing with it. I have my own opinion about tabs and spaces, and I've worked on code using each. The best thing to do is just to set up your editor to match the standardized style, and go with it. In vim, turn off expandtab, set tabstop to what you like.

If you still want to try, there are two primary ways:

  • Use autocommands in Vim to convert on read/write. You'd probably need BufReadPost, BufWritePre, and BufWritePost. (For writing, you convert to the standard, let Vim write it, then convert back to the way you like to edit.) Make sure tabstop is set the way you like, then something like this (untested):

    set tabstop=4
    autocmd BufReadPost * set expandtab | retab
    autocmd BufWritePre * set noexpandtab | retab!
    autocmd BufWritePost * set expandtab | retab
    

The * is the filepattern that this will apply to; you may have to mess with that, or only add the autocommands for files within a certain directory, to make sure this doesn't happen for everything you edit. Note that this is dangerous; it will for example replace literal tab characters inside strings.

  • Use Git's smudge/clean filters. You can read about them in man gitattributes, or in Pro Git. You could use those to convert for editing, then back to the standard for committing. If there's never any weird indentation, it could be as simple as changing leading tabs to some number of spaces, and leading spaces to a fraction of that number of tabs. Do it with sed/perl/indent, whatever you're comfortable with.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top