detect-indent ![Build Status](https://travis-ci.org/sindresorhus/detect-indent.svg?branch=master)
Detect the indentation of code
Pass in a string of any kind of text and get the indentation.
Use cases
- Persisting the indentation when modifying a file.
- Have new content match the existing indentation.
- Setting the right indentation in your editor.
Install
$ npm install --save detect-indent
Usage
var fs = require('fs');
var detectIndent = require('detect-indent');
var file = fs.readFileSync('foo.json', 'utf8');
var indent = detectIndent(file).indent || ' ';
var json = JSON.parse(file);
json.ilove = 'unicorns';
fs.writeFileSync('foo.json', JSON.stringify(json, null, indent));
API
Accepts a string and returns an object with stats about the indentation:
amount
: {Number} the amount of indentation, e.g. 2
type
: {String|Null} the type of indentation. Possible values are tab
, space
or null
if no indentation is detectedindent
: {String} the actual indentation
CLI
$ npm install --global detect-indent
$ detect-indent --help
Usage
detect-indent <file>
echo <string> | detect-indent
Example
echo ' foo\n bar' | detect-indent | wc --chars
2
Algorithm
It first strips off multi-line comments. Then goes through each line counting whether it's tabs or spaces and the indent size coerced to an even number. The resulting indent size is the GCD (Greates Common Divisor) of the gathered line indent sizes and the type is the most used type.
License
MIT © Sindre Sorhus