Debian Codegraph @

docs/use.md

raw
1 # Use and customize
2
3 This section describes major ways to use and control `sphinx-copybutton`'s behavior.
4
5 (configure-copy-text)=
6
7 ## Automatic exclusion of prompts from the copies
8
9 The Sphinx code highlighter, Pygments, tags the prompts (`>>>`, `...`,
10 `In [1]:`, `$`) of console sessions.
11 Sphinx by default excludes prompts from being selectable.
12 However, by default `sphinx-copybutton` will copy these prompts (for backwards compatibility with the other "manually-selectable exclude" options).
13
14 To make `sphinx-copybutton` skip all prompt characters generated by pygments, use the following setting:
15
16 ```{code-block} python
17 copybutton_exclude = '.linenos, .gp'
18 ```
19
20 To **skip all console outputs**, add `.go` to the string above.
21
22 For automatic exclusion, make sure to use the right highlight language.
23 For example: `pythonconsole` instead of `python`, `console` instead of `bash`,
24 `ipythonconsole` instead of `ipython`, etc.
25
26 This setting can also be used to exclude arbitrary css classes from
27 being copied. By default `.linenos` are excluded. `.linenos` is the
28 Sphinx default for line numbers, `.gp` is the Pygments class for the
29 prompts, and `.go` is the class for console outputs.
30
31 This setting conflicts with most of pattern-based copy-selection
32 settings below, so should not be used with them. This will hopefully
33 be improved in the future.
34
35
36 ## Strip and configure input prompts for code cells
37
38 By default, `sphinx-copybutton` will copy the entire contents of a code
39 block when the button is clicked. For many languages, it is common to
40 include **input prompts** with your examples, along with the outputs from
41 running the code.
42
43 `sphinx-copybutton` provides functionality to both
44 strip input prompts, as well as *only* select lines that begin with a prompt.
45 This allows users to click the button and *only* copy the input text,
46 excluding the prompts and outputs.
47
48 To define the prompt text that you'd like removed from copied text in your code
49 blocks, use the following configuration value in your `conf.py` file:
50
51 ```python
52 copybutton_prompt_text = "myinputprompt"
53 ```
54
55 When this variable is set, `sphinx-copybutton` will remove the prompt from
56 the beginning of any lines that start with the text you specify. In
57 addition, *only* the lines that contain prompts will be copied if any are
58 discovered. If no lines with prompts are found, then the full contents of
59 the cell will be copied.
60
61 For example, to exclude traditional Python prompts from your copied code,
62 use the following configuration:
63
64 ```python
65 copybutton_prompt_text = ">>> "
66 ```
67
68 ### Using regexp prompt identifiers
69
70 If your prompts are more complex than a single string, then you can use a regexp to match with.
71
72 :::{note}
73 Keep in mind that the
74 [RegExp](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
75 you are writing is
76 [evaluated in JavaScript](https://github.com/executablebooks/sphinx-copybutton/blob/a58da090dae6f4d38870929e0258a0c8ee626f8f/sphinx_copybutton/_static/copybutton_funcs.js#L7)
77 and not in Python.
78 In some edge cases this might lead to different results.
79 :::
80
81 If you enclose your regexp in a raw string (`r""`),
82 you can easily test that your RegExp matches all the wanted prompts,
83 i.e. at [RegEx101].
84
85 For example this documentation uses the following configuration:
86
87 ```python
88 copybutton_prompt_text = r">>> |\.\.\. |\$ |In \[\d*\]: | {2,5}\.\.\.: | {5,8}: "
89 copybutton_prompt_is_regexp = True
90 ```
91
92 Which matches the following prompts and their continuations if they exist:
93
94 ```{eval-rst}
95 .. list-table::
96 :widths: 30 37 33
97 :header-rows: 1
98
99 * - Prompt Name
100 - RegEx Pattern
101 - Matched String Examples
102 * - Python Repl + continuation
103 - ``r'>>> |\.\.\. '``
104 - ``'>>> '``, ``'... '``
105 * - Bash
106 - ``r'\$ '``
107 - ``'$ '``
108 * - ``ipython`` and ``qtconsole`` + continuation
109 - ``r'In \[\d*\]: | {2,5}\.\.\.: '``
110 - ``'In []: '``, ``'In [999]: '``, ``' ...: '``, ``' ...: '``
111 * - ``jupyter-console`` + continuation
112 - ``r'In \[\d*\]: | {5,8}: '``
113 - ``'In []: '``, ``'In [999]: '``, ``' ...: '``, ``' ...: '``
114 ```
115
116 An example usage would be the `ipython`-directive:
117
118 ```restructuredtext
119 ``ipython`` and ``qtconsole`` style:
120
121 .. code-block:: ipython
122
123 In [1]: first
124 ...: continuation
125 output
126 In [2]: second
127
128 ``jupyter`` style:
129
130 .. code-block:: ipython
131
132 In [1]: first
133 : continuation
134 output
135 In [2]: second
136 ```
137
138 `ipython` and `qtconsole` style:
139
140 ```ipython
141 In [1]: first
142 ...: continuation
143 output
144 In [2]: second
145 ```
146
147 `jupyter` style:
148
149 ```ipython
150 In [1]: first
151 : continuation
152 output
153 In [2]: second
154 ```
155
156 If you want a detailed explanation how the RegEx's work you can also use [RegEx101] and read the `Explanation` sidebar.
157
158 ### Configure whether *only* lines with prompts are copied
159
160 By default, if sphinx-copybutton detects lines that begin with code prompts,
161 it will *only* copy the text in those lines (after stripping the prompts).
162 This assumes that the rest of the code block contains outputs that shouldn't
163 be copied.
164
165 To disable this behavior, use the following configuration in `conf.py`:
166
167 ```python
168 copybutton_only_copy_prompt_lines = False
169 ```
170
171 In this case, all lines of the code blocks will be copied after the prompts
172 are stripped.
173
174 ### Configure whether the input prompts should be stripped
175
176 By default, sphinx-copybutton will remove the prompt text from lines
177 according to the value of `copybutton_prompt_text`.
178
179 To disable this behavior and copy the full text of lines with prompts
180 (for example, if you'd like to copy *only* the lines with prompts, but not
181 strip the prompts), use the following configuration in `conf.py`:
182
183 ```python
184 copybutton_remove_prompts = False
185 ```
186
187 ## Keep *empty* lines
188
189 By default, sphinx-copybutton will also copy / pass through empty lines,
190 determined by `line.trim() === ''`.
191
192 To disable copying empty lines, use the following configuration in `conf.py`:
193
194 ```python
195 copybutton_copy_empty_lines = False
196 ```
197
198 ## Multi-line snippets
199
200 Multi-line snippets are single commands that continue across multiple lines (usually to save horizontal space).
201 `sphinx-copybutton` tries to copy this text with the expectation that you'll want to past the text as a single line in some other application.
202 See below for how to control this.
203
204 ### Honor line continuation characters when copying multline-snippets
205
206 Sometimes you may wish to copy a code block like this one:
207
208 ```bash
209 $ datalad download-url http://www.tldp.org/LDP/Bash-Beginners-Guide/Bash-Beginners-Guide.pdf \
210 --dataset . \
211 -m "add beginners guide on bash" \
212 -O books/bash_guide.pdf
213 ```
214
215 Assuming that you specified `$` as your prompt, sphinx-copybutton will only copy
216 the first line by default.
217
218 To copy all lines above, you can use the following configuration:
219
220 ```python
221 copybutton_line_continuation_character = "\\"
222 ```
223
224 Note that if we want to define `\` as the line continuation character, we have to "escape"
225 it with another `\`, as with any Python string that should carry a literal `\`.
226
227 Next, this configuration will make the code look for lines to copy based on the rules above,
228 but if one of the lines to be copied contains a line continuation character,
229 then the next line will be automatically copied, regardless of whether it matches the other
230 rules.
231
232 ### Honor HERE-document syntax when copying multiline-snippets
233
234 [HERE-documents](https://en.wikipedia.org/wiki/Here_document) are a form of multiline string literals
235 in which line breaks and other whitespace (including indentation) is preserved.
236 For example:
237
238 ```bash
239 $ cat << EOT > notes.txt
240 This is an example sentence.
241 Put some indentation on this line.
242
243 EOT
244 ```
245
246 Executing this codeblock in the terminal will create a file `notes.txt` with the exact
247 text from line two of the codeblock until (but not including) the final line containing `EOT`.
248
249 However, assuming that you specified `$` as your prompt, sphinx-copybutton will only copy
250 the first line by default.
251
252 sphinx-copybutton can be configured to copy the whole "HERE-document" by using the following
253 configuration:
254
255 ```python
256 copybutton_here_doc_delimiter = "EOT"
257 ```
258
259 This will continue to look for lines to copy based on the rules above,
260 but if one of the lines to be copied contains the defined delimiter (here: `EOT`),
261 then all following lines will be copied literally until the next delimiter is
262 encountered in a line.
263
264 ## Change the copy button image
265
266 To use a different image for your copy buttons, do the following:
267
268 1. Find the `<svg>` code for the image that you'd like to use.
269 For example, find an SVG from [Font Awesome](https://fontawesome.com/), [Tabler](https://tablericons.com/), or [Octicons](https://primer.style/octicons/).
270 2. Set the `copybutton_image_svg` variable in your `conf.py` to the SVG that you'd like to use.
271
272 For example, if you wanted to use a **clipboard icon** instead of the default copy button icon, do the following:
273
274 1. Copy the `Clipboard Icon SVG` from [the Tabular icons pack](https://tablericons.com/).
275 Here is the SVG for reference:
276
277 ```
278 <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-clipboard" width="44" height="44" viewBox="0 0 24 24" stroke-width="1.5" stroke="#000000" fill="none" stroke-linecap="round" stroke-linejoin="round">
279 <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
280 <path d="M9 5h-2a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-12a2 2 0 0 0 -2 -2h-2" />
281 <rect x="9" y="3" width="6" height="4" rx="2" />
282 </svg>
283 ```
284
285 2. Configure `sphinx_copybutton` to use this icon instead, via the following configuration:
286
287 ```python
288 # Note that we do not include `_static`
289 # because the path should be *relative* to the static folder.
290 copybutton_image_svg = """
291 <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-clipboard" width="44" height="44" viewBox="0 0 24 24" stroke-width="1.5" stroke="#000000" fill="none" stroke-linecap="round" stroke-linejoin="round">
292 <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
293 <path d="M9 5h-2a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-12a2 2 0 0 0 -2 -2h-2" />
294 <rect x="9" y="3" width="6" height="4" rx="2" />
295 </svg>
296 """
297 ```
298
299 When you re-build your documentation, you should see this new icon in your copy buttons.
300
301 ## Add or remove copy buttons to any element with a CSS selector
302
303 By default, `sphinx-copybutton` will add a copy button to all elements
304 that match the following selection:
305
306 ```css
307 div.highlight pre
308 ```
309
310 To change this selector, use the following configuration in `conf.py`:
311
312 ```python
313 copybutton_selector = "div.myselector"
314 ```
315
316 In this case, all `<div>` elements that have a `myselector` will have a copy button
317 added to them.
318
319 ### Remove copybuttons using a CSS selector
320
321 You can prevent copybuttons from being added to code blocks by using [the `:not()` CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/:not).
322
323 For example, you can define a copybutton_selector like so:
324
325 ```python
326 copybutton_selector = "div:not(.no-copybutton) > div.highlight > pre"
327 ```
328
329 Then add a `no-copybutton` to any code blocks you don't want copied:
330
331 ````{example}
332 ```{code-block}
333 :class: no-copybutton
334 print("This won't have a copy button!")
335 ```
336 ````
337
338 ### A typical code cell HTML structure in Sphinx
339
340 Using CSS to modify the copy button requires you to know what kind of HTML structure code cells have in your documentation.
341 The easiest way to determine this is to look at the HTML generated by your Sphinx version.
342 A code block like this:
343
344 ```python
345 print("hi!")
346 ```
347
348 roughly results in this HTML:
349
350 ```html
351 <div class="{EXTRA CLASSES} highlight-python notranslate">
352 <div class="highlight">
353 <pre id="codecell7">
354 CODE CELL CONTENT HERE
355 </pre>
356 </div>
357 </div>
358 ```
359
360 Where `{EXTRA CLASSES}` consists of any extra classes you've added with the `:class:` keyword.
361
362 ## Modify the copy button's style with CSS
363
364 You can style the CSS of the copy button however you'd like by writing your own CSS with your Sphinx build.
365 To do so, first create a custom CSS file and add it to your Sphinx build:
366
367 1. Create a `custom.css` file in the `_static/` folder of your documentation.
368 2. Add the CSS file to Sphinx by ensuring that the following configuration exists in your `conf.py` file (see [the Sphinx documentation for more details](https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-html_css_files)):
369
370 ```python
371 html_static_path = ["_static"]
372 html_css_files = ["custom.css"]
373 ```
374
375 Next you can add CSS rules that use the `.copybtn` selector to modify the behavior of the button.
376
377 :::{admonition} example: button visibility
378 :class: tip
379 To make the copy button visible by default (not just when a code cell is hovered):
380
381 ```css
382 button.copybtn {
383 opacity: 1;
384 }
385 ```
386 :::
387
388 :::{admonition} example: style the color of the button
389 ```css
390 button.copybtn {
391 color: red;
392 }
393 ```
394 :::
395
396 See the [Sphinx documentation on custom CSS for more information](https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-html_static_path).
397
398 [regex101]: https://regex101.com