EditorConfig and consistency
Two editors on the same file disagree about almost nothing visible and about three things that are: a tab or two spaces, a newline of one byte or two, and whether the last line ends with one. An .editorconfig file answers those questions once for the project, and every editor with the plugin reads it before it writes a character.
The lesson writes the file, then a program that enforces it, which is what a project needs on a build server where no editor is involved. One file in the folder breaks four of the rules, the program names them, and Prettier repairs all four in one command.
One file for every editor
The format is a list of sections and keys: [*] applies to every file, [*.md] to one extension, and a later section overrides an earlier one for the files it matches. root = true at the top stops the search in the parent folders, so a project inside a home folder does not inherit a rule from outside the repository.
The file .editorconfig:
vi .editorconfig
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
indent_size = 2
[*.md]
trim_trailing_whitespace = false
Eight keys cover the whole style of the files. end_of_line takes lf, crlf or cr, and lf is the one to commit even on Windows, because a git checkout can convert it on the way out and a diff of mixed endings is unreadable. The markdown exception exists because two trailing spaces in markdown are a line break, and trimming them changes the rendering.
The editor honours the file only with a plugin or a built-in setting; the repository, the build server and the other tools do not read it at all. That is why the next section turns the same rules into a program.
A checker for the rules
The program reads the config, finds the section that matches each file and tests the four rules that a byte can decide. It is short because the format is short, and it prints one line per file with the count and the reasons.
The file check-style.js:
const { readFileSync, readdirSync } = require('node:fs');
const path = require('node:path');
function readConfig(text) {
const sections = new Map();
let current = null;
for (const raw of text.split('\n')) {
const line = raw.trim();
if (line === '' || line.startsWith('#')) {
continue;
}
const header = line.match(/^\[(.+)\]$/);
if (header !== null) {
current = header[1];
sections.set(current, new Map());
continue;
}
if (current === null) {
continue;
}
const [key, value] = line.split('=').map((part) => part.trim());
sections.get(current).set(key.toLowerCase(), value);
}
return sections;
}
function settingsFor(sections, file) {
const settings = {};
for (const [pattern, values] of sections) {
const matches = pattern === '*' || (pattern.startsWith('*.') && file.endsWith(pattern.slice(1)));
if (matches) {
Object.assign(settings, Object.fromEntries(values));
}
}
return settings;
}
function problemsOf(file, settings) {
const buffer = readFileSync(file);
const text = buffer.toString('utf8');
const problems = [];
if (settings.end_of_line === 'lf' && buffer.includes(13)) {
problems.push('line endings are CRLF');
}
if (settings.insert_final_newline === 'true' && !text.endsWith('\n')) {
problems.push('the last line has no newline');
}
if (settings.trim_trailing_whitespace === 'true' && /[ \t]+$/m.test(text)) {
problems.push('a line has whitespace before its newline');
}
const lines = text.split('\n');
const tabs = lines.filter((line) => line.startsWith('\t')).length;
if (settings.indent_style === 'space' && tabs > 0) {
problems.push(tabs + ' line(s) start with a tab');
}
const size = Number(settings.indent_size ?? 2);
const wrong = lines.filter((line) => {
const spaces = line.length - line.trimStart().length;
return line.trim() !== '' && spaces % size !== 0;
}).length;
if (wrong > 0) {
problems.push(wrong + ' line(s) are not indented by ' + size + ' spaces');
}
return problems;
}
const sections = readConfig(readFileSync('.editorconfig', 'utf8'));
const folder = process.argv[2] ?? '.';
let total = 0;
for (const name of readdirSync(folder).sort()) {
const file = path.join(folder, name);
const problems = problemsOf(file, settingsFor(sections, file));
total += problems.length;
console.log(file + (problems.length === 0 ? ': ok' : ': ' + problems.length + ' problem(s)'));
for (const problem of problems) {
console.log(' ' + problem);
}
}
console.log('problems in total:', total);
process.exitCode = total === 0 ? 0 : 1;
The folder has two source files. src/ok.js follows every rule, and src/tabs.js was written by an editor with other settings: tabs, CRLF and a space before the newline.
node check-style.js src
echo "the exit status: $?"
src/ok.js: ok
src/tabs.js: 4 problem(s)
line endings are CRLF
a line has whitespace before its newline
1 line(s) start with a tab
1 line(s) are not indented by 2 spaces
problems in total: 4
the exit status: 1
Four rules and four problems on one small file, and the status is 1, so the script is a check and not a report. The last two problems are counted separately from the first: a line that starts with a tab also fails the multiple-of-two test, and the reader is better served by both facts.
Line endings are bytes
The difference between LF and CRLF is invisible in an editor and obvious in a byte. A program reads the file as a buffer and counts the carriage returns, which is the number that decides whether a diff of the whole file will appear on the day somebody commits it.
The file bytes.js:
const { readFileSync } = require('node:fs');
const path = process.argv[2];
const buffer = readFileSync(path);
const bytes = Array.from(buffer);
const cr = bytes.filter((byte) => byte === 13).length;
const lf = bytes.filter((byte) => byte === 10).length;
const tabs = buffer.toString('utf8').split('\n').filter((line) => line.startsWith('\t')).length;
console.log(path + ':');
console.log(' bytes: ' + buffer.length);
console.log(' CR bytes: ' + cr + ', LF bytes: ' + lf);
console.log(' lines that start with a tab: ' + tabs);
node bytes.js src/tabs.js
src/tabs.js:
bytes: 87
CR bytes: 5, LF bytes: 5
lines that start with a tab: 1
Five newlines, each of them two bytes, which is why the file is 87 bytes for 82 characters. The carriage return is what an old terminal needed to move the cursor to the start of the line; a Unix editor stores only the line feed, and every tool of the last thirty years accepts it. A repository that mixes the two shows it in the diff, and git can normalise the endings on checkout with a setting, but the file in the history is what the next reader gets.
The formatter as the repair
Prettier has no support for .editorconfig, so its options have to say the same thing: endOfLine, tabWidth and useTabs. With the four options below, one command repairs all four problems of the file, and the checker proves it.
The file .prettierrc.json:
{
"singleQuote": true,
"endOfLine": "lf",
"tabWidth": 2,
"useTabs": false
}
npx prettier --write src --log-level warn
node bytes.js src/tabs.js
src/tabs.js:
bytes: 80
CR bytes: 0, LF bytes: 5
lines that start with a tab: 0
Seven bytes fewer, no carriage returns and no tab at the start of a line. The indentation went from a tab to two spaces, and the trailing space before the newline is gone. The check that failed a moment ago now passes on both files.
node check-style.js src
echo "the exit status: $?"
src/ok.js: ok
src/tabs.js: ok
problems in total: 0
the exit status: 0
A project keeps the file, the formatter options and the checker, because each one is read by a different reader: the editor reads the first, the formatter the second and the build server the third. The next lesson puts the checker, the linter and the tests behind one command.
Exercises
- Write a file without a final newline and run the checker. Which rule reports it, and why does a diff of such a file start with a warning?
- Add [*.json] with indent_size = 4 and run the checker on a JSON file. Which section wins, and why?
- Remove root = true and print the inherited settings of a file in a parent folder. Which file would a project pick up from above its own root?
- Change endOfLine to crlf in the Prettier config and run --write. Which counter of the byte program changes, and which editor option now disagrees?
- Run the checker on its own file. Which of the four rules does a program written in the style pass, and which one does it not test at all?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
.editorconfiganswer for a project?Answer
The indentation, the line endings and the final newline of every file
It is a set of per-file rules for the editor, and the other tools have to be told the same thing.
-
What does this program print?
const buffer = Buffer.from("a\r\nb\n"); console.log(buffer.includes(13), buffer.length);Answer
true 5
The carriage return is one byte, so the four characters and the extra byte make five.
-
What does
root = truedo?Answer
It stops the search for another .editorconfig above the folder
Without it an editor keeps looking upward and a rule from a home folder can leak into the project.
-
What does this program print?
const lines = ["a", "\tb", " c"]; console.log(lines.filter((line) => line.startsWith("\t")).length);Answer
1
Only the middle entry starts with the tab character.
-
How many bytes does a CRLF line ending take?
Answer
Two, a carriage return and a line feed
The pair is 13 and 10, while a Unix file stores only the 10.
-
What does this program print?
const text = "a line \nnext"; console.log(/[ \t]+$/m.test(text));Answer
true
The first line ends with spaces before its newline, and the m flag tests line by line.
-
Why does Prettier need
endOfLinewhen the project has an .editorconfig?Answer
Because Prettier does not read .editorconfig
The formatter has its own options, and a project keeps them in agreement by hand.
-
What does this program print?
const lines = ["a", "", "b "]; console.log(lines.filter((line) => line.trim() !== "").length);Answer
2
The empty line is dropped and the trailing spaces of the third line do not make it empty.
-
Which rule of the file is not about the text of a line but about its bytes?
Answer
The line ending
CRLF is two bytes for one newline, and a text editor shows no difference at all.
-
What does this program print?
const settings = { end_of_line: "lf", indent_size: "2" }; console.log(Number(settings.indent_size) * 2);Answer
4
The value is a string in the file, and Number turns it into the two that multiply.
The programs and commands on this page were run with Node.js 24.22.1, Prettier 3.9.10 and ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev