View All Posts. MiCHiLU.com powered by Django ;-)

[Python]: TextMate + reStructuredText + pygments

reStructuredText を TextMate で Preview する時も pygments で highlight するカスタマイズ。

オリジナルの rst2html.py をコピーして、 publish_cmdline() の前に pygments を追記する。

$ cp `which rst2html.py` /usr/local/bin/rst2html_css.py

/usr/local/bin/rst2html_css.py

...

from docutils import nodes
from docutils.parsers.rst import directives
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter

PYGMENTS_FORMATTER = HtmlFormatter()

def pygments_directive(name, arguments, options, content, lineno,
                      content_offset, block_text, state, state_machine):
    try:
        lexer = get_lexer_by_name(arguments[0])
    except ValueError:
        # no lexer found
        lexer = get_lexer_by_name('text')
    parsed = highlight(u'\n'.join(content), lexer, PYGMENTS_FORMATTER)
    return [nodes.raw('', parsed, format='html')]
pygments_directive.arguments = (1, 0, 1)
pygments_directive.content = 1
directives.register_directive('sourcecode', pygments_directive)

...
publish_cmdline(writer_name='html', description=description)

~/default.css を置きます。 pygments.pocoo.org とか、 これ とか。

TextMate のメニュー「 Bundles > Bundle Editor > Show Bundle Editor 」を開いてエディタを起動する。 「 reStructuredText > Preview 」を選択して command(s) を編集する。 レンダラを rst2html.py から rst2html_css.py に変更して、 cssの探索リストに $HOME/default.css を追加します。

TRST=${TM_RST2HTML:=rst2html_css.py}
...

if [[ -f "$TM_DIRECTORY/default.css" ]]
    then stylesheet="$TM_DIRECTORY/default.css"
elif [[ -f "$TM_PROJECT_DIRECTORY/default.css" ]]
    then stylesheet="$TM_PROJECT_DIRECTORY/default.css"
elif [[ -f "$HOME/default.css" ]]
    then stylesheet="$HOME/default.css"
else
...

「 reStructuredText > Preview 」コマンドを実行してみて、Preview結果にメッセージがでなければOK。

Fri, 16 Feb 2007 01:07:06 +0900 source edit
Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 2.1 Japan License.
View All Posts. MiCHiLU.com powered by Django ;-)