149

The single most common formatting mistake I see (many, many times per day) is code like this:

string firstLineIsFine = "yup";
        if (firstLineIsFine == "yup")
        {
            WhyIsEverythingElseMassivelyIndented();
        }

While it would be interesting to know exactly what causes this (I suspect it's to do with the way users copy and paste, but I'm not sure), I'd really welcome suggestions on how we could avoid it.

Note that in some languages, it may be deliberate - e.g. a Python question could describe a function, then include that function and the first line would be outdented further than the rest.

Perhaps we could have either a whitelist or blacklist of languages (as determined by tag and/or autodetection) and then on submission, if the system spots the overhang (which should be pretty simple) it could prompt the user to check - perhaps even suggesting an automatic correction.

(I've tagged this as feature-request, but it definitely needs more input before it's a fully-fledged request...)

10
  • 6
    I see that patter often too. That happens to me often, but I fix that before posting.
    – rekire
    Commented Sep 2, 2015 at 8:16
  • @rene: Mind if I steal that screenshot for my answer? (Credits where due, obviously)
    – Cerbrus
    Commented Sep 2, 2015 at 8:55
  • 1
    Credits and unicoins @Cerbrus ....
    – rene
    Commented Sep 2, 2015 at 8:59
  • 16
    Downvotes and verbal abuse.
    – user1228
    Commented Sep 2, 2015 at 17:01
  • Can't we implement a parser that takes care of those issues? The code itself will be surrounded by code tags anyway. Should be relatively simple to implement
    – deW1
    Commented Sep 2, 2015 at 20:49
  • 1
    there is a nifty extension for Chrome called StackOverflow Code Beautify that I use when i put code in, and the paste goes wonky.
    – ddavison
    Commented Sep 3, 2015 at 13:28
  • Would be great if the system could handle this. Would also be great if users knew that they should be doing it when they make edits on questions like this.
    – j08691
    Commented Sep 3, 2015 at 17:02
  • @sircapsalot Thanks for the tip :)
    – Kaitlyn
    Commented Sep 4, 2015 at 14:00
  • There are probably some people that manually indent this way. We'll never understand them, or the people who use two spaces.
    – TylerH
    Commented Sep 8, 2015 at 14:01
  • @TylerH: There may be some people who do it deliberately, but I suspect it's vanishingly small.
    – Jon Skeet
    Commented Sep 8, 2015 at 14:35

6 Answers 6

96

I think it's caused by people copy-pasting from the start of the function name, instead of from the start of the actual line, on indented code.

Like the selection in this .gif, kindly provided by @rene:

enter image description here

Imagine this is an function in your IDE:

// Copy this function:

        function MyFunction(){
            if(doStuff){
                doSomething();
            }
        }
<textarea style="width:100%;height:100px;"></textarea>

If you copy that code from the snippet to the text area, starting right before the "f" in function, you won't grab the whitespace in front of it.

This basically boils down to human error. I don't think it's a good idea to automatically attempt to fix this, since whitespace / proper indentation doesn't necessarily start at the first column, all the time.


However, a prompt asking the user to check the code, or one that suggests an edit seems reasonable and quite plausible. Personally, I like that suggestion.


Another something I just noticed, which looks like a bug (When editing the answer):

        function MyFunction(){
            if(doStuff){
                doSomething();
            }
        }

The code in this example is exactly the same as the previous example, except the comment has been removed. The editor preview appears to trim excess whitespace, on the first line, so no whitespace appears before the function, in the preview.

The posted answer and normal code blocks behave just fine:

        function MyFunction(){
            if(doStuff){
                doSomething();
            }
        }
