Code blocks with syntax highlighting

Quick Reference

A code block consists of a code-block directive and the actual code indented by four spaces for consistency with other code bases.

A code block can have one or more options. To make orientation in code examples easier try to always add a :caption: with the path and name of the file where the example should go:

Documentation/MyDocs.rst
..  code-block:: php
    :caption: EXT:site_package/Configuration/TCA/Overrides/sys_template.php

    /**
     * Add default TypoScript (constants and setup)
     */
    \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addStaticFile(
         'site_package',
         'Configuration/TypoScript',
         'Site Package'
    );
Copied!
EXT:site_package/Configuration/TCA/Overrides/sys_template.php
/**
 * Add default TypoScript (constants and setup)
 */
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addStaticFile(
     'site_package',
     'Configuration/TypoScript',
     'Site Package'
);
Copied!

Always use syntactically correct code in a code block.

Use placeholders in angle brackets (<placeholder-name>) to refer to a place in the code where the exact value is not important.

Code block directive

A code block has the following syntax:

Documentation/MyDocs.rst
..  code-block:: <language>
    :caption: <caption>
    <options>

    <code>
Copied!

There must be a newline between the options and the code. There must not be a newline between the directive line and options or within options. Otherwise the rendering will fail.

<language>

The language of the code-block. We commonly use the following: php, typoscript (also for TSconfig), yaml, javascript, html (also for Fluid), shell, xml, plaintext.

See all available languages

<caption>
To make orientation in code examples easier try to always add a caption with the name of the file where the example should go. If the code should be manually entered in the TYPO3 backend explain where it should go there.
<options>

The following options may be used, all options are optional, but caption is highly recommended:

..  code-block:: <language>
    :caption: <caption>
    :linenos:
    :lineno-start: <start-number>
    :emphasize-lines: <emphasized-line-numbers>
    :name: <reference-label>
Copied!
linenos
Show line numbers.
lineno-start
Start line numbers with <start-number>.
emphasize-lines
<emphasized-line-numbers> contains a comma separated list of line numbers to be emphasized.
name
Set a <reference-label>. This label can be used to link from any given text to the specific code block. The name needs to be unique within one manual.

See also the official sphinx documentation on code-blocks.

Examples

A simple code block with syntax highlighting

Documentation/MyDocs.rst
..  code-block:: php
    :caption: EXT:site_package/Configuration/TCA/Overrides/sys_template.php

    /**
     * Add default TypoScript (constants and setup)
     */
    \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addStaticFile(
         'site_package',
         'Configuration/TypoScript',
         'Site Package'
    );
Copied!
EXT:site_package/Configuration/TCA/Overrides/sys_template.php
/**
 * Add default TypoScript (constants and setup)
 */
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addStaticFile(
     'site_package',
     'Configuration/TypoScript',
     'Site Package'
);
Copied!

Code block with line numbers and highlighting of one line

Documentation/MyDocs.rst
..  code-block:: php
    :caption: EXT:site_package/Configuration/TCA/Overrides/sys_template.php
    :linenos:
    :emphasize-lines: 4, 7

    /**
     * Add default TypoScript (constants and setup)
     */
    \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addStaticFile(
         'site_package',
         'Configuration/TypoScript',
         'Site Package'
    );
Copied!
EXT:site_package/Configuration/TCA/Overrides/sys_template.php
/**
 * Add default TypoScript (constants and setup)
 */
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addStaticFile(
     'site_package',
     'Configuration/TypoScript',
     'Site Package'
);
Copied!

Use code blocks containing diffs

To emphasize changes that should be made:

Documentation/MyDocs.rst
..  code-block:: diff
    :caption: ext_localconf.php.diff

     <?php

    -defined('TYPO3_MODE') or die();
    +defined('TYPO3') or die();
Copied!
ext_localconf.php.diff
 <?php

-defined('TYPO3_MODE') or die();
+defined('TYPO3') or die();
Copied!

Show a directory tree

