MCPcopy Create free account
hub / github.com/ronreiter/interactive-tutorials / _getLang

Method _getLang

markdown/extensions/codehilite.py:128–173  ·  view source on GitHub ↗

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

(self)

Source from the content-addressed store, hash-verified

126
127
128 def _getLang(self):
129 """
130 Determines language of a code block from shebang lines and whether said
131 line should be removed or left in place. If the sheband line contains a
132 path (even a single /) then it is assumed to be a real shebang lines and
133 left alone. However, if no path is given (e.i.: #!python or :::python)
134 then it is assumed to be a mock shebang for language identifitation of a
135 code fragment and removed from the code block prior to processing for
136 code highlighting. When a mock shebang (e.i: #!python) is found, line
137 numbering is turned on. When colons are found in place of a shebang
138 (e.i.: :::python), line numbering is left in the current state - off
139 by default.
140
141 """
142
143 import re
144
145 #split text into lines
146 lines = self.src.split("\n")
147 #pull first line to examine
148 fl = lines.pop(0)
149
150 c = re.compile(r'''
151 (?:(?:::+)|(?P<shebang>[#]!)) # Shebang or 2 or more colons.
152 (?P<path>(?:/\w+)*[/ ])? # Zero or 1 path
153 (?P<lang>[\w+-]*) # The language
154 ''&#x27;, re.VERBOSE)
155 # search first line for shebang
156 m = c.search(fl)
157 if m:
158 # we have a match
159 try:
160 self.lang = m.group('lang').lower()
161 except IndexError:
162 self.lang = None
163 if m.group('path'):
164 # path exists - restore first line
165 lines.insert(0, fl)
166 if m.group('shebang'):
167 # shebang exists - use line numbers
168 self.linenos = True
169 else:
170 # No match
171 lines.insert(0, fl)
172
173 self.src = "\n".join(lines).strip("\n")
174
175
176

Callers 1

hiliteMethod · 0.95

Calls 3

splitMethod · 0.45
popMethod · 0.45
insertMethod · 0.45

Tested by

no test coverage detected