Git Product home page Git Product logo

indent.js's Introduction

indent.js - pure code indentation for js, jsx, json, ts, tsx, html, css, less, scss

Build Status

Fast, minimalistic, pure code indentation. Indents JavaScript, JSON, JSX, Typescript, TSX, CSS, LESS, SCSS, and HTML. Unlike JSBeautify, which adds new lines when reformatting code and changes single line expressions, indent.js preserves new lines in when indenting it. Indent.js is coded with simple, but universal, and unopinionated rules.

Indent.js is thoroughly tested to make sure it correctly indents all styles, and types of code.

If you like this project please leave a star. Your support is greatly appreciated.

Online indent.js demo

You have following options to get indent.js:

  1. Install with bower: bower install indent.js
  2. Install with npm: npm install indent.js

Download

Usage

Browser Global

var indented = indent.js(code, {tabString: '\t'});
console.log(indented);

Browser using AMD

define(['indent'] , function (indent) {
    var indented = indent.js(code, {tabString: '\t'});
    console.log(indented);
});

Node/CommonJS

var indent = require('indent');
var indented = indent.js(code, {tabString: '  '});
console.log(indented);

ES6/ES2015 Modules

import indent from 'indent.js';

var indentedJs = indent.js(code);  // JSX as well
var indentedTs = indent.ts(code);  // TSX as well
var indentedCss = indent.css(code);
var indentedHtml = indent.html(code);

Projects using indent.js:

  1. Spck Editor - Full-fledged code editor for the web

API Reference

Methods

js(code: String, options: Object): String
ts(code: String, options: Object): String
css(code: String, options: Object): String
html(code: String, options: Object): String

Options

Field Type Description
tabString string String to indent the code with. Counts as 1 indent.
indentHtmlTag bool Whether to indent contents inside <html> tag or not. Valid only for html(...).

Languages not supported:

  1. CoffeeScript
  2. Pug

Getting the project

  1. Clone the repo.
  2. Run npm install to install dependencies
  3. Run npm test to run tests in tests folder
  4. Run npm run build to build the project

indent.js's People

Contributors

zebzhao 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

Watchers

 avatar  avatar

indent.js's Issues

Typescript definition file?

This is an absolutely fantastic library! 👏🏻

I was just wondering whether you could create a typescript definition file:

index.d.ts

I want to use this with my node project, which is written in typescript, but when I try and run it, I get:

internal/modules/cjs/loader.js:883
  throw err;
  ^

Error: Cannot find module 'indent'

I am importing it like:

import indent from 'indent.js';

I have also tried:

const indent = require('indent');

And then:

indentCode(code, options) {
    var indented = indent.js(code, options);
    return indented;
}

I think the error is being thrown, because it cannot find a type definition?

UPDATE: 15.02.2024

I have attached the index.d.ts file to this comment.
If you want to add more type definitions, please feel free to do so. I just wanted to provide a quick, easy solution, to allow this library to work with typescript projects.

Add this file to your the following folder:

/lib

And then add this to the top of your js/ts file:

const indent = require(‘indent.js’);

index.d.zip

Switch statement default option is incorrectly indented following a return

Consider the following snippet:

#!/usr/bin/env node

var indent = require('indent.js');
var input = 'switch (foo) {\ncase \'bar\':\nreturn baz;\ncase \'baz\':\nreturn qux;\ndefault:\nreturn null;\n}';

console.log(indent.indentJS(input, '  '));

I would expect the output to line up the default statement with each of the case statements above it, but the actual output uses the same indentation as the preceding line:

switch (foo) {
  case 'bar':
    return baz;
  case 'baz':
    return qux;
    default:
    return null;
}

A failure with a JSX file

Hello,

The library does not correctly indents this JSX code:

class Widget extends React.PureComponent {

