GithubHelp home page GithubHelp logo

detect-indent's Introduction

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:

import fs from 'node:fs';
import detectIndent from '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, undefined, 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:

html {
  box-sizing: border-box;
}

body {
  background: gray;
}

p {
    line-height: 1.3em;
    margin-top: 1em;
    text-indent: 2em;
}

Source.

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:

body {
  background: gray;
}

p {
    line-height: 1.3em;
    margin-top: 1em;
    text-indent: 2em;
}

Related


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's People

Contributors

bendingbender avatar brandon93s avatar ethan-vanderheijden avatar eventualbuddha avatar fr6 avatar gwhitney avatar jonschlinkert avatar julien-f avatar mathiasbynens avatar richienb avatar roryokane avatar samverschueren avatar sindresorhus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

detect-indent's Issues

Mixup with files with equal amount of tabs and spaces

Issuehunt badges

I am using this project to write an extension for Brackets and it is working quite well.

However I have noticed one mixup when the file has equal amount of tabs and spaces.

If I have a file like this[1]

This file should not change the indentation setting
    1 tab
    1 tab
    4 spaces
    4 spaces

I get {amount: 1, type: "space", indent: " "} which is obviously incorrect.
It should either be 4 spaces or 1 tab (or null).

[1]: The GitHub parsing seems to make it all spaces, but if edited shows the original formatting.

fr6 earned $60.00 by resolving this issue!

Indentation on Github projects

I'm looking for statistics on code indentation (which is the most popular by language), and can't find any. Your tool seems appropriate for finding out the answer.

Have you already tried your tool on the most popular GitHub projects, perhaps via some script that pulls down popular repositories and analyzes them?

Improve algorithm

Right now it's fairly naive.

Would love to hear from someone on ways to improve this.

Breaks as a front-end dependency

We use this module on the front end (a wysiwyg code editor) and the recent switch to ES6 breaks in certain browsers. It's not a big deal to run babel over it, but in our case this packages is the one exception among hundreds of dependencies which are ES5 compatible. In my opinion, using this in-browser is a valid use case that should be supported.

Issue with vendor prefixed aligned CSS rules

#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);
}

It currently detects the indentation to 1 space.

Occurrences of indent sizes are not counted as per documentation.

Consider the attached example file. It is constructed (somewhat artificially in this case, but it comes from an actual source file I am working with in another project) to have exactly one occurrence of a single-space indentation change, at least as I interpret the documentation of this package. On the other hand, it has eleven occurrences of a four-space indentation change, and I think most any coder would consider it to have an indentation size of 4 spaces.

Yet currently detect-indent computes it to have an indent size of 1 space. The statistics gathered in makeIndentsMap are:

{ 's3' => [ 1, 0 ], 's1' => [ 22, 21 ], 's4' => [ 15, 4 ] }

The difficulty appears to be that on each of the many lines at the same indent level just after the 1-space indentation change, the usedCount (i.e., first entry) of the value for the s1 key is being incremented, which appears to contradict the documentation.

I will file a PR adding this as a test case, with a fix for the issue.
long-repeat.txt

Detect the mix of space and tabs

Hi,
For one of the project I work on, in JSON files I use tabs with an identation size of 2.
The .editorconfig looks like this :

[*.json]
indent_style = tab
indent_size = 2

The problem is that npm install re-indent the file with only tabs.
It suppose it's because more tabs are detected than spaces.

I wonder if there is a simple solution or if it is like the issue #17 about smart tabs ?
Or maybe it could try detecting an .editorconfig file ?

Thanks in advance

Playground

Would be nice to have a simple web UI to let users try it out.

Blows up when input contains no spaces

I’ve been using this module to help indent arbitrary bits of markup and it works well, but I notice that if the partial is small enough to not have spaces, it causes detect-indent to throw an error.

Example

var detect = require('detect-indent')

// This works
process.stdout.write(detect('<ul>\n  <li></li>\n</ul>'))

// This blows up
process.stdout.write(detect('<ul></ul>'))

Output

        var indentSize = spaces.reduce(gcd);
                                ^
TypeError: Reduce of empty array with no initial value

I’m thinking the function should return null if the spaces array is empty?

Fails for JSON file

var fs = require('fs');
var detectIndent = require('detect-indent');

module.exports = function (gulp, config) { 
  config = config || {};
  if(typeof gulp === 'undefined') {
    throw new Error("Gulp Undefined");
  }

  var file = fs.readFileSync(config.path || 'package.json');
  var pkg = JSON.parse(file);
  var indent = detectIndent(file).indent || '  ';
  var tasks = gulp.tasks;

  pkg.scripts = pkg.scripts || {};

  Object.keys(tasks).forEach(function (t) {
    pkg.scripts[t] = 'gulp '+tasks[t].name;
  });

  fs.writeFileSync(config.path || 'package.json', JSON.stringify(pkg, null, indent));

};

typeof fs.readFileSync('package.json'); is "object" since it is a JSON file. The script is expecting a string so it will fail.

Small issue in the provided usage example

The provided usage example has small issue in case it failed to detect the indentation and fall back to '    '. The value that is stored in detected variable is string, which doesn't have indent property as used later in JSON.stringify function.

Consider SmartTabs indentation style

Hello,

I personally use SmartTabs for indenting and spacing:

  • tabs for indentation
  • space for alignment

This is the most flexible mode since everybody see the same thing, just indentation change depending on the number of columns they configure for tabs.

Could you consider it?

Regards.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.