Beautifier for javascript

Overview

JS Beautifier

CI

PyPI version CDNJS version NPM @latest NPM @next

Join the chat at https://gitter.im/beautify-web/js-beautify Twitter Follow

NPM stats Greenkeeper badge

This little beautifier will reformat and re-indent bookmarklets, ugly JavaScript, unpack scripts packed by Dean Edward’s popular packer, as well as partly deobfuscate scripts processed by the npm package javascript-obfuscator.

Open beautifier.io to try it out. Options are available via the UI.

Contributors Needed

I'm putting this front and center above because existing owners have very limited time to work on this project currently. This is a popular project and widely used but it desperately needs contributors who have time to commit to fixing both customer facing bugs and underlying problems with the internal design and implementation.

If you are interested, please take a look at the CONTRIBUTING.md then fix an issue marked with the "Good first issue" label and submit a PR. Repeat as often as possible. Thanks!

Installation

You can install the beautifier for node.js or python.

Node.js JavaScript

You may install the NPM package js-beautify. When installed globally, it provides an executable js-beautify script. As with the Python script, the beautified result is sent to stdout unless otherwise configured.

$ npm -g install js-beautify
$ js-beautify foo.js

You can also use js-beautify as a node library (install locally, the npm default):

$ npm install js-beautify

Node.js JavaScript (vNext)

The above install the latest stable release. To install beta or RC versions:

$ npm install js-beautify@next

Web Library

The beautifier can be added on your page as web library.

JS Beautifier is hosted on two CDN services: cdnjs and rawgit.

To pull the latest version from one of these services include one set of the script tags below in your document:

<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.13.6/beautify.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.13.6/beautify-css.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.13.6/beautify-html.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.13.6/beautify.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.13.6/beautify-css.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.13.6/beautify-html.min.js"></script>

<script src="https://cdn.rawgit.com/beautify-web/js-beautify/v1.13.6/js/lib/beautify.js"></script>
<script src="https://cdn.rawgit.com/beautify-web/js-beautify/v1.13.6/js/lib/beautify-css.js"></script>
<script src="https://cdn.rawgit.com/beautify-web/js-beautify/v1.13.6/js/lib/beautify-html.js"></script>

Older versions are available by changing the version number.

Disclaimer: These are free services, so there are no uptime or support guarantees.

Python

To install the Python version of the beautifier:

$ pip install jsbeautifier

Unlike the JavaScript version, the Python version can only reformat JavaScript. It does not work against HTML or CSS files, but you can install css-beautify for CSS:

$ pip install cssbeautifier

Usage

You can beautify javascript using JS Beautifier in your web browser, or on the command-line using node.js or python.

Web Browser

Open beautifier.io. Options are available via the UI.

Web Library

The script tags above expose three functions: js_beautify, css_beautify, and html_beautify.

Node.js JavaScript

When installed globally, the beautifier provides an executable js-beautify script. The beautified result is sent to stdout unless otherwise configured.

$ js-beautify foo.js

To use js-beautify as a node library (after install locally), import and call the appropriate beautifier method for javascript (js), css, or html. All three method signatures are beautify(code, options). code is the string of code to be beautified. options is an object with the settings you would like used to beautify the code.

The configuration option names are the same as the CLI names but with underscores instead of dashes. For example, --indent-size 2 --space-in-empty-paren would be { indent_size: 2, space_in_empty_paren: true }.

var beautify = require('js-beautify').js,
    fs = require('fs');

fs.readFile('foo.js', 'utf8', function (err, data) {
    if (err) {
        throw err;
    }
    console.log(beautify(data, { indent_size: 2, space_in_empty_paren: true }));
});

Python

After installing, to beautify using Python:

$ js-beautify file.js

Beautified output goes to stdout by default.

To use jsbeautifier as a library is simple:

import jsbeautifier
res = jsbeautifier.beautify('your javascript string')
res = jsbeautifier.beautify_file('some_file.js')

...or, to specify some options:

opts = jsbeautifier.default_options()
opts.indent_size = 2
opts.space_in_empty_paren = True
res = jsbeautifier.beautify('some javascript', opts)

The configuration option names are the same as the CLI names but with underscores instead of dashes. The example above would be set on the command-line as --indent-size 2 --space-in-empty-paren.

Options

These are the command-line flags for both Python and JS scripts:

CLI Options:
  -f, --file       Input file(s) (Pass '-' for stdin)
  -r, --replace    Write output in-place, replacing input
  -o, --outfile    Write output to file (default stdout)
  --config         Path to config file
  --type           [js|css|html] ["js"] Select beautifier type (NOTE: Does *not* filter files, only defines which beautifier type to run)
  -q, --quiet      Suppress logging to stdout
  -h, --help       Show this help
  -v, --version    Show the version

