I would like to determine the tab width used in source files indented with spaces. This is not hard for files with particularly regular indentation, where the leading spaces are only used for indentation, always in multiples of the tab width, and with indentation increasing one level at at time. But many files will have some departure from this sort of regular indentation, generally for some form of vertical alignment. I'm thus looking for a good heuristic to estimate what tab width was used, allowing some possibility for irregular indentation.
The motivation for this is writing an extension for the SubEthaEdit editor. SubEthaEdit unfortunately doesn't make the tab width available for scripting, so I'm going to guess at it based on the text.
A suitable heuristic should:
- Perform well enough for interactive use. I don't imagine this will be a problem, and just a portion of the text can be used if need be.
- Be language independent.
- Return the longest suitable tab width. For example, any file with a tab width of four spaces could also be a file with two-space tabs, if every indentation was actually by twice as many levels. Clearly, four spaces would be the right choice.
- Always get it right if the indentation is completely regular.
Some simplifying factors:
- At least one line can be assumed to be indented.
- The tab width can be assumed to be at least two spaces.
- It's safe to assume that indentation is done with spaces only. It's not that I have anything against tabs---quite the contrary, I'll check first if there are any tabs used for indentation and handle it separately. This does mean that indentation mixing tabs and spaces might not be handled properly, but I don't consider it important.
- It may be assumed that there are no lines containing only whitespace.
- Not all languages need to be handled correctly. For example, success or failure with