13 Code fragments - practicalseries/GitHub-Wiki-Design-and-Implementation GitHub Wiki

PAL Logo showing Wiki Documentation heading

13SpacerCode fragments

GitHub, being a software development platform, needs some mechanism for allowing code to be displayed. Since code languages often include formatting characters within the various syntax arrangements, it is necessary that GitHub displays any code fragments exactly as they are entered without interpreting the various dashes, dots and backslashes as text formatting commands.

I.e. it displays code fragments in the literal sense: exactly as they are entered.

GitHub supports such code fragments, these can be displayed at a basic level (simply as code fragments without any coloration), they can also be displayed with syntax highlightingπŸ’ 1 (for known languages).

It also allows framed or fenced code highlights (these are large blocks of code that can cover several lines), again these can contain syntax highlighting.

⬆️ Top



13.1SpacerInline code

Inline code fragments can be inserted by surrounding the code with a single backtick character (`). On a UK keyboard, the backtick is usually the key to the right of the number 1 key (immediately below the esc key).

The Markdown and HTML is as follows:

Markdown, HTML equivalence and GitHub output
${\large \color{#0050C0}\text{M\ A\ R\ K\ D\ O\ W\ N}}$ πŸ”½

The print command is `printf` in C.

${\large \color{#00C050}\text{H\ T\ M\ L}}$ πŸ”½

The print command is <code>printf</code> in C

${\large \color{#B00000}\text{G\ I\ T\ H\ U\ B}\space\ \space\text{O\ U\ T\ P\ U\ T}}$ πŸ”½

The print command is printf in C.

Table 13.1 β€” An inline code fragment

The code is displayed in a monospaced font (in this case Consolas) in a grey rounded rectangle rgb: (240,241,242) #F0F1F2. The font colour is the same as body text: rgb: (31,35,40) #1F2328.

With the HTML, the <code> tag carries out the same function as the backtick character in Markdown.

The <code> tag is always used for HTML inline code fragments (it does not need the <pre> tag discussed in the following section).

⬆️ Top



13.2SpacerCode blocks

There are several ways to display code blocks in Markdown, some are more precise than others.

The simplest mechanism to display a block of code is to indent each line be at least four spaces (depending on the text editor, this is sometimes done with the tab key):

Markdown, HTML equivalence and GitHub output
${\large \color{#0050C0}\text{M\ A\ R\ K\ D\ O\ W\ N}}$ πŸ”½

    #include <stdio.h>

    int main() {
        printf("Hello World");
        return 0;
    }

${\large \color{#00C050}\text{H\ T\ M\ L}}$ πŸ”½

<pre><code>#include <stdio.h>

int main() {
    printf("Hello World");
    return 0;
}
</code></pre>

${\large \color{#B00000}\text{G\ I\ T\ H\ U\ B}\space\ \space\text{O\ U\ T\ P\ U\ T}}$ πŸ”½
#include <stdio.h>

int main() {
    printf("Hello World");
    return 0;
}
Table 13.2 β€” A simple code fragment

The code is again displayed in a monospaced font (in this case Consolas) in a grey rounded rectangle (see the previous section for colour details).

The clipboard icon (highlighted) allows the code to be copied verbatim for pasting into some other editor.

With the HTML, the <pre><code> at the start informs the browser that what follows is to be rendered in a monospaced font and that spaces must be displayed (the <pre> tag does this) and that the content is a fragment of computer code (the <code> tag).

Technically, the <code> tag is for information only, the <pre> tag does everything we need; but syntactically <pre><code> is the correct format.

The <pre><code> is on the same line as the first line of the code, this stops additional line-breaks being inserted before the code fragment.

Important

GitHub will add a scrollbar to a code fragment if a line is too long to be displayed, there is nothing you can do about this (no way to force it to wrap long lines), it is the way GitHub does it.

⬆️ Top



13.2.1SpacerPreferred mechanism for code blocks

Although indenting code by four spaces forces GitHub to interpret the text as code, it is not the preferred mechanism for doing so. Using tabs and spaces can be a bit hit and miss.

The preferred mechanism for Markdown code fragments is to surround the block with three backtick characters (```). This is unambiguous and clearly marks the text as a code fragment. This is the preferred format for the previous example:

