MCPcopy Create free account
hub / github.com/Python-Markdown/markdown / _parseHeader

Method _parseHeader

markdown/extensions/codehilite.py:195–248  ·  view source on GitHub ↗

Determines language of a code block from shebang line and whether the said line should be removed or left in place. If the shebang line contains a path (even a single /) then it is assumed to be a real shebang line and left alone. However, if no path is given

(self)

Source from the content-addressed store, hash-verified

193 )
194
195 def _parseHeader(self) -> None:
196 """
197 Determines language of a code block from shebang line and whether the
198 said line should be removed or left in place. If the shebang line
199 contains a path (even a single /) then it is assumed to be a real
200 shebang line and left alone. However, if no path is given
201 (e.i.: `#!python` or `:::python`) then it is assumed to be a mock shebang
202 for language identification of a code fragment and removed from the
203 code block prior to processing for code highlighting. When a mock
204 shebang (e.i: `#!python`) is found, line numbering is turned on. When
205 colons are found in place of a shebang (e.i.: `:::python`), line
206 numbering is left in the current state - off by default.
207
208 Also parses optional list of highlight lines, like:
209
210 :::python hl_lines="1 3"
211 """
212
213 import re
214
215 # split text into lines
216 lines = self.src.split("\n")
217 # pull first line to examine
218 fl = lines.pop(0)
219
220 c = re.compile(r'''
221 (?:(?:^::+)|(?P<shebang>^[#]!)) # Shebang or 2 or more colons
222 (?P<path>(?:/\w+)*[/ ])? # Zero or 1 path
223 (?P<lang>[\w#.+-]*) # The language
224 \s* # Arbitrary whitespace
225 # Optional highlight lines, single- or double-quote-delimited
226 (hl_lines=(?P<quot>"|&#x27;)(?P<hl_lines>.*?)(?P=quot))?
227 ''&#x27;, re.VERBOSE)
228 # search first line for shebang
229 m = c.search(fl)
230 if m:
231 # we have a match
232 try:
233 self.lang = m.group('lang').lower()
234 except IndexError: # pragma: no cover
235 self.lang = None
236 if m.group('path'):
237 # path exists - restore first line
238 lines.insert(0, fl)
239 if self.options['linenos'] is None and m.group('shebang'):
240 # Overridable and Shebang exists - use line numbers
241 self.options['linenos'] = True
242
243 self.options['hl_lines'] = parse_hl_lines(m.group('hl_lines'))
244 else:
245 # No match
246 lines.insert(0, fl)
247
248 self.src = "\n".join(lines).strip("\n")
249
250
251# ------------------ The Markdown Extension -------------------------------

Callers 1

hiliteMethod · 0.95

Calls 2

parse_hl_linesFunction · 0.85
searchMethod · 0.80

Tested by

no test coverage detected