3838MASK = "\x01 " # stands for code's words, an address: never markup, wherever the stars are
3939IMAGE_MASK = "\x03 " # stands for an image, its text and address: words, never a link
4040LINK_MASK = "\x04 " # stands for a link's address (LINK's, http or https in lower case): its link's
41+ MASKS = (MASK , "\x02 " , IMAGE_MASK , LINK_MASK )
42+ SCHEME = re .compile (r"(?i)https?://" )
4143# on a line masked (_masked): `code`, **bold** (no space just inside the stars), [words](its address, masked)
4244INLINE = re .compile (r"`([^`\n]+)`|\*\*(?=\S)(.+?)(?<=\S)\*\*|(?<!!)\[([^\[\]\n]+)\]\((\x04+)\)" )
4345MD_SPECIAL = re .compile (r"([\\`*_~\[\]<>|&])" )
@@ -63,7 +65,7 @@ class Run(NamedTuple):
6365def _masked (line : str ) -> str :
6466 """The line with code's words, images and bare addresses as MASK: what no markup is read in (a "**" in code, in
6567 an address, closes no bold; an image is no link)."""
66- m = list ( line )
68+ m = [ " \x00 " if c in MASKS else c for c in line ] # (a mark written in the text is none of these )
6769
6870 def blank (a : int , b : int , mark : str = MASK ) -> None :
6971 m [a :b ] = mark * (b - a )
@@ -76,8 +78,14 @@ def blank(a: int, b: int, mark: str = MASK) -> None:
7678 once = "" .join (m )
7779 # a bare address that starts outside any "[words](address)" and runs through one keeps it: the link is in its words
7880 candidates = [(x .start (), x .end ()) for x in LINK .finditer (once )]
79- bare = [(u .start (), u .start () + len (_trim_url (u .group ()))) for u in URL .finditer (once )
80- if not any (a <= u .start () < b for a , b in candidates )]
81+ bare : List [Tuple [int , int ]] = []
82+ for st in SCHEME .finditer (once ): # each address from its own start (one inside a link takes none after it)
83+ p = st .start ()
84+ if any (a <= p < b for a , b in candidates ) or (bare and p < bare [- 1 ][1 ]):
85+ continue
86+ u = URL .match (once , p )
87+ if u :
88+ bare .append ((p , p + len (_trim_url (u .group ()))))
8189 hidden = list (once ) # the links whole as MASK: no bare address starts in one, nor runs on from one
8290 for x in LINK .finditer (once ):
8391 if any (a < x .start () < b for a , b in bare ):
@@ -148,8 +156,10 @@ def _md_line(runs: List[Run]) -> str:
148156 for bold , group in itertools .groupby (runs , key = lambda r : r .bold ):
149157 parts = []
150158 for r in group :
151- if r .kind == "code" :
152- parts .append ("`%s`" % r .words )
159+ if r .kind == "code" : # (fenced by more backticks than any run in its words)
160+ ticks = "`" * (max ([len (t ) for t in re .findall (r"`+" , r .words )] + [0 ]) + 1 )
161+ pad = " " if r .words .startswith ("`" ) or r .words .endswith ("`" ) else ""
162+ parts .append ("%s%s%s%s%s" % (ticks , pad , r .words , pad , ticks ))
153163 elif r .kind == "link" :
154164 parts .append ("[%s](%s)" % (_md_escape (r .words ), r .url .replace ("&" , "\\ &" ))) # (no entity: "©")
155165 elif r .kind == "url" :
@@ -203,7 +213,10 @@ def markdown(self, src: Optional[str] = None) -> str:
203213 runs'."""
204214 k = self .kind
205215 if k == "code" :
206- body = self ["body" ] if src is None else src [self ["body_at" ]:self ["body_at" ] + len (self ["body" ])]
216+ body = self ["body" ]
217+ if src is not None : # (as written: a name in it too; a CRLF as an LF, as the body reads)
218+ body = "\n " .join (line [:- 1 ] if line .endswith ("\r " ) else line
219+ for line in src [self ["body_at" ]:self ["body_end" ]].split ("\n " )) if body else ""
207220 ticks = max ([len (t ) for t in re .findall (r"`{3,}" , body )] + [2 ]) + 1 # a fence the body never closes
208221 return "%s%s\n %s%s%s" % ("`" * ticks , self .get ("lang" ) or "" , body , "\n " if body else "" , "`" * ticks )
209222 # a line of only - = * _ is words, in a quote or a list too (never a heading's underline)
@@ -254,7 +267,8 @@ def end_of(j: int) -> int:
254267 body = "\n " .join (lines [i + 1 :j ])
255268 last = min (j , n - 1 ) # not closed: it runs to the end
256269 out .append (Block (kind = "code" , lang = fence .group (2 ).lower (), body = body , start = offs [i ], end = end_of (last ),
257- body_at = offs [i + 1 ] if i + 1 < n else end_of (i )))
270+ body_at = offs [i + 1 ] if i + 1 < n else end_of (i ),
271+ body_end = (offs [j ] - 1 ) if j < n else len (text or "" )))
258272 i = j + 1
259273 continue
260274 if not line .strip ():
0 commit comments