13
  • 16
    Feel free to grab my gif : i.sstatic.net/rAnuU.gif
    – rene
    Commented Sep 2, 2015 at 8:57
  • 13
    I wasn't suggesting an automatic fix - I was suggesting an automatic prompt for the user to check, possibly with an option to ask the editor to try to fix it automatically. I agree it's human error - but that doesn't mean we have to just live with it.
    – Jon Skeet
    Commented Sep 2, 2015 at 9:03
  • 1
    Oh, I overlooked the prompt suggestion. I like that :-)
    – Cerbrus
    Commented Sep 2, 2015 at 9:04
  • 1
    @Cerbrus, Prompt + automatic fix would be good. It's very likely people actually did notice that the formatting needs fixing, yet can't be bothered to fix it manually.
    – Pacerier
    Commented Sep 2, 2015 at 11:19
  • 28
    Why... why are there code snippets in your answer? Why? Oh, lawd, why oh why are there code snippets in this answer? Please, someone tell me, ere I die!
    – user1228
    Commented Sep 2, 2015 at 17:05
  • 6
    @Will The first snippet provides us a textarea where we can practice our copy-pasting skills, the second one demonstrates a bug.
    – izstas
    Commented Sep 2, 2015 at 20:05
  • 10
    @izstas Why are they formatted not as code but as code snippets? You do know the difference, don't you?
    – user1228
    Commented Sep 2, 2015 at 20:11
  • 8
    @Will In case of the first one, it's because it's the "Run code snippet" button which gives us the textarea I mentioned, in case of the second one, it's because it shows a bug which affects only snippets, but not regular code blocks, as the answer states.
    – izstas
    Commented Sep 2, 2015 at 20:24
  • @Will: iztas explained it perfectly well.
    – Cerbrus
    Commented Sep 2, 2015 at 20:25
  • 3
    @Will: You have to edit the answer and look at the preview. In the preview, the second snippet is formatted incorrectly; the first line appears outdented even though it isn't. The final code block contains the exact same text, but it's formatted correctly.
    – Alan Moore
    Commented Sep 2, 2015 at 20:30
  • The bug not only works when editing a post but also when clicking the Copy snippet to answer button. Commented Sep 3, 2015 at 2:53
  • right before the "f" in function. See also 'Sorry about the "f" in Fog', in a comedy sketch by the Two Ronnies. Weatherman with magnetised map. Of the magnetic letters F-O-G the F drops. Commented Sep 4, 2015 at 10:15
  • 2
    22+ upvotes on Will's comment -> 23+ people can't/don't read but just look at pictures&buttons without understanding :o
    – BartoszKP
    Commented Sep 4, 2015 at 14:25
22

Maybe a bit far-fetched, but how about providing inline editing controls without going to the full-on Edit page? For users with sufficient privileges, of course :-)

Clicking or double-clicking to edit a code block inline would make it far quicker to clean up posts.

Or, you could have per-line indentation controls, like this:

// Sorry, it's pretty messy... scroll down and click "Run"!

var lines = [
  "string firstLineIsFine = \"yup\";",
  "        if (firstLineIsFine == \"yup\")",
  "        {",
  "            WhyIsEverythingElseMassivelyIndented();",
  "        }"
];

for (var i = 0; i < lines.length; i++) {
  var line = $("<code>").addClass("line").text(lines[i]);
  var container = $("<div>").addClass("line-container").append(line);
  $("#stuff").append(container).append($("br"));
}


$(".line").each(function() {
  var leftButton = $("<a>").text("«").addClass("indent left");
  var rightButton = $("<a>").text("»").addClass("indent right");
  var controls = $("<span>").addClass("controls").append(leftButton).append(rightButton);
  $(this).parent().prepend(controls);
});

function linesFor(event, button) {
  var l = $(button).parent().parent().find("code");
  var ls = [l];
  if (event.shiftKey) {
    while (l.length > 0) {
      l = l.parent().next().find("code");
      if (l.length > 0) ls.push(l);
    }
  }
  return ls;
}
$(".indent.left").click(function(event) {
  $.each(linesFor(event, this), function(i,e) {
    $(e).text($(e).text().replace(/^(\t| {4})/, ""));
  });
});

