nikkie-ftnextの日記

イベントレポートや読書メモを発信

Sphinx の code-block ディレクティブは language をきめ細やかに設定できる! pycon や pytb を知っていますか?

はじめに

七尾百合子さん、お誕生日 155日目 おめでとうございます! nikkieです。

SphinxPythonコード表示の見た目に関する小ネタです

目次

code-blockのlanguage

Sphinxcode-blockディレクティブ1
https://www.sphinx-doc.org/ja/master/usage/restructuredtext/directives.html#directive-code-block

.. code-block:: python

   import this

pythonlanguageを指定できます。
これはPygmentsがサポートするlexerエイリアスにもなり得ます。

This directive takes a language name as an argument. It can be any lexer alias supported by Pygments.

https://pygments.org/languages/ を見ていくと、実はpythonだけではないのです!

language をきめ細やかに設定した例

pyconまたはpython-console

Python Conferenceではなく、python-consolepycon
https://pygments.org/docs/lexers/#pygments.lexers.python.PythonConsoleLexer

For Python console output or doctests,

対話モードを表現する際に便利で、存在に気づいてから愛用しています。
利用者増えますように!

python-consoleが追加されたと知りました。

pytbまたはpy3tb

Traceback用に指定できることに気づきました!
https://pygments.org/docs/lexers/#pygments.lexers.python.PythonTracebackLexer

For Python 3.x tracebacks, with support for chained exceptions.

pythonpython3も同じになるように、pytbpy3tbも同じになるのですね

python2 (danger)

使い所はほとんど無さそうですが、PygmentsはPython 2系向けのハイライトもサポートしています。

python2またはpy2
https://pygments.org/docs/lexers/#pygments.lexers.python.Python2Lexer

py2tb
https://pygments.org/docs/lexers/#pygments.lexers.python.Python2TracebackLexer

その他

py+ul4を初めて知りました。
https://pygments.org/docs/lexers/#pygments.lexers.ul4.PythonUL4Lexer

Lexer for UL4 embedded in Python.

Pythonとは関係ないのですが、「Text only」と「Text output」があることに気づきました

text
https://pygments.org/docs/lexers/#pygments.lexers.special.TextLexer

“Null” lexer, doesn’t highlight anything.

output
https://pygments.org/docs/lexers/#pygments.lexers.special.OutputLexer

Simple lexer that highlights everything as Token.Generic.Output.

例でアスキアート書いてる!!

終わりに

Sphinxcode-blocklanguageにはpythonだけでなく、pyconpytbを指定する余地があります!

Pygmentsのlexerを確認した背景は、直近いただいたこちらのissueです。


  1. 合わせてどうぞな過去記事