js-beautify icon indicating copy to clipboard operation
js-beautify copied to clipboard

Incorrect indentation of catch blocks in braceless if statement

Open palant opened this issue 5 years ago • 4 comments

Description

If an if statement contains a single try..catch statement, only the try block will get indented correctly. The catch block will be indented as if it were outside the if statement.

Input

The code looked like this before beautification:

if (a)
  try
  {
    a = 2;
  }
  catch (e)
  {
    // ignore
  }

Expected Output

The code should have looked like this after beautification:

if (a)
  try
  {
    a = 2;
  }
  catch (e)
  {
    // ignore
  }

Actual Output

The code actually looked like this after beautification:

if (a)
  try
  {
    a = 2;
  }
catch (e)
{
  // ignore
}

Environment

Reproduced on https://beautifier.io/ as well as locally.

Settings

{
  "indent_size": "2",
  "indent_char": " ",
  "max_preserve_newlines": "5",
  "preserve_newlines": true,
  "keep_array_indentation": false,
  "break_chained_methods": false,
  "indent_scripts": "normal",
  "brace_style": "expand",
  "space_before_conditional": true,
  "unescape_strings": false,
  "jslint_happy": false,
  "end_with_newline": false,
  "wrap_line_length": "0",
  "indent_inner_html": false,
  "comma_first": false,
  "e4x": false,
  "indent_empty_lines": false
}

palant avatar Dec 17 '19 10:12 palant

In fact, I can see the same issue with if..else as well - the else block is misindented, as if it belonged to the outer if statement:

if (a)
  if (x)
  {
    a = 2;
  }
else
{
  // ignore
}

palant avatar Dec 17 '19 10:12 palant

I wanted to understand what should be the ideal way to beautify this and please correct me if I'm wrong. I agree that braceless ifs are allowed for single statements and there's a big share of people who love that style of coding. From my perspective beautifying highly correlates with code readability, so should we not wrap them with braces in such cases. Or better should there a configuration setting to say select whether you would like to go ahead with braceless style or add braces.

Thoughts? @palant @bitwiseman

bhaveshvasnani avatar Feb 05 '22 10:02 bhaveshvasnani

At this time, The beautifier is a white space only reformatter. That means that we will not be adding braces. The expected output shown above is correct and that is what we should implement.

bitwiseman avatar Feb 05 '22 23:02 bitwiseman

@bitwiseman I'm interested to work on this issue. Could I please take this up?

bhaveshvasnani avatar Feb 13 '22 11:02 bhaveshvasnani