
from docutils import nodes, utils


class r(nodes.Inline, nodes.TextElement):
    pass

def r_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
    latex = utils.unescape(text, restore_backslashes=True)
    return [r(latex=latex)], []

def latex_visit_r(self, node):
    self.body.append(r'\ref{' + node['latex'] + '}')
    raise nodes.SkipNode


class vref(nodes.Inline, nodes.TextElement):
    pass

def vref_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
    latex = utils.unescape(text, restore_backslashes=True)
    return [vref(latex=latex)], []

def latex_visit_vref(self, node):
    self.body.append(r'\vref{' + node['latex'] + '}')
    raise nodes.SkipNode


class vrefr(nodes.Inline, nodes.TextElement):
    pass

def vrefr_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
    latex = utils.unescape(text, restore_backslashes=True)
    return [vrefr(latex=latex)], []

def latex_visit_vrefr(self, node):
    range = tuple(node['latex'].split(',', 1))
    self.body.append(r'\vrefrange{%s}{%s}' % range)
    raise nodes.SkipNode


def setup(app):
    app.add_node(r, latex=(latex_visit_r, None))
    app.add_node(vref, latex=(latex_visit_vref, None))
    app.add_node(vrefr, latex=(latex_visit_vrefr, None))
    app.add_role('r', r_role)
    app.add_role('vref', vref_role)
    app.add_role('vrefr', vrefr_role)

