LoginSignup
4
2

More than 3 years have passed since last update.

[Sphinx]code-blockの言語ごとに異なる書式を設定する

Last updated at Posted at 2019-07-21

やりたかったこと

ターミナルに入力するコマンドをcode-blockで表記することが多いと思います。
OSによって入力するコマンドが異なるため、Windowのコマンドの場合は何色、Linuxのコマンドの場合は何色など、OSによって異なる書式を設定したcode-blockを書きたくなりました。

やったこと

Sphinxでは独自のCSSを埋め込めます。

conf.pyの修正

html_static_path (静的ファイルのpath)とhtml_css_files (cssファイルの相対path)を conf.py に追記します。 html_static_path のほうはデフォルトで記述されているかもしれません。今回はCSSファイルを css/custom.css としました。

conf.py
html_static_path = ['_static']
html_css_files = ["css/custom.css"]

CSSファイルを作成

_staticディレクトリ配下にCSSファイルを作成します。今回はpowershellとbashのシンタックスハイライトの書式を変更します。今回は背景色を上書きしています。

_static/css/custom.css
.highlight-powershell pre {
    background: #AFEEEE;
}
.highlight-bash pre {
    background: #E9967A;
}

code-blockに言語名を指定する

あとは原稿(reStructuredText)の code-block ディレクティブに先程CSSのclassで定義した言語名を指定するだけです。せっかくなので :caption: オプションも追加してキャプションを表示させます。

xxx.rst
Windows
-------

.. code-block:: powershell
   :caption: Win

   Get-Command

Linux
-----

.. code-block:: bash
   :caption: Linux

   ls

HTMLにビルドする

make html コマンドなどでHTML形式にビルドするとこのようになります。ぱっと見でどっちのOSのターミナルなのかわかりやすくなりました。

image.png

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2