"""class RendererGenerates HTML from parsed token stream. Each instance has independentcopy of rules. Those can be rewritten with ease. Also, you can add newrules if you create plugin and adds new token types."""importinspectfromtypingimport(Any,ClassVar,MutableMapping,Optional,Sequence,)from.common.utilsimportunescapeAll,escapeHtmlfrom.tokenimportTokenfrom.utilsimportOptionsDicttry:fromtypingimportProtocolexceptImportError:# Python <3.8 doesn't have `Protocol` in the stdlibfromtyping_extensionsimportProtocol# type: ignore[misc]
[文档]classRendererHTML(RendererProtocol):"""Contains render rules for tokens. Can be updated and extended. Example: Each rule is called as independent static function with fixed signature: :: class Renderer: def token_type_name(self, tokens, idx, options, env) { # ... return renderedHTML :: class CustomRenderer(RendererHTML): def strong_open(self, tokens, idx, options, env): return '<b>' def strong_close(self, tokens, idx, options, env): return '</b>' md = MarkdownIt(renderer_cls=CustomRenderer) result = md.render(...) See https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.js for more details and examples. """__output__="html"def__init__(self,parser=None):self.rules={k:vfork,vininspect.getmembers(self,predicate=inspect.ismethod)ifnot(k.startswith("render")ork.startswith("_"))}
[文档]defrender(self,tokens:Sequence[Token],options:OptionsDict,env:MutableMapping)->str:"""Takes token stream and generates HTML. :param tokens: list on block tokens to render :param options: params of parser instance :param env: additional data from parsed input """result=""fori,tokeninenumerate(tokens):iftoken.type=="inline":asserttoken.childrenisnotNoneresult+=self.renderInline(token.children,options,env)eliftoken.typeinself.rules:result+=self.rules[token.type](tokens,i,options,env)else:result+=self.renderToken(tokens,i,options,env)returnresult
[文档]defrenderInline(self,tokens:Sequence[Token],options:OptionsDict,env:MutableMapping)->str:"""The same as ``render``, but for single token of `inline` type. :param tokens: list on block tokens to render :param options: params of parser instance :param env: additional data from parsed input (references, for example) """result=""fori,tokeninenumerate(tokens):iftoken.typeinself.rules:result+=self.rules[token.type](tokens,i,options,env)else:result+=self.renderToken(tokens,i,options,env)returnresult
[文档]defrenderToken(self,tokens:Sequence[Token],idx:int,options:OptionsDict,env:MutableMapping,)->str:"""Default token renderer. Can be overridden by custom function :param idx: token index to render :param options: params of parser instance """result=""needLf=Falsetoken=tokens[idx]# Tight list paragraphsiftoken.hidden:return""# Insert a newline between hidden paragraph and subsequent opening# block-level tag.## For example, here we should insert a newline before blockquote:# - a# >#iftoken.blockandtoken.nesting!=-1andidxandtokens[idx-1].hidden:result+="\n"# Add token name, e.g. `<img`result+=("</"iftoken.nesting==-1else"<")+token.tag# Encode attributes, e.g. `<img src="foo"`result+=self.renderAttrs(token)# Add a slash for self-closing tags, e.g. `<img src="foo" /`iftoken.nesting==0andoptions["xhtmlOut"]:result+=" /"# Check if we need to add a newline after this tagiftoken.block:needLf=Trueiftoken.nesting==1:ifidx+1<len(tokens):nextToken=tokens[idx+1]ifnextToken.type=="inline"ornextToken.hidden:# Block-level tag containing an inline tag.#needLf=FalseelifnextToken.nesting==-1andnextToken.tag==token.tag:# Opening tag + closing tag of the same type. E.g. `<li></li>`.#needLf=Falseresult+=">\n"ifneedLfelse">"returnresult
[文档]@staticmethoddefrenderAttrs(token:Token)->str:"""Render token attributes to string."""result=""forkey,valueintoken.attrItems():result+=" "+escapeHtml(key)+'="'+escapeHtml(str(value))+'"'returnresult
[文档]defrenderInlineAsText(self,tokens:Optional[Sequence[Token]],options:OptionsDict,env:MutableMapping,)->str:"""Special kludge for image `alt` attributes to conform CommonMark spec. Don't try to use it! Spec requires to show `alt` content with stripped markup, instead of simple escaping. :param tokens: list on block tokens to render :param options: params of parser instance :param env: additional data from parsed input """result=""fortokenintokensor[]:iftoken.type=="text":result+=token.contenteliftoken.type=="image":asserttoken.childrenisnotNoneresult+=self.renderInlineAsText(token.children,options,env)eliftoken.type=="softbreak":result+="\n"returnresult
[文档]deffence(self,tokens:Sequence[Token],idx:int,options:OptionsDict,env:MutableMapping,)->str:token=tokens[idx]info=unescapeAll(token.info).strip()iftoken.infoelse""langName=""langAttrs=""ifinfo:arr=info.split(maxsplit=1)langName=arr[0]iflen(arr)==2:langAttrs=arr[1]ifoptions.highlight:highlighted=options.highlight(token.content,langName,langAttrs)orescapeHtml(token.content)else:highlighted=escapeHtml(token.content)ifhighlighted.startswith("<pre"):returnhighlighted+"\n"# If language exists, inject class gently, without modifying original token.# May be, one day we will add .deepClone() for token and simplify this part, but# now we prefer to keep things local.ifinfo:# Fake token just to render attributestmpToken=Token(type="",tag="",nesting=0,attrs=token.attrs.copy())tmpToken.attrJoin("class",options.langPrefix+langName)return("<pre><code"+self.renderAttrs(tmpToken)+">"+highlighted+"</code></pre>\n")return("<pre><code"+self.renderAttrs(token)+">"+highlighted+"</code></pre>\n")
[文档]defimage(self,tokens:Sequence[Token],idx:int,options:OptionsDict,env:MutableMapping,)->str:token=tokens[idx]# "alt" attr MUST be set, even if empty. Because it's mandatory and# should be placed on proper position for tests.assert(token.attrsand"alt"intoken.attrs),'"image" token\'s attrs must contain `alt`'# Replace content with actual valuetoken.attrSet("alt",self.renderInlineAsText(token.children,options,env))returnself.renderToken(tokens,idx,options,env)