Caption or lines numbers by default for code blocks

23 views
Skip to first unread message

Denis Bitouzé

unread,
Oct 25, 2023, 1:07:36 PM10/25/23
to sphinx-users
Hi,

is there a way to configure Sphinx in order the default code blocks (I
mean the ones for the default language specified thanks to
`highlight_language`) should have:

- a (fixed) caption ⟨caption⟩,
- and/or lines numbers enabled?

Indeed, it's boring to have to specifiy each time:

┌────
│ .. code-block::
│ :caption: ⟨caption⟩
└────

or:

┌────
│ .. code-block::
│ :linenos:
└────

Thanks.
--
Denis

Shengyu Zhang

unread,
Oct 27, 2023, 9:52:18 AM10/27/23
to sphinx-users
I wrote an extension that allows users to create directives according
reStructuredText template.

In this case, you can create a wrapper directive like "code-block2",
and the wrapper generates a real "code-block" with fixed caption and linenos flag.

conf.py::

    from sphinxnotes.any import Schema, Field as F

    extensions = ['sphinxnotes.any']

    any_schemas = [
        Schema('code-block2',
               attrs={'language': F(referenceable=True)},
               content=F(form=F.Form.LINES),
               description_template='''
    .. code-block:: {{ language }}
       :caption: Your fixed caption
       :linenos:

       {% for line in content %}{{ line }}
       {% endfor %}'''),
    ]

in your documentation::

    .. code-block2::
       :language: python

       print('hello, world!')

For more details, please check https://github.com/sphinx-notes/any

Denis Bitouzé

unread,
Oct 28, 2023, 2:19:11 AM10/28/23
to sphinx-users
Le 27/10/23 à 06h52, Shengyu Zhang a écrit :

> I wrote an extension that allows users to create directives according
> reStructuredText template.
>
> In this case, you can create a wrapper directive like "code-block2",
> and the wrapper generates a real "code-block" with fixed caption and
> linenos flag.
>
> conf.py::
>
> from sphinxnotes.any import Schema, Field as F
>
> extensions = ['sphinxnotes.any']
>
> any_schemas = [
> Schema('code-block2',
> attrs={'language': F(referenceable=True)},
> content=F(form=F.Form.LINES),
> description_template='''
> .. code-block:: {{ language }}
> :caption: Your fixed caption
> :linenos:
>
> {% for line in content %}{{ line }}
> {% endfor %}'''),
> ]
>
> in your documentation::
>
> .. code-block2::
> :language: python
>
> print('hello, world!')
>
> For more details, please check https://github.com/sphinx-notes/any

Very nice indeed!

The only problem for me is that my sources are primarily in (MyST)
Markdown. But you gave me the idea: creating a custom directive.

Thanks!
--
Denis
Reply all
Reply to author
Forward
0 new messages