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