# Process [link](<to> "stuff")from..common.utilsimportnormalizeReference,isSpacefrom.state_inlineimportStateInline
[文档]deflink(state:StateInline,silent:bool):href=""title=""label=NoneoldPos=state.posmaximum=state.posMaxstart=state.posparseReference=Trueifstate.srcCharCode[state.pos]!=0x5B:# /* [ */returnFalselabelStart=state.pos+1labelEnd=state.md.helpers.parseLinkLabel(state,state.pos,True)# parser failed to find ']', so it's not a valid linkiflabelEnd<0:returnFalsepos=labelEnd+1ifpos<maximumandstate.srcCharCode[pos]==0x28:# /* ( */## Inline link## might have found a valid shortcut link, disable reference parsingparseReference=False# [link]( <href> "title" )# ^^ skipping these spacespos+=1whilepos<maximum:code=state.srcCharCode[pos]ifnotisSpace(code)andcode!=0x0A:breakpos+=1ifpos>=maximum: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<maximum: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<maximumandstart!=posandres.ok:title=res.strpos=res.pos# [link]( <href> "title" )# ^^ skipping these spaceswhilepos<maximum:code=state.srcCharCode[pos]ifnotisSpace(code)andcode!=0x0A:breakpos+=1ifpos>=maximumorstate.srcCharCode[pos]!=0x29:# /* ) */# parsing a valid shortcut link failed, fallback to referenceparseReference=Truepos+=1ifparseReference:## Link reference#if"references"notinstate.env:returnFalseifpos<maximumandstate.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"][label]iflabelinstate.env["references"]elseNone)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:state.pos=labelStartstate.posMax=labelEndtoken=state.push("link_open","a",1)token.attrs={"href":href}iftitle: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.md.inline.tokenize(state)token=state.push("link_close","a",-1)state.pos=posstate.posMax=maximumreturnTrue