def depart_title(self, node): close_tag = self.context[-1] if (self.permalink_text and self.builder.add_permalinks and node.parent.hasattr('ids') and node.parent['ids']): aname = '' for id in node.parent['ids']: if self.builder.env.domaindata['std']['labels'].has_key(id): ref_text = '. Label :ref:`%s`' % id aname = id break if aname: link_text = ':ref:' else: ref_text = '' aname = node.parent['ids'][0] link_text = self.permalink_text # add permalink anchor if close_tag.startswith('</h'): what = u'<a class="headerlink" href="#%s" ' % aname + u'title="%s">%s</a>' % ( _('Permalink to this headline') + ref_text, link_text) if 0: print 'what:', repr(what) print 'aname:', repr(aname) self.body.append(what) elif close_tag.startswith('</a></h'): what = u'</a><a class="headerlink" href="#%s" ' % aname + u'title="%s">%s' % ( _('Permalink to this headline') + ref_text, link_text) if 0: print 'what:', repr(what) print 'aname:', repr(aname) self.body.append(what) HTMLTranslator.depart_title(self, node)
def __init__(self, builder, document): HTMLTranslator.__init__(self, builder, document) self.builder = builder self.settings = settings = document.settings # document title, subtitle display self.body_pre_docinfo = [] # author, date, etc. self.docinfo = [] self.whole_contents = LazyEvaluateArray() self.body, self.reference, self.headings = self.initial_contents() self.fragment = [] self.section_level = 0 self.context = [] self.topic_classes = [] self.colspecs = [] self.compact_p = 1 self.compact_simple = None self.compact_field_list = None self.in_docinfo = None self.in_sidebar = None self.title = [] self.subtitle = [] self.in_document_title = 0 self.in_mailto = 0 self.author_in_authors = None self.kindle_title = None self.images = []
def visit_nxt_tab_head(self, node): self.body.append(''' <input name="{0}" type="radio" id="{1}" class="nxt_input" {2}/> '''.format(node.tabs_id, node.tab_id, node.tab_checked)) self.body.append(''' <label for="{0}" class="nxt_label">'''.format(node.tab_id)) HTMLTranslator.visit_Text(self, node)
def visit_image(self, node): self.body.append( self.starttag(node, 'div', '', CLASS='figure %s' % ' '.join(node['classes']))) HTMLTranslator.visit_image(self, node)
def visit_literal_block(self, node): if node['ids']: self.highlighter.set_node_id(node['ids'][0]) else: self.highlighter.set_node_id(None) HTMLTranslator.visit_literal_block(self, node)
def visit_reference(self, node): if self.in_subnav and 'subnav-toggle' in node['classes']: toggle = nodes.raw( '', '<b class="dropdown-toggle caret" data-toggle="dropdown"></b>') toggle['format'] = 'html' node.append(toggle) SphinxHTMLTranslator.visit_reference(self, node)
def __init__(self, builder, *args, **kwds): """ constructor """ HTMLTranslator.__init__(self, builder, *args, **kwds) for name, f1, f2 in builder._function_node: setattr(self.__class__, "visit_" + name, f1) setattr(self.__class__, "depart_" + name, f2)
def __init__(self, *args, **kwargs): HTMLTranslator.__init__(self, *args, **kwargs) self.section_count = 0 self.body_stack = [] self.current_slide = None self.slide_data = []
def visit_nxt_details(self, node): self.body.append(''' <details> <summary onclick="this.addEventListener('click', e => e.preventDefault())"><span>{0}</span></summary>'''.format( node.summary_text)) HTMLTranslator.visit_container(self, node)
def visit_reference(self, node): if node.hasattr('refuri') and node['refuri'].find( 'GAUGE_LATEST_VERSION_PLACEHOLDER') >= 0: refuri = node.attributes['refuri'] node.attributes['refuri'] = refuri.replace( 'GAUGE_LATEST_VERSION_PLACEHOLDER', environ.get('GAUGE_LATEST_VERSION')) HTMLTranslator.visit_reference(self, node)
def visit_nxt_details(self, node: Element) -> None: """Handles the nxt_details directive.""" self.body.append("""<details> <summary onclick="this.addEventListener('click', e => e.preventDefault())"><span>{0}</span></summary>""".format( node.summary_text)) HTMLTranslator.visit_container(self, node)
def visit_title(self, node): if isinstance(node.parent, nodes.section): level = self.section_level + self.initial_header_level - 1 tag = 'h%s' % level self.body.append(self.starttag(node, tag, '')) self.context.append('</%s>\n' % tag) else: HTMLTranslator.visit_subtitle(self, node)
def visit_title(self, node): if isinstance(node.parent, nodes.section): level = self.section_level + self.initial_header_level - 1 tag = 'h%s' % level self.body.append(self.starttag(node, tag, '')) self.context.append('</%s>\n' % tag) else: HTMLTranslator.visit_title(self, node)
def bs_visit_enumerated_list(self, node): # Tests dont work with rst-class. # Removes our arabic class from unstyled list if 'list-unstyled' in node['classes']: # pragma: no cover node.attributes.pop('enumtype', None) # then, Pass to parent HTMLTranslator.visit_enumerated_list_original(self, node) # pragma: no cover
def __init__(self, builder, document, *args, **kwargs): HTMLTranslator.__init__(self, builder, document, *args, **kwargs) self._title = None # section title self.parent = None self.add_to_toc = False self.order = 0 self.add_permalinks = False self.css = ['main.css'] self._images = set()
def depart_title(self, node): if node.parent.hasattr('ids') and node.parent['ids'] and \ self.section_level == 2: print "TITLE",self.section_level,node.parent['ids'][0] #self._title = node.parent['ids'][0] self._title = striptags(''.join(self.body[1:])) print "\t",str(node)[:50] print "\tBODY", self.body[:4] HTMLTranslator.depart_title(self, node)
def depart_title(self, node): if self.current_slide and isinstance(node.parent, (nodes.section, slide)): self.current_slide.title = ''.join(self.body) self.pop_body() else: HTMLTranslator.depart_title(self, node) title = ''.join(self.body) self.pop_body() self.body.append(title)
def visit_nxt_tab_head(self, node): self.body.append(''' <input name={0} type=radio id={1} class="nojs" {2}/>'''.format( node.tabs_id, node.tab_id, node.checked)) self.body.append(''' <label for={0} id={1}><a href=#{1} onclick="nxt_tab_click(event)">'''. format(node.tab_id, node.label_id)) HTMLTranslator.visit_Text(self, node)
def __init__(self, builder, document, *args, **kwargs): HTMLTranslator.__init__(self, builder, document, *args, **kwargs) self._title = None # section title self.parent = None self.add_to_toc = False self.order = 0 self.add_permalinks = False self.css = ['main.css'] self._images = set() self.doc_path = document.attributes['source']
def depart_title(self, node): if self.current_slide and isinstance(node.parent, (nodes.section, slide)): self.current_slide.title = "".join(self.body) self.pop_body() else: HTMLTranslator.depart_title(self, node) title = "".join(self.body) self.pop_body() self.body.append(title)
def visit_image(self, node): olduri = node['uri'] s = olduri.lower() go = True go = go and not Image is None go = go and not (s.endswith('svg') or s.endswith('svgz') or s.endswith('swf')) go = go and not (node.has_key('width') or node.has_key('height') or node.has_key('scale')) if go and node.has_key('classes'): go = go and not 'screenshot-detail' in node['classes'] if go: # Try to figure out image height and width. Docutils does that too, # but it tries the final file name, which does not necessarily exist # yet at the time the HTML file is written. try: im = Image.open(os.path.join(self.builder.srcdir, olduri)) except (IOError, # Source image can't be found or opened UnicodeError): # PIL doesn't like Unicode paths. go = False # better warn? else: im_width = str(im.size[0]) im_height = str(im.size[1]) del im if go: # rewrite the URI if the environment knows about it if olduri in self.builder.images: node['uri'] = posixpath.join(self.builder.imgpath, self.builder.images[olduri]) atts = {} atts['src'] = node['uri'] if not node.has_key('classes'): node['classes'] = ['img-scaling'] elif not 'img-scaling' in node['classes']: node['classes'].append('img-scaling') else: pass atts['style'] = 'max-width: %spx;' % im_width if node.has_key('alt'): atts['alt'] = node['alt'] else: atts['alt'] = node['uri'] if node.has_key('align'): self.body.append('<div align="%s" class="align-%s">' % (node['align'], node['align'])) self.context.append('</div>\n') else: self.context.append('') self.body.append(self.emptytag(node, 'img', '', **atts)) else: del s, go HTMLTranslator.visit_image(self,node) return
def visit_github_object_link_node(translator: HTMLTranslator, node: GitHubObjectLinkNode): """ Visit a :class:`~.GitHubObjectLinkNode`. :param translator: :param node: The node being visited. """ translator.body.append(f'<b class="github-object">') translator.visit_reference(node)
def depart_github_object_link_node(translator: HTMLTranslator, node: GitHubObjectLinkNode): """ Depart an :class:`~.GitHubObjectLinkNode`. :param translator: :param node: The node being visited. """ translator.depart_reference(node) translator.body.append("</b>")
def visit_title(self, node): if isinstance(node.parent, slide) or node.parent.attributes.get("include-as-slide", False): slide_level = node.parent.attributes.get("level", self.section_level) level = max(slide_level + self.initial_header_level - 1, 1) tag = "h%s" % level self.body.append(self.starttag(node, tag, "")) self.context.append("</%s>\n" % tag) else: HTMLTranslator.visit_title(self, node)
def depart_issue_node(translator: HTMLTranslator, node: IssueNode): """ Depart an :class:`~.IssueNode`. :param translator: :param node: The node being visited. """ if node.has_tooltip: translator.depart_reference(node) translator.body.append("</abbr>")
def visit_nxt_tab_head(self, node: Element) -> None: """Handles the nxt_tab_head node in an individual tab.""" self.body.append(""" <input name={0} type=radio id={1} class=nojs {2}/>""".format( node.tabs_id, node.tab_id, node.checked)) self.body.append("""<label for={0} id={1}> <a href=#{1} onclick="nxt_tab_click(event)">""".format( node.tab_id, node.label_id)) HTMLTranslator.visit_Text(self, node)
def visit_document(self, node): SphinxHTMLTranslator.visit_document(self, node) # used to detect that bullet_lists are for the global and page tocs self.is_partial = node.get('source') == '<partial node>' self.page_toc_position = self.builder.config.html_theme_options.get( 'page_toc_position', 'subnav') self.toc_nav = self.page_toc_position == 'nav' self.toc_subnav = self.page_toc_position == 'subnav' self.toc_sidebar = self.page_toc_position.startswith('sidebar-') self.page_toc_handled_first = False if self.toc_subnav: self.page_toc_maxdepth = 1 else: self.page_toc_maxdepth = int( self.builder.config.html_theme_options.get('page_toc_maxdepth', '-1')) self.in_subnav = False if not self.is_partial and self.toc_subnav: docname = os.path.relpath( node['source'], self.builder.env.srcdir ) suffixes = self.builder.config.source_suffix # retain backwards compatibility with sphinx < 1.3 if isinstance(suffixes, basestring): suffixes = [suffixes] for suffix in suffixes: if docname.endswith(suffix): docname = docname[:-len(suffix)] break self.page_toc = self.builder.env.get_toc_for(docname, self.builder) toc_empty = bool( not len(self.page_toc.children) or len(self.page_toc.children[0].children) <= 1) if not toc_empty: toc_empty = True for child in self.page_toc.children[0].children[1]: if isinstance(child, nodes.list_item): toc_empty = False break if not toc_empty: # for page toc in the subnav, skip the first list self.page_toc = self.page_toc.children[0].children[1] self.page_toc['classes'].append('nav') else: self.page_toc = None
def visit_title(self, node): if isinstance(node.parent, nodes.section) and not self.builder.has_title(self.document): h_level = self.section_level + self.initial_header_level - 1 if h_level == 1: # Confluence take first title for page title from rst # It use for making internal links self.builder.set_title(self.document, node.children[0]) # ignore first header; document must have title header raise nodes.SkipNode HTMLTranslator.visit_title(self, node)
def depart_title(self, node): if node.parent.hasattr("ids") and node.parent["ids"]: aname = node.parent["ids"][0] if self.builder.app.config.slide_link_to_html: self.body.append( u'<a class="headerlink" href="%s#%s" ' % (html.html_path(self.builder), aname) + u'title="%s">%s</a>' % (_("View HTML"), self.builder.app.config.slide_html_slide_link_symbol) ) HTMLTranslator.depart_title(self, node)
def visit_title(self, node): if isinstance(node.parent, nodes.section) and not TitlesCache.has_title(self.document): h_level = self.section_level + self.initial_header_level - 1 if h_level == 1: # Confluence take first title for page title from rst # It use for making internal links TitlesCache.set_title(self.document, node.children[0]) # ignore first header; document must have title header raise nodes.SkipNode HTMLTranslator.visit_title(self, node)
def dispatch_visit(self, node): # Be super defensive at the top-level so we don't break builds try: if hasattr(self.builder.env, 'comment_config_map'): config_map = self.builder.env.comment_config_map page_config = config_map.get(self.builder.current_docname, []) else: page_config = {'header'} if is_commentable(node, page_config): self.handle_visit_commentable(node) except Exception as e: print('[Commenting] Visit Error: %s' % e) HTMLTranslator.dispatch_visit(self, node)
def depart_title(self, node): # print "--TITLE", node.text if not self._title: self._title = striptags(''.join(self.body[1:])) print "\n\n**title", self.section_level, ''.join(self.body[1:])[:150] low_level = self.section_level \ <= int(self.builder.config.mobi_chapter_level) if node.parent.getattr('ids', False) and low_level: print "TITLE", self.section_level, node.parent['ids'][0] self._title = striptags(''.join(self.body[1:])) print "\t", str(node)[:50] print "\tBODY", self.body[:4] else: print "FALSE" HTMLTranslator.depart_title(self, node)
def depart_title(self, node): if node.parent.hasattr('ids') and node.parent['ids']: aname = node.parent['ids'][0] if self.builder.app.config.slide_link_to_html: self.body.append(u'<a class="headerlink" href="%s#%s" ' % ( html.html_path(self.builder), aname, ) + u'title="%s">%s</a>' % ( _('View HTML'), self.builder.app.config.slide_html_slide_link_symbol, )) HTMLTranslator.depart_title(self, node)
def visit_section(self, node): # insert the subnav after the section heading + optional lead if not self.is_partial and \ self.toc_subnav and \ self.page_toc and \ self.section_level == 0: index = 0 children = node.children if len(children) and isinstance(children[0], nodes.title): index = 1 if index and len(children) > 1 and 'lead' in children[1].get('classes'): index = 2 node.children.insert(index, self.page_toc) SphinxHTMLTranslator.visit_section(self, node)
def visit_literal_block(self, node): # pragma: no cover # type: (nodes.Node) -> None if node.rawsource != node.astext(): # most probably a parsed-literal block -- don't highlight return HTMLTranslator.visit_literal_block(self, node) lang = self.highlightlang linenos = node.rawsource.count('\n') >= \ self.highlightlinenothreshold - 1 highlight_args = node.get('highlight_args', {}) if 'language' in node: # code-block directives lang = node['language'] highlight_args['force'] = True if 'linenos' in node: linenos = node['linenos'] if lang is self.highlightlang_base: # only pass highlighter options for original language opts = self.highlightopts else: opts = {} highlighted = self.highlighter.highlight_block( node.rawsource, lang, opts=opts, linenos=linenos, location=(self.builder.current_docname, node.line), **highlight_args) node['classes'] += [('highlight-%s' % lang), 'literal-block'] joined_clss = " ".join(node['classes']) starttag = self.starttag(node, 'div', suffix='', CLASS=joined_clss) self.body.append(starttag + highlighted + '</div>\n') raise nodes.SkipNode
def visit_title(self, node): if (isinstance(node.parent, slide) or node.parent.attributes.get('include-as-slide', False)): slide_level = node.parent.attributes.get('level', self.section_level) level = max( slide_level + self.initial_header_level - 1, 1, ) tag = 'h%s' % level self.body.append(self.starttag(node, tag, '')) self.context.append('</%s>\n' % tag) else: HTMLTranslator.visit_title(self, node)
def visit_asset_node(translator: HTMLTranslator, node: AssetNode): """ Visit an :class:`~.AssetNode`. :param translator: :param node: The node being visited. """ if not hasattr(translator, "_asset_node_seen_files"): # Files that have already been seen translator._asset_node_seen_files = [] # type: ignore assets_out_dir = PathPlus(translator.builder.outdir) / "_assets" assets_out_dir.maybe_make(parents=True) source_file = PathPlus(translator.builder.confdir) / node["source_file"] if source_file not in translator._asset_node_seen_files and source_file.is_file(): # type: ignore # Avoid unnecessary copies of potentially large files. translator._asset_node_seen_files.append(source_file) # type: ignore shutil.copy2(source_file, assets_out_dir) elif not source_file.is_file(): stderr_writer(Fore.RED(f"{translator.builder.current_docname}: Asset file '{source_file}' not found.")) translator.context.append('') return # Create the HTML current_uri = (pathlib.PurePosixPath('/') / translator.builder.current_docname).parent refuri = posixpath.relpath(f"/_assets/{node['refuri']}", str(current_uri)) translator.body.append(f'<a class="reference external" href="{refuri}")/">') translator.context.append("</a>")
def visit_block_quote(self, node): quote_slide_tags = ['paragraph', 'attribution'] # see if this looks like a quote slide if (len(node.children) <= 2 and [c.tagname for c in node.children] == quote_slide_tags[:len(node.children)]): # process this as a quote slide # first child must be a paragraph, process it as a <q> element p = node.children[0] self.body.append(self.starttag(node, 'q')) for text_item in p: text_item.walkabout(self) self.body.append('</q>\n') # optional second child must be an attribution, processing as a <div> # following the <q> if len(node.children) > 1: attr = node.children[1] self.body.append(self.starttag(attr, 'div', CLASS="author")) for text_item in attr: text_item.walkabout(self) self.body.append('</div>\n') # skip all normal processing raise nodes.SkipNode else: return HTMLTranslator.visit_block_quote(self, node)
def visit_section(self, node): # insert the subnav after the section heading + optional lead if not self.is_partial and \ self.toc_subnav and \ self.page_toc and \ self.section_level == 0: index = 0 children = node.children if len(children) and isinstance(children[0], nodes.title): index = 1 if index and len(children) > 1 and 'lead' in children[1].get( 'classes'): index = 2 node.children.insert(index, self.page_toc) SphinxHTMLTranslator.visit_section(self, node)
def depart_title(self, node): SphinxHTMLTranslator.depart_title(self, node) # The second to last element added contains a "headerlink" class. # See https://bitbucket.org/birkenfeld/sphinx/src/72dceb35264e9429c8d9bb1a249a638ac21f0524/sphinx/writers/html.py#lines-501 if len(self.body) > 2 and "headerlink" in self.body[-2]: match = HREF.search(self.body[-2]) if match: link = match.group(1) # If header link was injected and the href could be # found, then change the href node to a closing </a> # anchor tag. Look at most at the 10 most recent nodes # to find where the anchor was opened. for i in range(-2, max(-10, -len(self.body)), -1): if self.body[i].startswith("<h"): self.body[i] += '<a href="' + link + '">' self.body[-2] = "</a>"
def visit_title(self, node): if (isinstance(node.parent, slide) or node.parent.attributes.get('include-as-slide', False)): slide_level = node.parent.attributes.get( 'level', self.section_level) level = max( slide_level + self.initial_header_level - 1, 1, ) tag = 'h%s' % level self.body.append(self.starttag(node, tag, '')) self.context.append('</%s>\n' % tag) else: HTMLTranslator.visit_title(self, node)
def visit_title(self, node): self.push_body() if isinstance(node.parent, slide) or node.parent.attributes.get("include-as-slide", False): slide_level = node.parent.attributes.get("level", self.section_level) level = max(slide_level + self.initial_header_level - 1, 1) self.current_slide.level = level # tag = 'h%s' % level # self.body.append(self.starttag(node, tag, '')) # self.context.append('</%s>\n' % tag) if self.current_slide and isinstance(node.parent, (nodes.section, slide)): self.current_slide.title = node.astext().strip() else: HTMLTranslator.visit_title(self, node)
def visit_image(self, node): olduri = node['uri'] import pdb;pdb.set_trace() # rewrite the URI if the environment knows about it # if olduri in self.builder.images: # node['uri'] = posixpath.join(self.builder.imgpath, # self.builder.images[olduri]) # #import pdb; pdb.set_trace() print "IMAGE!!!", node, node['uri'], path.abspath(node['uri']) if path.abspath(olduri) != olduri: pass # # relative # dest = path.join(self.builder.outdir,olduri) # print "COPYING TO", dest # olduri = path.join(path.dirname(self.doc_path), # dest) self._images.add(path.abspath(olduri)) self.builder.ebook.add_image(path.abspath(olduri), olduri, id='image_{0}'.format(len(self._images))) HTMLTranslator.visit_image(self, node)
def visit_issue_node(translator: HTMLTranslator, node: IssueNode): """ Visit an :class:`~.IssueNode`. If the node points to a valid issue / pull request, add a tooltip giving the title of the issue / pull request and a hyperlink to the page on GitHub. :param translator: :param node: The node being visited. """ issue_title = get_issue_title(node.issue_url) if issue_title: node.has_tooltip = True translator.body.append(f'<abbr title="{issue_title}">') translator.visit_reference(node) else: warnings.warn(f"Issue/Pull Request #{node.issue_number} not found.")
def visit_title(self, node): if not isinstance(node.parent, nodes.section): HTMLTranslator.visit_title(self, node) return h_level = self.section_level + self.initial_header_level - 1 atts = {} if (len(node.parent) >= 2 and isinstance(node.parent[1], nodes.subtitle)): atts['CLASS'] = 'with-subtitle' self.body.append(self.starttag(node, 'h%s' % h_level, '', **atts)) ids = node.parent.get('ids', []) for id_ in ids: self.body.append('<span id="%s" class="bookmark"></span>' % id_) atts = {} if node.hasattr('refid'): atts['class'] = 'toc-backref' atts['href'] = '#' + node['refid'] if atts: self.body.append(self.starttag({}, 'a', '', **atts)) close_tag = '</a></h%s>\n' % (h_level) else: close_tag = '</h%s>\n' % (h_level) self.context.append(close_tag)
def add_secnumber(self, node): """ overwrites this method to catch errors due when it is a single document being processed """ if node.get('secnumber'): HTMLTranslator.add_secnumber(self, node) elif len(node.parent['ids']) > 0: HTMLTranslator.add_secnumber(self, node) else: n = len(self.builder.secnumbers) node.parent['ids'].append("custom_label_%d" % n) HTMLTranslator.add_secnumber(self, node)
def dispatch_visit(self, node): if is_commentable(node): self.handle_visit_commentable(node) HTMLTranslator.dispatch_visit(self, node)
def visit_image(self, node): print "IMAGE!!!", node, node['uri'], path.abspath(node['uri']) self._images.add(path.abspath(node['uri'])) print "images", self._images HTMLTranslator.visit_image(self, node)
def visit_title(self, node): if self.section_level == 1: raise nodes.SkipNode HTMLTranslator.visit_title(self, node)
def visit_section(self, node): old_ids = node.get('ids', []) node['ids'] = ['s-' + i for i in old_ids] node['ids'].extend(old_ids) HTMLTranslator.visit_section(self, node) node['ids'] = old_ids
def __init__(self, builder, *args, **kwds): HTMLTranslator.__init__(self, builder, *args, **kwds) self.initial_header_level = 1
def __init__(self, builder, *args, **kwargs): HTMLTranslator.__init__(self, builder, *args, **kwargs) self.comment_class = 'sphinx-has-comment'
def depart_bullet_list(self, node): SphinxHTMLTranslator.depart_bullet_list(self, node) if not self.is_partial and self.toc_subnav and node is self.page_toc: self.in_subnav = False self.body.append('</div>\n</div>\n')
def __init__(self, *args, **kwargs): HTMLTranslator.__init__(self, *args, **kwargs) self.section_count = 0