Reindent Java/C/C++/etc. code Write a program that adds or removes whitespace to format code nicely. Rules for what the code should look like when you're done:

No line should contain more than one of { and }.
A { should always be the last thing on a line.
A } should always be the only thing on a line (besides whitespace that comes before it).
The amount of whitespace in front of each line should be a fixed multiple of the current nesting count. (You can use any amount of indentation you want, as long as it doesn't change.)
No whitespace should be inserted or removed that doesn't contribute to satisfying one of these rules.

The nesting count for the first line is 0. The nesting count of any other line is the nesting count of the previous line, plus one if the previous line contains a {, minus one if the current line contains a }.
{ and } inside string literals and comments don't count in the above rules. A string literal is text enclosed in single or double quotes, where single or double quotes with an odd number of backslashes immediately before them aren't interpreted as the end of the string literal. A comment is text enclosed in /* and */, or text going from // to the end of the line. In a line multiple comment start markers, only the first one counts. Comments are not parsed inside string literals.
Examples
    main() {printf(&quot;Hello!&quot;); // I don't care about the world...
        }

becomes:

main() {
    printf(&quot;Hello!&quot;); // I don't care about the world...
}




int main(){
    puts(&quot;a&quot;);
        puts(&quot;b&quot;);
}

becomes:

int main(){
    puts(&quot;a&quot;);
    puts(&quot;b&quot;);
}


main()
{ printf(&quot;{&quot;); /* }
} */
     printf(&quot;}//}&quot;); ///*
    }

becomes:

main()
{
    printf(&quot;{&quot;); /* }
} */
    printf(&quot;}//}&quot;); ///*
}


int test[] = {1, 2, 3};

becomes:

int test[] = {
    1, 2, 3
}
;
JavaScript (ES6), 376 373 378 393 bytes

This was... quite the challenge...



let f =

s=&gt;{F=(i,l=1)=&gt;[a=a.map(([q,y])=&gt;[q,y&lt;i+e?y:y+l]),e+=l]
for(a=b=[];b;s=s[r='replace'](/\/\*(?:(?!\/\*|\*\/)[^])*\*\/|\/\/.+|("|')(?:\\.|(?!\1).)*\1/,(q,_,y)=&gt;a.unshift(b=[q,y])&amp;0))b=l=0
s=s[e=1,r](/[{}](?=.)|.(?=})/g,(c,i)=&gt;F(i)&amp;&amp;c+`
`)[e=0,r](/.+/g,(x,i)=&gt;x[r](/^\s*/,y=&gt;" ".repeat(q=/{/.test(x)?l++:/}/.test(x)?--l:l,F(i,q-y.length))))
a.map(([q,y])=&gt;s=s.slice(0,y)+q+s.slice(-~y))
return s}
&lt;textarea rows=7 cols=50 oninput=O.innerText=f(value)&gt;    main() {printf("Hello!"); // I don't care about the world...
    }&lt;/textarea&gt;
&lt;pre id=O&gt;&lt;/pre&gt;




Let me know if there's anything wrong with the output, though I couldn't find anything can't find anything more.

Ungolfed version

I golfed the code as I wrote it, so let's see how this goes...



function prettify(code) {
  let excerpts = [], extras, level;
  
  // Extract comments and strings for easy parsing
  // This has to be done recursively because of the nested comments
  for (let done = false; !done; ) {
    done = true;
    code = code.replace(/\/\*(?:(?!\/\*|\*\/)[^])*\*\/|\/\/.+|("|')(?:\\.|(?!\1).)*\1/, (excerpt, _, index) =&gt; {
      excerpts.unshift([excerpt, index]);
      done = false;
      return "0";
    });
  }
  
  // Update the indices of the excerpts when the code is changed
  let adjustIndices = (index, length) =&gt; {
    index += extras;
    excerpts = excerpts.map(([string, oldIndex]) =&gt; {
      var newIndex = oldIndex;
      if (oldIndex &gt;= index) newIndex += length;
      return [string, newIndex];
    });
    extras += length;
  }
  
  // Add extra newlines where necessary:
  // - After a { or a } if there isn't one already
  // - Before a } if there isn't one already (note: already-indented '}'s will get an extra newline)
  extras = 0;
  code = code.replace(/[{}](?=.)|.(?=})/g, (char, index) =&gt; {
    adjustIndices(index + 1, 1);
    return char + "\n";
  });
  
  // Remove extra whitespace at the beginning of each line,
  // and the same time apply the necessary number of tabs
  extras = 0;
  level = 0;
  code = code.replace(/.+/g, (line, index) =&gt; 
    line.replace(/^\s*/, spaces =&gt; {
      let tabs;
      if (line.indexOf('{') &gt; -1)
        tabs = level, level += 1;
      else if (line.indexOf('}') &gt; -1)
        level -= 1, tabs = level;
      else
        tabs = level;

      adjustIndices(index, tabs - spaces.length);
      return "\t".repeat(tabs);
    })
  );
  
  // Add back in the excerpts
  for ([excerpt, index] of excerpts)
    code = code.slice(0, index) + excerpt + code.slice(index + 1);
  
  return code;
}
&lt;textarea rows = 7 cols = 50 oninput = "O.innerText = prettify(this.value)"&gt;    main() {printf("Hello!"); // I don't care about the world...
    }&lt;/textarea&gt;
&lt;pre id=O&gt;&lt;/pre&gt;