#!/usr/bin/python
# unproudly borrowed from David Goodger's rst2html.py

"""
A minimal front end to the Docutils Publisher, producing HTML.
"""

try:
    import locale
    locale.setlocale(locale.LC_ALL, '')
except:
    pass

from docutils.core import publish_cmdline, default_description
# ____________________________________________________________
from docutils import nodes, utils
from docutils.parsers.rst import roles

"""
description of the new roles:

`:api:` : link to the code

- code.py becomes api/code.html
- code.Code.code_test becomes api/code.Code.code_test.html
- code.Code() becomes api/code.Code.html

`:doc:`a link to an internal file
example become example.html

ref: link with anchor as in an external file 

:ref:`toto#titi` becomes toto.html#titi 
"""
from os.path import splitext

def api_reference_role(role, rawtext, text, lineno, inliner,
                    options={}, content=[]):
    basename = text
    if "(" in text:
        basename = text.split("(")[0]
    if ".py" in text:
        basename = splitext(text)[0]                
    if "test_" in text:
        refuri = "api/" + "tiramisu.test." + basename + '.html'
    else:
        refuri = "api/" + "tiramisu." + basename + '.html'
    roles.set_classes(options)
    node = nodes.reference(rawtext, utils.unescape(text), refuri=refuri,
                        **options)
    return [node], []

roles.register_local_role('api', api_reference_role)

def doc_reference_role(role, rawtext, text, lineno, inliner,
                    options={}, content=[]):
    refuri = text + '.html'
    roles.set_classes(options)
    node = nodes.reference(rawtext, utils.unescape(text), refuri=refuri,
                        **options)
    return [node], []

roles.register_local_role('doc', doc_reference_role)

def ref_reference_role(role, rawtext, text, lineno, inliner,
                    options={}, content=[]):
    fname, anchor = text.split('#')
    refuri = fname + '.html#' + anchor 
    roles.set_classes(options)
    node = nodes.reference(rawtext, utils.unescape(anchor), refuri=refuri,
                        **options)
    return [node], []

roles.register_local_role('ref', ref_reference_role)

# ____________________________________________________________

description = ('Generates (X)HTML documents from standalone reStructuredText '
               'sources.  ' + default_description)

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

