Beautifier for javascript
Go to file
Phil d83308d87e Add operator_position functionality
- Add sanitization of operator_position option.  Throws error if invalid.
 - Possible operator_position options are:
    1) 'before-newline' (default)
    2) 'after-newline'
    3) 'preserve-newline'
 - Move some code around in handle_operator in order to separate
    conflicting logic now that operator newlines are accounted for.
 - Modify allow_wrap_or_preserved_newline to handle operator
    preserved newlines as well.
 - Add -> build tests
 - Within the tests, add an 'inputlib.js' file holding common
    input arrays.  This was necessary due to the matrices not working
    cleanly with default behavior.

Changes not directly relevant to operator_position
 - Add Object.values polyfill
 - Ignore intellijidea project file
 - Fix 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
2016-02-03 13:05:30 -06:00
js Add operator_position functionality 2016-02-03 13:05:30 -06:00
python Add operator_position functionality 2016-02-03 13:05:30 -06:00
test Add operator_position functionality 2016-02-03 13:05:30 -06:00
tools Changelog with gsort -V 2016-01-29 10:52:00 -08:00
web Update codemirror and jquery 2015-11-19 14:46:35 -08:00
.gitignore Add operator_position functionality 2016-02-03 13:05:30 -06:00
.npmignore Reorganize file structure by language/platform 2013-04-04 15:51:19 -07:00
.travis.yml Replace makefile dependency with bash script 2016-01-20 15:45:45 -08:00
appveyor.yml Appveyor fix 2016-02-01 15:15:34 -08:00
bower.json Remove moot version property from bower.json 2015-06-10 20:59:28 -04:00
build Replace makefile dependency with bash script 2016-01-20 15:45:45 -08:00
CHANGELOG.md Update Changelog for 1.6.2 2016-01-31 13:36:35 -08:00
CONTRIBUTING.md Replace makefile dependency with bash script 2016-01-20 15:45:45 -08:00
index.html Update descriptions and start 1.6.0 pre-release 2016-01-26 11:41:50 -08:00
LICENSE Correct copyright 2013-03-20 12:48:57 -07:00
package.json 1.6.2 2016-01-31 13:36:58 -08:00
README.md Update descriptions and start 1.6.0 pre-release 2016-01-26 11:41:50 -08:00

JS Beautifier

Build Status Build status NPM version Download stats Join the chat at https://gitter.im/beautify-web/js-beautify

NPM stats

This little beautifier will reformat and reindent bookmarklets, ugly JavaScript, unpack scripts packed by Dean Edwards popular packer, as well as deobfuscate scripts processed by javascriptobfuscator.com.

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 jsbeautifier.org. Options are available via the UI.

Python

To beautify using python:

$ pip install jsbeautifier
$ js-beautify file.js

Beautified output goes to stdout.

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
res = jsbeautifier.beautify('some javascript', opts)

JavaScript

As an alternative to the Python script, 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
var beautify = require('js-beautify').js_beautify,
    fs = require('fs');

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

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"]
  -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 [" "]
  -e, --eol                         character(s) to use as line terminators. (default newline - "\\n")');
  -l, --indent-level                Initial indentation level [0]
  -t, --indent-with-tabs            Indent with tabs, overrides -s and -c
  -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 )
  -j, --jslint-happy                Enable jslint-stricter mode
  -a, --space-after-anon-function   Add a space before an anonymous function's parens, ie. function ()
  -b, --brace-style                 [collapse-preserve-inline|collapse|expand|end-expand|none] ["collapse"]
  -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 at next opportunity after N characters [0]
  -X, --e4x                         Pass E4X xml literals through untouched
  -n, --end-with-newline            End output with newline
  -C, --comma-first                 Put commas at the beginning of new line instead of end
  --good-stuff                      Warm the cockles of Crockford's heart

These largely correspond to the underscored option keys for both library interfaces, which have these defaults:

{
    "indent_size": 4,
    "indent_char": " ",
    "eol": "\n",
    "indent_level": 0,
    "indent_with_tabs": false,
    "preserve_newlines": true,
    "max_preserve_newlines": 10,
    "jslint_happy": false,
    "space_after_anon_function": false,
    "brace_style": "collapse",
    "keep_array_indentation": false,
    "keep_function_indentation": false,
    "space_before_conditional": true,
    "break_chained_methods": false,
    "eval_code": false,
    "unescape_strings": false,
    "wrap_line_length": 0,
    "wrap_attributes": "auto",
    "wrap_attributes_indent_size": 4,
    "end_with_newline": false
}

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.

You might notice that the CLI options and defaults hash aren't 100% correlated. Historically, the Python and JS APIs have not been 100% identical. For example, space_before_conditional is currently JS-only, and not addressable from the CLI script. There are a few other additional cases keeping us from 100% API-compatibility. Patches welcome!

Directives to Ignore or Preserve sections (Javascript only)

Beautifier for supports directives in comments inside the file. This allows you to tell the beautifier to preserve the formtatting of or completely ignore part of a file.
The example input below will remain changed after beautification

// Use preserve when the content is not javascript, but you don't want it reformatted.
/* beautify preserve:start */
{
    browserName: 'internet explorer',
    platform:    'Windows 7',
    version:     '8'
}
/* beautify preserve:end */

// Use ignore when the content is not parsable as javascript.  
var a =  1;
/* beautify ignore:start */
 {This is some strange{template language{using open-braces?
/* beautify ignore:end */

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
  -L, --selector-separator-newline   Add a newline between multiple selectors
  -N, --newline-between-rules        Add a newline between CSS rules

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] ["auto"]
  -i, --wrap-attributes-indent-size  Indent wrapped attributes to after N characters [indent-size]
  -U, --unformatted                  List of tags (defaults to inline) that should not be reformatted
  -E, --extra_liners                 List of tags (defaults to [head,body,/html] that should have an extra newline before them.

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.

js-beautify@1.6.0-0