399

How do I post text so that it is formatted as code?

What do I need to do so that my code shows up properly — not escaped or removed — when posted? And how to get the correct syntax highlighting?

For more information, see "How do I format my posts in HTML or Markdown?" in the Help Center.

Return to FAQ index

2
  • 1
    On MSO: How do I format my code blocks?. Commented Feb 28, 2022 at 11:51
  • 1
    @SebastianSimon Yeah; IIRC when MSO/MSE were split (they used to be one), there was a large effort to copy SO-relevant content that moved here back to MSO (I happened to do this one but it was a community effort).
    – Jason C
    Commented Feb 28, 2022 at 12:12

1 Answer 1

405

Inline code (for code that does not contain newlines)

  • When the cursor is not in the first column, or you've selected code that does not hold newlines, click the {} code button above the editor (pictured below) or hit Ctrl+K (Cmd+K on macOS)
  • Enclose with backticks: `<html>`
  • Embed within <code> tags, and manually encode HTML entities: <code>&lt;html&gt;</code>

Blocks of code (preserves newlines)

There are four ways to create blocks of code:

  • When the cursor is on an empty line, or you've selected code including a newline, click the {} code button above the editor (pictured below) or hit Ctrl+K (Cmd+K on macOS)
  • Create code fences with three backticks ``` or tildes ~~~, one on a line before the code, and one on a line after
  • Indent the code by four spaces
  • Enclose in <pre> or <pre><code> tags (in that order; using <code><pre> is invalid), and encode HTML entities (like &lt; for <) yourself.
    • In these blocks, HTML tags are applied rather than rendered as text. For example, the following code:
      This is <b>bold</b>, <i>italic</i>, and <s>striked out</s> text, and a <a href="https://example.com/">link</a>.
      
      ...renders as the following when enclosed in <pre><code> blocks:
      
      This is bold, italic, and striked out text, and a link.
      

Code copy/pasted from an IDE is often already tabbed. When rendering, tabs are replaced with spaces. However, you should remove tabs from the pasted code in case others have to apply additional formatting.

Formatting code in the editor

Using the four-space method inside another block

Inside a blockquote

Add one more space following the greater-than sign >

> Lorem ipsum dolor sit amet, consectetur adipiscing elit.
>
>     for(;;)
>       echo 'badger ';

renders as

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

for(;;)
  echo 'badger ';

Inside a List

Indent by the total number of leader characters for the list level plus an additional four spaces. Examples:

1. For example, the leader characters in this list
   item are `1. ` (three characters).  Indent 7 characters
   for a code block.

       for(;;)
         echo 'ow ';

   * In this second-level bullet, you need the 3 leader
     characters from the first-level numbered list, plus
     the two leader characters from this bullet (`* `), 
     plus 4 characters to start a code-block (9 spaces
     total):

         for(;;)
           echo 'ow';

2. Unfortunately, using the old-style (pre-Commonmark) rule 
   of "4 spaces for each list level" results in additional,
   unwanted spaces inside your code block:

        for(;;)
          echo 'ow';

   Note the additional space at the beginning of each line
   of code. This normally won't be a problem, but could be 
   when copying and pasting code where the leading white-space 
   is significant.

renders as:

  1. For example, the leader characters in this list item are 1. (three characters). Indent 7 characters for a code block.

    for(;;)
      echo 'ow ';
    
    • In this second-level bullet, you need the 3 leader characters from the first-level numbered list, plus the two leader characters from this bullet (* ), plus 4 characters to start a code-block (9 spaces total):

      for(;;)
        echo 'ow';
      
  2. Unfortunately, using the old-style (pre-Commonmark) rule of "4 spaces for each list level" results in additional, unwanted spaces inside your code block:

     for(;;)
       echo 'ow';
    

    Note the additional space at the beginning of each line of code. This normally won't be a problem, but could be when copying and pasting code where the leading white-space is significant.

Note: In June 2020, Stack Exchange implemented the CommonMark spec and Markdown processors. Posts prior to that date still work correctly with "4 spaces per level" and do not include unwanted leading space. However, if that post is edited, it will be re-rendered using CommonMark, and the indentation should be updated to use the new rules.

Syntax highlighting

On most coding-related sites, Highlight.js is used to add color to the code, but only if the language can be uniquely determined given the tags of the question (certain tags have language hints specified in their data), or if manual hints have been provided on the same line after the opening code fence, or in HTML comments:

```lang-or-tag-here
code goes here
```

<!-- language: lang-or-tag-here -->

    code goes here

<!-- language: lang-or-tag-here -->
<pre><code>
code goes here
</code></pre>

You can also specify the syntax for all code blocks in your post with the language-all hint:

<!-- language-all: lang-or-tag-here -->
Some text not in code blocks

    code goes here

More text not in code blocks

```
code goes here
```

See the full specification and list of languages hints.

Note that:

  • When using a tag to specify language, the tag name is case-sensitive
  • The HTML comments must not be indented
  • The blank line between <!-- language: ... --> and the indented code block is required
  • The space between language: and the language is required

If none of the tags have a highlighting language specified in their data, then no highlighting occurs at all. However, in the preview, or if multiple tags define different languages and no manual definition is used, a default highlighting is used in which Highlight.js makes a best guess.

There is a delay before the preview text highlighting is applied after you stop editing your Markdown source, of around 5 seconds.

On mobile devices

  • One sometimes needs to press and hold the regular single quote to get the backtick.

Backticks in text

  • To include a backtick without accidentally starting some inline code, escape it: \`
    • like \` so yields: like ` so
    • <kbd>Alt Gr</kbd>+<kbd>\`</kbd> gets `|` yields: Alt Gr+` gets |

