2

When looking at changes in a code base containing tabs for indentation with git diff the tab characters are replaced by a number of spaces. The same happens when looking at patches with git show. When I use git format-patch and look at the resulting file with cat everything seems fine.

As these commands display machine-readable patches that are broken by replacing characters, I wonder what is going on and how to stop this from happening.

stefanct
  • 2,503
  • 1
  • 28
  • 32

1 Answers1

3

Neither git command does modify any characters in its output apart from adding control characters to enable color output and external text conversion filters for binary files if specifically enabled. However, the output is usually piped through a pager application. On many Linux systems the default pager is less and that does do replace tabs! You can easily test this behavior by piping the diff output into a file or through another application, e.g. git diff | cat will not tinker with tabs and should make them visible if paging is the culprit.

However, some terminal emulators might also do this and piping through cat would still "show" spaces instead of tabs. This can be verified by piping through something like hexdump: git diff | hd where you should see 0x09 aka \t characters where tabs are in the actual source code.

You can disable paging temporarily by using git --no-pager [command] or by simply piping the output through cat. There are also different configuration options to influence the use of pagers more permanently, e.g., disabling it globally for specific commands, e.g., for diff: git config --global pager.diff false

stefanct
  • 2,503
  • 1
  • 28
  • 32
  • 1
    I mentioned the file option too, but I don't think it is good practice to do things. `git format-patch` is way better to create patch files so I made it a side note only. – stefanct Sep 03 '21 at 07:55
  • It's also the case that cut-and-paste will sometimes, on some platforms, replace tabs with spaces; other times it won't. This makes for an interesting dynamic when using Firefox on a Mac to copy code into a StackOverflow edit window, as it's physically impossible to *type in* a tab, but you can (sometimes!) cut-and-paste one in. – torek Sep 03 '21 at 16:17