Markdown and GitHub output
${\large \color{#0050C0}\text{M\ A\ R\ K\ D\ O\ W\ N}}$ πŸ”½

```
#include <stdio.h>

int main() {
    printf("Hello World");
    return 0;
}
```

${\large \color{#B00000}\text{G\ I\ T\ H\ U\ B}\space\ \space\text{O\ U\ T\ P\ U\ T}}$ πŸ”½
#include <stdio.h>

int main() {
    printf("Hello World");
    return 0;
}
Table 13.3 β€” Preferred Markdown for a code fragment

With this mechanism leading spaces are not required.

Each set of backticks must be on its own blank line.

Note

Using three backtick characters (```) works just like the single backtick (`) when used with inline code fragments.

To escape the triple backticks discussed in the previous section, wrap then in quadruple backticks:

Markdown and GitHub output
${\large \color{#0050C0}\text{M\ A\ R\ K\ D\ O\ W\ N}}$ πŸ”½

````
```
#include <stdio.h>

int main() {
    printf("Hello World");
    return 0;
}
```
````

${\large \color{#B00000}\text{G\ I\ T\ H\ U\ B}\space\ \space\text{O\ U\ T\ P\ U\ T}}$ πŸ”½
```
#include <stdio.h>

int main() {
    printf("Hello World");
    return 0;
}
```
Table 13.4 β€” Escaping three backticks

How to escape four backticks? You guessed it, use five β€” now it just gets silly.

⬆️ Top



13.3SpacerSyntax highlighting

Syntax highlighting is used to colour certain aspects of the programming language to make the text more readable and easier to understand.

Syntax highlighting is only possible with GitHub Markdown (there is no HTML equivalent that works with GitHub).

The above code fragment looks like this with GitHub syntax highlighting (it is written in the C programming language):

Markdown and GitHub output
${\large \color{#0050C0}\text{M\ A\ R\ K\ D\ O\ W\ N}}$ πŸ”½

```c
#include <stdio.h>

int main() {
    printf("Hello World");
    return 0;
}
```

${\large \color{#B00000}\text{G\ I\ T\ H\ U\ B}\space\ \space\text{O\ U\ T\ P\ U\ T}}$ πŸ”½
#include <stdio.h>

int main() {
    printf("Hello World");
    return 0;
}
Table 13.5 β€” Syntax highlighting in Markdown

To activate syntax highlighting, simply follow the first three backticks with the lowercase code for the language being used, the c in this case:

If the code were JavaScript, the three backticks would be followed by java for example (```java).

There is no space between the backticks and the language code.

⬆️ Top



13.3.1SpacerSupported languages

GitHub supports syntax highlighting for many programming languages, the following lists them all and the language code that must follow the three backticks:

Language Code Language Code Language Code
1C 1c Grammatical Framework gf PowerShell powershell, ps, ps1
4D 4d Golo golo, gololang Processing processing
ABAP sap-abap, abap Gradle gradle Prolog prolog
ABNF abnf GraphQL graphql, gql Properties properties
Access logs accesslog Groovy groovy Protocol Buffers proto, protobuf
Ada ada GSQL gsql Puppet puppet, pp
Apex apex HTML, XML xml, html, xhtml, rss, a Python python, py, gyp
Arduino arduino, ino HTTP http, https Python profiler results profile
ARM assembler armasm, arm Haml haml Python REPL python-repl, pycon
AVR assembler avrasm Handlebars handlebars, hbs, html.hb Q# qsharp
ActionScript actionscript, as Haskell haskell, hs Q k, kdb
Alan IF alan, i Haxe haxe, hx QML qml
Alan ln High-level shader language hlsl R r
AngelScript angelscript, asc Hy hy, hylang Raku raku, perl6, p6, pm6, ra
Apache apache, apacheconf Ini, TOML ini, toml RakuDoc pod6, rakudoc
AppleScript applescript, osascript Inform7 inform7, i7 RakuQuoting rakuquoting
Arcade arcade IRPF90 irpf90 RakuRegexe rakuregexe
AsciiDoc asciidoc, adoc Iptables iptables Razor CSHTML cshtml, razor, razor-csh
AspectJ aspectj JSON json, jsonc ReasonML reasonml, re
AutoHotkey autohotkey JSONata jsonata Rebol & Red redbol, rebol, red, red-
AutoIt autoit Java java, jsp RenderMan RIB rib
Awk awk, mawk, nawk, gawk JavaScript javascript, js, jsx RenderMan RSL rsl
Ballerina ballerina, bal Jolie jolie, iol, ol ReScript rescript, res
Bash bash, sh, zsh Julia julia, jl RiScript risc, riscript
Basic basic Julia REPL julia-repl RISC-V Assembly riscv, riscvasm
BBCode bbcode Kotlin kotlin, kt Roboconf graph, instances
Blade (Laravel) blade Lang lang Robot Framework robot, rf
BNF bnf LaTeX tex RPM spec files rpm-specfile, rpm, spec,
BQN bqn Leaf leaf Ruby ruby, rb, gemspec, podsp
Brainfuck brainfuck, bf Lean lean Rust rust, rs
C# csharp, cs Lasso lasso, ls, lassoscript RVT Script rvt, rvt-script
C c, h Less less SAS SAS, sas
C++ cpp, hpp, cc, hh, c++, h LDIF ldif SCSS scss
C/AL cal Liquid liquid SQL sql
C3 c3 Lisp lisp STEP Part 21 p21, step, stp
Cache Object Script cos, cls LiveCode Server livecodeserver Scala scala
Candid candid, did LiveScript livescript, ls Scheme scheme
CMake cmake, cmake.in LookML lookml Scilab scilab, sci
COBOL cobol, standard-cobol Lua lua, pluto SFZ sfz
CODEOWNERS codeowners Luau luau Shape Expressions shexc
Coq coq Macaulay2 macaulay2 Shell shell, console
CSP csp Makefile makefile, mk, mak, make Smali smali
CSS css Markdown markdown, md, mkdown, mk Smalltalk smalltalk, st
Cap’n Proto capnproto, capnp Mathematica mathematica, mma, wl SML sml, ml
Chaos chaos, kaos Matl+C86:D134ab matlab Solidity solidity, sol
Chapel chapel, chpl Maxima maxima Splunk SPL spl
Cisco CLI cisco Maya Embedded Language mel Stan stan, stanfuncs
Clojure clojure, clj Mercury mercury Stata stata
CoffeeScript coffeescript, coffee, cs MetaPost metapost Structured Text iecst, scl, stl, structu
CpcdosC+ cpc MIPS Assembler mips, mipsasm Stylus stylus, styl
Crmsh crmsh, crm, pcmk Mint mint SubUnit subunit
Crystal crystal, cr Mirth mirth Supercollider supercollider, sc
cURL curl mIRC Scripting Language mirc, mrc Svelte svelte
Cypher (Neo4j) cypher Mizar mizar Swift swift
D d MKB mkb Tcl tcl, tk
Dafny dafny MLIR mlir Terraform (HCL) terraform, tf, hcl
Dart dart Mojolicious mojolicious Test Anything Protocol tap
Delphi dpr, dfm, pas, pascal Monkey monkey Thrift thrift
Diff diff, patch Moonscript moonscript, moon Toit toit
Django django, jinja Motoko motoko, mo TP tp
DNS Zone file dns, zone, bind N1QL n1ql Transact-SQL tsql
Dockerfile dockerfile, docker NSIS nsis TTCN-3 ttcn, ttcnpp, ttcn3
DOS dos, bat, cmd Never never Twig twig, craftcms
dsconfig dsconfig Nginx nginx, nginxconf TypeScript typescript, ts, tsx, mts
DTS (Device Tree) dts Nim nim, nimrod Unicorn Rails log unicorn-rails-log
Dust dust, dst Nix nix Unison unison, u
Dylan dylan Oak oak VB.Net vbnet, vb
EBNF ebnf Object Constraint Language ocl VBA vba
Elixir elixir OCaml ocaml, ml VBScript vbscript, vbs
Elm elm Objective C objectivec, objc, ob VHDL vhdl
Erlang erlang, erl Odin odin Vala vala
Excel excel, xls, xlsx OpenGL Shading Language glsl Verilog verilog, v
Extempore extempore, xtlang, xtm OpenSCAD openscad, scad Vim Script vim
F# fsharp, fs, fsx, fsi, fs Oracle Rules Language ruleslanguage WGSL wgsl
FIX fix Oxygene oxygene X# xsharp, xs, prg
Flix flix PF pf, pf.conf X++ axapta, x++
Fortran fortran, f90, f95 PHP php x86 Assembly x86asm
FunC func Papyrus papyrus, psc x86 Assembly (AT&T) x86asmatt
G-Code gcode, nc Parser3 parser3 XL xl, tao
Gams gams, gms Perl perl, pl, pm XQuery xquery, xpath, xq, xqm
GAUSS gauss, gss Phix phix YAML yml, yaml
GDScript godot, gdscript Pine Script pine, pinescript ZenScript zenscript, zs
Gherkin gherkin Plaintext plaintext, txt, text Zephir zephir, zep
Glimmer and EmberJS hbs, glimmer, html.hbs, Pony pony Zig zig
GN for Ninja gn, gni PostgreSQL & PL/pgSQL pgsql, postgre
Go go, golang PowerOn poweron, po

Yeah, I’ve no idea what most of them are either. Especially Brainfuck.

⬆️ Top



13.4SpacerHTML code fragments

Things can get a bit confusing when using HTML to display an HTML code fragment.

Let’s say for example that you wanted to use HTML to display the following as a code fragment:

<table align="center">
<tr><td align="center"><img src="./01-0000/02-images/figm-01-01.png"></td></tr>
</table>

You would think we would simply wrap it in the <pre><code> tags as follows:

<pre><code><table align="center">
<tr><td align="center"><img src="./01-0000/02-images/figm-01-01.png"></td></tr>
</table></code></pre>

What this give however is this:

It has got the grey background of a code fragment, but the HTML starting with <table> has simply rendered as HTML, we don’t see the code, but the code has been executed and displays the image.

Important

This doesn’t happen if we use Markdown with three backticks.

The solution to this problem is that we must replace all the greater than and less than symbols with their HTML escape codes (these were first discussed in section 7.1.2), the table of which is reproduced below:

Less than

<

Replacement code:

&lt;

Greater than

>

Replacement code:

&gt;

Ampersand

&

Replacement code:

&amp;

Double quotation mark

"

Replacement code:

&quot;

Single quotation mark

'

Replacement code:

&apos;

Table 13.7 β€” HTML reserved characters and escape sequences

To make the HTML code fragment work, it must be re-written as:

HTML and GitHub output
${\large \color{#00C050}\text{H\ T\ M\ L}}$ πŸ”½

<pre><code>&lt;table align="center"&gt;
&lt;tr&gt;&lt;td align="center"&gt;&lt;img src="./01-0000/02-images/figm-01-01.png"&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;</code></pre>

${\large \color{#B00000}\text{G\ I\ T\ H\ U\ B}\space\ \space\text{O\ U\ T\ P\ U\ T}}$ πŸ”½
<table align="center">
<tr><td align="center"><img src="./01-0000/02-images/figm-01-01.png"></td></tr>
</table>
Table 13.8 β€” Corrected HTML code fragment using HTML

⬆️ Top



13.4.1SpacerConverting HTML to code fragments

Converting all the reserved characters in a HTML code fragment into escape codes, is, to put it bluntly, a pain in the arse.

It’s something I’ve had to do a lot when producing the PracticalSeries website. In the end I used a Word document with embedded macros to do the conversion, it is available here for you to use:

   ps-html-converter.docm

To use this document: download the document, open it and enable the macrosπŸ’ 2 (Word will try to stop you, especially since you downloaded it from the internet).

Copy the HTML you want to convert onto a blank page in the document (the one starting paste your stuff here will do), in this example I’m copying the HTML table example from the previous section, it looks like this in the document

HTML conversion
Figure 13.1 β€” HTML code copied into the conversion document

Now select the code to be converted:

HTML conversion
Figure 13.2 β€” Select the code fragment

Now press ctrl+alt+R to run the macro to convert the code. It does this:

HTML conversion
Figure 13.3 β€” Converted the code fragment

Cut and paste the converted code into the HTML code fragment:

HTML and GitHub output
${\large \color{#00C050}\text{H\ T\ M\ L}}$ πŸ”½

<pre><code>&lt;table align=&quot;center&quot;&gt;
&lt;tr&gt;&lt;td align=&quot;center&quot;&gt;&lt;img src=&quot;https://github.com/practicalseries/GitHub-Wiki-Design-and-Implementation/wiki/01-0000/02-images/fig-01-01.png&quot;&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;</code></pre>

${\large \color{#B00000}\text{G\ I\ T\ H\ U\ B}\space\ \space\text{O\ U\ T\ P\ U\ T}}$ πŸ”½
<table align="center">
<tr><td align="center"><img src="https://github.com/practicalseries/GitHub-Wiki-Design-and-Implementation/wiki/01-0000/02-images/fig-01-01.png"></td></tr>
</table>
Table 13.9 β€” Converted code fragment

Hope this helps.

⬆️ Top


Footnotes:     


Note

πŸ’ 1 Syntax highlighting is the colouring of various commands, attributes, variables &c. within a code fragment to highlight different components of the code. It is done to make the code more readable.↩

Note

πŸ’ 2 To enable macros in Word, select the File tab, options, trust centre, trust centre settings (button on the right), this opens a new window. Select macro settings and click the enable all macros button and click ok to exit.

That’s the first part, now set the trusted locations, this is still in the trust centre settings, select Trusted locations and select add new location, navigate to wher-ever you have saved the document and select the folder containing it, select include subfolders if required.

Now save, close and re-open the document.↩




⚠️ **GitHub.com Fallback** ⚠️