Giter Club home page Giter Club logo

js-beautify's Introduction

JS Beautifier

CI Greenkeeper badge

PyPI version CDNJS version NPM @latest NPM @next

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

NPM stats

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.15.1/beautify.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.15.1/beautify-css.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.15.1/beautify-html.js"></script>

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

Example usage of a JS tag in html:

<!DOCTYPE html>
<html lang="en">
  <body>

. . .

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

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

After you embed the <script> tags in your html file, they expose three functions: js_beautify, css_beautify, and html_beautify

Example usage of beautifying a json string:

const options = { indent_size: 2, space_in_empty_paren: true }

const dataObj = {completed: false,id: 1,title: "delectus aut autem",userId: 1,}

const dataJson = JSON.stringify(dataObj)

js_beautify(dataJson, options)

/* OUTPUT
{
  "completed": false,
  "id": 1,
  "title": "delectus aut autem",
  "userId": 1,
}
*/

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').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 }));
});

If you are using ESM Imports, you can import js-beautify like this:

// 'beautify' can be any name here.
import beautify from 'js-beautify';

beautify.js(data, options);
beautify.html(data, options);
beautify.css(data, options);

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,angular) ["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"]
  -M, --wrap-attributes-min-attrs    Minimum number of html tag attributes for force wrap attribute options [2]
  -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
  --inline_custom_elements           Inline custom elements [true]
  -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,angular) ["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])

js-beautify's People

Contributors

aecepoglu avatar ang-zeyu avatar antoniusanggito avatar asteinha avatar bhaveshvasnani avatar bitwiseman avatar c32hedge avatar dependabot[bot] avatar einars avatar ephox-mogran avatar esseks avatar evocateur avatar greenkeeper[bot] avatar hanabishirecca avatar infocatcher avatar juanfml avatar mackless avatar madman-bob avatar mfaou avatar mhnaeem avatar mho22 avatar mokkabonna avatar mrmonroe avatar nightwing avatar oneofone avatar pr0grammm avatar rasmuserik avatar swan46 avatar thoger-rh avatar vittgam 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  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

js-beautify's Issues

for loop + regex

Formatting the following (minimal) JS snippet results in mangled code:

for(;;) { /abc/i.test('abcd'); }

Weird indentation when using switch-case

switch (v) { case 1: break; case 2: break; case 3: break; default: break; }

…becomes…

switch (v) {
case 1:
    break;
case 2:
    break;
case 3:
    break;
default:
    break;
}

Maybe this is intentional, but I would expect the case to be indented by 1 level (based on the settings).

Strange behavior with minus minus leading code.

When I beautify this piece of code, which shouldn't need any changes:
xbDebug.prototype.pop = function () {
this.on = this.stack[this.stack.length - 1];
--this.stack.length;
};
It turns into this:
xbDebug.prototype.pop = function () {
this.on = this.stack[this.stack.length - 1]; --this.stack.length;
};

block comment breaks the meaning of the code

As reported by Ari Entlich,

return /* comment */ {
a: 5,
b: 10
};

Gets beautified to:

return /* comment */
{
a: 5,
b: 10
};

Which has a different meaning. This also happens when the return is replaced with a variable assignment or something similar.

dot notation

numbers in dot notation should have a leading zero before a dot. ie .5 shall be beautified to 0.5.

mfG Hase

inline comments get put on the following line

Simplified example case:

module.exports = {
  lib: {
    fs: require('fs'), // file system
    path: require('path')
  },
  ...

becomes

module.exports = {
  lib: {
    fs: require('fs'),
    // file system
    path: require('path')
  },
  ...

It would be less of an issue if it puts it on the preceeding line, instead of on the following line.

(Thanks for a very handy library!)

Crash with keep array indentation

JS beautify with keep array indentation breaks my code.

It change this:

var a = [
    // item 1:
    {
        foo: 'bar'
    },
    // item 2:
    {
        pig: 'hug'
    }
];

to this:

var a = [
    // item 1: {
    foo: 'bar'
},
    // item 2: {
    pig: 'hug'
}
];

functions in var statements

Having a function as the first value in a variable definition leads to some weird indentation:

var a = function () {
    return null;
},
    b = false;

The expected result is rather:

var a = function () {
        return null;
    },
    b = false;

If the function is not the first value though, the indentation is correct.

mfG Hase

Create new indentation level inside array

Using the latest beautify.js (commit 78b3bf3), the following formatting error occurs:

var arr = [
 7, // true
 10, // false
 37, // true
 60, // false
 373, // true
 390, // false
 1427, // true
 1683, // false
 7879, // true
 7881 // false
];

…becomes…

var arr = [
7, // true
10, // false
37, // true
60, // false
373, // true
390, // false
1427, // true
1683, // false
7879, // true
7881 // false
];

There should probably be a new indentation level inside the array.

As always, you can reproduce this bug using the latest GitHub version of beautify.js at http://mathiasbynens.be/demo/js-beautify

Issue with single-line comments preceding functions

Using the latest beautify.js (commit 868cf0e), the following formatting errors occur:

// Foo
function foo(bar) {
 bar();
};

// Foo 2
function foo2(bar) {
  bar();
};

…becomes…

// Foo


function foo(bar) {
 bar();
};

// Foo 2


function foo2(bar) {
 bar();
};

Two linebreaks are added after the single-line comments preceding the function. I doubt this is intentional (?).

Comment handling options?

It would be nice to have some comment handling options.
Currently the program moves inline comments on its own line up when at times it would be more accurate to move it down, and if I want to keep comments where they are, I don't have a choice in the matter.
Keep up the great work.

The regexp in _filterargs fails when packed code has embedded new lines

Just what it says in the title. I fixed it by removing the new line characters before applying the regex. Here is the patch:

diff --git a/python/jsbeautifier/unpackers/packer.py b/python/jsbeautifier/unpackers/packer.py
index 1029f56..05515bc 100644
--- a/python/jsbeautifier/unpackers/packer.py
+++ b/python/jsbeautifier/unpackers/packer.py
@@ -43,7 +43,7 @@ def _filterargs(source):
     """Juice from a source file the four args needed by decoder."""
     argsregex = (r"}\('(.*)', *(\d+), *(\d+), *'(.*)'\."
                  r"split\('\|'\), *(\d+), *(.*)\)\)")
-    args = re.search(argsregex, source).groups()
+    args = re.search(argsregex, source.replace("\n", "")).groups()
     try:
         return args[0], args[3].split('|'), int(args[1]), int(args[2])
     except ValueError:
diff --git a/tests/run-tests b/tests/run-tests
index fd3b953..1618258 100755
--- a/tests/run-tests
+++ b/tests/run-tests
@@ -1,4 +1,4 @@
-#!/usr/bin/js
+#!/usr/bin/jsscript-1.6

 // a little helper for testing from command line
 // just run it, it will output the test results

print function in Python 2.6

To reproduce:

$ python jsbeautifier.py
  File "jsbeautifier.py", line 267
    def print(self, s):
            ^
SyntaxError: invalid syntax

Quick patch:

--- jsbeautifier.py 2011-03-29 10:34:27.000000000 +0700
+++ jsbeautifier    2011-03-29 10:35:26.000000000 +0700
@@ -265,5 +265,5 @@


-    def print(self, s):
+    def prnt(self, s):
         if s == ' ':
             # make sure only single space gets drawn
@@ -613,7 +613,7 @@
             if self.last_type == 'TK_WORD' or self.last_text == ')':
                 if self.last_text in self.line_starters:
-                    self.print(' ')
+                    self.prnt(' ')
                 self.set_mode('(EXPRESSION)')
-                self.print(token_text)
+                self.prnt(token_text)
                 return

@@ -651,13 +651,13 @@
             pass
         elif self.last_type not in ['TK_WORD', 'TK_OPERATOR']:
-            self.print(' ')
+            self.prnt(' ')
         elif self.last_word == 'function':
             # function() vs function ()
             if self.opts.space_after_anon_function:
-                self.print(' ')
+                self.prnt(' ')
         elif self.last_text in self.line_starters or self.last_text == 'catch':
-            self.print(' ')
+            self.prnt(' ')

-        self.print(token_text)
+        self.prnt(token_text)


@@ -667,5 +667,5 @@
                 if self.last_text == '}':
                     self.remove_indent()
-                    self.print(token_text)
+                    self.prnt(token_text)
                     self.restore_mode()
                     return
@@ -675,8 +675,8 @@
                         self.restore_mode()
                         self.print_newline()
-                        self.print(token_text)
+                        self.prnt(token_text)
                         return
         self.restore_mode()
-        self.print(token_text)
+        self.prnt(token_text)


@@ -690,9 +690,9 @@
             if self.last_type != 'TK_OPERATOR':
                 if self.last_text in ['return', '=']:
-                    self.print(' ')
+                    self.prnt(' ')
                 else:
                     self.print_newline(True)

-            self.print(token_text)
+            self.prnt(token_text)
             self.indent()
         else:
@@ -701,14 +701,14 @@
                     self.print_newline()
                 else:
-                    self.print(' ')
+                    self.prnt(' ')
             else:
                 # if TK_OPERATOR or TK_START_EXPR
                 if self.is_array(self.flags.previous_mode) and self.last_text == ',':
                     if self.last_last_text == '}':
-                        self.print(' ')
+                        self.prnt(' ')
                     else:
                         self.print_newline()
             self.indent()
-            self.print(token_text)
+            self.prnt(token_text)


@@ -736,12 +736,12 @@
                     self.print_newline()

-        self.print(token_text)
+        self.prnt(token_text)


     def handle_word(self, token_text):
         if self.do_block_just_closed:
-            self.print(' ')
-            self.print(token_text)
-            self.print(' ')
+            self.prnt(' ')
+            self.prnt(token_text)
+            self.prnt(' ')
             self.do_block_just_closed = False
             return
@@ -766,5 +766,5 @@
                 self.print_newline()
                 self.flags.indentation_level += 1
-            self.print(token_text)
+            self.prnt(token_text)
             self.flags.in_case = True
             return
@@ -780,5 +780,5 @@
                 else:
                     prefix = 'SPACE'
-                    self.print(' ')
+                    self.prnt(' ')
         elif self.last_type == 'TK_SEMICOLON' and self.flags.mode in ['BLOCK', 'DO_BLOCK']:
             prefix = 'NEWLINE'
@@ -796,5 +796,5 @@
             prefix = 'NEWLINE'
         elif self.last_type == 'TK_END_EXPR':
-            self.print(' ')
+            self.prnt(' ')
             prefix = 'NEWLINE'

@@ -812,5 +812,5 @@
             else:
                 self.trim_output(True)
-                self.print(' ')
+                self.prnt(' ')
         elif prefix == 'NEWLINE':
             if token_text == 'function' and (self.last_type == 'TK_START_EXPR' or self.last_text in '=,'):
@@ -826,5 +826,5 @@
                     # for (var x = 0...
                     if token_text == 'if' and self.last_word == 'else' and self.last_text != '{':
-                        self.print(' ')
+                        self.prnt(' ')
                     else:
                         self.print_newline()
@@ -834,8 +834,8 @@
                 self.print_newline() # }, in lists get a newline
         elif prefix == 'SPACE':
-            self.print(' ')
+            self.prnt(' ')


-        self.print(token_text)
+        self.prnt(token_text)
         self.last_word = token_text

@@ -854,5 +854,5 @@

     def handle_semicolon(self, token_text):
-        self.print(token_text)
+        self.prnt(token_text)
         self.flags.var_line = False
         self.flags.var_line_reindented = False
@@ -863,7 +863,7 @@
             self.print_newline()
         elif self.last_type == 'TK_WORD':
-            self.print(' ')
+            self.prnt(' ')

-        self.print(token_text)
+        self.prnt(token_text)


@@ -873,7 +873,7 @@
             self.flags.var_line_tainted = True

-        self.print(' ')
-        self.print(token_text)
-        self.print(' ')
+        self.prnt(' ')
+        self.prnt(token_text)
+        self.prnt(' ')


@@ -888,5 +888,5 @@
         if self.flags.var_line and token_text == ',':
             if self.flags.var_line_tainted:
-                self.print(token_text)
+                self.prnt(token_text)
                 self.flags.var_line_reindented = True
                 self.flags.var_line_tainted = False
@@ -898,10 +898,10 @@
         if self.last_text in ['return', 'throw']:
             # return had a special handling in TK_WORD
-            self.print(' ')
-            self.print(token_text)
+            self.prnt(' ')
+            self.prnt(token_text)
             return

         if token_text == ':' and self.flags.in_case:
-            self.print(token_text)
+            self.prnt(token_text)
             self.print_newline()
             self.flags.in_case = False
@@ -910,5 +910,5 @@
         if token_text == '::':
             # no spaces around the exotic namespacing syntax operator
-            self.print(token_text)
+            self.prnt(token_text)
             return

@@ -917,24 +917,24 @@
                 if self.flags.var_line_tainted:
                     # This never happens, as it's handled previously, right?
-                    self.print(token_text)
+                    self.prnt(token_text)
                     self.print_newline()
                     self.flags.var_line_tainted = False
                 else:
-                    self.print(token_text)
-                    self.print(' ')
+                    self.prnt(token_text)
+                    self.prnt(' ')
             elif self.last_type == 'TK_END_BLOCK' and self.flags.mode != '(EXPRESSION)':
-                self.print(token_text)
+                self.prnt(token_text)
                 if self.flags.mode == 'OBJECT' and self.last_text == '}':
                     self.print_newline()
                 else:
-                    self.print(' ')
+                    self.prnt(' ')
             else:
                 if self.flags.mode == 'OBJECT':
-                    self.print(token_text)
+                    self.prnt(token_text)
                     self.print_newline()
                 else:
                     # EXPR or DO_BLOCK
-                    self.print(token_text)
-                    self.print(' ')
+                    self.prnt(token_text)
+                    self.prnt(' ')
             # comma handled
             return
@@ -970,10 +970,10 @@

         if space_before:
-            self.print(' ')
+            self.prnt(' ')

-        self.print(token_text)
+        self.prnt(token_text)

         if space_after:
-            self.print(' ')
+            self.prnt(' ')


@@ -986,8 +986,8 @@
             # javadoc: reformat and reindent
             self.print_newline()
-            self.print(lines[0])
+            self.prnt(lines[0])
             for line in lines[1:]:
                 self.print_newline()
-                self.print(' ' + line.strip())
+                self.prnt(' ' + line.strip())
         else:
             # simple block comment: leave intact
@@ -998,16 +998,16 @@
             else:
                 # single line /* ... */ comment stays on the same line
-                self.print(' ')
+                self.prnt(' ')
             for line in lines:
-                self.print(line)
-                self.print('\n')
+                self.prnt(line)
+                self.prnt('\n')
         self.print_newline()


     def handle_inline_comment(self, token_text):
-        self.print(' ')
-        self.print(token_text)
+        self.prnt(' ')
+        self.prnt(token_text)
         if self.is_expression(self.flags.mode):
-            self.print(' ')
+            self.prnt(' ')
         else:
             self.print_newline()
@@ -1018,7 +1018,7 @@
             self.print_newline()
         else:
-            self.print(' ')
+            self.prnt(' ')

-        self.print(token_text)
+        self.prnt(token_text)
         self.print_newline()

@@ -1026,7 +1026,7 @@
     def handle_unknown(self, token_text):
         if self.last_text in ['return', 'throw']:
-            self.print(' ')
+            self.prnt(' ')

-        self.print(token_text)
+        self.prnt(token_text)

Support CSS?

HTML and JS formatted perfectly, but no CSS

Will support CSS in future?

Thanks

Make signature of `style_html` match that of `js_beautify`

function js_beautify(js_source_text, options) {}

…versus…

function style_html(html_source, indent_size, indent_character, max_char, brace_style) {}

Would be cool if style_html accepted an options object instead, just like js_beautify.

Wrong behavior with indent_level > 0

Example:

var res = js_beautify(
    "\tif(something)\n\t\tdoSomething(); // ...",
    {
        indent_size:               1,
        indent_char:               "\t",
        preserve_newlines:         true,
        brace_style:               "end-expand",
        keep_array_indentation:    true,
        jslint_happy:              false,
        indent_level:              1 //!
    }
);
alert("[" + res + "]");

Result:

[if (something) doSomething(); // ...
    ]

And first spaces are always missing.

[Feature request] --disable-preserve-newlines to one line

Could it be configurable so that multiple consecutive empty lines can be replaced with one empty line rather than removed entirely?

e.g.

function Whatever ()
{
  var a = 1;


  this.something = 1;
  this.blah = function ()
  {

  }



  this.blah2 = function ()
  {

  }




};

becomes

function Whatever ()
{
  var a = 1;

  this.something = 1;
  this.blah = function ()
  {

  }

  this.blah2 = function ()
  {

  }

};

rather than

function Whatever ()
{
  var a = 1;
  this.something = 1;
  this.blah = function ()
  {
  }
  this.blah2 = function ()
  {
  }
};

Thanks again for your time.

Issue with single-line comments at end of line

Using the latest beautify.js (commit 868cf0e), the following formatting errors occur:

var arr = [
 7, // true
 10, // false
 37, // true
 60, // false
 373, // true
 390, // false
 1427, // true
 1683, // false
 7879, // true
 7881 // false
];

…becomes…

var arr = [
  7, // true10, // false37, // true60, // false373, // true390, // false1427, // true1683, // false7879, // true7881 // false];

FWIW, this is tested with these settings: { indent_size: 2, indent_char: ' ' }.

What's weird is that I don't get this error on http://jsbeautifier.org/, although I was able to reproduce the problem in a test case (using the JS straight from GitHub): http://mathiasbynens.be/demo/js-beautify. This could mean the bug was introduced by a recent commit (if jsbeautifier.org is not using the latest version).

Division after parentheses

The beautifier leaves this alone:

var one = (1)/1+1;var two=one;

instead of turning it into

var one = (1) / 1 + 1;

var two = one;

this bug then leads to an error with the following:

var preview_left=(width-preview_width)/2+1;var preview_top=height-preview_height+1;var preview_style="height: "+preview_height+"px; width: "+preview_width+"px; left: "+preview_left+"px; top:"+preview_top+"px;";new Insertion.Top(preview,'xxxxxxxxxxxxxxxxxxxxxxxxx" border="0" class="plus-preview" style="visibility: hidden; position: absolute;'+preview_style+'"/>');Event.observe(el,"mouseover",toggle_visible.bind(el,preview.down('img.plus-preview')));Event.observe(el,"mouseout",toggle_invisible.bind(el,preview.down('img.plus-preview')));

turning into the following, which creates an error due to a linebreak in the middle of quotes

var preview_left = (width - preview_width)/2+1;var preview_top=height-preview_height+1;var preview_style="height: "+preview_height+"px; width: "+preview_width+"px; left: "+preview_left+"px; top:"+preview_top+"px;";new Insertion.Top(preview,'xxxxxxxxxxxxxxxxxxxxxxxxx" border="0" class="plus-preview" style="visibility: hidden; position: absolute;'+preview_style+'"/ > ');Event.observe(el,"mouseover",toggle_visible.bind(el,preview.down('
img.plus - preview ')));Event.observe(el,"mouseout",toggle_invisible.bind(el,preview.down('
img.plus - preview ')));

huge fan of the beautifier by the way, I'd tried to make one before, it's a very useful tool. I'm impressed it parses the syntax so well. It should definitely get integrated into firebug in some form.

keep-array-indentation does not seem to work

This might be a problem with my expectations?

I'm using the version in commit 6f47408.

Starting with this:

var arrg = ["one",
            "two",
            "three",
            "fou",
            "afdas",
            "adfa"];

Becomes:

var arrg = ["one", "two", "three", "fou", "afdas", "adfa"];

When I run:

jsbeautifier.py -k ~/test.js

Request for referencing jsBeautifier.net in Readme

I have created a .Net wrapper for js-beautify that can be executed directly from command line and has no external dependency.
The github repo for the wrapper is here:
https://github.com/rhoney/jsBeautifier.net

And a blog post discussing the wrapper is here:
http://www.rahulsingla.com/blog/2010/12/jsbeautifier-net-javascript-beautifier-in-net

I thought Windows users might find using the .Net wrapper intuitive, and am therefore requesting a reference to the wrapper from the Readme for js-beauitfy.

Suppressing the call to "trim_output()"

Dear Einar Lielmanis,

I read the Javascript beautifier code and I noticed that often "trim_output()" is called to cut off the indentation added after calling "print_newline()".

I think adding the indentantion should have been carried out by a function ad hoc (i.e. "print_indent()") just before calling "print_token()" and only in case it would have been necessary adding such indentation.

I would like to optimize the code this manner, but I fear I would miss something that would mess the code formatting if I take away from print_newline() the part in which the indentation is added.

Is there a way to add the indentation only when necessary, so to avoid redundant calls to "trim_output()"?

Could you publish a more detailed explanation of your code so that I would be able to apply these modifies?

Can you publish some test code to beautify which test all of the beautifier conditions, so to be sure that after a modify the beautifier still works properly?

Thanks,
Francesco.

Incorrect indenting with multiple var declarations

When declaring multiple variables in one go, e.g. var a = 1, b = 2, c = 3; the beautified code looks like this:

// indent with 4 spaces { indent_size: 4, indent_char: ' ' }
var a = 1,
    b = 2,
    c = 3;

This looks fine. However, when different settings are used, things can go wrong:

// indent with 2 spaces { indent_size: 2, indent_char: ' ' }
var a = 1,
  b = 2,
  c = 3;

It would be great if the variable names would all align, regardless of the indentation settings used.

I’m currently ‘fixing’ this without altering the jsbeautify code by doing .replace(/,\n/g, ',\n ') on the string js_beautify() returns, but that doesn’t account for situations like var a = 1, b = { a: 1, b: 1, c: 1 }, c = 3;.

Support for base 10,36,95 of php PORTED p,a,c,k,e,r

HI the Dean Edwards 's packer ported for php has base 10,36,62,95 encoding options the current unpacker only supports base 62 unpacking, be nice to have the other ones as well, also the eval(function(p,a,c,k,e,r) is actually eval(function(p,a,c,k,e,d) so the current decoder does not recognize it testd changing the d to r and for base62 it works fine.

Object argument is not indented when following an array of arrays argument.

On http://jsbeautifier.org/ with options,

"indent with 3 spaces"
checked "Preserve empty lines"
unchecked "Detect packers"
checked "Keep array indentation"

This line:

var f = function () { g.drawPath([[0, 1], [2.5, -1.5]], { stroke: 'green' }); };

indents like:

var f = function () {
   g.drawPath([[0, 1], [2.5, -1.5]], {
   stroke: 'green'
});
};

It should probably indent like:

var f = function () {
   g.drawPath([[0, 1], [2.5, -1.5]], {
      stroke: 'green'
   });
};

brace_style + HTML bug

For

<html>
<head>
    <script>
        if(true) { alert(0); }
        else { alert(1); }
    </script>
</head>
<body></body>
</html>

always work as for "collapse"

Weird formatting for array with nested objects

Using the latest beautify.js (commit bebfb37), the following formatting errors occur:

var b=[{a:1},{a:1},{a:1},{a:1},{a:1}];

…beautifies to…

var b = [{
  a: 1},
{
  a: 1},
{
  a: 1},
{
  a: 1},
{
  a: 1}];

I would expect the closing } brackets to be on a new line like the opening { brackets:

var b = [{
    a: 1
},
{
    a: 1
},
{
    a: 1
},
{
    a: 1
},
{
    a: 1
}];

(Arguably, it would be nice if there was a new indentation level inside the array as well, but that's just a personal preference.)

Note that jsbeautifier.org does this correctly at the moment.

Here's my test page for the latest beautify.js, straight from GitHub: http://mathiasbynens.be/demo/js-beautify You can reproduce the error there.

if/else alignment bug

if(true)
    alert(0);
else
    alert(1);

wrongly converted to

if (true) alert(0);
else
alert(1);

Set base indentation level

It would be nice if there was a setting for a base indentation level.

For example, when fixing fugly code on Stackoverflow it needs be indented with 4 spaces to trigger syntax highlighting and code formatting (monospace, pre).

Another case is when cleaning up some code - while most editors can easily indent a block of code not all can do this quickly. So why not let jsbeautify do it ;)

beautify button doesn't look like a button

web buttons tend to have rounded corners and gradients. It took me a while to find the submit button with the latest design.

This just needs some css (generate from http://css3please.com/)

button#submit {
margin-top: 5px;
height: 30px;
line-height: 28px;
width: 100%;
border: 1px solid #aaa;
border-left: 1px solid #666;
border-top: 1px solid #666;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
-moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box;
background: #ccc;
background-image: -webkit-gradient(linear, left top, left bottom, from(#AAAAAA), to(#CCCCCC));
background-image: -webkit-linear-gradient(top, #AAAAAA, #CCCCCC);
background-image: -moz-linear-gradient(top, #AAAAAA, #CCCCCC);
background-image: -ms-linear-gradient(top, #AAAAAA, #CCCCCC);
background-image: -o-linear-gradient(top, #AAAAAA, #CCCCCC);
background-image: linear-gradient(top, #AAAAAA, #CCCCCC);
filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#AAAAAA', EndColorStr='#CCCCCC');
cursor: pointer;
color: #444;
}

space_after_anon_function default

space_after_anon_function (default true) — if true, then space is added between "function ()"
(jslint is happy about this); if false, then the common "function()" output is used.

but in code, it is

var opt_space_after_anon_function = options.space_after_anon_function === 'undefined' ? false : options.space_after_anon_function;

default as 'false'? it should be true?

Thanks.

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.