# Process fromtypingimportListfrom.state_inlineimportStateInlinefrom..tokenimportTokenfrom..common.utilsimportisSpace,normalizeReference
[文档]defimage(state:StateInline,silent:bool):label=Nonehref=""oldPos=state.posmax=state.posMax# /* ! */ifstate.srcCharCode[state.pos]!=0x21:returnFalse# /* [ */ifstate.pos+1<state.posMaxandstate.srcCharCode[state.pos+1]!=0x5B:returnFalselabelStart=state.pos+2labelEnd=state.md.helpers.parseLinkLabel(state,state.pos+1,False)# parser failed to find ']', so it's not a valid linkiflabelEnd<0:returnFalsepos=labelEnd+1# /* ( */ifpos<maxandstate.srcCharCode[pos]==0x28:## Inline link## [link]( <href> "title" )# ^^ skipping these spacespos+=1whilepos<max:code=state.srcCharCode[pos]ifnotisSpace(code)andcode!=0x0A:breakpos+=1ifpos>=max:returnFalse# [link]( <href> "title" )# ^^^^^^ parsing link destinationstart=posres=state.md.helpers.parseLinkDestination(state.src,pos,state.posMax)ifres.ok:href=state.md.normalizeLink(res.str)ifstate.md.validateLink(href):pos=res.poselse:href=""# [link]( <href> "title" )# ^^ skipping these spacesstart=poswhilepos<max:code=state.srcCharCode[pos]ifnotisSpace(code)andcode!=0x0A:breakpos+=1# [link]( <href> "title" )# ^^^^^^^ parsing link titleres=state.md.helpers.parseLinkTitle(state.src,pos,state.posMax)ifpos<maxandstart!=posandres.ok:title=res.strpos=res.pos# [link]( <href> "title" )# ^^ skipping these spaceswhilepos<max:code=state.srcCharCode[pos]ifnotisSpace(code)andcode!=0x0A:breakpos+=1else:title=""# /* ) */ifpos>=maxorstate.srcCharCode[pos]!=0x29:state.pos=oldPosreturnFalsepos+=1else:## Link reference#if"references"notinstate.env:returnFalse# /* [ */ifpos<maxandstate.srcCharCode[pos]==0x5B:start=pos+1pos=state.md.helpers.parseLinkLabel(state,pos)ifpos>=0:label=state.src[start:pos]pos+=1else:pos=labelEnd+1else:pos=labelEnd+1# covers label == '' and label == undefined# (collapsed reference link and shortcut reference link respectively)ifnotlabel:label=state.src[labelStart:labelEnd]label=normalizeReference(label)ref=state.env["references"].get(label,None)ifnotref:state.pos=oldPosreturnFalsehref=ref["href"]title=ref["title"]## We found the end of the link, and know for a fact it's a valid link# so all that's left to do is to call tokenizer.#ifnotsilent:content=state.src[labelStart:labelEnd]tokens:List[Token]=[]state.md.inline.parse(content,state.md,state.env,tokens)token=state.push("image","img",0)token.attrs={"src":href,"alt":""}token.children=tokensorNonetoken.content=contentiftitle:token.attrSet("title",title)# note, this is not part of markdown-it JS, but is useful for renderersiflabelandstate.md.options.get("store_labels",False):token.meta["label"]=labelstate.pos=posstate.posMax=maxreturnTrue