How to post code or preformatted text

Have a line of code you need to share? Perhaps you need to share an error log from your site? Reading code without formatting can be tough, if not impossible if the code depends on spacing or contains special characters Discourse transforms. This guide focuses on Markdown, but Discourse also support a subset of BBCode and HTML, so pick whichever style you like best.

Inline code formatting

To format a specific section of text, use a single backtick on each side of the code. This can be done within regular text, or when the code is on its own line. Inline formatting does not apply any automatic code formatting (see below), and only applies the “code style” to the text between backticks.

Example 1:

Typing:

`This is a line of code`

Produces:

This is a line of code

Example 2:

Typing:

Here’s some text with `a bit of code` inside!

Produces:

Here’s some text with a bit of code inside!

Entire line code formatting

To format an entire line, add 4 spaces at the start of a line. All text until the next line break will be code.

Example:

Typing:

    All text after 4 spaces will be formatted.

Produces:

All text after 4 spaces will be formatted.

Block code formatting

While you can use the 4-space method to produce multiple lines of code, this can be tedious, especially if you are copying and pasting and need to type 4 spaces on multiple lines of text.

Instead, use 3 backticks (```) on their own line above and below your code. Be sure there are no spaces on the lines with the backticks, or this will not work.

Example:

Typing:

```
public class CodeFormatting {
    public static void main(String[] args) {
        System.out.println("I can format code now!");
    }
}
```

Produces:

public class CodeFormatting {
    public static void main(String[] args) {
        System.out.println("I can format code now!");
    }
}

Automatic code styling

By default, Discourse will try to automatically detect what language you are typing and style your code accordingly. This might be nice for sharing code, but tends to produce strange results when sharing other preformatted text. To avoid the automatic styling, declare your code to be “raw text” by typing text after the first 3 back ticks.

Example:

Typing:

```text
public class CodeFormatting {
    public static void main(String[] args) {
        System.out.println("I can format code now!");
    }
}
```

Produces:

public class CodeFormatting {
    public static void main(String[] args) {
        System.out.println("I can format code now!");
    }
}

In addition to text, you can choose a number of other languages. The default list can be found on GitHub. Site admins can add or remove from the list to customize it for their site.

BBCode and HTML

In addition to markdown, Discourse also support a subset of BBCode and HTML. For HTML, use the <pre> and <code> tags. For BBCode, use the [code] tag.


Lovingly borrowed from:

3 Likes