Beautifier Options:
  -s, --indent-size                 Indentation size [4]
  -c, --indent-char                 Indentation character [" "]
  -t, --indent-with-tabs            Indent with tabs, overrides -s and -c
  -e, --eol                         Character(s) to use as line terminators.
                                    [first newline in file, otherwise "\n]
  -n, --end-with-newline            End output with newline
  --editorconfig                    Use EditorConfig to set up the options
  -l, --indent-level                Initial indentation level [0]
  -p, --preserve-newlines           Preserve line-breaks (--no-preserve-newlines disables)
  -m, --max-preserve-newlines       Number of line-breaks to be preserved in one chunk [10]
  -P, --space-in-paren              Add padding spaces within paren, ie. f( a, b )
  -E, --space-in-empty-paren        Add a single space inside empty paren, ie. f( )
  -j, --jslint-happy                Enable jslint-stricter mode
  -a, --space-after-anon-function   Add a space before an anonymous function's parens, ie. function ()
  --space-after-named-function      Add a space before a named function's parens, i.e. function example ()
  -b, --brace-style                 [collapse|expand|end-expand|none][,preserve-inline] [collapse,preserve-inline]
  -u, --unindent-chained-methods    Don't indent chained method calls
  -B, --break-chained-methods       Break chained method calls across subsequent lines
  -k, --keep-array-indentation      Preserve array indentation
  -x, --unescape-strings            Decode printable characters encoded in xNN notation
  -w, --wrap-line-length            Wrap lines that exceed N characters [0]
  -X, --e4x                         Pass E4X xml literals through untouched
  --good-stuff                      Warm the cockles of Crockford's heart
  -C, --comma-first                 Put commas at the beginning of new line instead of end
  -O, --operator-position           Set operator position (before-newline|after-newline|preserve-newline) [before-newline]
  --indent-empty-lines              Keep indentation on empty lines
  --templating                      List of templating languages (auto,django,erb,handlebars,php,smarty) ["auto"] auto = none in JavaScript, all in html

Which correspond to the underscored option keys for both library interfaces

defaults per CLI options

{
    "indent_size": 4,
    "indent_char": " ",
    "indent_with_tabs": false,
    "editorconfig": false,
    "eol": "\n",
    "end_with_newline": false,
    "indent_level": 0,
    "preserve_newlines": true,
    "max_preserve_newlines": 10,
    "space_in_paren": false,
    "space_in_empty_paren": false,
    "jslint_happy": false,
    "space_after_anon_function": false,
    "space_after_named_function": false,
    "brace_style": "collapse",
    "unindent_chained_methods": false,
    "break_chained_methods": false,
    "keep_array_indentation": false,
    "unescape_strings": false,
    "wrap_line_length": 0,
    "e4x": false,
    "comma_first": false,
    "operator_position": "before-newline",
    "indent_empty_lines": false,
    "templating": ["auto"]
}

defaults not exposed in the cli

{
  "eval_code": false,
  "space_before_conditional": true
}

Notice not all defaults are exposed via the CLI. Historically, the Python and JS APIs have not been 100% identical. There are still a few other additional cases keeping us from 100% API-compatibility.

Loading settings from environment or .jsbeautifyrc (JavaScript-Only)

In addition to CLI arguments, you may pass config to the JS executable via:

  • any jsbeautify_-prefixed environment variables
  • a JSON-formatted file indicated by the --config parameter
  • a .jsbeautifyrc file containing JSON data at any level of the filesystem above $PWD

Configuration sources provided earlier in this stack will override later ones.

Setting inheritance and Language-specific overrides

The settings are a shallow tree whose values are inherited for all languages, but can be overridden. This works for settings passed directly to the API in either implementation. In the Javascript implementation, settings loaded from a config file, such as .jsbeautifyrc, can also use inheritance/overriding.

Below is an example configuration tree showing all the supported locations for language override nodes. We'll use indent_size to discuss how this configuration would behave, but any number of settings can be inherited or overridden:

{
    "indent_size": 4,
    "html": {
        "end_with_newline": true,
        "js": {
            "indent_size": 2
        },
        "css": {
            "indent_size": 2
        }
    },
    "css": {
        "indent_size": 1
    },
    "js": {
       "preserve-newlines": true
    }
}

Using the above example would have the following result:

  • HTML files
    • Inherit indent_size of 4 spaces from the top-level setting.
    • The files would also end with a newline.
    • JavaScript and CSS inside HTML
      • Inherit the HTML end_with_newline setting.
      • Override their indentation to 2 spaces.
  • CSS files
    • Override the top-level setting to an indent_size of 1 space.
  • JavaScript files
    • Inherit indent_size of 4 spaces from the top-level setting.
    • Set preserve-newlines to true.

CSS & HTML

In addition to the js-beautify executable, css-beautify and html-beautify are also provided as an easy interface into those scripts. Alternatively, js-beautify --css or js-beautify --html will accomplish the same thing, respectively.

// Programmatic access
var beautify_js = require('js-beautify'); // also available under "js" export
var beautify_css = require('js-beautify').css;
var beautify_html = require('js-beautify').html;

// All methods accept two arguments, the string to be beautified, and an options object.

The CSS & HTML beautifiers are much simpler in scope, and possess far fewer options.

CSS Beautifier Options:
  -s, --indent-size                  Indentation size [4]
  -c, --indent-char                  Indentation character [" "]
  -t, --indent-with-tabs             Indent with tabs, overrides -s and -c
  -e, --eol                          Character(s) to use as line terminators. (default newline - "\\n")
  -n, --end-with-newline             End output with newline
  -b, --brace-style                  [collapse|expand] ["collapse"]
  -L, --selector-separator-newline   Add a newline between multiple selectors
  -N, --newline-between-rules        Add a newline between CSS rules
  --indent-empty-lines               Keep indentation on empty lines

HTML Beautifier Options:
  -s, --indent-size                  Indentation size [4]
  -c, --indent-char                  Indentation character [" "]
  -t, --indent-with-tabs             Indent with tabs, overrides -s and -c
  -e, --eol                          Character(s) to use as line terminators. (default newline - "\\n")
  -n, --end-with-newline             End output with newline
  -p, --preserve-newlines            Preserve existing line-breaks (--no-preserve-newlines disables)
  -m, --max-preserve-newlines        Maximum number of line-breaks to be preserved in one chunk [10]
  -I, --indent-inner-html            Indent <head> and <body> sections. Default is false.
  -b, --brace-style                  [collapse-preserve-inline|collapse|expand|end-expand|none] ["collapse"]
  -S, --indent-scripts               [keep|separate|normal] ["normal"]
  -w, --wrap-line-length             Maximum characters per line (0 disables) [250]
  -A, --wrap-attributes              Wrap attributes to new lines [auto|force|force-aligned|force-expand-multiline|aligned-multiple|preserve|preserve-aligned] ["auto"]
  -i, --wrap-attributes-indent-size  Indent wrapped attributes to after N characters [indent-size] (ignored if wrap-attributes is "aligned")
  -d, --inline                       List of tags to be considered inline tags
  -U, --unformatted                  List of tags (defaults to inline) that should not be reformatted
  -T, --content_unformatted          List of tags (defaults to pre) whose content should not be reformatted
  -E, --extra_liners                 List of tags (defaults to [head,body,/html] that should have an extra newline before them.
  --editorconfig                     Use EditorConfig to set up the options
  --indent_scripts                   Sets indent level inside script tags ("normal", "keep", "separate")
  --unformatted_content_delimiter    Keep text content together between this string [""]
  --indent-empty-lines               Keep indentation on empty lines
  --templating                       List of templating languages (auto,none,django,erb,handlebars,php,smarty) ["auto"] auto = none in JavaScript, all in html

Directives

Directives let you control the behavior of the Beautifier from within your source files. Directives are placed in comments inside the file. Directives are in the format /* beautify {name}:{value} */ in CSS and JavaScript. In HTML they are formatted as <!-- beautify {name}:{value} -->.

Ignore directive

The ignore directive makes the beautifier completely ignore part of a file, treating it as literal text that is not parsed. The input below will remain unchanged after beautification:

// Use ignore when the content is not parsable in the current language, JavaScript in this case.
var a =  1;
/* beautify ignore:start */
 {This is some strange{template language{using open-braces?
/* beautify ignore:end */

Preserve directive

NOTE: this directive only works in HTML and JavaScript, not CSS.

The preserve directive makes the Beautifier parse and then keep the existing formatting of a section of code.

The input below will remain unchanged after beautification:

// Use preserve when the content is valid syntax in the current language, JavaScript in this case.
// This will parse the code and preserve the existing formatting.
/* beautify preserve:start */
{
    browserName: 'internet explorer',
    platform:    'Windows 7',
    version:     '8'
}
/* beautify preserve:end */

License

You are free to use this in any way you want, in case you find this useful or working for you but you must keep the copyright notice and license. (MIT)

Credits

Thanks also to Jason Diamond, Patrick Hof, Nochum Sossonko, Andreas Schneider, Dave Vasilevsky, Vital Batmanov, Ron Baldwin, Gabriel Harrison, Chris J. Shull, Mathias Bynens, Vittorio Gambaletta and others.

(README.md: [email protected])

Comments
  • Installing js-beautify fails

    Installing js-beautify fails

    Description

    I am trying to install a library, which is dependant on this one, and starting today (I've tried the last week the last time) I get the following error when installing my dependencies:

    npm ERR! path /Users/daniel.rotter/Development/massiveart/sulu-minimal/vendor/sulu/sulu/node_modules/js-beautify/js/bin/css-beautify.js
    npm ERR! code ENOENT
    npm ERR! errno -2
    npm ERR! syscall chmod
    npm ERR! enoent ENOENT: no such file or directory, chmod '/Users/daniel.rotter/Development/massiveart/sulu-minimal/vendor/sulu/sulu/node_modules/js-beautify/js/bin/css-beautify.js'
    npm ERR! enoent This is related to npm not being able to find a file.
    npm ERR! enoent
    
    npm ERR! A complete log of this run can be found in:
    npm ERR!     /Users/daniel.rotter/.npm/_logs/2017-09-18T05_55_47_583Z-debug.log
    

    It looks to me like this is somehow connected to the latest 1.7.0 release... Any ideas?

    Steps to Reproduce

    Create a new folder and install this library as dependency using npm install js-beautify.

    Environment

    OS: Mac OSX 10.11.6

    Deleted most of the PR template, since it's not relevant.

    opened by danrot 249
  • Option to preserve or inline

    Option to preserve or inline "short objects" on a single line

    Typically the JS Beautifier expands all JS object declarations into multiple lines, each line having a key value pair. However, this is overly verbose for many situations (e.g. short objects which could easily fit on a single line).

    Additional details found here: https://github.com/einars/js-beautify/pull/55

    type: enhancement 
    opened by mrchief 109
  • Newline inserted after ES6 module import/export

    Newline inserted after ES6 module import/export

    Hey,

    I'm running jsbeautifier on a collection of Ember.JS ES6 modules and I've noticed a small issue with export statements.

    Suppose I have a module that exports as below

    export default DS.FixtureAdapter.extend();
    

    jsbeautifier will add a newline after export

    export
    default DS.FixtureAdapter.extend();
    

    It's a minor problem that is only an issue for us as we enforce a jsbeautifier run before a commit is accepted. So, if a developer removes the newline, the file in question will be included in the commit even though it may have nothing to do with the changes being commited.

    type: enhancement 
    opened by redking 54
  • newline_between_rules support for Sass (enhancement)

    newline_between_rules support for Sass (enhancement)

    Now newline_between_rules option in v1.5.5 is supported for CSS only https://github.com/beautify-web/js-beautify/pull/574 So, in Sass for nesting doesn't work.

    Here my test.js file:

    var fs = require('fs');
    var beautify_css = require('js-beautify').css;
    
    fs.readFile('test.scss', 'utf8', function(err, data) {
      if (err) {
        throw err;
      }
    
      console.log(beautify_css(data, {
        indent_size: 2,
        newline_between_rules: true
      }));
    });
    

    Output:

    $ node test.js
    
    .icons {
      padding: 0;
      li {
        display: inline-block;
      }
      a {
        display: block;
        color: #000;
      }
      a:hover {
        color: #ccc;
      }
    }
    

    I hope to add newline_between_rules support for Sass. Regards.

    type: enhancement language: css language: templating good first issue 
    opened by joseluisq 49
  • first draft of operator_position functionality

    first draft of operator_position functionality

    • Added verification of operator_position option. Throws error if invalid.
    • Possible operator_position options are:
      1. undefined (use default behavior)
      2. 'before_newline'
      3. 'after_newline'
      4. 'preserve_newline'
      5. 'remove_newline'
    • Moved some code around in handle_operator in order to separate conflicting logic when handling operators.
    • Modified allow_wrap_or_preserved_newline to handle operator preserved newlines as well.
    • Fixed a few boolean variable assignments within if statements. Though not always the case, the expression within the if can be assigned directly to the variable
    • Added -> built tests
    • Within the tests, added an 'inputlib.js' file which holds common input arrays. This was necessary due to the matrices not working cleanly with default behavior.
    • It is worth noting that although the python test file was modified, this is a result of the built test and not actually providing a python port for this option (yet).
    opened by olsonpm 45
  • Publish v1.8.0

    Publish v1.8.0

    @garretwilson @amandabot @HookyQR @astronomersiva @madman-bob @swan46 @LoganDark @MacKLess @Mlocik97-issues @Hirse @jdavisclark

    At this point the 1.8.0 release includes at least 80 fixed bugs and enhancements. HTML and CSS/LESS/SCSS beautification have both seen massive improvements. Not that performance is primary focus of this project, but the HTML beautifier in particular has seen 10x or more performance improvement.

    I'd like to tie off this RC cycle and publish 1.8.0 (release). The latest 1.8.0-rc12 is up on http://jsbeautifier.org/ and npm and pypi.

    If you can try out some of the inputs you use most or otherwise give this RC a sanity test drive, I'd be most grateful.

    I plan to release soon.

    type: task 
    opened by bitwiseman 31
  • JSX support

    JSX support

    Any plans to support JSX (http://facebook.github.io/react/jsx-compiler.html)? I've tried using --e4x but still some files are getting wrong formatting.

    type: enhancement 
    opened by sebastianzebrowski 31
  • Support comma first style of variable declaration

    Support comma first style of variable declaration

    Allow code to be formatted like this:

    var a = 1
      , b = "somethign else"
      , isAwesome = true;
    

    And apparently, we have a somewhat ready patch available. Would be great if this can get included in here!

    type: enhancement 
    opened by mrchief 27
  • not correctly joining lines for HTML

    not correctly joining lines for HTML

    This is really hurting me. Here is an example HTML file:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html>
    <html lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
    
    <head>
        <title>Test Line Join</title>
    </head>
    
    <body>
        <p>The key words <q><span class="spec-must">must</span></q>, <q><span
    
              class="spec-must-not">must not</span></q>, <q><span class="spec-must">required</span></q>, <q><span
    
              class="spec-must">shall</span></q>, <q><span class="spec-must-not">shall not</span></q>, <q><span
    
              class="spec-should">should</span></q>, <q><span class="spec-should-not">should not</span></q>, <q><span
    
              class="spec-should">recommended</span></q>, <q><span class="spec-may">may</span></q>, and <q><span
    
              class="spec-may">optional</span></q> in this document are to be interpreted as described in <a href="#ref-rfc2119" class="ref">RFC 2119</a>.</p>
    </body>
    
    </html>
    

    js-beautify should be getting rid of all that whitespace inside the <span …> tag. I want js-beautify to give me this:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html>
    <html lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
    
    <head>
        <title>Test Line Join</title>
    </head>
    
    <body>
        <p>The key words <q><span class="spec-must">must</span></q>, <q><span class="spec-must-not">must not</span></q>, <q><span class="spec-must">required</span></q>, <q><span class="spec-must">shall</span></q>, <q><span class="spec-must-not">shall not</span></q>, <q><span class="spec-should">should</span></q>, <q><span class="spec-should-not">should not</span></q>, <q><span class="spec-should">recommended</span></q>, <q><span class="spec-may">may</span></q>, and <q><span class="spec-may">optional</span></q> in this document are to be interpreted as described in <a href="#ref-rfc2119" class="ref">RFC 2119</a>.</p>
    </body>
    
    </html>
    

    But it doesn't. This is a huge problem and is really dragging down the workflow. (The reason the lines are like that to begin with is a bug in BlueGriffon. So bugs in js-beautify are preventing it from fixing the bugs in BlueGriffon. Such is life.)

    See #841.

    Perhaps you could point me to a place in the code I might go to try to put in some workaround?

    type: enhancement 
    opened by garretwilson 26
  • Support comma-first for vars/object declarations

    Support comma-first for vars/object declarations

    Support "comma first" style when declaring variables or properties inside an object, as discussed on issue #245.

    The proposed solution is based on changing the order of the newline (before / after the comma) depending on the value for the new option "comma_first". The proposed command line argument for this option is "-F" or "--comma_first").

    It is also necessary to modify the indentation string used for some particular lines, in order to include the comma as part of the indentation string and achieve the desired result regarding indentation (in some cases it is easier to think of the comma as part of the indentation string, in replace of a whitespace).

    TODO 1: tests for this feature

    TODO 2: implement the feature in the python version (I prefer to get feedback for this commit first and, once the feature's JS code is considered correct, then proceed with the py code).

    TODO 3: in the future, other variations for the indentation pattern, for object properties, could be allowed. The currently allowed one looks like this:

    {
      prop1: 1
    , prop2: 2
    , prop3: 3
    }
    

    Another version could be:

    {
        prop1: 1
      , prop2: 2
      , prop3: 3
    }
    

    In "other words", the first property is double indented. However, it must be noted that jslint errors related with the indentation could arise (tested with JSHint).

    type: enhancement type: discussion 
    opened by tgirardi 26
  • Lines are not un-indented correctly when attributes are wrapped

    Lines are not un-indented correctly when attributes are wrapped

    Description

    Indenting is broken whenever attribute wrapping happens.

    Using js-beautify v1.6.8.

    Input

    The code looked like this before beautification:

    <div first second>content</div>
    <div>content</div>
    

    Expected Output

    The code should have looked like this after beautification:

    <div first 
         second>content</div>
    <div>content</div>
    

    Actual Output

    The code actually looked like this after beautification:

    <div first
         second>content</div>
        <div>content</div>
    

    Steps to Reproduce

    Beautify the code

    Environment

    OS: MacOS

    Settings

    Example:

    {
        "wrap_attributes": "force-aligned"
    }
    

    Note: wrap_attributes doesn't have to be set to force-aligned. Any wrapping (excluding "force-expand-multiline") introduces, including if "auto" caused the wrapping will demonstrate this issue.

    language: html type: bug 
    opened by HookyQR 23
  • add wrong space in attribute when formating html

    add wrong space in attribute when formating html

    Input

    The code looked like this before beautification:

    <a to="'/playground/video-manage?contentPlanId='"/>
    

    Expected Output

    The code should have looked like this after beautification:

    <a to="'/playground/video-manage?contentPlanId='"/>
    

    Actual Output

    The code actually looked like this after beautification:

    <a to="' /playground/video-manage?contentPlanId='"/>
    

    Steps to Reproduce

    Environment

    OS:All

    Settings

    with any Setting

    opened by kunhualqk 1
  • Preserve Existing Newlines

    Preserve Existing Newlines

    Description

    Preserve all newlines in existing HTML.

    Input

    With this requested feature, this input:

    <body>
    
    	<!-- Some Comments --->
    
    	<!-------------- CONTAINER: GROUP CONTAINER 1  ------------------->
    	<span data-header="team-members" data-meta="
    	TITLE: Product Management
    	RECORDS: advisers-prod-mgmt
    	ITEM-CLASS: team-member
    	">
    </span>
    	<hr>
    
    </body>
    

    Expected Output

    Should give this output:

    <body>
      
    	<!-- Some Comments --->
      
    	<!-------------- CONTAINER: GROUP CONTAINER 1  ------------------->
    	<span data-header="team-members" data-meta="
    		TITLE: Product Management
    		RECORDS: advisers-prod-mgmt
    		ITEM-CLASS: team-member
    		">
    	</span>
    	<hr>
      
    </body>
    

    Environment

    OS: Online

    Also, attributes on newlines should get indented, as shown above.

    opened by johnaweiss 1
  • Wrong indent

    Wrong indent

    Description

    when using function "each" in block

    Input

    The code looked like this before beautification:

    #Parent {
    	each(range(10),{
    	});
    
    	#Others {
    		
    	}
    }
    

    Expected Output

    The code should have looked like this after beautification:

    #Parent {
    	each(range(10),{
    	});
    
    	#Others {
    		
    	}
    }
    

    Actual Output

    The code actually looked like this after beautification:

    #Parent {
    	each(range(10),{
    	});
    
    #Others {
    	
    }
    }
    

    Steps to Reproduce

    Environment

    OS:

    Settings

    all default

    opened by WNinja 0
  • Delete .DS_Store

    Delete .DS_Store

    Description

    • [x] Source branch in your fork has meaningful name (not main)

    Fixes Issue:

    Before Merge Checklist

    These items can be completed after PR is created.

    (Check any items that are not applicable (NA) for this PR)

    • [ ] JavaScript implementation
    • [ ] Python implementation (NA if HTML beautifier)
    • [ ] Added Tests to data file(s)
    • [ ] Added command-line option(s) (NA if
    • [ ] README.md documents new feature/option(s)
    opened by Mogyuchi 0
  • Broken CI workflow due to incompatible NPM and Node versions

    Broken CI workflow due to incompatible NPM and Node versions

    Description

    The Github action workflows are broken due to incompatible new version of NPM being run against Node. The offending code is below, it can easily be fixed if I can find out the original reason for its existence. https://github.com/beautify-web/js-beautify/blob/12bc378bd465dc8771609c4a181d49462dbf7dd1/tools/npm#L7-L11

    Error:

    ERROR: npm v9.1.2 is known not to run on Node.js v12.22.12. You'll need to
    upgrade to a newer Node.js version in order to use this version of npm. This
    version of npm supports the following node versions: `^14.17.0 || ^16.13.0 ||
    >=18.0.0`. You can find the latest version at [https://nodejs.org/.](https://nodejs.org/)
    

    On a related note, @bitwiseman I was wondering why does this package have node, npm and python* scripts in the tools directory. Those scripts make it hard to use any of the language engines on individual machines. A better alternative would be to have Docker files to run commands instead of updating packages on every computer that runs the tests or build code.

    opened by mhnaeem 0
  • issue with packer on python module

    issue with packer on python module

    Description

    I have noticed with the jsbeautifier library for python, certain code does not unpack. An example of this is:

    eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('f $7={H:a(2){4 B(9.7.h(y z("(?:(?:^|.*;)\\\\s*"+d(2).h(/[\\-\\.\\+\\*]/g,"\\\\$&")+"\\\\s*\\\\=\\\\s*([^;]*).*$)|^.*$"),"$1"))||G},E:a(2,q,3,6,5,t){k(!2||/^(?:8|r\\-v|o|m|p)$/i.D(2)){4 w}f b="";k(3){F(3.J){j K:b=3===P?"; 8=O, I N Q M:u:u A":"; r-v="+3;n;j L:b="; 8="+3;n;j S:b="; 8="+3.Z();n}}9.7=d(2)+"="+d(q)+b+(5?"; m="+5:"")+(6?"; o="+6:"")+(t?"; p":"");4 x},Y:a(2,6,5){k(!2||!11.C(2)){4 w}9.7=d(2)+"=; 8=12, R 10 W l:l:l A"+(5?"; m="+5:"")+(6?"; o="+6:"");4 x},C:a(2){4(y z("(?:^|;\\\\s*)"+d(2).h(/[\\-\\.\\+\\*]/g,"\\\\$&")+"\\\\s*\\\\=")).D(9.7)},X:a(){f c=9.7.h(/((?:^|\\s*;)[^\\=]+)(?=;|$)|^\\s*|\\s*(?:\\=[^;]*)?(?:\\1|$)/g,"").T(/\\s*(?:\\=[^;]*)?;\\s*/);U(f e=0;e<c.V;e++){c[e]=B(c[e])}4 c}};',62,65,'||sKey|vEnd|return|sDomain|sPath|cookie|expires|document|function|sExpires|aKeys|encodeURIComponent|nIdx|var||replace||case|if|00|domain|break|path|secure|sValue|max||bSecure|59|age|false|true|new|RegExp|GMT|decodeURIComponent|hasItem|test|setItem|switch|null|getItem|31|constructor|Number|String|23|Dec|Fri|Infinity|9999|01|Date|split|for|length|1970|keys|removeItem|toUTCString|Jan|this|Thu'.split('|'),0,{}));eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('h o=\'1A://1z-1y.1x.1w.1v/1u/1t/1s/1r.1q\';h d=s.r(\'d\');h 0=B 1p(d,{\'1o\':{\'1n\':i},\'1m\':\'16:9\',\'D\':1,\'1l\':5,\'1k\':{\'1j\':\'1i\'},1h:[\'7-1g\',\'7\',\'1f\',\'1e-1d\',\'1c\',\'D\',\'1b\',\'1a\',\'19\',\'18\',\'C\',\'17\'],\'C\':{\'15\':i}});8(!A.14()){d.13=o}x{j z={12:11,10:Z,Y:X,W:i,V:i};h c=B A(z);c.U(o);c.T(d);g.c=c}0.3("S",6=>{g.R.Q.P("O")});0.N=1;k v(b,n,m){8(b.y){b.y(n,m,M)}x 8(b.w){b.w(\'3\'+n,m)}}j 4=k(l){g.L.K(l,\'*\')};v(g,\'l\',k(e){j a=e.a;8(a===\'7\')0.7();8(a===\'f\')0.f();8(a===\'u\')0.u()});0.3(\'t\',6=>{4(\'t\')});0.3(\'7\',6=>{4(\'7\')});0.3(\'f\',6=>{4(\'f\')});0.3(\'J\',6=>{4(0.q);s.r(\'.I-H\').G=F(0.q.E(2))});0.3(\'p\',6=>{4(\'p\')});',62,99,'player|||on|sendMessage||event|play|if||data|element|hls|video||pause|window|const|true|var|function|message|eventHandler|eventName|source|ended|currentTime|querySelector|document|ready|stop|bindEvent|attachEvent|else|addEventListener|config|Hls|new|fullscreen|volume|toFixed|String|innerHTML|timestamp|ss|timeupdate|postMessage|parent|false|speed|landscape|lock|orientation|screen|enterfullscreen|attachMedia|loadSource|lowLatencyMode|enableWorker|Infinity|backBufferLength|600|maxMaxBufferLength|180|maxBufferLength|src|isSupported|iosNative||capture|airplay|pip|settings|captions|mute|time|current|progress|large|controls|kwik|key|storage|seekTime|ratio|global|keyboard|Plyr|m3u8|uwu|c989297659739b02ddedf0c686537e7b099e77360263803760baa6aaae30d465|04|stream|org|nextcdn|files|021|na|https'.split('|'),0,{}))
    
    

    Expected Output

    The code should have looked like this after beautification:

    var $cookie = {
        getItem: function(sKey) {
            return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null
        },
        setItem: function(sKey, sValue, vEnd, sPath, sDomain, bSecure) {
            if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) {
                return false
            }
            var sExpires = "";
            if (vEnd) {
                switch (vEnd.constructor) {
                    case Number:
                        sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
                        break;
                    case String:
                        sExpires = "; expires=" + vEnd;
                        break;
                    case Date:
                        sExpires = "; expires=" + vEnd.toUTCString();
                        break
                }
            }
            document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
            return true
        },
        removeItem: function(sKey, sPath, sDomain) {
            if (!sKey || !this.hasItem(sKey)) {
                return false
            }
            document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
            return true
        },
        hasItem: function(sKey) {
            return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie)
        },
        keys: function() {
            var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
            for (var nIdx = 0; nIdx < aKeys.length; nIdx++) {
                aKeys[nIdx] = decodeURIComponent(aKeys[nIdx])
            }
            return aKeys
        }
    };
    const source = 'https://na-021.files.nextcdn.org/stream/04/c989297659739b02ddedf0c686537e7b099e77360263803760baa6aaae30d465/uwu.m3u8';
    const video = document.querySelector('video');
    const player = new Plyr(video, {
        'keyboard': {
            'global': true
        },
        'ratio': '16:9',
        'volume': 1,
        'seekTime': 5,
        'storage': {
            'key': 'kwik'
        },
        controls: ['play-large', 'play', 'progress', 'current-time', 'mute', 'volume', 'captions', 'settings', 'pip', 'airplay', 'fullscreen', 'capture'],
        'fullscreen': {
            'iosNative': true
        }
    });
    if (!Hls.isSupported()) {
        video.src = source
    } else {
        var config = {
            maxBufferLength: 180,
            maxMaxBufferLength: 600,
            backBufferLength: Infinity,
            enableWorker: true,
            lowLatencyMode: true
        };
        const hls = new Hls(config);
        hls.loadSource(source);
        hls.attachMedia(video);
        window.hls = hls
    }
    player.on("enterfullscreen", event => {
        window.screen.orientation.lock("landscape")
    });
    player.speed = 1;
    
    function bindEvent(element, eventName, eventHandler) {
        if (element.addEventListener) {
            element.addEventListener(eventName, eventHandler, false)
        } else if (element.attachEvent) {
            element.attachEvent('on' + eventName, eventHandler)
        }
    }
    var sendMessage = function(message) {
        window.parent.postMessage(message, '*')
    };
    bindEvent(window, 'message', function(e) {
        var data = e.data;
        if (data === 'play') player.play();
        if (data === 'pause') player.pause();
        if (data === 'stop') player.stop()
    });
    player.on('ready', event => {
        sendMessage('ready')
    });
    player.on('play', event => {
        sendMessage('play')
    });
    player.on('pause', event => {
        sendMessage('pause')
    });
    player.on('timeupdate', event => {
        sendMessage(player.currentTime);
        document.querySelector('.ss-timestamp').innerHTML = String(player.currentTime.toFixed(2))
    });
    player.on('ended', event => {
        sendMessage('ended')
    });
    

    Actual Output

    The code actually looked like this after beautification:

    Traceback (most recent call last):
      File "/home/itori/prettifier/meow.py", line 7, in <module>
        res = jsbeautifier.beautify(meow, opts)
      File "/home/itori/.local/lib/python3.10/site-packages/jsbeautifier/__init__.py", line 82, in beautify
        return b.beautify(string, opts)
      File "/home/itori/.local/lib/python3.10/site-packages/jsbeautifier/javascript/beautifier.py", line 185, in beautify
        source_text = self.unpack(source_text, self._options.eval_code)
      File "/home/itori/.local/lib/python3.10/site-packages/jsbeautifier/javascript/beautifier.py", line 274, in unpack
        return unpackers.run(source, evalcode)
      File "/home/itori/.local/lib/python3.10/site-packages/jsbeautifier/unpackers/__init__.py", line 50, in run
        source = unpacker.unpack(source)
      File "/home/itori/.local/lib/python3.10/site-packages/jsbeautifier/unpackers/packer.py", line 72, in unpack
        source = re.sub(r"\b\w+\b", lookup, payload, flags=re.ASCII)
      File "/usr/lib/python3.10/re.py", line 209, in sub
        return _compile(pattern, flags).sub(repl, string, count)
      File "/home/itori/.local/lib/python3.10/site-packages/jsbeautifier/unpackers/packer.py", line 66, in lookup
        return symtab[unbase(word)] or word
    IndexError: list index out of range
    

    Steps to Reproduce

    Simply use this code provided above and try to run it

    import jsbeautifier
    
    meow = """eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('f $7={H:a(2){4 B(9.7.h(y z("(?:(?:^|.*;)\\\\s*"+d(2).h(/[\\-\\.\\+\\*]/g,"\\\\$&")+"\\\\s*\\\\=\\\\s*([^;]*).*$)|^.*$"),"$1"))||G},E:a(2,q,3,6,5,t){k(!2||/^(?:8|r\\-v|o|m|p)$/i.D(2)){4 w}f b="";k(3){F(3.J){j K:b=3===P?"; 8=O, I N Q M:u:u A":"; r-v="+3;n;j L:b="; 8="+3;n;j S:b="; 8="+3.Z();n}}9.7=d(2)+"="+d(q)+b+(5?"; m="+5:"")+(6?"; o="+6:"")+(t?"; p":"");4 x},Y:a(2,6,5){k(!2||!11.C(2)){4 w}9.7=d(2)+"=; 8=12, R 10 W l:l:l A"+(5?"; m="+5:"")+(6?"; o="+6:"");4 x},C:a(2){4(y z("(?:^|;\\\\s*)"+d(2).h(/[\\-\\.\\+\\*]/g,"\\\\$&")+"\\\\s*\\\\=")).D(9.7)},X:a(){f c=9.7.h(/((?:^|\\s*;)[^\\=]+)(?=;|$)|^\\s*|\\s*(?:\\=[^;]*)?(?:\\1|$)/g,"").T(/\\s*(?:\\=[^;]*)?;\\s*/);U(f e=0;e<c.V;e++){c[e]=B(c[e])}4 c}};',62,65,'||sKey|vEnd|return|sDomain|sPath|cookie|expires|document|function|sExpires|aKeys|encodeURIComponent|nIdx|var||replace||case|if|00|domain|break|path|secure|sValue|max||bSecure|59|age|false|true|new|RegExp|GMT|decodeURIComponent|hasItem|test|setItem|switch|null|getItem|31|constructor|Number|String|23|Dec|Fri|Infinity|9999|01|Date|split|for|length|1970|keys|removeItem|toUTCString|Jan|this|Thu'.split('|'),0,{}));eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('h o=\'1A://1z-1y.1x.1w.1v/1u/1t/1s/1r.1q\';h d=s.r(\'d\');h 0=B 1p(d,{\'1o\':{\'1n\':i},\'1m\':\'16:9\',\'D\':1,\'1l\':5,\'1k\':{\'1j\':\'1i\'},1h:[\'7-1g\',\'7\',\'1f\',\'1e-1d\',\'1c\',\'D\',\'1b\',\'1a\',\'19\',\'18\',\'C\',\'17\'],\'C\':{\'15\':i}});8(!A.14()){d.13=o}x{j z={12:11,10:Z,Y:X,W:i,V:i};h c=B A(z);c.U(o);c.T(d);g.c=c}0.3("S",6=>{g.R.Q.P("O")});0.N=1;k v(b,n,m){8(b.y){b.y(n,m,M)}x 8(b.w){b.w(\'3\'+n,m)}}j 4=k(l){g.L.K(l,\'*\')};v(g,\'l\',k(e){j a=e.a;8(a===\'7\')0.7();8(a===\'f\')0.f();8(a===\'u\')0.u()});0.3(\'t\',6=>{4(\'t\')});0.3(\'7\',6=>{4(\'7\')});0.3(\'f\',6=>{4(\'f\')});0.3(\'J\',6=>{4(0.q);s.r(\'.I-H\').G=F(0.q.E(2))});0.3(\'p\',6=>{4(\'p\')});',62,99,'player|||on|sendMessage||event|play|if||data|element|hls|video||pause|window|const|true|var|function|message|eventHandler|eventName|source|ended|currentTime|querySelector|document|ready|stop|bindEvent|attachEvent|else|addEventListener|config|Hls|new|fullscreen|volume|toFixed|String|innerHTML|timestamp|ss|timeupdate|postMessage|parent|false|speed|landscape|lock|orientation|screen|enterfullscreen|attachMedia|loadSource|lowLatencyMode|enableWorker|Infinity|backBufferLength|600|maxMaxBufferLength|180|maxBufferLength|src|isSupported|iosNative||capture|airplay|pip|settings|captions|mute|time|current|progress|large|controls|kwik|key|storage|seekTime|ratio|global|keyboard|Plyr|m3u8|uwu|c989297659739b02ddedf0c686537e7b099e77360263803760baa6aaae30d465|04|stream|org|nextcdn|files|021|na|https'.split('|'),0,{}))"""
    opts = jsbeautifier.default_options()
    opts.indent_size = 2
    opts.space_in_empty_paren = True
    res = jsbeautifier.beautify(meow, opts)
    print(res)
    

    Environment

    OS: EndeavourOS (Linux Distro)

    type: bug language: javascript 
    opened by ToriDevz 2