$(".indent.right").click(function(event) {
  $.each(linesFor(event, this), function(i,e) {
    $(e).text("    " + $(e).text());
  });
});
.line-container {
  display: block;
  margin-left: 40px;
  position: relative;
  background-color: #eee;
}
.controls {
  position: absolute;
  left: -40px;
}
.line {
  white-space: pre;
}
.indent {
  visibility: hidden;
  padding: 0 5px;
}
.controls {
  width: 20px;
}
.indent:hover {
  cursor: pointer;
  background: #f7f7f7;
}
.line-container:hover .indent {
  visibility: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="stuff"></div>

<p>Click buttons to indent/undent. Hold Shift to modify <b>all subsequent lines</b>.</p>

9
  • 18
    Wow, this is clever.
    – Purag
    Commented Sep 3, 2015 at 2:24
  • 11
    That is horrible... why not just support tab/shift+tab for indenting?
    – Petah
    Commented Sep 3, 2015 at 2:25
  • 21
    @Petah Because tab/shift+tab already have a clearly defined function when filling out forms on the web. They are used for navigating between input fields. Breaking established patterns like that is not a good idea.
    – ivarni
    Commented Sep 3, 2015 at 4:57
  • 5
    ...whereas having toolbar buttons or something for shifting would be useful. Commented Sep 3, 2015 at 13:06
  • 1
    Can you turn this into a TamperMonkey/GreaseMonkey script? I like it a lot.
    – DavidG
    Commented Sep 3, 2015 at 13:11
  • 3
    Will this detect 2 spaces vs 4 spaces and indent accordingly? And for that matter, what if indentation is simply uneven? (These shouldn't complicate anything too much)
    – Purag
    Commented Sep 3, 2015 at 20:29
  • @ivarni how about shift+alt+left/right (thats standard in some IDE's)
    – Petah
    Commented Sep 3, 2015 at 22:27
  • @Petah: Not in mine. Shift+alt +rangeselection (arrows, mouse, ..) also is often used for "vertical" block selection. Commented Sep 4, 2015 at 7:42
  • 1
    How about a button "Unindent all" ? :) In the example you provided, instead of indenting that first line x2, I could unindent all x2. While I can manually add a few spaces to a line or two, removing tons of spurious indentation from a 20+line code sample is horrible if you can't temporarily copy-paste-elsewhere-autoformat-copy-paste-back.. Commented Sep 4, 2015 at 7:44
8

Ooooh, this request is a very good idea!

First of all, I don't think anything should happen automatically.

Second, I think if we generalize and check for all bad indentation, warning the user about it has a lot of benefits, a few of which come to mind immediately:

  1. If the user copied the code improperly, they will have a chance to fix it. This reduces confusion for everybody involved.

  2. This will greatly reduce the number of suggested edits that correct code formatting. The review queue will thus deal with more pertinent edits.

  3. But perhaps best of all, detecting bad indentation could help solve the problem before the question is even asked.

I don't have statistics on this, but questions that arise simply due to poor indentation (compile errors due to extra/missing brackets, scope-related issues like misplaced returns, etc) can be avoided completely if the user gets a warning that they have bad indentation.

Even if there are no formatting issues (like the intentional irregular indentation Roy mentioned), it never hurts to encourage an additional look at the question and the code. Maybe the popup could have two options -- one to dismiss and continue improving, and one to post anyway.

The best solution here will be a popup that reads something like (of course, this could probably be greatly improved):

It looks like your code is poorly indented. This could confuse readers.

Before posting, consider improving the formatting of your code. It may reveal the problem.

Perhaps we could then ask if they'd like their code to be fixed automatically.

5
  • The suggestion of a warning + fix/leave it choice seems good. Mandatory auto fix not so much. On a somewhat tangential point (line?), as a new comer to Python I still struggle with the concept of white space as a delimiter; at least these examples have matching braces which will assist the (mechanical) editor.
    – RFlack
    Commented Sep 3, 2015 at 5:01
  • @RFlack Yeah, it will never be mandatory to fix the code, and definitely not mandatory to automate it. Python is a hard one, but definitely parsable if need be. In C-like languages (which I imagine dominate the questions asked on SO), you can do really simple checks for whether the level a line is indented matches the one before it, except if there was an open/close bracket. That's a really simple thing to implement actually.
    – Purag
    Commented Sep 3, 2015 at 5:09
  • Item 3, adding a prompt try improving the formatting of your included code. It could reveal the problem, deserves its own spot here. Commented Sep 3, 2015 at 5:17
  • 3
    I'll play the devil's advocate for a little bit here. We already have a non-trivial amount of warnings that pop up left and right when someone is asking a question (tag blacklist, content blacklist, automated quality checks, etc.). I'm a little worried adding another one for something that isn't actually making the post un-usable (i.e. it's annoying, but it's easy to unambiguously spot and fix for a human) isn't necessarily a step in the right direction. Doesn't mean we shouldn't do something about it, of course — only that warnings have a cost to the user.
    – Thomas Orozco Staff
    Commented Sep 3, 2015 at 7:50
  • 1
    @Thomas Fair point! I wonder if there's a way to have more subtle warnings on the ask page. I feel like this is immensely valuable, and I feel the benefits would greatly outweigh the cost.
    – Purag
    Commented Sep 3, 2015 at 20:45
3

This could be caused by the way the code snippet tool reacts to JavaScript code with four leading spaces being pasted into it. I've seen it remove the leading spaces from the first line, but not the rest of the code. When I tried to post an example now, the code was correctly indented, so it doesn't always happen, but have a look at this screenshot:

code indentation in snippet tool

2
  • 3
    That may be true for snippets - and a separate issue to address - but that's not particularly the situation I see it in. I see it for normal non-js snippets, where the problem really is in the markdown.
    – Jon Skeet
    Commented Sep 4, 2015 at 5:47
  • 4
    I actually tried to click that button after the previous few posts above >.<
    – Kaitlyn
    Commented Sep 4, 2015 at 14:05
1

It's nice if questions are nicely formatted, but I think we might be becoming a bit overzealous now. Formatting can help understand the question/answer, but I feel this potential feature-request puts us on a slippery slope that leads down to a Stack Overflow where there are too many rules and checks that make it harder to just post the question/answer. These are especially confusing to newcomers (who will never post on meta).

Another problem is that I think this feature can never be implemented with complete satisfication. I do not think that we can define a rule/check that can accurately detect if the indentation was intended or not. For example, in C# most people add extra indentation for lambda's/delegates:

So this is intended:

var c = x => // Intended indentation difference
    {
        Foo();
    }

Also most people divide long statements over two lines, indenting the second line. So this too is intended:

var x = MyList.Select(x => x.Something).Where(y => y.IsTrue)
    .OrderBy(z => z.Ordering);

But most people start the brackets of their method at the same indentation level. So this isn't intended:

void Foo() // Unintended indentation difference
    {
        Bar();
    }

Attempting to detect all these scenarios for all kinds of languages will lead to extremely convoluted rules and will only appear to the end user as some random algorithm that bugs them, sometimes correctly, sometimes unneeded.

7
  • 2
    And that's why this would only be a suggestion to check. And note that in the first two examples you've given, there would often (but not always) be another statement below, at the correct indentation - so the warning wouldn't trigger. (It would only be if just the first line was indented less than everything else.)
    – Jon Skeet
    Commented Sep 4, 2015 at 9:30
  • These are just a few examples that I thought of immediately, for a single language. There are of course many more scenarios. Which of course can all be detected, if you're willing too. The '(but not always)' is what I'm hammering at here :). I understand you want a check. That will, in one way or another, lead to feedback to the user. I think that will add at least a little confusion and I personally don't feel that we should add that.
    – Roy T.
    Commented Sep 4, 2015 at 9:32
  • 1
    Well-written feedback shouldn't add confusion - but it can improve the quality of the site. There is absolutely no reason for us to have so many badly-formatted questions. Now I believe users should check the preview before they post and actually put some effort into making their questions legible anyway, but if they're not doing that already, I see nothing wrong with prompting them to.
    – Jon Skeet
    Commented Sep 4, 2015 at 9:34
  • Say you have a completely blank screen. Anything you add to that will add some 'confusion' or detraction from the main function. A small percentage of people not understanding it immediately. This is especially true since the check will be in English, while most StackOverFlow users are not native English speakers.
    – Roy T.
    Commented Sep 4, 2015 at 9:43
  • I also think there is a very good reason for this site having many badly-formatted questions. Most people are not here to curate an encyclopedia. They just want to ask a question or be helpful by answering one. I think there should be a point where this is OK. Forcing people to take more time for formatting might even be considered unreasonable for the goal of the user and site (of course I'm now exaggerating a bit, but I hope you see what I'm getting at :) ).
    – Roy T.
    Commented Sep 4, 2015 at 9:47
  • 5
    I think we'll have to agree to disagree. I think if you're asking a community of experts to put time into answering your question, it's disrespectful to not care enough to take a few seconds to format your code. The goal of the site is to create a repository of high-quality questions and answers.
    – Jon Skeet
    Commented Sep 4, 2015 at 9:48
  • You might want to look at en.wikipedia.org/wiki/Indent_style#GNU_style, which your third example is somewhat similar too. Commented Sep 4, 2015 at 10:16
