magics.py
42 lines
| 1.3 KiB
| text/x-python
|
PythonLexer
Thomas Kluyver
|
r18184 | import re | ||
from sphinx import addnodes | ||||
Thomas Kluyver
|
r18296 | from sphinx.domains.std import StandardDomain | ||
from sphinx.roles import XRefRole | ||||
Thomas Kluyver
|
r18184 | |||
Thomas Kluyver
|
r18296 | name_re = re.compile(r"[\w_]+") | ||
Thomas Kluyver
|
r18184 | |||
def parse_magic(env, sig, signode): | ||||
Thomas Kluyver
|
r18296 | m = name_re.match(sig) | ||
Thomas Kluyver
|
r18184 | if not m: | ||
raise Exception("Invalid magic command: %s" % sig) | ||||
Thomas Kluyver
|
r18296 | name = "%" + sig | ||
signode += addnodes.desc_name(name, name) | ||||
return m.group(0) | ||||
class LineMagicRole(XRefRole): | ||||
"""Cross reference role displayed with a % prefix""" | ||||
prefix = "%" | ||||
def process_link(self, env, refnode, has_explicit_title, title, target): | ||||
if not has_explicit_title: | ||||
title = self.prefix + title.lstrip("%") | ||||
target = target.lstrip("%") | ||||
return title, target | ||||
Thomas Kluyver
|
r18184 | |||
def parse_cell_magic(env, sig, signode): | ||||
Thomas Kluyver
|
r18296 | m = name_re.match(sig) | ||
Thomas Kluyver
|
r18184 | if not m: | ||
raise ValueError("Invalid cell magic: %s" % sig) | ||||
Thomas Kluyver
|
r18296 | name = "%%" + sig | ||
signode += addnodes.desc_name(name, name) | ||||
return m.group(0) | ||||
Thomas Kluyver
|
r18184 | |||
Thomas Kluyver
|
r18296 | class CellMagicRole(LineMagicRole): | ||
"""Cross reference role displayed with a %% prefix""" | ||||
prefix = "%%" | ||||
Thomas Kluyver
|
r18184 | |||
Thomas Kluyver
|
r18296 | def setup(app): | ||
Thomas Kluyver
|
r18294 | app.add_object_type('magic', 'magic', 'pair: %s; magic command', parse_magic) | ||
Thomas Kluyver
|
r18296 | StandardDomain.roles['magic'] = LineMagicRole() | ||
Thomas Kluyver
|
r18294 | app.add_object_type('cellmagic', 'cellmagic', 'pair: %s; cell magic', parse_cell_magic) | ||
Thomas Kluyver
|
r18296 | StandardDomain.roles['cellmagic'] = CellMagicRole() | ||