Skip to content

Commit

Permalink
Merge pull request #17 from morganwillcock/extension
Browse files Browse the repository at this point in the history
Insert indicies with Sphinx extension
  • Loading branch information
ericoporto authored Sep 12, 2018
2 parents 2f3e5fa + b6459b8 commit 54cd375
Show file tree
Hide file tree
Showing 3 changed files with 180 additions and 29 deletions.
105 changes: 105 additions & 0 deletions _extensions/h2r.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# -*- coding: utf-8 -*-
"""
sphinx.ext.h2r
~~~~~~~~~~~~~~
(markdown)headers-2-reStructuredText
For when you need indicies and you have none, this extension
generates some based on H2 and H3 markdown headers
h2r_script_object_from_header is a regular expression that matches
a script object in match group 1, from the H2 header
h2r_script_object_force_global is a dictionary which maps script
objects matched in H2 headers against a list of H3 headers which
should not be be treated as functions or properties
"""

import sphinx
import re
from sphinx.util import logging

logger = logging.getLogger(__name__)

## track subtitles to identify common attributes on script objects
seen_script_attr = []
## e.g. '.ID', '.Animate', etc.
shared_script_attr = []
## docname = (source offset, title, subtitle, is a script object)
changes = {}

def get_script_object(pattern, title):
match = re.search(pattern, title)

if match is not None:
return match.group(1)

return None

def map_page(app, env, docnames):
title = None
script_object = None

for docname in env.found_docs:
with open(env.doc2path(docname)) as f:
changes[docname] = []
offset = 0

for line in f:
if line.startswith('## '):
title = line[3:].strip()
script_object = get_script_object(app.config.h2r_script_object_from_header, title)
elif line.startswith('### '):
subtitle = line[4:].strip()

if isinstance(script_object, str):
logger.info('Found script object: %s.%s' % (script_object, subtitle))
changes[docname].append((offset, script_object, subtitle, True))

if subtitle in seen_script_attr:
if subtitle not in shared_script_attr:
shared_script_attr.append(subtitle)
else:
seen_script_attr.append(subtitle)
else:
logger.info('Found help section: %s, %s' % (title, subtitle))
changes[docname].append((offset, title, subtitle, False))

offset += len(line)

def add_indices(app, docname, source):
modified = []
offset = 0

for insert_at, title, subtitle, is_script in changes[docname]:
modified.append(source[0][offset:insert_at])
offset = insert_at
force_global = False

try:
if subtitle in app.config.h2r_script_object_force_global[title]:
force_global = True
except KeyError:
pass

if is_script:
if not force_global:
modified.append('.. index::\n single: %s.%s\n\n' % (title, subtitle))
else:
logger.info('Script item \'%s\' forced as global' % (subtitle))

if subtitle not in shared_script_attr:
modified.append('.. index::\n single: %s\n\n' % (subtitle))
else:
modified.append('.. index::\n pair: %s; %s\n\n' % (title, subtitle))

modified.append(source[0][offset:])
source[0] = ''.join(modified)
logger.info('Added %d indicies for document \'%s\'' % (len(changes[docname]), docname))

def setup(app):
app.add_config_value('h2r_script_object_from_header', r'(.*)', 'html')
app.add_config_value('h2r_script_object_force_global', {}, 'html')
app.connect('env-before-read-docs', map_page)
app.connect('source-read', add_indices)
return {'version': sphinx.__display_version__, 'parallel_read_safe': True}
79 changes: 75 additions & 4 deletions conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
import os
import sys
sys.path.insert(0, os.path.abspath('_extensions'))


# -- Project information -----------------------------------------------------
Expand All @@ -38,11 +38,82 @@
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['m2r']
extensions = ['m2r', 'h2r']

# Settings for m2r
m2r_parse_relative_links = True

# Settings for h2r
h2r_script_object_from_header = r'^(\w+) ([Pp]roperties|[Ff]unctions)'
h2r_script_object_force_global = {
'Display': [
'Display',
'DisplayAt',
'DisplayAtY',
'DisplayMessage',
'DisplayMessageAtY',
'DisplayTopBar'
],
'Game': [
'AbortGame',
'CallRoomScript',
'ClaimEvent',
'Debug',
'DeleteSaveSlot',
'DisableInterface',
'EnableInterface',
'EndCutscene',
'GetGameOption',
'GetGameParameter',
'GetGameSpeed',
'GetGlobalInt',
'GetGraphicalVariable',
'GetLocationType',
'GetTextHeight',
'GetTextWidth',
'GetTranslation',
'GiveScore',
'GetFontHeight',
'GetFontLineSpacing',
'InventoryScreen',
'IsGamePaused',
'IsInterfaceEnabled',
'IsInteractionAvailable',
'IsKeyPressed',
'IsTimerExpired',
'IsTranslationAvailable',
'MoveCharacterToHotspot',
'MoveCharacterToObject',
'PauseGame',
'QuitGame',
'Random',
'RestartGame',
'RestoreGameDialog',
'RestoreGameSlot',
'RunAGSGame',
'SaveGameDialog',
'SaveGameSlot',
'SaveScreenShot',
'SetAmbientLightLevel',
'SetAmbientTint',
'SetGameOption',
'SetGameSpeed',
'SetGlobalInt',
'SetGraphicalVariable',
'SetMultitaskingMode',
'SetRestartPoint',
'SetTextWindowGUI',
'SetTimer',
'SkipUntilCharacterStops',
'StartCutscene',
'UpdateInventory',
'UnPauseGame',
'Wait',
'WaitKey',
'WaitMouseKey'
]
}

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

Expand Down
25 changes: 0 additions & 25 deletions get-help-source.sh
Original file line number Diff line number Diff line change
Expand Up @@ -47,28 +47,3 @@ END {
printf("\n.. toctree::\n :glob:\n :hidden:\n\n *\n") >> outfile
}
' < source/Home.md && rm -f source/Home.md

# insert index directives
echo "--> Inserting index directives for H2 and H3"
sed -E -i.bak '
/^### / {
i\
.. index::
H;x
s/(.*)\n### +(.*)/ pair: \1; \2\
/
p
s/ pair: (.*);.*/\1/
x
}
/^## / {
s/^## +//
h
i\
.. index::
s/^/ single: /
p
s/ single: (.*)/\
## \1/
}
' source/*.md && rm -f source/*.md.bak

0 comments on commit 54cd375

Please sign in to comment.