1
|
# detect-indent [](https://travis-ci.org/sindresorhus/detect-indent)
|
2
|
|
3
|
> Detect the indentation of code
|
4
|
|
5
|
Pass in a string of any kind of text and get the indentation.
|
6
|
|
7
|
|
8
|
## Use cases
|
9
|
|
10
|
- Persisting the indentation when modifying a file.
|
11
|
- Have new content match the existing indentation.
|
12
|
- Setting the right indentation in your editor.
|
13
|
|
14
|
|
15
|
## Install
|
16
|
|
17
|
```
|
18
|
$ npm install --save detect-indent
|
19
|
```
|
20
|
|
21
|
|
22
|
## Usage
|
23
|
|
24
|
Here we modify a JSON file while persisting the indentation:
|
25
|
|
26
|
```js
|
27
|
var fs = require('fs');
|
28
|
var detectIndent = require('detect-indent');
|
29
|
|
30
|
/*
|
31
|
{
|
32
|
"ilove": "pizza"
|
33
|
}
|
34
|
*/
|
35
|
var file = fs.readFileSync('foo.json', 'utf8');
|
36
|
|
37
|
// tries to detect the indentation and falls back to a default if it can't
|
38
|
var indent = detectIndent(file).indent || ' ';
|
39
|
|
40
|
var json = JSON.parse(file);
|
41
|
|
42
|
json.ilove = 'unicorns';
|
43
|
|
44
|
fs.writeFileSync('foo.json', JSON.stringify(json, null, indent));
|
45
|
/*
|
46
|
{
|
47
|
"ilove": "unicorns"
|
48
|
}
|
49
|
*/
|
50
|
```
|
51
|
|
52
|
|
53
|
## API
|
54
|
|
55
|
Accepts a string and returns an object with stats about the indentation:
|
56
|
|
57
|
* `amount` {number} - Amount of indentation, e.g. `2`
|
58
|
* `type` {string|null} - Type of indentation. Possible values are `tab`, `space` or `null` if no indentation is detected
|
59
|
* `indent` {string} - Actual indentation
|
60
|
|
61
|
|
62
|
## Algorithm
|
63
|
|
64
|
The current algorithm looks for the most common difference between two consecutive non-empty lines.
|
65
|
|
66
|
In the following example, even if the 4-space indentation is used 3 times whereas the 2-space one is used 2 times, it is detected as less used because there were only 2 differences with this value instead of 4 for the 2-space indentation:
|
67
|
|
68
|
```css
|
69
|
html {
|
70
|
box-sizing: border-box;
|
71
|
}
|
72
|
|
73
|
body {
|
74
|
background: gray;
|
75
|
}
|
76
|
|
77
|
p {
|
78
|
line-height: 1.3em;
|
79
|
margin-top: 1em;
|
80
|
text-indent: 2em;
|
81
|
}
|
82
|
```
|
83
|
|
84
|
[Source.](https://medium.com/@heatherarthur/detecting-code-indentation-eff3ed0fb56b#3918)
|
85
|
|
86
|
Furthermore, if there are more than one most used difference, the indentation with the most lines is selected.
|
87
|
|
88
|
In the following example, the indentation is detected as 4-spaces:
|
89
|
|
90
|
```css
|
91
|
body {
|
92
|
background: gray;
|
93
|
}
|
94
|
|
95
|
p {
|
96
|
line-height: 1.3em;
|
97
|
margin-top: 1em;
|
98
|
text-indent: 2em;
|
99
|
}
|
100
|
```
|
101
|
|
102
|
|
103
|
## Related
|
104
|
|
105
|
- [detect-indent-cli](https://github.com/sindresorhus/detect-indent-cli) - CLI for this module
|
106
|
|
107
|
|
108
|
## License
|
109
|
|
110
|
MIT © [Sindre Sorhus](http://sindresorhus.com)
|