  constructor(props) {
    super(props);
    this.state = {
      value: this.props.value
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(value){
    this.setState({value: value});
    this.props.setShinyValue(parseFloat(value));
  }

  componentDidUpdate(prevProps, prevState) {
    if(this.props.value > this.props.max || this.props.value < this.props.min){
      this.props.setShinyValue(parseFloat(prevProps.value));
    }
    this.setState({value: this.props.value});
  }

  render() {

    let slider = null;
    if(this.props.slider) {
      slider = (
      <Slider
        flex = "1"
        min = {this.props.min}
        max = {this.props.max}
        step = {this.props.step}
        size = {this.props.size}
        value = {this.state.value}
        onChange = {this.handleChange}
      >
        <SliderTrack
          bg = {this.props.trackColor[1]}
        >
          <SliderFilledTrack
            bg = {this.props.trackColor[0]}
          />
        </SliderTrack>
        <SliderThumb
          fontSize = "sm"
          width = {this.props.thumbOptions.width}
          height = {this.props.thumbOptions.height}
          bg = {this.props.thumbOptions.color}
          borderColor = {this.props.thumbOptions.borderColor}
          borderWidth = {this.props.thumbOptions.borderWidth}
        >
          {createThumb(
            this.props.thumbOptions.icon,
            this.props.thumbOptions.iconColor,
            this.props.thumbOptions.iconSize
          )}
        </SliderThumb>
      </Slider>);
    }

    let marginRight = this.props.slider ? this.props.gap : 0;

    return (
      <ChakraProvider theme = {theme}>
        <CSSReset />
        {createLabel(this.props.label)}
        <Flex>
          <NumberInput
            min = {this.props.min}
            max = {this.props.max}
            step = {this.props.step}
            size = {this.props.size}
            maxW = {this.props.numberInputOptions.width}
            mr = {marginRight}
            value = {this.state.value}
            onChange = {this.handleChange}
          >
            <NumberInputField
              type = "number"
              fontSize = {this.props.numberInputOptions.fontSize}
              color = {this.props.numberInputOptions.fontColor}
              borderColor = {this.props.numberInputOptions.borderColor}
              focusBorderColor = {this.props.numberInputOptions.focusBorderColor}
              borderWidth = {this.props.numberInputOptions.borderWidth}
            />
            <NumberInputStepper>
              <NumberIncrementStepper
                bg = {this.props.numberInputOptions.stepperColor[0]}
              />
              <NumberDecrementStepper
                bg = {this.props.numberInputOptions.stepperColor[1]}
              />
            </NumberInputStepper>
          </NumberInput>
          {slider}
        </Flex>
      </ChakraProvider>
    );
  }
}

const Input = ({ configuration, value, setValue }) => {
  return (
    <Widget
      label = {configuration.label}
      setShinyValue = {setValue}
      value = {value}
      min = {configuration.min}
      max = {configuration.max}
      step = {configuration.step}
      size = {configuration.size}
      numberInputOptions = {configuration.numberInputOptions}
      trackColor = {configuration.trackColor}
      thumbOptions = {configuration.thumbOptions}
      gap = {configuration.gap}
      slider = {configuration.slider}
    />
  );
};

This is the result:

class Widget extends React.PureComponent {
  
  constructor(props) {
    super(props);
    this.state = {
      value: this.props.value
    };
    this.handleChange = this.handleChange.bind(this);
  }
  
  handleChange(value){
    this.setState({value: value});
    this.props.setShinyValue(parseFloat(value));
  }
  
  componentDidUpdate(prevProps, prevState) {
    if(this.props.value > this.props.max || this.props.value < this.props.min){
      this.props.setShinyValue(parseFloat(prevProps.value));
    }
    this.setState({value: this.props.value});
  }
  
  render() {
    
    let slider = null;
    if(this.props.slider) {
      slider = (
        <Slider
          flex = "1"
          min = {this.props.min}
          max = {this.props.max}
          step = {this.props.step}
          size = {this.props.size}
          value = {this.state.value}
          onChange = {this.handleChange}
          >
          <SliderTrack
            bg = {this.props.trackColor[1]}
            >
            <SliderFilledTrack
              bg = {this.props.trackColor[0]}
              />
              </SliderTrack>
              <SliderThumb
                fontSize = "sm"
                width = {this.props.thumbOptions.width}
                height = {this.props.thumbOptions.height}
                bg = {this.props.thumbOptions.color}
                borderColor = {this.props.thumbOptions.borderColor}
                borderWidth = {this.props.thumbOptions.borderWidth}
                >
                {createThumb(
                  this.props.thumbOptions.icon,
                  this.props.thumbOptions.iconColor,
                  this.props.thumbOptions.iconSize
                )}
              </SliderThumb>
              </Slider>);
              }
              
              let marginRight = this.props.slider ? this.props.gap : 0;
              
              return (
                <ChakraProvider theme = {theme}>
                  <CSSReset />
                  {createLabel(this.props.label)}
                  <Flex>
                    <NumberInput
                      min = {this.props.min}
                      max = {this.props.max}
                      step = {this.props.step}
                      size = {this.props.size}
                      maxW = {this.props.numberInputOptions.width}
                      mr = {marginRight}
                      value = {this.state.value}
                      onChange = {this.handleChange}
                      >
                      <NumberInputField
                        type = "number"
                        fontSize = {this.props.numberInputOptions.fontSize}
                        color = {this.props.numberInputOptions.fontColor}
                        borderColor = {this.props.numberInputOptions.borderColor}
                        focusBorderColor = {this.props.numberInputOptions.focusBorderColor}
                        borderWidth = {this.props.numberInputOptions.borderWidth}
                        />
                        <NumberInputStepper>
                          <NumberIncrementStepper
                            bg = {this.props.numberInputOptions.stepperColor[0]}
                            />
                            <NumberDecrementStepper
                              bg = {this.props.numberInputOptions.stepperColor[1]}
                              />
                              </NumberInputStepper>
                              </NumberInput>
                              {slider}
                              </Flex>
                              </ChakraProvider>
                              );
                              }
                              }
                              
                              const Input = ({ configuration, value, setValue }) => {
                                return (
                                  <Widget
                                    label = {configuration.label}
                                    setShinyValue = {setValue}
                                    value = {value}
                                    min = {configuration.min}
                                    max = {configuration.max}
                                    step = {configuration.step}
                                    size = {configuration.size}
                                    numberInputOptions = {configuration.numberInputOptions}
                                    trackColor = {configuration.trackColor}
                                    thumbOptions = {configuration.thumbOptions}
                                    gap = {configuration.gap}
                                    slider = {configuration.slider}
                                    />
                                    );
                                    };

Include a LICENSE file

The package is listed on npm with an MIT license, but the repo itself does not include a license file. If the project truly is meant to be MIT licensed, then add a file called "LICENSE" to the repo's root with the following content (copied from https://opensource.org/licenses/MIT):

MIT License

Copyright (c) 2017 <<<YOUR NAME HERE>>>

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.

indentHTML not detecting self-closing img tags

The third master-rule should include self-closing img tags. Otherwise it skips an indentation on the tag.
{
langs: "html",
name: "link|br|input|meta|img",
startToken: [/<(link|br|input|meta|img)/i],
endToken: [/>/],
advance: true
},

ES6 import doc wrong

I was looking for something to prettify my css. Didn't read the docs at first (shame on me) otherwise I would have seen it clearly mention it doesn't add new lines.

But while I was finally there, I noticed that ES6 import is wrong.

TL;DR:

Docs say import indent from 'indent.js';
Correct usage: import { indent } from 'indent.js';

Contact

Hey Zeb, sorry to send you a message via an issue but I couldn't find your email anywhere on the internet. I'm CEO and founder of Repl.it. I'm impressed with your work and I'd like to talk to you about potential opportunities. Plz email me [email protected]

Type script can't indent while the program include the type casting statement

call indent.js BEFORE

constructor(data?: ITest) {
    if (data) {
        for (let property in data) {
            if (data.hasOwnProperty(property))
                (<any>this)[property] = (<any>data)[property];
        }
    }
    if (!data) {
        this.id = -1;
    }
}

call indent.js AFTER

constructor(data?: ITest) {
	if (data) {
		for (let property in data) {
			if (data.hasOwnProperty(property))
				(<any>this)[property] = (<any>data)[property];
					}
					}
					if (!data) {
						this.id = -1;
					}
					}

I think indent.js can't recognize the or statements.

Incorrect TypeScript conversion

import { createSelector } from '@ngrx/store';
export const selectShoppingCartItems = createSelector(
(state) => state.shoppingCart,
(shoppingCart) => shoppingCart.items
);
export const selectTotalItems = createSelector{
selectShoppingCartItems,
(items) => items.length
};

This is converted to:

import { createSelector } from '@ngrx/store';
export const selectShoppingCartItems = createSelector(
	(state) => state.shoppingCart,
		(shoppingCart) => shoppingCart.items
);
export const selectTotalItems = createSelector{
	selectShoppingCartItems,
	(items) => items.length
};

And here is the solution:

{
      $languages: "js",
      $name: "=",
      $excludeIf: [HTML_TAG_RULES],
      $startPatterns: [/=/],
      $endPatterns: [/[,;\)\]}]/, NEW_LINE_REGEX]
},

