35

Quite often, a question is asked with excessive whitespace in front of all the code, like this:

        var a = 1;
        var b = 3;
        if(a > 0) {
          b--;
          alert(b);
        }

Within 10 minutes, I was able to screenshot not one, not two, but three examples of this sort of thing happening. These were all corrected through editing, but it begs the question: Why does this happen so often?

What is even more curious is that the code formatting button and the Ctrl+K shortcut physically do not let you format code with excess whitespace like this: The selected code toggles between an indent of zero to four spaces.

So my questions are:

  • How do users manage to indent code with a ridiculous amount of spaces when pasting or writing code into their question?
  • And more importantly, how can we reduce occurrences like these?

Is some sort of a 'excessive whitespace' warning tooltip needed?

32
  • 52
    People copy and paste already indented code from their editor, is why. Experienced editors simply select the block and hit CTRL-K an appropriate number of times to unindent.
    – Martijn Pieters Mod
    Jan 7, 2015 at 11:40
  • 7
    You cannot reliably detect occurrences like these. It is, as you note, always dealt with swiftly, just like all the other usual mistakes, like thanks and looking forward to your answers, etc. There is little point in trying to battle this, it is not a big problem.
    – Martijn Pieters Mod
    Jan 7, 2015 at 11:41
  • 12
    @MartijnPieters Ctrl-K won't clean all the extra space if your starting indentation is not a multiple of 4.
    – Louis
    Jan 7, 2015 at 11:51
  • 16
    Why does this happen so often? Because people are apparently unable to look at the preview when posting a question (or answer as well). What you should do, of course, is downvote the post and tell the OP to fix their formatting. If it's bad enough to severely harm readability I'd also closevote with the off-topic/MCVE reason, as a mangled heap of code is not a sufficient example. While this does nothing to improve formatting for new users, it hopefully helps to get the offending users to more carefully format their code - or get them questionbanned if they don't learn.
    – l4mpi
    Jan 7, 2015 at 11:54
  • 3
    @Louis: nope, at which point I'd use a local editor to remove the 1-3 extra spaces in there real quick. Those are more of an exception however.
    – Martijn Pieters Mod
    Jan 7, 2015 at 11:56
  • 15
    People are unfamiliar with the SO-specific Ctrl+K shortcut. I always wondered why they never implemented indentation with the standard Tab/Shift+Tab keys. Jan 7, 2015 at 13:26
  • 3
    You should know by now that programmers are lazy people. Jan 7, 2015 at 14:30
  • 12
    There should really be a reminder near the editor about Ctrl-K, I have been around here awhile and didn't know about it. I have had this issue where my code will be over-indented and I've always just manually remove the white space. -_- Very annoying.
    – eddie_cat
    Jan 7, 2015 at 14:53
  • 6
    Some languages are whitespace-sensitive and parse errors depend on the number of tabs and spaces on each line. It's important to NOT automatically remove whitespace from code.
    – AndrewC
    Jan 7, 2015 at 23:01
  • 4
    Would it be particularly difficult to implement Tab/Shift+Tab for indent/unindent? Jan 8, 2015 at 4:26
  • 4
    @MartijnPieters I would think it would be possible to detect when an entire code block has a large amount of indentation and show the poster one of those red message bubbles suggesting the Ctrl+K option.
    – JLRishe
    Jan 8, 2015 at 4:44
  • 4
    @JLRishe: because there are a) legitimate uses of using extra indentation (breaking up a correctly indented codeblock with interspersed paragraphs) and b) Markdown bullets and blockquotes also use indentation, so detecting when a codeblock contains extra indentation is more complicated and requires a full parse. I simply don't think it is worth the effort, because it is not a big problem.
    – Martijn Pieters Mod
    Jan 8, 2015 at 9:43
  • 4
    @JonathanDrapeau: Speak for yourself. Good programmers are diligent and thoughtful people who consider all the cases and needs. Jan 8, 2015 at 11:54
  • 3
    @AndrewC what language is harmed if every block of code in a post had identical whitespace removed from the start of every line in the post? (Identical, in that ` ` and ` ` are never the same) Jan 8, 2015 at 16:34
  • 2
    @Yakk I can write you a code block that compiles where each line starts with 5 spaces, and then some continue with a further three spaces, and some continue with a tab. If you remove 4 spaces (or 5 spaces) from the start of each line of that, they no longer line up at the 8-space tabstop, and you get a parse error. It's worse than you thought - it could introduce new parse errors that answerers would respond to! The golden rule is, in a whitespace-sensitive language, DO NOT automatically edit the whitespace.
    – AndrewC
    Jan 8, 2015 at 19:18

4 Answers 4

24

As Martijn mentions in the comments, this is a result of pasting existing code in the asker's editor into the question. This is even more likely if the code being pasted is buried even slightly into a larger program.

