Tip: Select the highlight language for code blocks

I just ran across this article:

When inserting a block of fixed-width text in a post (e.g. using the ~~~ or ``` delimiters), the Discourse system runs it through highlight.js in order to apply syntactic coloring. It has code to guess at what programming language that text represents, and does a pretty good job when the language type is obvious:

#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("Hello, world!\n");
    return 0;
}

But when it guesses wrong (usually because it’s not actual code), the highlighting can be really annoying. For instance, the output of a dig command:

```
$ dig www.apple.com
...
```

Gets rendered very strangely, because the script is guessing wrong about its language:

$ dig www.apple.com

; <<>> DiG 9.10.6 <<>> www.apple.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 3394
;; flags: qr rd ra; QUERY: 1, ANSWER: 4, AUTHORITY: 8, ADDITIONAL: 10

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;www.apple.com.			IN	A

;; ANSWER SECTION:
www.apple.com.		1136	IN	CNAME	www.apple.com.edgekey.net.
www.apple.com.edgekey.net. 20936 IN	CNAME	www.apple.com.edgekey.net.globalredir.akadns.net.
www.apple.com.edgekey.net.globalredir.akadns.net. 2937 IN CNAME	e6858.dscx.akamaiedge.net.
e6858.dscx.akamaiedge.net. 20	IN	A	23.220.132.219

But you can specify the language immediately after the opening delimiter (or use text to specify that there should be no highlighting). For example:

``` text
$ dig www.apple.com
...
```

will render it as:

$ dig www.apple.com

; <<>> DiG 9.10.6 <<>> www.apple.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 3394
;; flags: qr rd ra; QUERY: 1, ANSWER: 4, AUTHORITY: 8, ADDITIONAL: 10

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;www.apple.com.			IN	A

;; ANSWER SECTION:
www.apple.com.		1136	IN	CNAME	www.apple.com.edgekey.net.
www.apple.com.edgekey.net. 20936 IN	CNAME	www.apple.com.edgekey.net.globalredir.akadns.net.
www.apple.com.edgekey.net.globalredir.akadns.net. 2937 IN CNAME	e6858.dscx.akamaiedge.net.
e6858.dscx.akamaiedge.net. 20	IN	A	23.220.132.219

The specific set of languages that may be chosen is a part of the forum’s configuration but here’s the full list of everything the script can support.

4 Likes