2009年4月18日

ブログにソースコードを掲載する方法のメモ

ブログにソースコードを掲載する方法は2006年にブログにコードを貼り付ける方法で悩むの巻が元でいろいろ議論されて結構まとまった記事がネット上にある。

今自分のブログはEmacs Museで生成するとコード部分がpreタグだけなのでpreだけなのだけど、現在の状況を調査してメモしてみる。

まずこれ関連に標準があるかと言うことなのだけれど、おそらく標準と呼べるのはHTML5 W3C Working Draftではないかと思われます。 Working Draftなので確定ではないけれど参考にはなります。

この文書の中で「The code element」がcodeの定義ですが、以下のような記述があります。

The following example shows how a block of code could be marked up using the pre and code elements.

<pre><code>var i: Integer; begin i := 1; end.</code></pre>

A class is used in that example to indicate the language used.

この記述を見るとpreとcodeで囲って、codeにclassを指定するのが良いと読めます。

続いて「The pre element」を見るとこのあたりが詳細に説明されています。 preの目的が以下の様に定義されています。

・Including an e-mail, with paragraphs indicated by blank lines, lists indicated by lines prefixed with a bullet, and so on.
・Including fragments of computer code, with structure indicated according to the conventions of that language.
・Displaying ASCII art.

「Including fragments of computer code」の記述がありますからソースコードに使えってことですね。

「samp」と「kbd」に関しても記述があります。

「samp」がoutputに利用するとのことで、プロンプトの表示などはsampですね。

「kbd」がinputに利用するとのことで、キーのショートカットとか画面に打つ文字とかですね。

これに従うのが良さそうです。

HTMLのエスケープなどはEmacs Museにまかせます。

codeの方にclassを指定すると自分のブログだと不便なのでpreの方にclass指定することにします。 でこんな感じにCSSを設定して、以後はpreとcodeで囲むようにしてみる。


pre.src {
  border: 1px solid gray;
  padding: 4px;
  overflow: auto;
  white-space: pre;
  width: 97.5%;
  cursor: text;
  line-height: 12pt;
  font-family: 'Consolas', 'Bitstream Vera Sans Mono', 'Andale Mono', 'Courier New', Monospace;
  color: #FFFFFF;
  background-color: #555555;
}
*:first-child+html pre.src {
    overflow: scroll;
}

なんかまだまだ変だけどとりあえず後で修正する。Emacs Museの生成コードに修正が必要かもしれない。