Documentation/MyDocs.rst
..  code-block:: none
    :caption: Page tree of directory :file:`vendor/composer`

    $ tree vendor/composer
    ├── ClassLoader.php
    ├── LICENSE
    ├── autoload_classmap.php
    ├── ...
    └── installed.json
Copied!
Page tree of directory vendor/composer
$ tree vendor/composer
├── ClassLoader.php
├── LICENSE
├── autoload_classmap.php
├── ...
└── installed.json
Copied!

Use syntactically correct code

Highlight directive

You can set the default language with the highlight directive. All following code blocks will use the language as specified in the highlight directive for syntax highlighting.

This language works as fall back for the outdated code blocks that do not specify the desired language.

For TYPO3 we have adopted the convention that each reStructuredText source file imports the Documentation/Includes.rst.txt file at the top. And in the included file - in general - we set PHP as default language for highlighting. Exception: In the TypoScript manuals we are using typoscript as default.

Available languages

The following languages are supported. They can be used in a code-block and a literalinclude directive.

  • 1c
  • abnf
  • accesslog
  • actionscript
  • ada
  • angelscript
  • apache
  • applescript
  • arcade
  • arduino
  • armasm
  • asciidoc
  • aspectj
  • autohotkey
  • autoit
  • avrasm
  • awk
  • axapta
  • bash
  • basic
  • bnf
  • brainfuck
  • cal
  • capnproto
  • ceylon
  • clean
  • clojure
  • clojure-repl
  • cmake
  • coffeescript
  • coq
  • cos
  • cpp
  • crmsh
  • crystal
  • cs
  • csp
  • css
  • d
  • dart
  • delphi
  • diff
  • django
  • dns
  • dockerfile
  • dos
  • dsconfig
  • dts
  • dust
  • ebnf
  • elixir
  • elm
  • erb
  • erlang
  • erlang-repl
  • excel
  • fix
  • flix
  • fortran
  • fsharp
  • gams
  • gauss
  • gcode
  • gherkin
  • glsl
  • gml
  • go
  • golo
  • gradle
  • groovy
  • haml
  • handlebars
  • haskell
  • haxe
  • hsp
  • htmlbars
  • http
  • hy
  • inform7
  • ini
  • irpf90
  • isbl
  • java
  • javascript
  • jboss-cli
  • json
  • julia
  • julia-repl
  • kotlin
  • lasso
  • ldif
  • leaf
  • less
  • lisp
  • livecodeserver
  • livescript
  • llvm
  • lsl
  • lua
  • makefile
  • markdown
  • mathematica
  • matlab
  • maxima
  • mel
  • mercury
  • mipsasm
  • mizar
  • mojolicious
  • monkey
  • moonscript
  • n1ql
  • nginx
  • nimrod
  • nix
  • nsis
  • objectivec
  • ocaml
  • openscad
  • oxygene
  • parser3
  • perl
  • pf
  • pgsql
  • php
  • plaintext
  • pony
  • powershell
  • processing
  • profile
  • prolog
  • properties
  • protobuf
  • puppet
  • purebasic
  • python
  • q
  • qml
  • r
  • reasonml
  • rib
  • roboconf
  • routeros
  • rsl
  • rst
  • ruby
  • ruleslanguage
  • rust
  • sas
  • scala
  • scheme
  • scilab
  • scss
  • shell
  • smali
  • smalltalk
  • sml
  • sqf
  • sql
  • stan
  • stata
  • step21
  • stylus
  • subunit
  • swift
  • taggerscript
  • tap
  • tcl
  • tex
  • thrift
  • tp
  • twig
  • typescript
  • typoscript
  • vala
  • vbnet
  • vbscript
  • vbscript-html
  • verilog
  • vhdl
  • vim
  • x86asm
  • xl
  • xml
  • xquery
  • yaml
  • zephir

Literalinclude

A drawback of code blocks is that most editors cannot properly highlight or indent code within code blocks. The directive literalinclude enables you to store longer code blocks in an external file with the proper file extension.

