')
raise nodes.SkipNode
class HTMLHelpBuilder(StandaloneHTMLBuilder):
"""
Builder that also outputs Windows HTML help project, contents and
index files. Adapted from the original Doc/tools/prechm.py.
"""
name = 'htmlhelp'
epilog = __('You can now run HTML Help Workshop with the .htp file in '
'%(outdir)s.')
# don't copy the reST source
copysource = False
supported_image_types = ['image/png', 'image/gif', 'image/jpeg']
# don't add links
add_permalinks = False
# don't add sidebar etc.
embedded = True
# don't generate search index or include search page
search = False
lcid = 0x409
encoding = 'cp1252'
def init(self) -> None:
# the output files for HTML help is .html by default
self.out_suffix = '.html'
self.link_suffix = '.html'
super().init()
# determine the correct locale setting
locale = chm_locales.get(self.config.language)
if locale is not None:
self.lcid, self.encoding = locale
def prepare_writing(self, docnames: set[str]) -> None:
super().prepare_writing(docnames)
self.globalcontext['html5_doctype'] = False
def update_page_context(
self,
pagename: str,
templatename: str,
ctx: dict[str, Any],
event_arg: str,
) -> None:
ctx['encoding'] = self.encoding
# escape the `body` part to 7-bit ASCII
body = ctx.get("body")
if body is not None:
ctx["body"] = re.sub(r"[^\x00-\x7F]", self._escape, body)
@staticmethod
def _escape(match: re.Match[str]) -> str:
codepoint = ord(match.group(0))
if codepoint in codepoint2name:
return f"&{codepoint2name[codepoint]};"
return f"{codepoint};"
def handle_finish(self) -> None:
self.copy_stopword_list()
self.build_project_file()
self.build_toc_file()
self.build_hhx(self.outdir, self.config.htmlhelp_basename)
def write_doc(self, docname: str, doctree: nodes.document) -> None:
for node in doctree.findall(nodes.reference):
# add ``target=_blank`` attributes to external links
if node.get('internal') is None and 'refuri' in node:
node['target'] = '_blank'
super().write_doc(docname, doctree)
def render(self, name: str, context: dict[str, Any]) -> str:
template = SphinxRenderer(template_dir)
return template.render(name, context)
@progress_message(__('copying stopword list'))
def copy_stopword_list(self) -> None:
"""Copy a stopword list (.stp) to outdir.
The stopword list contains a list of words the full text search facility
shouldn't index. Note that this list must be pretty small. Different
versions of the MS docs claim the file has a maximum size of 256 or 512
bytes (including \r\n at the end of each line). Note that "and", "or",
"not" and "near" are operators in the search language, so no point
indexing them even if we wanted to.
"""
template = path.join(template_dir, 'project.stp')
filename = path.join(self.outdir, self.config.htmlhelp_basename + '.stp')
copy_asset_file(template, filename)
@progress_message(__('writing project file'))
def build_project_file(self) -> None:
"""Create a project file (.hhp) on outdir."""
# scan project files
project_files: list[str] = []
for root, dirs, files in os.walk(self.outdir):
dirs.sort()
files.sort()
in_staticdir = root.startswith(path.join(self.outdir, '_static'))
for fn in sorted(files):
if (in_staticdir and not fn.endswith('.js')) or fn.endswith('.html'):
fn = relpath(path.join(root, fn), self.outdir)
project_files.append(fn.replace(os.sep, '\\'))
context = {
'outname': self.config.htmlhelp_basename,
'title': self.config.html_title,
'version': self.config.version,
'project': self.config.project,
'lcid': self.lcid,
'master_doc': self.config.master_doc + self.out_suffix,
'files': project_files,
}
body = self.render('project.hhp', context)
filename = Path(self.outdir, f'{self.config.htmlhelp_basename}.hhp')
filename.write_text(body, encoding=self.encoding, errors='xmlcharrefreplace')
@progress_message(__('writing TOC file'))
def build_toc_file(self) -> None:
"""Create a ToC file (.hhp) on outdir."""
toctree = self.env.get_and_resolve_doctree(self.config.master_doc, self,
prune_toctrees=False)
visitor = ToCTreeVisitor(toctree)
matcher = NodeMatcher(addnodes.compact_paragraph, toctree=True)
for node in toctree.findall(matcher):
node.walkabout(visitor)
context = {
'body': visitor.astext(),
'suffix': self.out_suffix,
'short_title': self.config.html_short_title,
'master_doc': self.config.master_doc,
'domain_indices': self.domain_indices,
}
body = self.render('project.hhc', context)
filename = Path(self.outdir, f'{self.config.htmlhelp_basename}.hhc')
filename.write_text(body, encoding=self.encoding, errors='xmlcharrefreplace')
def build_hhx(self, outdir: str | os.PathLike[str], outname: str) -> None:
logger.info(__('writing index file...'))
index = IndexEntries(self.env).create_index(self)
filename = Path(outdir, outname + '.hhk')
with open(filename, 'w', encoding=self.encoding, errors='xmlcharrefreplace') as f:
f.write('