To:

{
      $languages: "js",
      $name: "=",
      $excludeIf: [HTML_TAG_RULES],
      $startPatterns: [/=(?!>)/],
      $endPatterns: [/[,;\)\]}]/, NEW_LINE_REGEX]
},

indent.js splits newlines incorrectly in internet explorer 11

Problem

indent.js not working in internet explorer 11 due to the way lines are split. Specifically, the following line does not work correctly:

var lines = code.split(/[\r]?\n/gi);

Example

In Chrome, this "test\n".split(/[\r]?\n/gi) produces:

["test", ""]

In IE11, this "test\n".split(/[\r]?\n/gi) produces:

["t", "e", "s", "t", "  "]

Notes

Looks like there are a variety of issues with regular expressions in IE 11.

This seems to work in IE11 ("asdf\n" + "asdf\n" + "asdf\n").split("\n"), but I don't know if that works in all cases.

Switch statement default block is not indented

Consider the following snippet:

#!/usr/bin/env node

var indent = require('indent.js');
var input = 'switch (foo) {\n case \'bar\':\nbaz = foo;\nfoo = null;\nbreak;\ndefault:\nbaz = null;\n}';

console.log(indent.indentJS(input, '  '));

I would expect the output to indent the default block's body (i.e. baz = null;) by two characters, but the actual output uses the same indentation as the preceding line:

