15

Possible Duplicates:
How to post code in SO
How do I format my code blocks?

When I post code here it ends up all mangled. How do I make it look pretty?

For example, posting //#include (minus the //) ends up looking like this:

include

What am I doing wrong?

2
  • 1
    Isn't there an explanation to the right of where you type the question?
    – Earlz
    May 25, 2010 at 18:46
  • Actually there doesn't seem to be a duplicate for this question, though an old one of mine is related meta.stackexchange.com/questions/34588/… Maybe this should be a FAQ?
    – Earlz
    May 25, 2010 at 18:47

6 Answers 6

14

If you post code or XML, highlight those lines in the text editor and click on the "code" button (101 010) on the editor toolbar to nicely format and syntax highlight it.

example

6
  • 7
    @marc_s -- not a circle, not freehand, it is red and points in roughly the correct area; I give it a 5.5.
    – tvanfosson
    May 25, 2010 at 20:26
  • 4
    @tvanfosson: out of 6? Not bad..... heck - I'm a dev, not a graphics artist! ;-) You don't want to see my complete UI's......
    – marc_s
    May 25, 2010 at 20:29
  • This method worked for me, It will automatically detect the language. Example : Java for me.
    – vanduc1102
    May 3, 2015 at 11:21
  • 3
    Only works in answers, not in comments on answers. However, backticks work in both. Feb 26, 2016 at 12:17
  • I don't see the 101010 button when writing a question.
    – quant_dev
    Mar 20, 2016 at 9:21
  • Since some time, you can run code snippet Dec 6, 2020 at 12:16
10

You surround your code in backticks `` (like this)

Or for block code, you indent your code by four spaces:

function test()
{
    alert("it works!")
}

You can view the source for this post here.

1
  • The post's link seems to be broken. May 31, 2019 at 21:43
5

You can also use keyboard shortcut: just highlight and hit ctrl-k

1
  • The shortcut is such a life-saver for me. Pressing it while writing a comment initiates for me Google's Search in the address bar in Chrome, which was also a nifty little shortcut for me to find out about. May 31, 2019 at 21:48
4

If you want to do this manually, you add 4 spaces in front of every line of code.

With the editor, there is a code button (101010) you can press after highlighting the code.

0
0

like this, highligh what you want then click the code button

#include
1
  • 1
    you can use this shortcut ctrl+k Jan 30, 2015 at 20:43
0

I think this is one of those things that should belong on meta.stackoverflow.com or some such, but... in the post box, if you click the orange question mark in the top-left of the box, it will take you to a page with Markdown help. Basically, you prefix each line with four spaces:

like this 

and you should see the text show up as 'code' in the preview area below the edit box.