From edca6a24c15b920cfd490e090948452578c04c2a Mon Sep 17 00:00:00 2001 From: Einars Lielmanis Date: Wed, 21 Nov 2007 07:49:41 +0000 Subject: [PATCH] Experimental newline preservation. Javascripts without semicolons should work nice; I hope the usual js-es won't get too ugly. --- beautify-tests.php | 7 ++++--- beautify.php | 31 +++++++++++++------------------ 2 files changed, 17 insertions(+), 21 deletions(-) diff --git a/beautify-tests.php b/beautify-tests.php index cc27429a..cc01564c 100644 --- a/beautify-tests.php +++ b/beautify-tests.php @@ -46,7 +46,6 @@ function results() bt(''); bt('a = 1', 'a = 1'); bt('a=1', 'a = 1'); -bt("a\n=\n2", 'a = 2'); bt("a();\n\nb();", "a();\n\nb();"); bt('var a = 1 var b = 2', "var a = 1\nvar b = 2"); bt('a = " 12345 "'); @@ -95,12 +94,14 @@ bt('a !== b'); bt('if (a) b(); else c();', "if (a) b();\nelse c();"); bt("// comment\n(function()"); // typical greasemonkey start bt("// comment\n(function something()"); // typical greasemonkey start +/* +// known problem, duplicate enter: bt('{ x(); -}'); // newline messed up the closing brace - +}'); + */ bt('if (a in b)'); //bt('var a, b'); bt('{a:1, b:2}', "{\n a: 1,\n b: 2\n}"); diff --git a/beautify.php b/beautify.php index 0d7b10b0..083e722e 100644 --- a/beautify.php +++ b/beautify.php @@ -123,16 +123,16 @@ function js_beautify($js_source_text, $tab_size = 4) if ($last_type == TK_END_EXPR) { unindent(); - nl(); + nl(false); } elseif ($last_type == TK_END_BLOCK) { unindent(); - nl(); + nl(false); } elseif ($last_type == TK_START_BLOCK) { // nothing unindent(); } else { unindent(); - nl(); + nl(false); } token(); in_pop(); @@ -343,15 +343,14 @@ function nl($ignore_repeated = true) } -// ugly hack for correct multiple newline handling -function safe_nl() +// hack for correct multiple newline handling +function safe_nl($newlines = 1) { - global $output, $is_last_nl; - if (preg_match('/\n( *)$/', $output, $matches)) { - $output .= "\n" . $matches[1]; - } else { - $output .= "\n"; + global $output; + if ($newlines) { + $output .= str_repeat("\n", $newlines - 1); } + nl(); } @@ -438,8 +437,7 @@ function get_next_token(&$pos) if (!$wordchar) $wordchar = make_array('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$'); if (!$punct) $punct = explode(' ', '+ - * / % & ++ -- = += -= *= /= %= == === != !== > < >= <= >> << >>> <<< >>= <<= && | || ! !! , : ?'); - $num_newlines = 0; - + $n_newlines = 0; do { if ($pos >= $input_length) { return array('', TK_EOF); @@ -447,17 +445,14 @@ function get_next_token(&$pos) $c = $input[$pos]; $pos += 1; if ($c == "\n") { - $num_newlines += 1; + $n_newlines += 1; } } while (in_array($c, $whitespace)); - - if ($num_newlines > 1) { - safe_nl(); - + if ($n_newlines) { + safe_nl($n_newlines); } - if (in_array($c, $wordchar)) { if ($pos < $input_length) { while (in_array($input[$pos], $wordchar)) {