0

This is a fairly simple (and probably very naive) implementation of something that might fix the problem, but I believe to be a good start. It looks to see if you have more than one line that isn't left aligned. If you have more than one, it offers to strip the extra spacing for you.

JsFiddle

$(document).ready(function () {
    $("pre code").each(function () {
        var lines = $(this).text().split(/[\r\n]+/);
        var paddingAmounts = [];
        var linesWithZeroPaddingCount = 0;
        for (var i = 0; i < lines.length - 1; i++) {
            var padding = /^(\s*).*/g.exec(lines[i])[1].length;
            if (padding === 0) {
                linesWithZeroPaddingCount++;
                if (linesWithZeroPaddingCount > 1) {
                    //more than one line starts on the left, so code is probably ok
                    return;
                }
            } else {
                paddingAmounts.push(padding);
            }
        }
        var minPaddingAmount = Math.min.apply(null, paddingAmounts);
        var removeSpacing = confirm("looks like your code is mostly intented by " + minPaddingAmount + " spaces.  Reomove extra spacing (ok to remove, cancel to leave it alone)?");
        if (removeSpacing) {
            var replaceString = "";
            for (var i = 0; i < minPaddingAmount; i ++) {
                replaceString += " ";
            }
            var finalText = "";
            for (var i = 0; i < lines.length - 1; i++) {
                finalText += lines[i].replace(replaceString, "") + "\r\n";
            }
            $(this).text(finalText);
        }
    });
});
1
  • 3
    Dammit, realized I just got nerd sniped.
    – Becuzz
    Commented Sep 4, 2015 at 15:16

You must log in to answer this question.

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