Another way to define code blocks

The Fenced Code Blocks extension adds a secondary way to define code blocks, which overcomes a few limitations of indented code blocks.

Warning

Fenced Code Blocks are only supported at the document root level.

Configuration

# mkdocs.yml

markdown_extensions:
  - fenced_code

To enable syntax highlighting, the codehilite extension must be enabled.

Syntax

```python
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

for num in fibonacci(10):
    print(num)
```

produces the raw code:

def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

for num in fibonacci(10):
    print(num)

if attr_list is enabled, you can add attributes to the code block by adding them after the language name:

``` { .python #code-id .custom-class  }
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

for num in fibonacci(10):
    print(num)
```

If produces the same code block as above, but with the id and class attributes added.

def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

for num in fibonacci(10):
    print(num)

If codehilite is enabled. You can add any pygments html formatter options.

Warning

With codehilite enabled, attr_list key/value attributes are not supported.

``` { .python linenos="table" hl_lines="4 5" }
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

for num in fibonacci(10):
    print(num)
```
1
2
3
4
5
6
7
8
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

for num in fibonacci(10):
    print(num)

As another example, you can also add references to the lines of code (goto line 4 and line 5).

``` { .python linenos="inline" hl_lines="4 5" anchorlinenos="true" lineanchors="fibo" }
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

for num in fibonacci(10):
    print(num)
```
1def fibonacci(n):
2    a, b = 0, 1
3    for _ in range(n):
4        yield a
5        a, b = b, a + b
6
7for num in fibonacci(10):
8    print(num)