Code in MarkDown

How to properly put code in MarkDown-based systems, such as Discord, Blender.Chat, and various forums.

Many systems like Discord, Blender.Chat, Stack Exchange, Discourse, Slack, etc. use MarkDown for their markup. In short, this allows you to share snippets of code with each other. The thing that makes this worth writing about, is that natural text should behave differently from code. Natural text can be rewrapped to comfortably match the device you’re reading it on. With code, however, this should not be done, as it makes it horrible to read.

Whatever you do, do not post a screenshot of your code. It may look like the simple solution, but it’s only simple for you. It’s impossible to copy-paste code from a screenshot into a text editor, so if someone wants to help you out by adjusting your code for you, you’ve now forced them into typing it all by hand.

The solution is that you have to mark blocks of code with triple backticks. On many keyboards this is one of the left-most keys, left of the 1, under the Escape key. This is what it looks like:

```
def function():
    print("This is just some code")
```

The above will look like this:

def function():
    print("This is just some code")

If you want to get syntax highlighting as well, be sure to type the language name directly after the opening backticks, like this:

```python
def function():
    print("This is just some code")
```
def function():
    print("This is just some code")

This is not always supported by all MarkDown systems, though. For example, Phabricator, the Blender tracker uses lang=python as marker, instead of just python.

dr. Sybren A. Stüvel
dr. Sybren A. Stüvel
Open Source software developer, photographer, drummer, and electronics tinkerer

Related