The literalinclude directive imports the file and displays its content as code block.

Documentation/SiteConfiguration/Index.rst
..  literalinclude:: /CodeSnippets/LiteralIncludes/example.yaml
    :language: yaml
    :emphasize-lines: 5,10-13
    :linenos:
Copied!
base: /
errorHandling: {  }
languages:
  -
    title: English
    enabled: true
    languageId: 0
    base: /
    typo3Language: default
    locale: en_US.UTF-8
    iso-639-1: en
    navigationTitle: English
    hreflang: en-us
    direction: ltr
    flag: us
rootPageId: 1
routes: {  }
Copied!

Literal includes can even be used to render the difference between files, without having to create a diff file first:

Documentation/SiteConfiguration/Index.rst
..  literalinclude:: /CodeSnippets/LiteralIncludes/example.yaml
    :diff: /CodeSnippets/LiteralIncludes/example_de.yaml
Copied!
base: /
errorHandling: {  }
languages:
  -
    title: English
    enabled: true
    languageId: 0
    base: /
    typo3Language: default
    locale: en_US.UTF-8
    iso-639-1: en
    navigationTitle: English
    hreflang: en-us
    direction: ltr
    flag: us
rootPageId: 1
routes: {  }
Copied!

See also literalinclude directive.

Placeholders

Placeholders in this context are named tags in code and example URLs where the exact value does not matter, but is referenced in the surrounding documentation. Use the Backus-Naur form <placeholder-name> for placeholders in code and URLs, i.e. use angle brackets to encapsulate the placeholder name.

For example in PHP

Set up a controller class to handle user interaction with the entity data
model:

..  code-block:: php

    class <Entity>Controller extends ActionController
    {
        ..
    }

where `<Entity>` corresponds to the entity data model class name.
Copied!

or on the command line

Importing a TYPO3 dump file is as simple as running:

..  code-block:: bash

    typo3/sysext/core/bin/typo3 impexp:import <file>

where `<file>` can be the absolute path on the server or the relative path
in the TYPO3 project folder.
Copied!

or in an example URL

The TYPO3 backend normally appends the session token ID to the URL as
follows: :samp:`https://example.org/typo3/main?token=<token-id>`.
Copied!

In the XML and HTML markup languages, which make extensive use of angle brackets, the comment tag <!-- placeholder-name --> is used to insert placeholders. A <placeholder-name> looks like a regular element and would lead to confusion.

Outdated code block formats

For historic reasons the :caption: option is missing in many code blocks. Try to add them whenever you touch the RST files. Do not add new code blocks without a caption stating the file name. It is often very confusing for new developers where a certain code snippet should go. The recommended file name can help to clear this up.

We recommend that you always write the language name after the code block directive. This makes it easier for first time contributors to adjust or copy-paste code blocks. For historic reasons there are code blocks without an explicit language.

If you do not explicitly set the language, the default language (as set with the Highlight directive) is used. If no highlight directive was used, the default set in Documentation/Includes.rst.txt is used.

In the past a simplified shorthand directive was widely used: A sentence ending with two double colon ::, followed by a new line and an indented block of code. This quick syntax has several drawbacks:

  • It is confusing to developers who seldom contribute
  • We cannot give a caption and state the file name where the code should go.
  • The script language is only stated implicitly.
  • Such code blocks cannot be easily copy-pasted to use them as a foundation for your own code blocks.

You can change these code blocks like this:

UpdateShorthandCode.diff
 The extension already contains some unit tests that extend `typo3/testing-framework`'s base
-unit test class in directory :file:`Tests/Unit/Hooks` (stripped)::
+unit test class:
+
+..  code-block:: php
+    :caption: <extension_key>/Tests/Unit/Hooks/DataHandlerFlushByTagHookTest.php

      <?php
      namespace Lolli\Enetcache\Tests\Unit\Hooks;
Copied!