Debian Codegraph @

docs/extensions/code_hilite.md

raw
1 title: CodeHilite Extension
2
3 # CodeHilite
4
5 ## Summary
6
7 The CodeHilite extension adds code/syntax highlighting to standard
8 Python-Markdown code blocks using [Pygments][].
9
10 [Pygments]: http://pygments.org/
11
12 This extension is included in the standard Markdown library.
13
14 !!! Note
15
16 This extension is in __maintenance mode__. We will continue to fix bugs
17 and keep it up-to-date with the core parser, but no new features or
18 changes in behavior will be made. If you need a feature that this
19 extension does not offer, then you have three options (1) find an
20 existing [third-party extension] which meets your needs, (2) [build your
21 own extension], or (3) fork this extension (pursuant to its licensing
22 requirements) and maintain it as a third-party extension.
23
24 We recommend [Highlight] as an actively developed alternative.
25
26 [third-party extension]: index.md#third-party-extensions
27 [build your own extension]: api.md
28 [Highlight]: https://facelessuser.github.io/pymdown-extensions/extensions/highlight/
29
30 ## Setup
31
32 ### Step 1: Download and Install Pygments
33
34 You will also need to [download][dl] and install the Pygments package on your
35 `PYTHONPATH`. The CodeHilite extension will produce HTML output without
36 Pygments, but it won't highlight anything (same behavior as setting
37 `use_pygments` to `False`).
38
39 [dl]: http://pygments.org/download/
40
41 ### Step 2: Add CSS Classes
42
43 You will need to define the appropriate CSS classes with appropriate rules.
44 The CSS rules either need to be defined in or linked from the header of your
45 HTML templates. Pygments can generate CSS rules for you. Just run the following
46 command from the command line:
47
48 ```bash
49 pygmentize -S default -f html -a .codehilite > styles.css
50 ```
51
52 If you are using a different `css_class` (default: `.codehilite`), then
53 set the value of the `-a` option to that class name. The CSS rules will be
54 written to the `styles.css` file which you can copy to your site and link from
55 your HTML templates.
56
57 If you would like to use a different theme, swap out `default` for the desired
58 theme. For a list of themes installed on your system (additional themes can be
59 installed via Pygments plugins), run the following command:
60
61 ```bash
62 pygmentize -L style
63 ```
64
65 See Pygments' excellent [documentation] for more details. If no language is
66 defined, Pygments will attempt to guess the language. When that fails, the code
67 block will not be highlighted.
68
69 !!! seealso "See Also"
70
71 GitHub user [richeland] has provided a number of different [CSS style
72 sheets][rich] which work with Pygments along with a [preview] of each theme.
73 The `css_class` used is `.highlight`. Therefore, one would need to override the
74 [`css_class`](#css_class) option when using richeland's CSS styles. However, the
75 Python-Markdown project makes no guarantee that richeland's CSS styles will
76 work with the version of Pygments you are using. To ensure complete
77 compatibility, you should generate the CSS rules from your own installation
78 of Pygments.
79
80 [richeland]: https://github.com/richleland
81 [rich]: https://github.com/richleland/pygments-css
82 [preview]: https://richleland.github.io/pygments-css/
83 [documentation]: http://pygments.org/docs/
84
85 ## Syntax
86
87 The CodeHilite extension follows the same [syntax][] as regular Markdown code
88 blocks, with one exception. The highlighter needs to know what language to use for
89 the code block. There are three ways to tell the highlighter what language the
90 code block contains and each one has a different result.
91
92 !!! Note
93 The format of the language identifier only effects the display of line numbers
94 if `linenums` is set to `None` (the default). If set to `True` or `False`
95 (see [Usage](#usage) below) the format of the identifier has no effect on the
96 display of line numbers -- it only serves as a means to define the language
97 of the code block.
98
99 [syntax]: https://daringfireball.net/projects/markdown/syntax#precode
100
101 ### Shebang (with path)
102
103 If the first line of the code block contains a shebang, the language is derived
104 from that and line numbers are used.
105
106 ```md
107 #!/usr/bin/python
108 # Code goes here ...
109 ```
110
111 Will result in:
112
113 #!/usr/bin/python
114 # Code goes here ...
115
116 ### Shebang (no path)
117
118 If the first line contains a shebang, but the shebang line does not contain a
119 path (a single `/` or even a space), then that line is removed from the code
120 block before processing. Line numbers are used.
121
122 ```md
123 #!python
124 # Code goes here ...
125 ```
126
127 Will result in:
128
129 #!python
130 # Code goes here ...
131
132 ### Colons
133
134 If the first line begins with three or more colons, the text following the
135 colons identifies the language. The first line is removed from the code block
136 before processing and line numbers are not used.
137
138 ```md
139 :::python
140 # Code goes here ...
141 ```
142
143 Will result in:
144
145 :::python
146 # Code goes here ...
147
148 Certain lines can be selected for emphasis with the colon syntax. When
149 using Pygments' default CSS styles, emphasized lines have a yellow background.
150 This is useful to direct the reader's attention to specific lines.
151
152 ```md
153 :::python hl_lines="1 3"
154 # This line is emphasized
155 # This line isn't
156 # This line is emphasized
157 ```
158
159 Will result in:
160
161 :::python hl_lines="1 3"
162 # This line is emphasized
163 # This line isn't
164 # This line is emphasized
165
166 !!! Note
167 `hl_lines` is named for Pygments' option meaning "highlighted lines".
168
169 ### When No Language is Defined
170
171 CodeHilite is completely backwards compatible so that if a code block is
172 encountered that does not define a language, the block is simply wrapped in
173 `<pre>` tags and output.
174
175 ```md
176 # Code goes here ...
177 ```
178
179 Will result in:
180
181 # Code goes here ...
182
183 Lets see the source for that:
184
185 ```html
186 <div class="codehilite"><pre><code># Code goes here ...
187 </code></pre></div>
188 ```
189
190 !!! Note
191 When no language is defined, the Pygments highlighting engine will try to guess
192 the language (unless `guess_lang` is set to `False`). Upon failure, the same
193 behavior will happen as described above.
194
195 ## Usage
196
197 See [Extensions](index.md) for general extension usage. Use `codehilite` as the
198 name of the extension.
199
200 See the [Library Reference](../reference.md#extensions) for information about
201 configuring extensions.
202
203 The following options are provided to configure the output:
204
205 * **`linenums`**{ #linenums }:
206 An alias to Pygments' `linenos` formatter option. Possible values are `True` for yes, `False` for no and `None`
207 for auto. Defaults to `None`.
208
209 Using `True` will force every code block to have line numbers, even when
210 using colons (`:::`) for language identification.
211
212 Using `False` will turn off all line numbers, even when using shebangs
213 (`#!`) for language identification.
214
215 * **`guess_lang`**{ #guess_lang }:
216 Automatic language detection. Defaults to `True`.
217
218 Using `False` will prevent Pygments from guessing the language, and thus
219 highlighting blocks only when you explicitly set the language.
220
221 * **`css_class`**{ #css_class }:
222 An alias to Pygments `cssclass` formatter option. Set CSS class name for the wrapper `<div>` tag. Defaults to
223 `codehilite`.
224
225 * **`pygments_style`**{ #pygments_style }:
226 Pygments HTML Formatter Style (`ColorScheme`). Defaults to `default`.
227
228 !!! Note
229 This is useful only when `noclasses` is set to `True`, otherwise the
230 CSS styles must be provided by the end user.
231
232 * **`noclasses`**{ #noclasses }:
233 Use inline styles instead of CSS classes. Defaults to `False`.
234
235 * **`use_pygments`**{ #use_pygments }:
236 Specifies the use of Pygments in generating the output.
237
238 If `True` (the default) and Pygments is available, CodeHilite will use
239 Pygments to analyze and format the output. Additionally, if using Pygments
240 &gt;= 2.4, the output will be wrapped in `<code>` tags, whereas earlier
241 versions will not.
242
243 Otherwise, Pygments will not be used. If a language is defined for a code block, it will be assigned to the
244 `<code>` tag as a class in the manner suggested by the [HTML5 spec][spec] and may be used by a JavaScript library
245 in the browser to highlight the code block. See the [`lang_prefix`](#lang_prefix) option to customize the prefix.
246
247 * **`lang_prefix`**{ #lang_prefix }:
248 The prefix prepended to the language class assigned to the HTML `<code>` tag. Default: `language-`.
249
250 * **`pygments_formatter`**{ #pygments_formatter }:
251 This option can be used to change the Pygments formatter used for highlighting code blocks. By default, this
252 is set to the string `'html'`, which means it'll use the default `HtmlFormatter` provided by Pygments.
253
254 This can be set to a string representing any of the other default formatters, or set to a formatter class (or
255 any callable).
256
257 The code's language is always passed to the formatter as an extra option `lang_str`, with the value formatted as
258 `{lang_prefix}{lang}`. If the language is unspecified, the language guessed by Pygments will be used. While
259 this option has no effect to the Pygments's builtin formatters, a user can make use of the language in their custom
260 formatter. See an example below.
261
262 To see what formatters are available and how to subclass an existing formatter, please visit [Pygments
263 documentation on this topic][pygments formatters].
264
265 * Any other Pygments' options:
266
267 All other options are accepted and passed on to Pygments' lexer and formatter. Therefore,
268 valid options include any options which are accepted by the [html formatter] or
269 whichever [lexer] the code's language uses. Invalid options are ignored without error.
270
271 A trivial example:
272
273 ```python
274 markdown.markdown(some_text, extensions=['codehilite'])
275 ```
276
277 To keep the code block's language in the Pygments generated HTML output, one can provide a custom Pygments formatter
278 that takes the `lang_str` option. For example,
279
280 ```python
281 from pygments.formatters import HtmlFormatter
282 from markdown.extensions.codehilite import CodeHiliteExtension
283
284
285 class CustomHtmlFormatter(HtmlFormatter):
286 def __init__(self, lang_str='', **options):
287 super().__init__(**options)
288 # lang_str has the value {lang_prefix}{lang}
289 # specified by the CodeHilite's options
290 self.lang_str = lang_str
291
292 def _wrap_code(self, source):
293 yield 0, f'<code class="{self.lang_str}">'
294 yield from source
295 yield 0, '</code>'
296
297
298 some_text = '''\
299 :::python
300 print('hellow world')
301 '''
302
303 markdown.markdown(
304 some_text,
305 extensions=[CodeHiliteExtension(pygments_formatter=CustomHtmlFormatter)],
306 )
307 ```
308
309 The formatter above will output the following HTML structure for a code block:
310
311 ```html
312 <div class="codehilite">
313 <pre>
314 <code class="language-python">
315 ...
316 </code>
317 </pre>
318 </div>
319 ```
320
321 [html formatter]: https://pygments.org/docs/formatters/#HtmlFormatter
322 [lexer]: https://pygments.org/docs/lexers/
323 [spec]: https://www.w3.org/TR/html5/text-level-semantics.html#the-code-element
324 [pygments formatters]: https://pygments.org/docs/formatters/