Releases(v1.14.6)
For formatting, searching, and rewriting JavaScript.

jsfmt For formatting, searching, and rewriting JavaScript. Analogous to gofmt. Installation npm install -g jsfmt Usage $ jsfmt --help Usage: jsfmt [

Rdio 1.7k Dec 9, 2022
Magic number detection for JavaScript

Magic number detection for javascript. Let Buddy sniff out the unnamed numerical constants in your code. Overview What are magic numbers? Installation

Daniel St. Jules 827 Dec 24, 2022
Find and fix problems in your JavaScript code.

ESLint Website | Configuring | Rules | Contributing | Reporting Bugs | Code of Conduct | Twitter | Mailing List | Chat Room ESLint is a tool for ident

ESLint 21.9k Dec 31, 2022
The JavaScript Code Quality Tool

JSLint, The JavaScript Code Quality Tool Douglas Crockford [email protected] 2019-03-15 jslint.js contains the jslint function. It parses and a

Douglas Crockford 3.5k Jan 6, 2023
🌟 JavaScript Style Guide, with linter & automatic code fixer

JavaScript Standard Style Sponsored by English • Español (Latinoamérica) • Français • Bahasa Indonesia • Italiano (Italian) • 日本語 (Japanese) • 한국어 (Ko

Standard JS 27.8k Dec 31, 2022
ECMAScript code beautifier/formatter

esformatter ECMAScript code beautifier/formatter. Important This tool is still missing support for many important features. Please report any bugs you

Miller Medeiros 968 Nov 1, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
This is my to-do list website built with html, css and JavaScript. In this project I used Webpack to bundle JavaScript and ES6 modules to write modular JavaScript.

To-Do-List App This is my to-do list website built with html, css and JavaScript. In this project I used Webpack to bundle JavaScript and ES6 modules

Samuel Mwape 18 Sep 20, 2022
The best JavaScript Data Table for building Enterprise Applications. Supports React / Angular / Vue / Plain JavaScript.

Module SonarCloud Status ag-grid-community ag-grid-enterprise AG Grid AG Grid is a fully-featured and highly customizable JavaScript data grid. It del

AG Grid 9.5k Dec 30, 2022
A transparent, in-memory, streaming write-on-update JavaScript database for Small Web applications that persists to a JavaScript transaction log.

JavaScript Database (JSDB) A zero-dependency, transparent, in-memory, streaming write-on-update JavaScript database for the Small Web that persists to

Small Technology Foundation 237 Nov 13, 2022
Reference for How to Write an Open Source JavaScript Library - https://egghead.io/series/how-to-write-an-open-source-javascript-library

Reference for How to Write an Open Source JavaScript Library The purpose of this document is to serve as a reference for: How to Write an Open Source

Sarbbottam Bandyopadhyay 175 Dec 24, 2022
Traceur is a JavaScript.next-to-JavaScript-of-today compiler

What is Traceur? Traceur is a JavaScript.next-to-JavaScript-of-today compiler that allows you to use features from the future today. Traceur supports

Google 8.2k Dec 31, 2022
Dynamic tracing for javascript, in javascript (similar dtrace, ktap etc)

jstrace Dynamic tracing for JavaScript, written in JavaScript, providing you insight into your live nodejs applications, at the process, machine, or c

null 387 Oct 28, 2022
Open Source projects are a project to improve your JavaScript knowledge with JavaScript documentation, design patterns, books, playlists.

It is a project I am trying to list the repos that have received thousands of stars on Github and deemed useful by the JavaScript community. It's a gi

Cihat Salik 22 Aug 14, 2022
Javascript-testing-practical-approach-2021-course-v3 - Javascript Testing, a Practical Approach (v3)

Javascript Testing, a Practical Approach Description This is the reference repository with all the contents and the examples of the "Javascript Testin

Stefano Magni 2 Nov 14, 2022
Pickle tree - Javascript tree component made with pure javascript

Pickle Tree Pickle tree is a tree component written as completely pure javascript. Just send json file to object and have fun :-D Pickle tree does't n

Kadir Barış Bozat 17 Nov 13, 2022