Last updated
Tabs vs Spaces: The Eternal Debate
The tabs vs spaces debate is one of the oldest in programming. Tabs are a single character that can be displayed at any width (2, 4, 8 spaces) depending on editor settings. Spaces are explicit — 4 spaces always look like 4 spaces. Most modern style guides (PEP 8 for Python, Google Style Guide, Prettier defaults) prefer spaces. The key rule: never mix tabs and spaces in the same file.
Converting with Regex
// Convert tabs to spaces (handles mixed indentation)
function tabsToSpaces(code, tabSize = 4) {
const spaces = ' '.repeat(tabSize);
return code.split('
').map(line => {
let result = '';
let col = 0;
for (const char of line) {
if (char === ' ') {
// Expand tab to next tab stop
const spaces_needed = tabSize - (col % tabSize);
result += ' '.repeat(spaces_needed);
col += spaces_needed;
} else {
result += char;
col++;
}
}
return result;
}).join('
');
}
// Convert spaces to tabs (only leading whitespace)
function spacesToTabs(code, tabSize = 4) {
const spacePattern = new RegExp(`^ {${tabSize}}`, 'gm');
let prev;
do {
prev = code;
code = code.replace(spacePattern, ' ');
} while (code !== prev);
return code;
}
Editor Configuration
// .editorconfig — enforces consistent indentation across editors
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.{js,ts,jsx,tsx,json,css,html}]
indent_size = 2
[Makefile]
indent_style = tab // Makefiles require tabs