36

I was wondering if there is an easy way to indent the code in Stack Overflow. Whenever I paste in code, all the code loses its indentation; what I have been doing is manually indenting every line with the space button. Is there a quicker way to do all of this?

3
  • 4
    Highlight it and hit the "code" button. This belongs on meta.
    – BlueRaja
    Commented May 8, 2011 at 22:49
  • You could always make a short program in your language of choice to accept text and replace all tabs with four spaces, but that might be a bit overkill.
    – Maxpm
    Commented May 8, 2011 at 22:50
  • Hardly seems worth moving it - use the "code" button and move on.
    – duffymo
    Commented May 8, 2011 at 22:51

4 Answers 4

34

To properly format code you should indent your code in the markdown source, either by a tab character or by 4 spaces.

There is handy button on the toolbar which can do this automatically for you, simply select the code section of your question and press this button (or type it's key shortcut Ctrl + K):

enter image description here

1
  • 2
    It would be nice if there was a handy button that added indention for code in lists.
    – NetMage
    Commented Oct 31, 2017 at 15:52
12

It would be nice if SO could automatically indent new lines to the same level as the previous line, like most text editors and IDEs do. This would make typing up answers that include code a lot easier.

1
2

Fixing indentation would be the minimum what I would expect from StackOverflow (by fixing indentation I understand removing unncessary spaces as well as adding them when necessary, for example on if/for/while loops, nested XML tags etc.).

I'd expect also auto-breaking too long lines, formatting tag hierarchy for XML etc. It shouldn't be so hard to implement in JavaScript. Yes, you can write your own browser/greasemonkey plugin. No, you can't always use browser with such tools installed (workspace, for example, where you are dependent on what you become).

Of course, such features would require choosing the source language of code block - this is another feature that is missing. You can learn by heart language: lang blocks, but it should be a menu option.

Of course, there are esoteric languages where space is a part of syntax, not formatting (Python AFAIK) so such feature must be optional and activated only by taskbar button.

-2

You could paste you code into nano in a Unix terminal, say you've got this:

enter image description here

Save it as sad.txt in nano, then run the following line of code:

enter image description here

Here, we're replacing, as it were, the start of each line with four spaces, so when you open happy.txt you'll be happy because you'll get the most amazing result:

enter image description here

From here just paste this directly into your post. Hope this helps/makes sense.

1
  • 4
    That's a long and complex way to do something that can be done by clicking one single icon in the editor. Commented Feb 10, 2014 at 8:02