switch (foo) {
  case 'bar':
    baz = foo;
    foo = null;
  break;
  default:
  baz = null;
}

Also, arguably the break statement should be indented by two characters to match the indentation of the case block's body.

Cannot read properties of undefined (reading 'Int16Array')

Hello,
with

import  { indent } from "indent.js";
html=indent.html(html)

I am getting

Uncaught TypeError: Cannot read properties of undefined (reading 'Int16Array')
    at intArray (indent.js:677)
    at indent (indent.js:474)
    at Object.html (indent.js:451)
    at App.svelte:62

Any idea?

Broken formatting on UMD files

I have example.js:

const fs = require('fs');
const indent = require('indent.js');

const data = fs.readFileSync('./index.js', 'utf8');
console.log(data);
console.log(indent.js(data, {tabString: 4}));             

When I run it, I see:

(function(mod) {
    'use strict';

    if (typeof exports === 'object' && typeof module === 'object') // CommonJS
        mod(require('../../lib/codemirror'));
    else if (typeof define === 'function' && define.amd) // AMD
        define(['../../lib/codemirror'], mod);
    else // Plain browser env
        mod(CodeMirror);
})(function(CodeMirror) {
});


(function(mod) {
    'use strict';

    if (typeof exports === 'object' && typeof module === 'object') // CommonJS
    mod(require('../../lib/codemirror'));
    else if (typeof define === 'function' && define.amd) // AMD
    define(['../../lib/codemirror'], mod);
    else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
    });

Would be great to have ability not add windows line endings:
screen shot 2019-01-16 at 6 05 51 pm

indent.html does not exist when using es modules

running this in node 14:

import indent from "indent";

export default async function processfile(data) {
  return indent.html(data);
}

errors out going

(node:6724) UnhandledPromiseRejectionWarning: TypeError: indent.html is not a function
    at ....

So that's literally useless? =(

There is an error the name export in docs

The docs state that you can import with the library like: import {indent} form 'indent.js', but that yields undefined. It should be import indent from 'indent.js'

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.