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

Method hilite

markdown/extensions/codehilite.py:136–193  ·  view source on GitHub ↗

Pass code to the [Pygments](https://pygments.org/) highlighter with optional line numbers. The output should then be styled with CSS to your liking. No styles are applied by default - only styling hooks (i.e.: ` `). returns : A string of html.

(self, shebang: bool = True)

Source from the content-addressed store, hash-verified

134 self.options = options
135
136 def hilite(self, shebang: bool = True) -> str:
137 """
138 Pass code to the [Pygments](https://pygments.org/) highlighter with
139 optional line numbers. The output should then be styled with CSS to
140 your liking. No styles are applied by default - only styling hooks
141 (i.e.: `<span class="k">`).
142
143 returns : A string of html.
144
145 """
146
147 self.src = self.src.strip('\n')
148
149 if self.lang is None and shebang:
150 self._parseHeader()
151
152 if pygments and self.use_pygments:
153 try:
154 lexer = get_lexer_by_name(self.lang, **self.options)
155 except ValueError:
156 try:
157 if self.guess_lang:
158 lexer = guess_lexer(self.src, **self.options)
159 else:
160 lexer = get_lexer_by_name('text', **self.options)
161 except ValueError: # pragma: no cover
162 lexer = get_lexer_by_name('text', **self.options)
163 if not self.lang:
164 # Use the guessed lexer's language instead
165 self.lang = lexer.aliases[0]
166 lang_str = f'{self.lang_prefix}{self.lang}'
167 if isinstance(self.pygments_formatter, str):
168 try:
169 formatter = get_formatter_by_name(self.pygments_formatter, **self.options)
170 except ClassNotFound:
171 formatter = get_formatter_by_name('html', **self.options)
172 else:
173 formatter = self.pygments_formatter(lang_str=lang_str, **self.options)
174 return highlight(self.src, lexer, formatter)
175 else:
176 # just escape and build markup usable by JavaScript highlighting libraries
177 txt = self.src.replace('&', '&amp;')
178 txt = txt.replace('<', '&lt;')
179 txt = txt.replace('>', '&gt;')
180 txt = txt.replace('"', '&quot;')
181 classes = []
182 if self.lang:
183 classes.append('{}{}'.format(self.lang_prefix, _escape_attrib_html(self.lang)))
184 if self.options['linenos']:
185 classes.append('linenums')
186 class_str = ''
187 if classes:
188 class_str = ' class="{}"'.format(' '.join(classes))
189 return '<pre class="{}"><code{}>{}\n</code></pre>\n'.format(
190 self.options['cssclass'],
191 class_str,
192 txt
193 )

Callers 3

runMethod · 0.95
runMethod · 0.95
assertOutputEqualsMethod · 0.80

Calls 2

_parseHeaderMethod · 0.95
_escape_attrib_htmlFunction · 0.85

Tested by 1

assertOutputEqualsMethod · 0.64