Skip to content

Code highlight

sysid edited this page Feb 25, 2024 · 1 revision

Markdown code blocks are styled when card is added to Anki. For example:

---

1. How to create a parameterized decorator in *Python*?

> You have to wrap the decorator function inside another function that will take arguments and return a decorator:
>
> ```python
> def check_non_negative(index):
>     def validator(f):
>         def wrap(*args, **kwargs):
>             if args[index] < 0:
>                 raise ValueError(
>                     f'Argument {index} must be non-negative'
>                 )
>             return f(*args, **kwargs)
>         return wrap
>     return validator
>
> @check_non_negative(1)
> def create_list(value, size):
>     return [value] * size
> ```

2. The subclause {1::`GROUPING SETS`} of `GROUP BY` clause in *SQL* allows {2::to specify several grouping sets at once, optimizing the query}.

{1::
\```sql
SELECT
    brand,
    segment,
    SUM(quantity)
FROM
    sales
GROUP BY
    GROUPING SETS (
                (brand, segment),
                (brand),
                (segment),
                ()
        );
\```
}

---

I had to escape (with \) the beginning and end of the sql code block, because otherwise I would not be able to put it into the Markdown code block that is on this page. In a real situation, this is not necessary.

Changing style

Highlighting is done using highlight.js. So you can use whatever style it supports.

The style is applied to the Anki note type, so you can't have different styles for each card.

To change the style, you need to change the highlight.style config option. The value should be the name of the style file from the highlight.js repository without the .css extension. For example:

  • agate.css => agate
  • kimbie.dark.css => kimbie.dark
  • qtcreator_dark.css => qtcreator_dark
  • solarized-light.css => solarized-light

To apply style you need to run inka2 collect command on whatever file/folder you want. Styles are downloaded from the Internet, so you must have a working Internet connection.

Support for other languages

By default, only those languages that highlight.js considers common are supported. If you want highlighting to work on other languages, you must manually download custom highlight.min.js file, rename it to _hl.pack.js and place it in your Anki media folder.

How does it work

As mentioned above, highlight.js is used to highlight code blocks. It consists of two components: a style and a library.

The library is downloaded only once and placed in Anki media folder named _hl.pack.js. This library is then referenced by the Front and Back fields of the Anki note type (the one specified in anki.note_type config option). At the end, a short script is added to the same fields to start coloring code blocks.

Style downloaded each time config option highlight.style is changed and then placed into your note type styling field.

Clone this wiki locally