LoginSignup
0
1

More than 1 year has passed since last update.

Jupyter notebookで章番号の付与を自動化する方法

Last updated at Posted at 2022-10-16

はじめに

Qiita初投稿なのでわかりにくかったり,何度も編集作業をするかも知れません

記事の目的

修論をJupterNotebookで書くときに今まで章番号を手で書いていたけど,修正作業を行う上でものすごく非効率だと感じたためcustom.cssを使ってその自動化を試みた.

この記事はその結果についてだけ書く。
そもそもcustom.cssってなんだよって人でも問題なく実践できると思います.

なお,開発環境はMacですが,linuxでも多分同じだと思います。Windowsは知らないごめん

事前知識

custom.cssってなに?

jupyter notebookはサーバーを立ち上げてブラウザで開いたりすると思う。その場合,ブラウザに見えてるjupyter notebookはただのHTMLなので開発者ツールを開いてみればcustom/custom.cssを読み込んでいるタグがheadタグから見えるはず。こんな感じ
readcustomcss.jpg
見づらいかもですが赤枠内に注目してください.

というわけで,今回はこのcustom.cssを作成していく.

Markdown記法とHTMLタグの対応

基本的には#の数の分のhタグに対応すると思っておけばいいかも。
詳しくは以下の対応表を参照のこと。

Markdown HTML
# Chapter <h1>Chapter</h1>
## Section <h2>Section</h2>
### SubSection <h3>SubSection</h3>
#### Proposition <h4>Proposition</h4>

実際の作業

想定される結果

ブラウザ(Chrome)で開いたときに
customTestJupy.png
これが

customTest.jpg

こうなればOK.

見ればわかる通りですがh1タグを章としてh2をセクション,h3をサブセクション,h4を命題(定義,系,補題,例,注意も含む)として利用しています.
なおh3タグとh4タグの章番号の変動はそれぞれ独立していて,h1,h2タグが挿入されたときにリセットされるようにしています.

それじゃ作業開始!!!!

Step1 custom.cssの作成

ターミナル内で以下のコマンドを叩く

cd $(jupyter --config-dir) 
mkdir custom && touch custom/custom.css

その後ls customを打ったときにcustom.cssと表示されればOKです

ちなみにjupyter --config-dirでjupyterのconfigディレクトリのパスが表示されるはずです。

Step2 custom.cssの編集

適当なテキストエディタでcustom.cssに以下を追記

body {
    counter-set: chapter section subsection proposition;
}

h1 {
    counter-set: section 0 proposition 0 subsection 0;
}


h1::before {
    content: counter(chapter)".";
    counter-increment: chapter;
}


h2 {
    counter-set: subsection 0 proposition 0;
}

h2::before {
    content: counter(chapter)"." counter(section)".";
    counter-increment: section;
}


h3::before {
    content: counter(chapter)"." counter(section) "." counter(subsection);
    counter-increment: subsection;
}

h4::after {
    content: counter(chapter)"." counter(section) "." counter(proposition);
    counter-increment: proposition;
}


a.anchor-link {
    display: none;
}

あとはいつも通りjupyterを立ち上げればOKです

余談

章番号を自動化するにあたっていろんなサイトを訪問した。どのサイトもcustom.css内でcounter-resetを使っていたが,自分のJupyterの場合セルを分割した瞬間に章番号がおかしくなったりしてうまくいかなかった。
もしかしたらcounter-resetが間違ってんじゃねと思いcounter-setを用いたらうまくいった。
またjupyter notebookはhタグのとなりに決まってaタグを出してくるのですが, そいつの左右のpaddingがなぜか消えてくれずh4:afterで定義番号を付与するときの邪魔になったのでdisplay:noneで非表示にしました.

0
1
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
0
1