codetagifyフィルタの例

初回公開:2018/10/14
最終更新:未

サンプルコード

DefaultStyle.cssのComment.Specialの定義が他のコメントと同色になっていて表示させた時に違いがわからないので、前半部分で独自のスタイルMyStyleを定義している。

from pygments.styles.default import DefaultStyle
from pygments.token import Comment

class MyStyle(DefaultStyle):
    styles = DefaultStyle.styles.copy()
    styles[Comment.Special]="bold #FF0000"

# ------------------------------------------------------------

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter

code='print "a  def" # xxx  a abc yyy def'
lexer = get_lexer_by_name("python")
formatter = HtmlFormatter(style=MyStyle)

with open("fileter_none.html", 'w') as outfile:
    highlight(code, lexer, formatter,outfile)

lexer.add_filter('codetagify', codetags =['a','def'])
with open("filter_codetagify.html", 'w') as outfile:
    highlight(code, lexer, formatter,outfile)

実行結果

htmlコード

fileter_none.html

<div class="highlight"><pre><span></span><span class="k">print</span> <span class="s2">&quot;a  def&quot;</span> <span class="c1"># xxx  a abc yyy def</span>
</pre></div>

filter_codetagify.html

<div class="highlight"><pre><span></span><span class="k">print</span> <span class="s2">&quot;a  def&quot;</span> <span class="c1"># xxx  </span><span class="cs">a</span><span class="c1"> abc yyy </span><span class="cs">def</span>
</pre></div>

コードのコメント「a」と「def」の部分に<span class="cs">が追加されているのがわかる。

html表示イメージ

MyStyleクラスのstyle定義を反映させるにはdefault.cssのComment.Specialのcssの定義を以下のように変更する必要がある。

body .cs { color: #FF0000; font-weight: bold; font-style: italic } /* Comment.Special */

fileter_none.html

print "a  def" # xxx  a abc yyy def

filter_codetagify.html

print "a  def" # xxx  a abc yyy def
ページのトップへ戻る