Skip to content

Commit

Permalink
Preserve newlines on either side of ++ and --
Browse files Browse the repository at this point in the history
This closes #56 and openes the new less severe case of #203.
  • Loading branch information
bitwiseman committed Mar 25, 2013
1 parent bc80349 commit d5ec851
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
12 changes: 10 additions & 2 deletions beautify.js
Expand Up @@ -1000,8 +1000,9 @@
if (start_of_statement()) {
// The conditional starts the statement if appropriate.
} else if (wanted_newline && !is_expression(flags.mode) &&
last_type !== 'TK_OPERATOR' && last_type !== 'TK_EQUALS' && (
opt.preserve_newlines || flags.last_text !== 'var')) {
(last_type !== 'TK_OPERATOR' || (flags.last_text === '--' || flags.last_text === '++')) &&
last_type !== 'TK_EQUALS' &&
(opt.preserve_newlines || flags.last_text !== 'var')) {

print_newline();
}
Expand Down Expand Up @@ -1291,6 +1292,12 @@
return;
}

// http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1
// if there is a newline between -- or ++ and anything else we should preserve it.
if (wanted_newline && (token_text === '--' || token_text === '++')) {
print_newline();
}

if (in_array(token_text, ['--', '++', '!']) || (in_array(token_text, ['-', '+']) && (in_array(last_type, ['TK_START_BLOCK', 'TK_START_EXPR', 'TK_EQUALS', 'TK_OPERATOR']) || in_array (flags.last_text, line_starters) || flags.last_text === ','))) {
// unary operators (and binary +/- pretending to be unary) special cases

Expand All @@ -1302,6 +1309,7 @@
// ^^^
space_before = true;
}

if (last_type === 'TK_WORD' && in_array (flags.last_text, line_starters)) {
space_before = true;
}
Expand Down
8 changes: 8 additions & 0 deletions tests/beautify-tests.js
Expand Up @@ -269,6 +269,14 @@ function run_beautifier_tests(test_obj, Urlencoded, js_beautify)
bt('{--bar;}', '{\n --bar;\n}');
bt('{++bar;}', '{\n ++bar;\n}');

// Handling of newlines around unary ++ and -- operators
bt('{foo\n++bar;}', '{\n foo\n ++bar;\n}');
bt('{foo++\nbar;}', '{\n foo++\n bar;\n}');

// This is invalid, but harder to guard against. Issue #203.
bt('{foo\n++\nbar;}', '{\n foo\n ++\n bar;\n}');


// regexps
bt('a(/abc\\/\\/def/);b()', "a(/abc\\/\\/def/);\nb()");
bt('a(/a[b\\[\\]c]d/);b()', "a(/a[b\\[\\]c]d/);\nb()");
Expand Down

0 comments on commit d5ec851

Please sign in to comment.