Skip to content

Instantly share code, notes, and snippets.

@sambrightman
Last active October 4, 2020 21:47
Show Gist options
  • Save sambrightman/9b722db816c0fae4d67645ead33f0443 to your computer and use it in GitHub Desktop.
Save sambrightman/9b722db816c0fae4d67645ead33f0443 to your computer and use it in GitHub Desktop.
Get equivalent text for ReStructured Text literal includes when they aren't supported
import docutils.nodes
def unparse_literal_includes(doc, indent=''):
texts = {}
for node in doc.traverse(docutils.nodes.literal_block):
if 'source' in node.attributes:
classes = iter(node.attributes['classes'])
names = iter(node.attributes['names'])
primary_class = next(classes, None)
if primary_class == 'code':
language = next(classes, '')
# warn if any remain?
primary_class = next(classes, None)
primary_name = next(names, None)
lines = ['.. code:: {}'.format(language)]
else:
# warn if any remain?
primary_name = next(names, None)
lines = ['.. parsed-literal::']
if primary_class is not None:
lines.append(':class: {}'.format(primary_class))
if primary_name is not None:
lines.append(':name: {}'.format(primary_name))
lines.extend(node.astext().splitlines())
lines.append('')
texts[node.attributes['source']] = '\n '.join('{}{}'.format(indent, line) for line in lines)
return texts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment