pax_global_header00006660000000000000000000000064140541057240014514gustar00rootroot0000000000000052 comment=30044e44e9f29104a04a1b5fc94dbf60b27eaa1b detect-indent-6.1.0/000077500000000000000000000000001405410572400142475ustar00rootroot00000000000000detect-indent-6.1.0/.editorconfig000066400000000000000000000002571405410572400167300ustar00rootroot00000000000000root = true [*] indent_style = tab end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.yml] indent_style = space indent_size = 2 detect-indent-6.1.0/.gitattributes000066400000000000000000000000231405410572400171350ustar00rootroot00000000000000* text=auto eol=lf detect-indent-6.1.0/.github/000077500000000000000000000000001405410572400156075ustar00rootroot00000000000000detect-indent-6.1.0/.github/funding.yml000066400000000000000000000001671405410572400177700ustar00rootroot00000000000000github: sindresorhus open_collective: sindresorhus tidelift: npm/detect-indent custom: https://sindresorhus.com/donate detect-indent-6.1.0/.github/security.md000066400000000000000000000002631405410572400200010ustar00rootroot00000000000000# Security Policy To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. detect-indent-6.1.0/.github/workflows/000077500000000000000000000000001405410572400176445ustar00rootroot00000000000000detect-indent-6.1.0/.github/workflows/main.yml000066400000000000000000000007021405410572400213120ustar00rootroot00000000000000name: CI on: - push - pull_request jobs: test: name: Node.js ${{ matrix.node-version }} runs-on: ubuntu-latest strategy: fail-fast: false matrix: node-version: - 14 - 12 - 10 - 8 steps: - uses: actions/checkout@v2 - uses: actions/setup-node@v1 with: node-version: ${{ matrix.node-version }} - run: npm install - run: npm test detect-indent-6.1.0/.gitignore000066400000000000000000000000271405410572400162360ustar00rootroot00000000000000node_modules yarn.lock detect-indent-6.1.0/.npmrc000066400000000000000000000000231405410572400153620ustar00rootroot00000000000000package-lock=false detect-indent-6.1.0/fixture/000077500000000000000000000000001405410572400157355ustar00rootroot00000000000000detect-indent-6.1.0/fixture/fifty-fifty-space-first.js000066400000000000000000000000501405410572400227440ustar00rootroot00000000000000 4 spaces 4 spaces 1 tab 1 tab detect-indent-6.1.0/fixture/fifty-fifty-tab-first.js000066400000000000000000000000501405410572400224170ustar00rootroot00000000000000 1 tab 1 tab 4 spaces 4 spaces detect-indent-6.1.0/fixture/mixed-space.js000066400000000000000000000014001405410572400204650ustar00rootroot00000000000000// devtools-detect // by Sindre Sorhus // MIT License (function (window) { /*global CustomEvent */ 'use strict'; var devtools = window.devtools = { open: false }; var threshold = 150; var emitEvent = function (state) { window.dispatchEvent(new CustomEvent('devtoolschange', { detail: { open: state } })); }; setInterval(function () { if (window.outerWidth - window.innerWidth > threshold || window.outerHeight - window.innerHeight > threshold) { if (!devtools.open) { emitEvent(true); } devtools.open = true; } else { if (devtools.open) { emitEvent(false); } devtools.open = false; } }, 500); })(window); detect-indent-6.1.0/fixture/mixed-tab.js000066400000000000000000000012701405410572400201450ustar00rootroot00000000000000// devtools-detect // by Sindre Sorhus // MIT License (function (window) { /*global CustomEvent */ 'use strict'; var devtools = window.devtools = { open: false }; var threshold = 150; var emitEvent = function (state) { window.dispatchEvent(new CustomEvent('devtoolschange', { detail: { open: state } })); }; setInterval(function () { if (window.outerWidth - window.innerWidth > threshold || window.outerHeight - window.innerHeight > threshold) { if (!devtools.open) { emitEvent(true); } devtools.open = true; } else { if (devtools.open) { emitEvent(false); } devtools.open = false; } }, 500); })(window); detect-indent-6.1.0/fixture/single-space-ignore.js000066400000000000000000000001411405410572400221220ustar00rootroot00000000000000/** * * Long * Multi-line * Single space * Comment * */ 4 spaces 4 spaces 1 tab detect-indent-6.1.0/fixture/single-space-only.js000066400000000000000000000000331405410572400216200ustar00rootroot00000000000000 1 space 1 space 1 space detect-indent-6.1.0/fixture/space-tab-last.js000066400000000000000000000000561405410572400210740ustar00rootroot00000000000000 4 spaces 4 spaces 1 tab 1 tab 1 tabdetect-indent-6.1.0/fixture/space.js000066400000000000000000000015021405410572400173640ustar00rootroot00000000000000// devtools-detect // by Sindre Sorhus // MIT License (function (window) { /*global CustomEvent */ 'use strict'; var devtools = window.devtools = { open: false }; var threshold = 150; var emitEvent = function (state) { window.dispatchEvent(new CustomEvent('devtoolschange', { detail: { open: state } })); }; setInterval(function () { if (window.outerWidth - window.innerWidth > threshold || window.outerHeight - window.innerHeight > threshold) { if (!devtools.open) { emitEvent(true); } devtools.open = true; } else { if (devtools.open) { emitEvent(false); } devtools.open = false; } }, 500); })(window); detect-indent-6.1.0/fixture/tab-four.js000066400000000000000000000000261405410572400200100ustar00rootroot00000000000000 * four * tabs detect-indent-6.1.0/fixture/tab.js000066400000000000000000000012271405410572400170430ustar00rootroot00000000000000// devtools-detect // by Sindre Sorhus // MIT License (function (window) { /*global CustomEvent */ 'use strict'; var devtools = window.devtools = { open: false }; var threshold = 150; var emitEvent = function (state) { window.dispatchEvent(new CustomEvent('devtoolschange', { detail: { open: state } })); }; setInterval(function () { if (window.outerWidth - window.innerWidth > threshold || window.outerHeight - window.innerHeight > threshold) { if (!devtools.open) { emitEvent(true); } devtools.open = true; } else { if (devtools.open) { emitEvent(false); } devtools.open = false; } }, 500); })(window); detect-indent-6.1.0/fixture/vendor-prefixed-css.css000066400000000000000000000004331405410572400223360ustar00rootroot00000000000000#leaflet { position: absolute; top: 0; right: 0; bottom: 0; left: 0; -webkit-box-shadow: inset -5px -5px 5px rgba(0, 0, 0, 0.6); -moz-box-shadow: inset -5px -5px 5px rgba(0, 0, 0, 0.6); box-shadow: inset -5px -5px 5px rgba(0, 0, 0, 0.6); } detect-indent-6.1.0/index.d.ts000066400000000000000000000016611405410572400161540ustar00rootroot00000000000000declare namespace detectIndent { interface Indent { /** Type of indentation. Is `undefined` if no indentation is detected. */ type: 'tab' | 'space' | undefined; /** Amount of indentation, for example `2`. */ amount: number; /** Actual indentation. */ indent: string; } } /** Detect the indentation of code. @param string - A string of any kind of text. @example ``` import * as fs from 'fs'; import detectIndent = require('detect-indent'); // { // "ilove": "pizza" // } const file = fs.readFileSync('foo.json', 'utf8'); // Tries to detect the indentation and falls back to a default if it can't const indent = detectIndent(file).indent || ' '; const json = JSON.parse(file); json.ilove = 'unicorns'; fs.writeFileSync('foo.json', JSON.stringify(json, null, indent)); // { // "ilove": "unicorns" // } ``` */ declare function detectIndent(string: string): detectIndent.Indent; export = detectIndent; detect-indent-6.1.0/index.js000066400000000000000000000100131405410572400157070ustar00rootroot00000000000000'use strict'; // Detect either spaces or tabs but not both to properly handle tabs for indentation and spaces for alignment const INDENT_REGEX = /^(?:( )+|\t+)/; const INDENT_TYPE_SPACE = 'space'; const INDENT_TYPE_TAB = 'tab'; // Make a Map that counts how many indents/unindents have occurred for a given size and how many lines follow a given indentation. // The key is a concatenation of the indentation type (s = space and t = tab) and the size of the indents/unindents. // // indents = { // t3: [1, 0], // t4: [1, 5], // s5: [1, 0], // s12: [1, 0], // } function makeIndentsMap(string, ignoreSingleSpaces) { const indents = new Map(); // Remember the size of previous line's indentation let previousSize = 0; let previousIndentType; // Indents key (ident type + size of the indents/unindents) let key; for (const line of string.split(/\n/g)) { if (!line) { // Ignore empty lines continue; } let indent; let indentType; let weight; let entry; const matches = line.match(INDENT_REGEX); if (matches === null) { previousSize = 0; previousIndentType = ''; } else { indent = matches[0].length; if (matches[1]) { indentType = INDENT_TYPE_SPACE; } else { indentType = INDENT_TYPE_TAB; } // Ignore single space unless it's the only indent detected to prevent common false positives if (ignoreSingleSpaces && indentType === INDENT_TYPE_SPACE && indent === 1) { continue; } if (indentType !== previousIndentType) { previousSize = 0; } previousIndentType = indentType; weight = 0; const indentDifference = indent - previousSize; previousSize = indent; // Previous line have same indent? if (indentDifference === 0) { weight++; // We use the key from previous loop } else { const absoluteIndentDifference = indentDifference > 0 ? indentDifference : -indentDifference; key = encodeIndentsKey(indentType, absoluteIndentDifference); } // Update the stats entry = indents.get(key); if (entry === undefined) { entry = [1, 0]; // Init } else { entry = [++entry[0], entry[1] + weight]; } indents.set(key, entry); } } return indents; } // Encode the indent type and amount as a string (e.g. 's4') for use as a compound key in the indents Map. function encodeIndentsKey(indentType, indentAmount) { const typeCharacter = indentType === INDENT_TYPE_SPACE ? 's' : 't'; return typeCharacter + String(indentAmount); } // Extract the indent type and amount from a key of the indents Map. function decodeIndentsKey(indentsKey) { const keyHasTypeSpace = indentsKey[0] === 's'; const type = keyHasTypeSpace ? INDENT_TYPE_SPACE : INDENT_TYPE_TAB; const amount = Number(indentsKey.slice(1)); return {type, amount}; } // Return the key (e.g. 's4') from the indents Map that represents the most common indent, // or return undefined if there are no indents. function getMostUsedKey(indents) { let result; let maxUsed = 0; let maxWeight = 0; for (const [key, [usedCount, weight]] of indents) { if (usedCount > maxUsed || (usedCount === maxUsed && weight > maxWeight)) { maxUsed = usedCount; maxWeight = weight; result = key; } } return result; } function makeIndentString(type, amount) { const indentCharacter = type === INDENT_TYPE_SPACE ? ' ' : '\t'; return indentCharacter.repeat(amount); } module.exports = string => { if (typeof string !== 'string') { throw new TypeError('Expected a string'); } // Identify indents while skipping single space indents to avoid common edge cases (e.g. code comments) // If no indents are identified, run again and include all indents for comprehensive detection let indents = makeIndentsMap(string, true); if (indents.size === 0) { indents = makeIndentsMap(string, false); } const keyOfMostUsedIndent = getMostUsedKey(indents); let type; let amount = 0; let indent = ''; if (keyOfMostUsedIndent !== undefined) { ({type, amount} = decodeIndentsKey(keyOfMostUsedIndent)); indent = makeIndentString(type, amount); } return { amount, type, indent }; }; detect-indent-6.1.0/index.test-d.ts000066400000000000000000000004131405410572400171230ustar00rootroot00000000000000import {expectType} from 'tsd'; import detectIndent = require('.'); const indent = detectIndent(''); expectType(indent); expectType(indent.amount); expectType(indent.indent); expectType<'space' | 'tab' | undefined>(indent.type); detect-indent-6.1.0/license000066400000000000000000000021251405410572400156140ustar00rootroot00000000000000MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. detect-indent-6.1.0/package.json000066400000000000000000000012421405410572400165340ustar00rootroot00000000000000{ "name": "detect-indent", "version": "6.1.0", "description": "Detect the indentation of code", "license": "MIT", "repository": "sindresorhus/detect-indent", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "sindresorhus.com" }, "engines": { "node": ">=8" }, "scripts": { "test": "xo && ava && tsd" }, "files": [ "index.js", "index.d.ts" ], "keywords": [ "indent", "indentation", "detect", "infer", "identify", "code", "string", "text", "source", "space", "tab" ], "devDependencies": { "ava": "^1.4.1", "tsd": "^0.7.2", "xo": "^0.24.0" }, "xo": { "ignores": [ "fixture" ] } } detect-indent-6.1.0/readme.md000066400000000000000000000054361405410572400160360ustar00rootroot00000000000000# detect-indent > 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 detect-indent ``` ## Usage Here we modify a JSON file while persisting the indentation: ```js const fs = require('fs'); const detectIndent = require('detect-indent'); /* { "ilove": "pizza" } */ const file = fs.readFileSync('foo.json', 'utf8'); // Tries to detect the indentation and falls back to a default if it can't const indent = detectIndent(file).indent || ' '; const json = JSON.parse(file); json.ilove = 'unicorns'; fs.writeFileSync('foo.json', JSON.stringify(json, null, indent)); /* { "ilove": "unicorns" } */ ``` ## API Accepts a string and returns an object with stats about the indentation: * `amount` {number} - Amount of indentation, for example `2` * `type` {'tab' | 'space' | undefined} - Type of indentation. Possible values are `'tab'`, `'space'` or `undefined` if no indentation is detected * `indent` {string} - Actual indentation ## Algorithm The current algorithm looks for the most common difference between two consecutive non-empty lines. 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: ```css html { box-sizing: border-box; } body { background: gray; } p { line-height: 1.3em; margin-top: 1em; text-indent: 2em; } ``` [Source.](https://medium.com/@heatherarthur/detecting-code-indentation-eff3ed0fb56b#3918) Furthermore, if there are more than one most used difference, the indentation with the most lines is selected. In the following example, the indentation is detected as 4-spaces: ```css body { background: gray; } p { line-height: 1.3em; margin-top: 1em; text-indent: 2em; } ``` ## Related - [detect-indent-cli](https://github.com/sindresorhus/detect-indent-cli) - CLI for this module - [detect-newline](https://github.com/sindresorhus/detect-newline) - Detect the dominant newline character of a string - [detect-indent-rs](https://github.com/stefanpenner/detect-indent-rs) - Rust port ---
Get professional support for this package with a Tidelift subscription
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.
detect-indent-6.1.0/test.js000066400000000000000000000067251405410572400155760ustar00rootroot00000000000000import fs from 'fs'; import path from 'path'; import test from 'ava'; import detectIndent from '.'; const getFile = file => fs.readFileSync(path.join(__dirname, file), 'utf8'); test('detect the indent of a file with space indent', t => { t.is(detectIndent(getFile('fixture/space.js')).indent, ' '); }); test('return indentation stats for spaces', t => { const stats = detectIndent(getFile('fixture/space.js')); t.deepEqual(stats, { amount: 4, indent: ' ', type: 'space' }); }); test('return indentation stats for multiple tabs', t => { const stats = detectIndent(getFile('fixture/tab-four.js')); t.deepEqual(stats, { amount: 4, indent: '\t\t\t\t', type: 'tab' }); }); test('detect the indent of a file with tab indent', t => { t.is(detectIndent(getFile('fixture/tab.js')).indent, '\t'); }); test('return indentation stats for tabs', t => { const stats = detectIndent(getFile('fixture/tab.js')); t.deepEqual(stats, { amount: 1, indent: '\t', type: 'tab' }); }); test('detect the indent of a file with equal tabs and spaces', t => { t.is(detectIndent(getFile('fixture/mixed-tab.js')).indent, '\t'); }); test('return indentation stats for equal tabs and spaces', t => { const indent = detectIndent(getFile('fixture/mixed-tab.js')); t.deepEqual(indent, { amount: 1, indent: '\t', type: 'tab' }); }); test('detect the indent of a file with mostly spaces', t => { const stats = detectIndent(getFile('fixture/mixed-space.js')); t.is(stats.indent, ' '); }); test('return indentation stats for mostly spaces', t => { const stats = detectIndent(getFile('fixture/mixed-space.js')); t.deepEqual(stats, { amount: 4, indent: ' ', type: 'space' }); }); test('detect the indent of a weirdly indented vendor prefixed CSS', t => { const stats = detectIndent(getFile('fixture/vendor-prefixed-css.css')); t.is(stats.indent, ' '); }); test('return indentation stats for various spaces', t => { const stats = detectIndent(getFile('fixture/vendor-prefixed-css.css')); t.deepEqual(stats, { amount: 4, indent: ' ', type: 'space' }); }); test('return `0` when there is no indentation', t => { t.is(detectIndent('
    ').amount, 0); }); test('return indentation stats for no indentation', t => { const stats = detectIndent('
      '); t.deepEqual(stats, { amount: 0, indent: '', type: undefined }); }); test('return indentation stats for fifty-fifty indented files with spaces first', t => { const stats = detectIndent(getFile('fixture/fifty-fifty-space-first.js')); t.deepEqual(stats, { amount: 4, indent: ' ', type: 'space' }); }); test('return indentation stats for fifty-fifty indented files with tabs first', t => { const stats = detectIndent(getFile('fixture/fifty-fifty-tab-first.js')); t.deepEqual(stats, { amount: 1, indent: ' ', type: 'tab' }); }); test('return indentation stats for indented files with spaces and tabs last', t => { const stats = detectIndent(getFile('fixture/space-tab-last.js')); t.deepEqual(stats, { amount: 1, indent: ' ', type: 'tab' }); }); test('detect the indent of a file with single line comments', t => { const stats = detectIndent(getFile('fixture/single-space-ignore.js')); t.deepEqual(stats, { amount: 4, indent: ' ', type: 'space' }); }); test('return indentations status for indented files with single spaces only', t => { const stats = detectIndent(getFile('fixture/single-space-only.js')); t.deepEqual(stats, { amount: 1, indent: ' ', type: 'space' }); });