Backticks within backticks

  • To use literal backticks within a code span, use any unique number of multiple backticks as the opening and closing delimiters: both ``literal backtick (`) here`` and, for example, ``````literal backtick (`) here`````` yield literal backtick (`) here. This works in comments too.
  • To use literal backticks at the start and/or end, add one space to both the opening and closing delimiters: `` `<html>` `` yields `<html>`. In comments, the additional space in the delimiters is not supported. Instead, escape the backtick: `\`<html>\`` to get `<html>` in a comment.

Code snippet (added 2014-09-16)

Add a code snippet by clicking the JavaScript/HTML/CSS toolbar button [<>] or Ctrl+M. This will insert the following boilerplate which can be edited with the Snippet editor (a link will appear in the preview, saying edit the above snippet) .

Please click TIDY before inserting the code into the answer/question

NOTE If the snippet does not actually run, you can remove the comment with begin snippet to still produce a nicely formatted set of HTML/JavaScript/CSS

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->
//javascript goes here
<!-- language: lang-css -->
.css .goes .here {background-color: blue;}
<!-- language: lang-html -->
<div>html goes here</div>
<!-- end snippet -->
16
  • How can I write with blue or red color? Is it possible to do this also on iPhone? Because, right now I’m using only iPhone. And I tried many times to do as others did, but it did not worked to write with blue color. So how can I write with blue, red, green etc...?
    – Dreadbot
    Commented Jan 31, 2018 at 15:41
  • @Dreadbot why would you need to do such a thing?
    – eis
    Commented Feb 13, 2018 at 1:31
  • @eis Because, there are many users who know how to do this but me I don’t know. And I wish I can know how to do that.
    – Dreadbot
    Commented Feb 14, 2018 at 22:09
  • 1
    @Dreadbot There is no way to use specific colors. You can do a code block, and the code block will do syntax highlighting/formatting, or you can add a link to another page, and the link is colored blue because it's a link. That's it. Commented Feb 15, 2018 at 14:56
  • @JoelCoehoorn Can you tell me what are the code blocks? And what is the link for blue and other colors?
    – Dreadbot
    Commented Feb 15, 2018 at 14:59
  • @Dreadbot You can't just write in blue and other colors. There is no way to do it. Commented Feb 15, 2018 at 15:07
  • How would we do back ticks in comments while preserving structure?
    – CyberMew
    Commented Mar 29, 2018 at 4:09
  • 2
    Ctrl-K doesn't always work. Commented Jun 6, 2018 at 15:29
  • Another thing -- if your code is being interrupted by line breaks (e.g. when it reaches the end of the line) in places that you don't want it to, you can add &nbsp; elements inside the <code> block to fix it.
    – Jwosty
    Commented Aug 2, 2018 at 18:50
  • 6
    TAB doesn't work...I don't remember if it ever worked
    – mihai
    Commented Nov 5, 2018 at 17:02
  • @mihai you can paste tab characters into the textbox, but... ewww. Commented Nov 5, 2018 at 17:04
  • @Joel mihai's talking about pressing Tab to increase the indent. And he's right, it doesn't work.
    – wjandrea
    Commented Jun 22, 2019 at 21:08
  • No support for powershell in that list?
    – js2010
    Commented Aug 17, 2019 at 0:55
  • It uses prettify.js, or did. I don't think powershell existed yet when this answer was first written. Commented Aug 17, 2019 at 3:32
  • Is it possible to add multiline code blocks to list items without indenting every code line? I tried to use triple backticks and just indent them, but no luck. Commented Jun 26, 2021 at 17:11

You must log in to answer this question.