264

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 do I 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

1

1 Answer 1

334

For inline code (that does not hold newlines), any of the following will work:

  • Enclose with backticks: `<html>`.
  • Embed within <code> tags, and manually encode HTML entities: <code>&lt;html&gt;</code>
  • Select the partial text and hit CtrlK (K on OS X) or click the {} button above the editor (pictured below)

For blocks of code, to preserve newlines, use one of the following methods:

  • Use the {} button above the editor (pictured below)
  • Paste your code, select the full lines, and hit CtrlK (K on OS X)
  • Use fenced code blocks by surrounding your code with ``` or with ~~~
    • Opening and closing fence have to be on their own line, and can be indented with up to three spaces
    • More than three backticks or tildes can be used, as long as the closing fence uses the same character and is at least as long as the opening fence
  • Indent everything four (4) spaces or one (1) tab
    • Ensure there is a blank line between the top of the block and other text
  • Encase in <pre> or <pre><code> tags (in that order; using <code><pre> is invalid), and encode HTML entities (like &lt; for <) yourself
    • In <pre> blocks, HTML tags are applied rather than rendered as text. But in <pre><code> blocks with Syntax highlighting (see below), all HTML tags are stripped out. A lang-none language hint (see below) prevents syntax highlighting and keeps HTML tags.
      (Code highlighting is disabled by default on meta sites.)

Code copy/pasted from an IDE is often already tabbed. When rendering, tabs are replaced with spaces.

(click here to find the button in the Ask Question Wizard)

gif demonstration

Code within a blockquote

To include code within a blockquote, make sure to include the space after the > as well as the four spaces before the code.

> Lorem ipsum dolor sit amet, consectetur adipiscing elit. 

>     for(;;) 
        echo 'badger ';

Or, put the blockquote character (and its following space) at the beginning of every blank line, including the one immediately before the code.

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

You can also use fenced code blocks within quotes:

> Text before code
> ```
> for (;;;)
>   echo 'badger';
> ```
> Text after code

Code within a numbered or bulleted list

Normally within lists, a line starting with at least enough spaces to match the list Markdown (e.g, - , including the space) indicates that the line is within the list item and will be treated (within the list item) as if it was another line of Markdown. It's possible to embed a code block within a list item. When you do so, it makes it a bit complex, as the indentation has two different purposes:

  1. The indent indicating it's within the list item (match this indent to the list item's text)
  2. Other Markdown formatting for the line within the list (e.g., four spaces for code, or a code fence)

Putting the code within the list

First, match the number of spaces to the indent of the list item (e.g., typically two spaces for unordered lists and three spaces for ordered lists, per level within the list), then add the same Markdown formatting you would have used for that line format if it was not within a list (e.g., four spaces for code or a code fence).

Examples

Four space indented code in unordered list
- First bullet
- Second bullet (note additional 2 space indent, total 6, on the code)

      for(;;) 
        echo 'ow ';
  - Sub bullet (note additional 2 space indent here and 8 total on the code)

        for(;;) 
          echo 'ow ';
Renders as
  • First bullet

  • Second bullet (note additional 2 space indent, total 6, on the code)

    for(;;) 
      echo 'ow ';
    
    • Sub bullet (note additional 2 space indent here and 8 total on the code)

      for(;;) 
        echo 'ow ';
      
Code fences in unordered list
- First bullet
- Second bullet (note 2 space indent on the code fence)
  ```
  for(;;)
    echo 'ow ';
  ```
  - Sub bullet (note additional 2 space indent here, with 4 total on the code fence)
    ```
    for(;;)
      echo 'ow ';
    ```
Renders as
  • First bullet
  • Second bullet (note 2 space indent on the code fence)
    for(;;)
      echo 'ow ';
    
    • Sub bullet (note additional 2 space indent here, with 4 total on the code fence)
      for(;;)
        echo 'ow ';
      
Four space indented code in ordered list
1. First item
2. Second item (note additional 3 space indent, total 7, on the code)

       for(;;)
         echo 'ow ';
   1. First sub-item (note additional 3 space indent here and 10 total on the code)

          for(;;) 
            echo 'ow ';
Renders as
  1. First item

  2. Second item (note additional 3 space indent, total 7, on the code)

    for(;;)
      echo 'ow ';
    
    1. First sub-item (note additional 3 space indent here and 10 total on the code)

      for(;;) 
        echo 'ow ';
      
Code fences in ordered list
1. First item
2. Second item (note 3 space indent on the code; line up with list item text)
   ```
   for(;;)
     echo 'ow ';
   ```
   1. First sub-item (note additional 3 space indent here and 8 total on the code; line up with list item text)
      ```
      for(;;)
        echo 'ow ';
      ```
Renders as
  1. First item
  2. Second item (note 3 space indent on the code; line up with list item text)
    for(;;)
      echo 'ow ';
    
    1. First sub-item (note additional 3 space indent here and 8 total on the code; line up with list item text)
      for(;;)
        echo 'ow ';
      

Putting the code after the list

If you use indentation to format a block of code, but want it to appear after the list, without being nested, you'll need to put something in between. An HTML comment is sufficient, and won't produce anything in the rendered result, so it can be used as a "marker" for the end of the list:

- First bullet
- Second bullet

<!-- -->

    for(;;) 
        echo 'ow ';

With code fences, no alteration is required.

Syntax highlighting

Highlight.js is used to add colour to the code, but only if the language can be uniquely determined given the tags of the question, or if manual hints have been provided.

For any code block, you can use these HTML comments to specify the language:

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

    code goes here

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

    code goes here

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

```
code goes here
```

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

~~~
code goes here
~~~

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

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

    code goes here

More text not in code blocks

    code goes here

Alternatively, if you use fenced code blocks, you can specify the language right after the first fence:

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

~~~lang-or-tag-here
code goes here
~~~

This goes for fenced code blocks elsewhere as well:

> ```javascript
> for (;;;) {
>   console.log('badger');
> }
> ```

See the full specification and list of languages hints.

Note that:

  • 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
  • When using a tag to specify language, the tag name is case-sensitive
  • If you combine the fenced style with the HTML comments, the HTML comments are ignored

If no language is defined then no highlighting occurs at all. But in the preview, or if multiple language tags define very different languages and no manual definition is used, a default highlighting is used in which Prettify 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.

Stack Snippets – Executable JavaScript/HTML/CSS snippets

Stack snippets can group a JavaScript, HTML and CSS code snippet and make them runnable. This feature can be accessed by the icon that looks like a page with a <> on it. Alternatively, you can press CtrlM (M on OS X).

Toolbar button to access Stack Snippets

The code snippet tool allows you to format code automatically using the Tidy button on the left. You can use this option to take care of replacing tabs by spaces, correct code indentation, and general improvement of readability

Once you save your snippet, you’ll get something like this in the editor:

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

<!-- language: lang-js -->

    // JavaScript code

<!-- language: lang-css -->

    /* CSS code */

<!-- language: lang-html -->

    HTML code

<!-- end snippet -->

If you delete the begin snippet and end snippet comments, you’re left with three adjacent code snippets that are not executable. You may also keep a single block of code which will have the correct formatting and indentation.

Using 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>`, and `` $` `` yields the Perl $` operator. In comments, the additional space in the delimiters is not supported. Instead, escape the backtick: `\`<html>\`` and `$\`` to get `<html>` or $` in a comment.
12
  • If something looks like a html-tag and is not in a markdown code-block (indented), it is either interpreted as HTML (a very limited subset is allowed) or silently dropped. Please block posts containing unsupported HTML Commented Feb 23, 2016 at 18:38
  • In chat only ctrl-k works on OS X, not cmd-k. OS X 10.12.6, Chrome 66.0.3359.181.
    – MoxieBall
    Commented Jun 18, 2018 at 18:57
  • 1
    It would be nice to know how to do a code backslash in a comment. Update: apparently that is backtick backtick backslash backtick backtick.
    – NetMage
    Commented Nov 27, 2018 at 20:40
  • @animuson: Prettify is used to add colour to the code ... I assume, this is outdated? Commented Apr 22, 2022 at 23:15
  • Is it possible to syntax-highlight a code in case it's in quote?
    – Artfaith
    Commented Apr 27, 2022 at 3:22
  • 1
    @Faither Apologies for the late reply, but you can use code fences (with language hint) inside a quote (see updated answer). Commented Jul 12, 2022 at 13:57
  • Code fences > indented blocks. Commented Jul 26, 2022 at 12:25
  • @rene that image is a good addition to have (prompted by the recent duplicate question), but I feel like there should be an expanded explanation. Commented Mar 7, 2023 at 0:36
  • @KarlKnechtel yeah, I'm pondering on the best edit, given the standard editor and ask wizard editor are different in their feature set. it is not only confusing / mismatching toolbar images.
    – rene
    Commented Mar 7, 2023 at 18:16
  • So how do you enter code-formatted double-backslashes in a comment?
    – Wyck
    Commented Mar 1 at 13:45
  • 1
    @Wyck \\ two backslashes surrounded by DOUBLE backticks
    – Jason C
    Commented Mar 1 at 15:10
  • For a longer block of a MATLAB script, the block quote ``` actually worked, others not! Commented Apr 8 at 17:08

You must log in to answer this question.

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