This type of error can be corrected by highlighting the code block while editing, and using the Ctrl+K shortcut to unindent the code. This will work if the spacing is a multiple of 4.

7
  • 1
    Alternatively, if the code is javascript, you can paste it in a snippet, unident the first line and click tidy.
    – Sumurai8
    Jan 8, 2015 at 8:47
  • 16
    All this time, I never knew about the CTRL-K shortcut. Argh, how much time have I wasted manually changing each line!!
    – freefaller
    Jan 8, 2015 at 11:34
  • 1
    I think one reason peoples often do not use properly the Code Sample command (either by clicking on it or through Ctrl+K) is because it works differently depending if there was a selection or not. Many code editors allow you to indent/unident the current line. The SO editor does not. You have to select at least one whole line first. Maybe an indent/unindent button might have been a better choice there ? Jan 8, 2015 at 11:49
  • 13
    I've been using this site for two years and just found out about CTRL-K by reading this question/answer. I've been manually de-indenting my code one line at a time, and I'm not surprised new users won't go to all that effort. If we want new users to use that shortcut, we should probably document it a lot better.
    – Edward
    Jan 8, 2015 at 18:22
  • @Edward Or have a button for it. IMHO, a keyboard shortcut should just be a... shortcut. Not the only way of doing something. I think I had seen it mentioned before, but forgot what the key combination was before I had a chance to use it. Jan 9, 2015 at 7:10
  • 1
    Do people not have text editors anymore? In vim it's trivial to change any code to the format required for SO, and I guess it should be simple in any other editor worth using. Does the vast majority of users actually type all their code directly in the SO textbox? I only do so for oneliners and small answer snippets, everything more complex is written in vim. And @RetoKoradi of course there is a button for that functionality, it's not just a keyboard shortcut.
    – l4mpi
    Jan 9, 2015 at 7:42
  • @RetoKoradi There is a button for it. Ctrl + K is just the shortcut for "Code Sample".
    – Ajedi32
    Jan 9, 2015 at 17:26
10

And more importantly, how can we reduce occurrences like these?

Why don't we add some intelligence to the Ctrl+K command? It is possible to calculate the smallest number of leading whitespace in the selected code, eliminate that many from all lines, then add 4 leading spaces to each line.

Test

function ctrlk() {
  var lines = document.getElementById("code").value.replace(/\t/g, "    ").split(/^/m),
    lws = Number.MAX_VALUE,
    i;
  for (i = 0; i < lines.length; i++) {
    if (lines[i].length) {
      lws = Math.min(lws, lines[i].match(/^ */)[0].length);
    }
  }
  for (i = 0; i < lines.length; i++) {
    lines[i] = lws < 4 ? ("    ".substr(0, 4 - lws) + lines[i]) : lines[i].substr(lws);
  }
  document.getElementById("code").value = lines.join("");
}
textarea {
  box-sizing: border-box;
  width: 100%;
  height: 10em;
}
input[type=button] {
  box-sizing: border-box;
  width: 100%;
}
<textarea id="code">
        var a = 1;
        var b = 3;
        if(a > 0) {
          b--;
          alert(b);
        }
</textarea>
<input type="button" onclick="ctrlk()" value="Toggle Code Sample">

Note: not tested against edge cases.

6
  • 2
    I use code which requires at least one leading space on each line. Please don't do that. Jan 8, 2015 at 17:15
  • @BillWoodger can you please post an example?
    – Salman A
    Jan 8, 2015 at 17:16
  • 2
    ` MOVE example-identifier-1 TO example-identifier-2. OPTION COPY`. The first is COBOL the second is DFSORT/SyncSort. Ah, turned out to be trickier than I thought, as here in the comments even within the backticks the leading spaces are being eaten :-) Thats seven on the first, and one on the second. Jan 8, 2015 at 17:46
  • Here's a random link: stackoverflow.com/questions/27777666/… . You only see three spaces, because the others are already there. This is less handy with the SORT examples, where you copy from the displayed code... Jan 8, 2015 at 17:49
  • 2
    Snippet duly eats three/one of required spaces :-) Jan 8, 2015 at 17:56
  • 8
    The assumption that whitespace is only ever for human readability is simply false. Not all languages are based on the curly bace semicolon model of syntax.
    – AndrewC
    Jan 9, 2015 at 8:46
0

To build on @Salman A's idea of formatting, there's already language detection occurring in code blocks. Perhaps make some of the subsequent formatting not just highlighting but whitespace "fixing" or an option (button?) to do so.

ex LANG_X detected: offer to/do beautify for LANG_X rules.

For user's hair, any action taken automatically might need to be done only once in the event the user wants the spacing as they put.

Downside is the need for individual language comprehension. But then, that's the issue @AndrewC brought up.

0

After reading all the comments and answers, I'm surprised no one has mentioned the {} button in the editor. Highlight and click. That's what I use

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .