├── .gitignore ├── LICENSE ├── README.md ├── examples ├── full_width.py └── start.py ├── handout ├── __init__.py ├── blocks.py ├── data │ ├── favicon.ico │ ├── highlight.css │ ├── highlight.js │ ├── marked.js │ ├── script.js │ └── style.css ├── handout.py ├── tests │ └── test_handout.py └── tools.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Python 2 | __pycache__/ 3 | .pytest_cache/ 4 | *.py[cod] 5 | 6 | # Pip 7 | pip-selfcheck.json 8 | *.whl 9 | *.egg 10 | *.egg-info 11 | 12 | # Setuptools 13 | /build 14 | /dist 15 | *.eggs 16 | 17 | # Mac 18 | .DS_Store 19 | 20 | # Example 21 | /output 22 | /examples/output 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Handout 2 | 3 | [![PyPI](https://img.shields.io/pypi/v/handout.svg)](https://pypi.python.org/pypi/handout/#history) 4 | 5 | Turn Python scripts into handouts with Markdown comments and inline figures. An 6 | alternative to Jupyter notebooks without hidden state that supports any text 7 | editor. 8 | 9 | | Code | Handout | 10 | | ---- | ------- | 11 | | ![Code](https://i.imgur.com/YEvUB9U.png) | ![Handout](https://i.imgur.com/dEGxaAz.png) | 12 | 13 | ## Getting started 14 | 15 | You use Python Handout as a library inside a normal Python program: 16 | 17 | 1. Install via `pip3 install -U handout`. 18 | 2. Run your script via `python3 script.py`. (You can start with 19 | `examples/start.py` from the repository.) 20 | 3. Open `output/index.html` in your browser to view the result. 21 | 4. Iterate and refresh your browser. 22 | 23 | ## Features 24 | 25 | Create the handout via `doc = handout.Handout(outdir)` to access these features: 26 | 27 | | Feature | Example | 28 | | ------- | ------- | 29 | | Add [Markdown text][markdown] as triple-quote comments. | `"""Markdown text"""` | 30 | | Add text via `print()` syntax. | `doc.add_text('text:', variable)` | 31 | | Add image from array or url. | `doc.add_image(image, 'png', width=1)` | 32 | | Add video from array or url. | `doc.add_video(video, 'gif', fps=30, width=1)` | 33 | | Add matplotlib figure. | `doc.add_figure(fig, width=1)` | 34 | | Add custom HTML. | `doc.add_html(string)` | 35 | | Insert added items and save to `/index.html`. | `doc.show()` | 36 | 37 | [markdown]: https://commonmark.org/help/ 38 | 39 | ## Questions 40 | 41 | Feel free to create an issue on Github. 42 | -------------------------------------------------------------------------------- /examples/full_width.py: -------------------------------------------------------------------------------- 1 | import handout 2 | import numpy as np 3 | 4 | doc = handout.Handout('output/full_width') 5 | 6 | # Add some images. 7 | for _ in range(16): 8 | image = np.ones((64, 64, 3)) * np.random.uniform(0, 1, 3) 9 | doc.add_image((255 * image).astype(np.uint8), width=0.24) 10 | 11 | # Unset document width. 12 | doc.add_html('') 13 | doc.show() 14 | -------------------------------------------------------------------------------- /examples/start.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Python Handout 3 | 4 | Turn Python scripts into handouts with Markdown comments and inline figures. An 5 | alternative to Jupyter notebooks without hidden state that supports any text 6 | editor. 7 | """ 8 | 9 | import handout 10 | import matplotlib.pyplot as plt 11 | import numpy as np 12 | 13 | """Start your handout with an output directory.""" 14 | 15 | doc = handout.Handout('output/start') 16 | 17 | """ 18 | ## Markdown comments 19 | 20 | Comments with triple quotes are converted to text blocks. 21 | 22 | Text blocks support [Markdown formatting][1], for example: 23 | 24 | - Headlines 25 | - Hyperlinks 26 | - Inline `code()` snippets 27 | - **Bold** and *italic* 28 | - LaTeX math $f(x)=x^2$ 29 | 30 | [1]: https://commonmark.org/help/ 31 | """ 32 | 33 | """ 34 | ## Add text and variables 35 | 36 | Write to our handout using the same syntax as Python's `print()`: 37 | """ 38 | for index in range(3): 39 | doc.add_text('Iteration', index) 40 | doc.show() 41 | 42 | """ 43 | ## Add Matplotlib figures 44 | 45 | Display matplotlib figures on the handout: 46 | """ 47 | fig, ax = plt.subplots(figsize=(4, 3)) 48 | ax.plot(np.arange(100)) 49 | fig.tight_layout() 50 | doc.add_figure(fig) 51 | doc.show() # Display figure below this line. 52 | 53 | """ 54 | Set the width to display multiple figures side by side: 55 | """ 56 | 57 | for iteration in range(3): 58 | fig, ax = plt.subplots(figsize=(3, 2)) 59 | ax.plot(np.sin(np.linspace(0, 20 / (iteration + 1), 100))) 60 | doc.add_figure(fig, width=0.33) 61 | doc.show() 62 | 63 | """ 64 | ## Add images and videos 65 | 66 | This requires the `imageio` pip package. 67 | """ 68 | image_a = np.random.uniform(0, 255, (200, 400, 3)).astype(np.uint8) 69 | image_b = np.random.uniform(0, 255, (100, 200, 1)).astype(np.uint8) 70 | doc.add_image(image_a, 'png', width=0.4) 71 | doc.add_image(image_b, 'jpg', width=0.4) 72 | doc.show() 73 | video = np.random.uniform(0, 255, (100, 64, 128, 3)).astype(np.uint8) 74 | doc.add_video(video, 'gif', fps=30, width=0.4) 75 | doc.add_video(video, 'mp4', fps=30, width=0.4) 76 | doc.show() 77 | 78 | """ 79 | ## Exclude lines 80 | 81 | Hide code from the handout with the `# handout: exclude` comment: 82 | """ 83 | 84 | # Invisible below: 85 | value = 13 # handout: exclude 86 | 87 | """ 88 | Exclude whole ranges between `# handout: begin-exclude` and `# handout: 89 | end-exclude` lines. 90 | """ 91 | 92 | """ 93 | ## View the handout 94 | 95 | The handout is automatically saved when you call `doc.show()`. Just open 96 | `output/index.html` in your browser. 97 | """ 98 | -------------------------------------------------------------------------------- /handout/__init__.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import logging 3 | 4 | from .handout import Handout 5 | 6 | 7 | # Set up logger. 8 | logger = logging.getLogger('handout') 9 | logger.setLevel(logging.INFO) 10 | logger.propagate = False # Global logger should not print messages again. 11 | if not logger.handlers: # Reloading the module should not add another handler. 12 | handler = logging.StreamHandler(sys.stdout) 13 | handler.setFormatter(logging.Formatter('%(message)s')) 14 | logger.addHandler(handler) 15 | -------------------------------------------------------------------------------- /handout/blocks.py: -------------------------------------------------------------------------------- 1 | from handout import tools 2 | 3 | 4 | class Html(object): 5 | 6 | def __init__(self, lines=None): 7 | self._lines = lines or [] 8 | 9 | def append(self, line): 10 | self._lines.append(line) 11 | 12 | def render(self): 13 | return '\n'.join(tools.strip_empty_lines(self._lines)) 14 | 15 | 16 | class Code(object): 17 | 18 | def __init__(self, lines=None): 19 | self._lines = lines or [] 20 | 21 | def append(self, line): 22 | self._lines.append(line) 23 | 24 | def render(self): 25 | lines = '\n'.join(tools.strip_empty_lines(self._lines)) 26 | if not lines: 27 | return '' 28 | lines = lines.replace("&", "&") 29 | lines = lines.replace("<", "<") 30 | lines = lines.replace(">", ">") 31 | return '
' + lines + '
\n' 32 | 33 | 34 | class Text(object): 35 | 36 | def __init__(self, lines=None): 37 | self._lines = lines or [] 38 | 39 | def append(self, line): 40 | self._lines.append(line) 41 | 42 | def render(self): 43 | lines = '\n'.join(tools.strip_empty_lines(self._lines)) 44 | if not lines: 45 | return '' 46 | lines = lines.replace("&", "&") 47 | lines = lines.replace("<", "<") 48 | lines = lines.replace(">", ">") 49 | return '
' + lines + '
\n' 50 | 51 | 52 | class Image(object): 53 | 54 | def __init__(self, filename, width=None): 55 | self._filename = filename 56 | self._width = width 57 | 58 | def append(self, line): 59 | raise NotImplementedError() 60 | 61 | def render(self): 62 | output = '", ">") 102 | return '
' + lines + '
\n' 103 | -------------------------------------------------------------------------------- /handout/data/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danijar/handout/c5a357223d6b7f08fa67465104dbb01c0ea73822/handout/data/favicon.ico -------------------------------------------------------------------------------- /handout/data/highlight.css: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | github.com style (c) Vasily Polovnyov 4 | 5 | */ 6 | 7 | .hljs { 8 | display: block; 9 | overflow-x: auto; 10 | padding: 0.5em; 11 | color: #333; 12 | background: #f8f8f8; 13 | } 14 | 15 | .hljs-comment, 16 | .hljs-quote { 17 | color: #998; 18 | font-style: italic; 19 | } 20 | 21 | .hljs-keyword, 22 | .hljs-selector-tag, 23 | .hljs-subst { 24 | color: #333; 25 | font-weight: bold; 26 | } 27 | 28 | .hljs-number, 29 | .hljs-literal, 30 | .hljs-variable, 31 | .hljs-template-variable, 32 | .hljs-tag .hljs-attr { 33 | color: #008080; 34 | } 35 | 36 | .hljs-string, 37 | .hljs-doctag { 38 | color: #d14; 39 | } 40 | 41 | .hljs-title, 42 | .hljs-section, 43 | .hljs-selector-id { 44 | color: #900; 45 | font-weight: bold; 46 | } 47 | 48 | .hljs-subst { 49 | font-weight: normal; 50 | } 51 | 52 | .hljs-type, 53 | .hljs-class .hljs-title { 54 | color: #458; 55 | font-weight: bold; 56 | } 57 | 58 | .hljs-tag, 59 | .hljs-name, 60 | .hljs-attribute { 61 | color: #000080; 62 | font-weight: normal; 63 | } 64 | 65 | .hljs-regexp, 66 | .hljs-link { 67 | color: #009926; 68 | } 69 | 70 | .hljs-symbol, 71 | .hljs-bullet { 72 | color: #990073; 73 | } 74 | 75 | .hljs-built_in, 76 | .hljs-builtin-name { 77 | color: #0086b3; 78 | } 79 | 80 | .hljs-meta { 81 | color: #999; 82 | font-weight: bold; 83 | } 84 | 85 | .hljs-deletion { 86 | background: #fdd; 87 | } 88 | 89 | .hljs-addition { 90 | background: #dfd; 91 | } 92 | 93 | .hljs-emphasis { 94 | font-style: italic; 95 | } 96 | 97 | .hljs-strong { 98 | font-weight: bold; 99 | } 100 | -------------------------------------------------------------------------------- /handout/data/highlight.js: -------------------------------------------------------------------------------- 1 | /*! highlight.js v9.13.1 | BSD3 License | git.io/hljslicense */ 2 | !function(e){var n="object"==typeof window&&window||"object"==typeof self&&self;"undefined"!=typeof exports?e(exports):n&&(n.hljs=e({}),"function"==typeof define&&define.amd&&define([],function(){return n.hljs}))}(function(e){function n(e){return e.replace(/&/g,"&").replace(//g,">")}function t(e){return e.nodeName.toLowerCase()}function r(e,n){var t=e&&e.exec(n);return t&&0===t.index}function a(e){return k.test(e)}function i(e){var n,t,r,i,o=e.className+" ";if(o+=e.parentNode?e.parentNode.className:"",t=M.exec(o))return w(t[1])?t[1]:"no-highlight";for(o=o.split(/\s+/),n=0,r=o.length;r>n;n++)if(i=o[n],a(i)||w(i))return i}function o(e){var n,t={},r=Array.prototype.slice.call(arguments,1);for(n in e)t[n]=e[n];return r.forEach(function(e){for(n in e)t[n]=e[n]}),t}function c(e){var n=[];return function r(e,a){for(var i=e.firstChild;i;i=i.nextSibling)3===i.nodeType?a+=i.nodeValue.length:1===i.nodeType&&(n.push({event:"start",offset:a,node:i}),a=r(i,a),t(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:a,node:i}));return a}(e,0),n}function u(e,r,a){function i(){return e.length&&r.length?e[0].offset!==r[0].offset?e[0].offset"}function c(e){l+=""}function u(e){("start"===e.event?o:c)(e.node)}for(var s=0,l="",f=[];e.length||r.length;){var g=i();if(l+=n(a.substring(s,g[0].offset)),s=g[0].offset,g===e){f.reverse().forEach(c);do u(g.splice(0,1)[0]),g=i();while(g===e&&g.length&&g[0].offset===s);f.reverse().forEach(o)}else"start"===g[0].event?f.push(g[0].node):f.pop(),u(g.splice(0,1)[0])}return l+n(a.substr(s))}function s(e){return e.v&&!e.cached_variants&&(e.cached_variants=e.v.map(function(n){return o(e,{v:null},n)})),e.cached_variants||e.eW&&[o(e)]||[e]}function l(e){function n(e){return e&&e.source||e}function t(t,r){return new RegExp(n(t),"m"+(e.cI?"i":"")+(r?"g":""))}function r(a,i){if(!a.compiled){if(a.compiled=!0,a.k=a.k||a.bK,a.k){var o={},c=function(n,t){e.cI&&(t=t.toLowerCase()),t.split(" ").forEach(function(e){var t=e.split("|");o[t[0]]=[n,t[1]?Number(t[1]):1]})};"string"==typeof a.k?c("keyword",a.k):B(a.k).forEach(function(e){c(e,a.k[e])}),a.k=o}a.lR=t(a.l||/\w+/,!0),i&&(a.bK&&(a.b="\\b("+a.bK.split(" ").join("|")+")\\b"),a.b||(a.b=/\B|\b/),a.bR=t(a.b),a.endSameAsBegin&&(a.e=a.b),a.e||a.eW||(a.e=/\B|\b/),a.e&&(a.eR=t(a.e)),a.tE=n(a.e)||"",a.eW&&i.tE&&(a.tE+=(a.e?"|":"")+i.tE)),a.i&&(a.iR=t(a.i)),null==a.r&&(a.r=1),a.c||(a.c=[]),a.c=Array.prototype.concat.apply([],a.c.map(function(e){return s("self"===e?a:e)})),a.c.forEach(function(e){r(e,a)}),a.starts&&r(a.starts,i);var u=a.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([a.tE,a.i]).map(n).filter(Boolean);a.t=u.length?t(u.join("|"),!0):{exec:function(){return null}}}}r(e)}function f(e,t,a,i){function o(e){return new RegExp(e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),"m")}function c(e,n){var t,a;for(t=0,a=n.c.length;a>t;t++)if(r(n.c[t].bR,e))return n.c[t].endSameAsBegin&&(n.c[t].eR=o(n.c[t].bR.exec(e)[0])),n.c[t]}function u(e,n){if(r(e.eR,n)){for(;e.endsParent&&e.parent;)e=e.parent;return e}return e.eW?u(e.parent,n):void 0}function s(e,n){return!a&&r(n.iR,e)}function p(e,n){var t=R.cI?n[0].toLowerCase():n[0];return e.k.hasOwnProperty(t)&&e.k[t]}function d(e,n,t,r){var a=r?"":j.classPrefix,i='',i+n+o}function h(){var e,t,r,a;if(!E.k)return n(k);for(a="",t=0,E.lR.lastIndex=0,r=E.lR.exec(k);r;)a+=n(k.substring(t,r.index)),e=p(E,r),e?(M+=e[1],a+=d(e[0],n(r[0]))):a+=n(r[0]),t=E.lR.lastIndex,r=E.lR.exec(k);return a+n(k.substr(t))}function b(){var e="string"==typeof E.sL;if(e&&!L[E.sL])return n(k);var t=e?f(E.sL,k,!0,B[E.sL]):g(k,E.sL.length?E.sL:void 0);return E.r>0&&(M+=t.r),e&&(B[E.sL]=t.top),d(t.language,t.value,!1,!0)}function v(){y+=null!=E.sL?b():h(),k=""}function m(e){y+=e.cN?d(e.cN,"",!0):"",E=Object.create(e,{parent:{value:E}})}function N(e,n){if(k+=e,null==n)return v(),0;var t=c(n,E);if(t)return t.skip?k+=n:(t.eB&&(k+=n),v(),t.rB||t.eB||(k=n)),m(t,n),t.rB?0:n.length;var r=u(E,n);if(r){var a=E;a.skip?k+=n:(a.rE||a.eE||(k+=n),v(),a.eE&&(k=n));do E.cN&&(y+=I),E.skip||E.sL||(M+=E.r),E=E.parent;while(E!==r.parent);return r.starts&&(r.endSameAsBegin&&(r.starts.eR=r.eR),m(r.starts,"")),a.rE?0:n.length}if(s(n,E))throw new Error('Illegal lexeme "'+n+'" for mode "'+(E.cN||"")+'"');return k+=n,n.length||1}var R=w(e);if(!R)throw new Error('Unknown language: "'+e+'"');l(R);var x,E=i||R,B={},y="";for(x=E;x!==R;x=x.parent)x.cN&&(y=d(x.cN,"",!0)+y);var k="",M=0;try{for(var C,A,S=0;;){if(E.t.lastIndex=S,C=E.t.exec(t),!C)break;A=N(t.substring(S,C.index),C[0]),S=C.index+A}for(N(t.substr(S)),x=E;x.parent;x=x.parent)x.cN&&(y+=I);return{r:M,value:y,language:e,top:E}}catch(O){if(O.message&&-1!==O.message.indexOf("Illegal"))return{r:0,value:n(t)};throw O}}function g(e,t){t=t||j.languages||B(L);var r={r:0,value:n(e)},a=r;return t.filter(w).filter(x).forEach(function(n){var t=f(n,e,!1);t.language=n,t.r>a.r&&(a=t),t.r>r.r&&(a=r,r=t)}),a.language&&(r.second_best=a),r}function p(e){return j.tabReplace||j.useBR?e.replace(C,function(e,n){return j.useBR&&"\n"===e?"
":j.tabReplace?n.replace(/\t/g,j.tabReplace):""}):e}function d(e,n,t){var r=n?y[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}function h(e){var n,t,r,o,s,l=i(e);a(l)||(j.useBR?(n=document.createElementNS("http://www.w3.org/1999/xhtml","div"),n.innerHTML=e.innerHTML.replace(/\n/g,"").replace(//g,"\n")):n=e,s=n.textContent,r=l?f(l,s,!0):g(s),t=c(n),t.length&&(o=document.createElementNS("http://www.w3.org/1999/xhtml","div"),o.innerHTML=r.value,r.value=u(t,c(o),s)),r.value=p(r.value),e.innerHTML=r.value,e.className=d(e.className,l,r.language),e.result={language:r.language,re:r.r},r.second_best&&(e.second_best={language:r.second_best.language,re:r.second_best.r}))}function b(e){j=o(j,e)}function v(){if(!v.called){v.called=!0;var e=document.querySelectorAll("pre code");E.forEach.call(e,h)}}function m(){addEventListener("DOMContentLoaded",v,!1),addEventListener("load",v,!1)}function N(n,t){var r=L[n]=t(e);r.aliases&&r.aliases.forEach(function(e){y[e]=n})}function R(){return B(L)}function w(e){return e=(e||"").toLowerCase(),L[e]||L[y[e]]}function x(e){var n=w(e);return n&&!n.disableAutodetect}var E=[],B=Object.keys,L={},y={},k=/^(no-?highlight|plain|text)$/i,M=/\blang(?:uage)?-([\w-]+)\b/i,C=/((^(<[^>]+>|\t|)+|(?:\n)))/gm,I="
",j={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0};return e.highlight=f,e.highlightAuto=g,e.fixMarkup=p,e.highlightBlock=h,e.configure=b,e.initHighlighting=v,e.initHighlightingOnLoad=m,e.registerLanguage=N,e.listLanguages=R,e.getLanguage=w,e.autoDetection=x,e.inherit=o,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},e.C=function(n,t,r){var a=e.inherit({cN:"comment",b:n,e:t,c:[]},r||{});return a.c.push(e.PWM),a.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),a},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e.METHOD_GUARD={b:"\\.\\s*"+e.UIR,r:0},e});hljs.registerLanguage("python",function(e){var r={keyword:"and elif is global as in if from raise for except finally print import pass return exec else break not with class assert yield try while continue del or def lambda async await nonlocal|10 None True False",built_in:"Ellipsis NotImplemented"},b={cN:"meta",b:/^(>>>|\.\.\.) /},c={cN:"subst",b:/\{/,e:/\}/,k:r,i:/#/},a={cN:"string",c:[e.BE],v:[{b:/(u|b)?r?'''/,e:/'''/,c:[e.BE,b],r:10},{b:/(u|b)?r?"""/,e:/"""/,c:[e.BE,b],r:10},{b:/(fr|rf|f)'''/,e:/'''/,c:[e.BE,b,c]},{b:/(fr|rf|f)"""/,e:/"""/,c:[e.BE,b,c]},{b:/(u|r|ur)'/,e:/'/,r:10},{b:/(u|r|ur)"/,e:/"/,r:10},{b:/(b|br)'/,e:/'/},{b:/(b|br)"/,e:/"/},{b:/(fr|rf|f)'/,e:/'/,c:[e.BE,c]},{b:/(fr|rf|f)"/,e:/"/,c:[e.BE,c]},e.ASM,e.QSM]},s={cN:"number",r:0,v:[{b:e.BNR+"[lLjJ]?"},{b:"\\b(0o[0-7]+)[lLjJ]?"},{b:e.CNR+"[lLjJ]?"}]},i={cN:"params",b:/\(/,e:/\)/,c:["self",b,s,a]};return c.c=[a,s,b],{aliases:["py","gyp"],k:r,i:/(<\/|->|\?)|=>/,c:[b,s,a,e.HCM,{v:[{cN:"function",bK:"def"},{cN:"class",bK:"class"}],e:/:/,i:/[${=;\n,]/,c:[e.UTM,i,{b:/->/,eW:!0,k:"None"}]},{cN:"meta",b:/^[\t ]*@/,e:/$/},{b:/\b(print|exec)\(/}]}}); -------------------------------------------------------------------------------- /handout/data/marked.js: -------------------------------------------------------------------------------- 1 | /** 2 | * marked - a markdown parser 3 | * Copyright (c) 2011-2018, Christopher Jeffrey. (MIT Licensed) 4 | * https://github.com/markedjs/marked 5 | */ 6 | !function(e){"use strict";var k={newline:/^\n+/,code:/^( {4}[^\n]+\n*)+/,fences:g,hr:/^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/,heading:/^ *(#{1,6}) *([^\n]+?) *(?:#+ *)?(?:\n+|$)/,nptable:g,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,html:"^ {0,3}(?:<(script|pre|style)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?\\?>\\n*|\\n*|\\n*|)[\\s\\S]*?(?:\\n{2,}|$)|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=\\h*\\n)[\\s\\S]*?(?:\\n{2,}|$)|(?=\\h*\\n)[\\s\\S]*?(?:\\n{2,}|$))",def:/^ {0,3}\[(label)\]: *\n? *]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/,table:g,lheading:/^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading| {0,3}>|<\/?(?:tag)(?: +|\n|\/?>)|<(?:script|pre|style|!--))[^\n]+)*)/,text:/^[^\n]+/};function a(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||d.defaults,this.rules=k.normal,this.options.pedantic?this.rules=k.pedantic:this.options.gfm&&(this.options.tables?this.rules=k.tables:this.rules=k.gfm)}k._label=/(?!\s*\])(?:\\[\[\]]|[^\[\]])+/,k._title=/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/,k.def=t(k.def).replace("label",k._label).replace("title",k._title).getRegex(),k.bullet=/(?:[*+-]|\d+\.)/,k.item=/^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/,k.item=t(k.item,"gm").replace(/bull/g,k.bullet).getRegex(),k.list=t(k.list).replace(/bull/g,k.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+k.def.source+")").getRegex(),k._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",k._comment=//,k.html=t(k.html,"i").replace("comment",k._comment).replace("tag",k._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),k.paragraph=t(k.paragraph).replace("hr",k.hr).replace("heading",k.heading).replace("lheading",k.lheading).replace("tag",k._tag).getRegex(),k.blockquote=t(k.blockquote).replace("paragraph",k.paragraph).getRegex(),k.normal=f({},k),k.gfm=f({},k.normal,{fences:/^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\n? *\1 *(?:\n+|$)/,paragraph:/^/,heading:/^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/}),k.gfm.paragraph=t(k.paragraph).replace("(?!","(?!"+k.gfm.fences.source.replace("\\1","\\2")+"|"+k.list.source.replace("\\1","\\3")+"|").getRegex(),k.tables=f({},k.gfm,{nptable:/^ *([^|\n ].*\|.*)\n *([-:]+ *\|[-| :]*)(?:\n((?:.*[^>\n ].*(?:\n|$))*)\n*|$)/,table:/^ *\|(.+)\n *\|?( *[-:]+[-| :]*)(?:\n((?: *[^>\n ].*(?:\n|$))*)\n*|$)/}),k.pedantic=f({},k.normal,{html:t("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",k._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/}),a.rules=k,a.lex=function(e,t){return new a(t).lex(e)},a.prototype.lex=function(e){return e=e.replace(/\r\n|\r/g,"\n").replace(/\t/g," ").replace(/\u00a0/g," ").replace(/\u2424/g,"\n"),this.token(e,!0)},a.prototype.token=function(e,t){var n,r,s,i,l,o,a,h,p,c,u,g,f,d,b,m;for(e=e.replace(/^ +$/gm,"");e;)if((s=this.rules.newline.exec(e))&&(e=e.substring(s[0].length),1 ?/gm,""),this.token(s,t),this.tokens.push({type:"blockquote_end"});else if(s=this.rules.list.exec(e)){for(e=e.substring(s[0].length),a={type:"list_start",ordered:d=1<(i=s[2]).length,start:d?+i:"",loose:!1},this.tokens.push(a),n=!(h=[]),f=(s=s[0].match(this.rules.item)).length,u=0;u?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:g,tag:"^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^",link:/^!?\[(label)\]\(href(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,nolink:/^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,strong:/^__([^\s])__(?!_)|^\*\*([^\s])\*\*(?!\*)|^__([^\s][\s\S]*?[^\s])__(?!_)|^\*\*([^\s][\s\S]*?[^\s])\*\*(?!\*)/,em:/^_([^\s_])_(?!_)|^\*([^\s*"<\[])\*(?!\*)|^_([^\s][\s\S]*?[^\s_])_(?!_|[^\s.])|^_([^\s_][\s\S]*?[^\s])_(?!_|[^\s.])|^\*([^\s"<\[][\s\S]*?[^\s*])\*(?!\*)|^\*([^\s*"<\[][\s\S]*?[^\s])\*(?!\*)/,code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:g,text:/^(`+|[^`])[\s\S]*?(?=[\\?@\[\]\\^_`{|}~])/g,n._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,n._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,n.autolink=t(n.autolink).replace("scheme",n._scheme).replace("email",n._email).getRegex(),n._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,n.tag=t(n.tag).replace("comment",k._comment).replace("attribute",n._attribute).getRegex(),n._label=/(?:\[[^\[\]]*\]|\\[\[\]]?|`[^`]*`|[^\[\]\\])*?/,n._href=/\s*(<(?:\\[<>]?|[^\s<>\\])*>|(?:\\[()]?|\([^\s\x00-\x1f\\]*\)|[^\s\x00-\x1f()\\])*?)/,n._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,n.link=t(n.link).replace("label",n._label).replace("href",n._href).replace("title",n._title).getRegex(),n.reflink=t(n.reflink).replace("label",n._label).getRegex(),n.normal=f({},n),n.pedantic=f({},n.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/,link:t(/^!?\[(label)\]\((.*?)\)/).replace("label",n._label).getRegex(),reflink:t(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",n._label).getRegex()}),n.gfm=f({},n.normal,{escape:t(n.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,del:/^~+(?=\S)([\s\S]*?\S)~+/,text:t(n.text).replace("]|","~]|").replace("|$","|https?://|ftp://|www\\.|[a-zA-Z0-9.!#$%&'*+/=?^_`{\\|}~-]+@|$").getRegex()}),n.gfm.url=t(n.gfm.url).replace("email",n.gfm._extended_email).getRegex(),n.breaks=f({},n.gfm,{br:t(n.br).replace("{2,}","*").getRegex(),text:t(n.gfm.text).replace("{2,}","*").getRegex()}),h.rules=n,h.output=function(e,t,n){return new h(t,n).output(e)},h.prototype.output=function(e){for(var t,n,r,s,i,l,o="";e;)if(i=this.rules.escape.exec(e))e=e.substring(i[0].length),o+=i[1];else if(i=this.rules.autolink.exec(e))e=e.substring(i[0].length),r="@"===i[2]?"mailto:"+(n=c(this.mangle(i[1]))):n=c(i[1]),o+=this.renderer.link(r,null,n);else if(this.inLink||!(i=this.rules.url.exec(e))){if(i=this.rules.tag.exec(e))!this.inLink&&/^/i.test(i[0])&&(this.inLink=!1),!this.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(i[0])?this.inRawBlock=!0:this.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(i[0])&&(this.inRawBlock=!1),e=e.substring(i[0].length),o+=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(i[0]):c(i[0]):i[0];else if(i=this.rules.link.exec(e))e=e.substring(i[0].length),this.inLink=!0,r=i[2],this.options.pedantic?(t=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(r))?(r=t[1],s=t[3]):s="":s=i[3]?i[3].slice(1,-1):"",r=r.trim().replace(/^<([\s\S]*)>$/,"$1"),o+=this.outputLink(i,{href:h.escapes(r),title:h.escapes(s)}),this.inLink=!1;else if((i=this.rules.reflink.exec(e))||(i=this.rules.nolink.exec(e))){if(e=e.substring(i[0].length),t=(i[2]||i[1]).replace(/\s+/g," "),!(t=this.links[t.toLowerCase()])||!t.href){o+=i[0].charAt(0),e=i[0].substring(1)+e;continue}this.inLink=!0,o+=this.outputLink(i,t),this.inLink=!1}else if(i=this.rules.strong.exec(e))e=e.substring(i[0].length),o+=this.renderer.strong(this.output(i[4]||i[3]||i[2]||i[1]));else if(i=this.rules.em.exec(e))e=e.substring(i[0].length),o+=this.renderer.em(this.output(i[6]||i[5]||i[4]||i[3]||i[2]||i[1]));else if(i=this.rules.code.exec(e))e=e.substring(i[0].length),o+=this.renderer.codespan(c(i[2].trim(),!0));else if(i=this.rules.br.exec(e))e=e.substring(i[0].length),o+=this.renderer.br();else if(i=this.rules.del.exec(e))e=e.substring(i[0].length),o+=this.renderer.del(this.output(i[1]));else if(i=this.rules.text.exec(e))e=e.substring(i[0].length),this.inRawBlock?o+=this.renderer.text(i[0]):o+=this.renderer.text(c(this.smartypants(i[0])));else if(e)throw new Error("Infinite loop on byte: "+e.charCodeAt(0))}else{if("@"===i[2])r="mailto:"+(n=c(i[0]));else{for(;l=i[0],i[0]=this.rules._backpedal.exec(i[0])[0],l!==i[0];);n=c(i[0]),r="www."===i[1]?"http://"+n:n}e=e.substring(i[0].length),o+=this.renderer.link(r,null,n)}return o},h.escapes=function(e){return e?e.replace(h.rules._escapes,"$1"):e},h.prototype.outputLink=function(e,t){var n=t.href,r=t.title?c(t.title):null;return"!"!==e[0].charAt(0)?this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,c(e[1]))},h.prototype.smartypants=function(e){return this.options.smartypants?e.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…"):e},h.prototype.mangle=function(e){if(!this.options.mangle)return e;for(var t,n="",r=e.length,s=0;s'+(n?e:c(e,!0))+"\n":"
"+(n?e:c(e,!0))+"
"},r.prototype.blockquote=function(e){return"
\n"+e+"
\n"},r.prototype.html=function(e){return e},r.prototype.heading=function(e,t,n){return this.options.headerIds?"'+e+"\n":""+e+"\n"},r.prototype.hr=function(){return this.options.xhtml?"
\n":"
\n"},r.prototype.list=function(e,t,n){var r=t?"ol":"ul";return"<"+r+(t&&1!==n?' start="'+n+'"':"")+">\n"+e+"\n"},r.prototype.listitem=function(e){return"
  • "+e+"
  • \n"},r.prototype.checkbox=function(e){return" "},r.prototype.paragraph=function(e){return"

    "+e+"

    \n"},r.prototype.table=function(e,t){return t&&(t=""+t+""),"\n\n"+e+"\n"+t+"
    \n"},r.prototype.tablerow=function(e){return"\n"+e+"\n"},r.prototype.tablecell=function(e,t){var n=t.header?"th":"td";return(t.align?"<"+n+' align="'+t.align+'">':"<"+n+">")+e+"\n"},r.prototype.strong=function(e){return""+e+""},r.prototype.em=function(e){return""+e+""},r.prototype.codespan=function(e){return""+e+""},r.prototype.br=function(){return this.options.xhtml?"
    ":"
    "},r.prototype.del=function(e){return""+e+""},r.prototype.link=function(e,t,n){if(null===(e=i(this.options.sanitize,this.options.baseUrl,e)))return n;var r='
    "},r.prototype.image=function(e,t,n){if(null===(e=i(this.options.sanitize,this.options.baseUrl,e)))return n;var r=''+n+'":">"},r.prototype.text=function(e){return e},s.prototype.strong=s.prototype.em=s.prototype.codespan=s.prototype.del=s.prototype.text=function(e){return e},s.prototype.link=s.prototype.image=function(e,t,n){return""+n},s.prototype.br=function(){return""},p.parse=function(e,t){return new p(t).parse(e)},p.prototype.parse=function(e){this.inline=new h(e.links,this.options),this.inlineText=new h(e.links,f({},this.options,{renderer:new s})),this.tokens=e.reverse();for(var t="";this.next();)t+=this.tok();return t},p.prototype.next=function(){return this.token=this.tokens.pop()},p.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0},p.prototype.parseText=function(){for(var e=this.token.text;"text"===this.peek().type;)e+="\n"+this.next().text;return this.inline.output(e)},p.prototype.tok=function(){switch(this.token.type){case"space":return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,u(this.inlineText.output(this.token.text)));case"code":return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table":var e,t,n,r,s="",i="";for(n="",e=0;e"']/,c.escapeReplace=/[&<>"']/g,c.replacements={"&":"&","<":"<",">":">",'"':""","'":"'"},c.escapeTestNoEncode=/[<>"']|&(?!#?\w+;)/,c.escapeReplaceNoEncode=/[<>"']|&(?!#?\w+;)/g;var l={},o=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function g(){}function f(e){for(var t,n,r=1;rt)n.splice(t);else for(;n.lengthAn error occurred:

    "+c(e.message+"",!0)+"
    ";throw e}}g.exec=g,d.options=d.setOptions=function(e){return f(d.defaults,e),d},d.getDefaults=function(){return{baseUrl:null,breaks:!1,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:new r,sanitize:!1,sanitizer:null,silent:!1,smartLists:!1,smartypants:!1,tables:!0,xhtml:!1}},d.defaults=d.getDefaults(),d.Parser=p,d.parser=p.parse,d.Renderer=r,d.TextRenderer=s,d.Lexer=a,d.lexer=a.lex,d.InlineLexer=h,d.inlineLexer=h.output,d.parse=d,"undefined"!=typeof module&&"object"==typeof exports?module.exports=d:"function"==typeof define&&define.amd?define(function(){return d}):e.marked=d}(this||("undefined"!=typeof window?window:global)); -------------------------------------------------------------------------------- /handout/data/script.js: -------------------------------------------------------------------------------- 1 | document.addEventListener('DOMContentLoaded', function(){ 2 | var elements = document.getElementsByClassName('markdown'); 3 | for (var index = 0; index < elements.length; index++) { 4 | var element = elements[index]; 5 | element.innerHTML = marked(element.textContent); 6 | } 7 | }, false); 8 | -------------------------------------------------------------------------------- /handout/data/style.css: -------------------------------------------------------------------------------- 1 | @media print { 2 | html, article { 3 | background: #fff !important; 4 | margin: 0 !important; 5 | padding: 0 !important; 6 | max-width: none !important; 7 | border: none !important; 8 | font-size: 13px !important; 9 | } 10 | article { 11 | /* This prevents page breaks within images. However, it also means images 12 | * in one line will be centered without margin rather than spaced evenly. */ 13 | display: block !important; 14 | } 15 | } 16 | 17 | html { 18 | background: #eee; 19 | } 20 | 21 | h1 { font-size: 2.0em; margin: 0.4em 0; } 22 | h2 { font-size: 1.5em; margin: 0.4em 0; } 23 | h3 { font-size: 1.3em; margin: 0.4em 0; } 24 | h4 { font-size: 1.2em; margin: 0.4em 0; } 25 | h5 { font-size: 1.1em; margin: 0.4em 0; } 26 | h6 { font-size: 1.0em; margin: 0.4em 0; } 27 | 28 | article { 29 | max-width: 48.5em; /* Fit 79 characters. */ 30 | margin: 2em auto; 31 | padding: 3em; 32 | text-align: center; 33 | font-size: 15px; 34 | font-family: Helvetica, sans-serif; 35 | background: #fff; 36 | border-radius: .3em; 37 | border: 1px solid #ddd; 38 | display: flex; 39 | flex-wrap: wrap; 40 | justify-content: space-around; 41 | } 42 | 43 | article > * { 44 | text-align: left; 45 | } 46 | 47 | article > div, article > pre, article > .message { 48 | width: 100%; 49 | } 50 | 51 | article > div p, article > pre, article > .message { 52 | margin: 0 0 1em; 53 | } 54 | 55 | article > .message + .message { 56 | margin-top: -1em; 57 | } 58 | 59 | code { 60 | text-align: left; 61 | border-radius: .25em; 62 | border: 1px solid #eee; 63 | } 64 | 65 | .message { 66 | white-space: pre-wrap; 67 | word-break: break-all; 68 | } 69 | 70 | img, video { 71 | display: inline-block; 72 | margin: 0 0 1em; 73 | max-width: 100%; 74 | } 75 | -------------------------------------------------------------------------------- /handout/handout.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import inspect 3 | import io 4 | import logging 5 | import pathlib 6 | import shutil 7 | 8 | from handout import blocks 9 | 10 | 11 | MATHJAX_SCRIPTS = ( 12 | '' 15 | '' 17 | ) 18 | 19 | 20 | class Handout(object): 21 | 22 | def __init__(self, directory, title='Handout'): 23 | self._directory = pathlib.Path(directory).expanduser() 24 | self._directory.mkdir(parents=True, exist_ok=True) 25 | self._title = title 26 | self._blocks = collections.defaultdict(list) 27 | self._pending = [] 28 | # The logger is configured in handout/__init__.py to make it available 29 | # right after importing the handout package. This allows the user to change 30 | # the logging level, message format, etc. 31 | self._logger = logging.getLogger('handout') 32 | for info in inspect.stack(): 33 | if info.filename == __file__: 34 | continue 35 | break 36 | module = inspect.getmodule(info.frame) 37 | self._source_name = info.filename 38 | self._source_text = inspect.getsource(module) 39 | self._num_images = 0 40 | self._num_videos = 0 41 | self._num_figures = 0 42 | 43 | def add_text(self, *args, **kwargs): 44 | show = kwargs.pop('show', False) 45 | stream = io.StringIO() 46 | kwargs['file'] = stream 47 | print(*args, **kwargs) # Print into custom stream. 48 | message = stream.getvalue() 49 | block = blocks.Message([message]) 50 | self._pending.append(block) 51 | # Remove up to one line break since the logger adds one. 52 | if message.endswith('\n'): 53 | message = message[:-1] 54 | self._logger.info(message) 55 | 56 | def add_image(self, image, format='png', width=None): 57 | if isinstance(image, str): 58 | filename = image 59 | else: 60 | import imageio 61 | filename = 'image-{}.{}'.format(self._num_images, format) 62 | imageio.imsave(self._directory / filename, image) 63 | self._logger.info('Saved image: {}'.format(filename)) 64 | block = blocks.Image(filename, width) 65 | self._pending.append(block) 66 | self._num_images += 1 67 | 68 | def add_video(self, video, format='gif', fps=30, width=None): 69 | if isinstance(video, str): 70 | filename = video 71 | else: 72 | import imageio 73 | filename = 'video-{}.{}'.format(self._num_videos, format) 74 | imageio.mimsave(self._directory / filename, video, fps=fps) 75 | self._logger.info('Saved video: {}'.format(filename)) 76 | if filename.endswith('.gif'): 77 | block = blocks.Image(filename, width) 78 | else: 79 | block = blocks.Video(filename, width) 80 | self._pending.append(block) 81 | self._num_videos += 1 82 | 83 | def add_html(self, string): 84 | block = blocks.Html([string]) 85 | self._pending.append(block) 86 | self._logger.info(string) 87 | 88 | def add_figure(self, figure, width=None): 89 | filename = 'figure-{}.png'.format(self._num_figures) 90 | block = blocks.Image(filename, width) 91 | self._pending.append(block) 92 | filename = self._directory / filename 93 | figure.savefig(filename) 94 | self._logger.info('Saved figure: {}'.format(filename)) 95 | self._num_figures += 1 96 | 97 | def show(self): 98 | self._blocks[self._get_current_line()] += self._pending 99 | self._pending = [] 100 | output = self._generate(self._source_text) 101 | filename = self._directory / 'index.html' 102 | with open(str(filename), 'w') as f: 103 | f.write(output) 104 | datadir = pathlib.Path(__file__).parent / 'data' 105 | for source in datadir.glob('**/*'): 106 | target = self._directory / source.relative_to(datadir) 107 | if source.is_dir() or target.exists(): 108 | continue 109 | target.parent.mkdir(exist_ok=True) 110 | shutil.copyfile(str(source), str(target)) 111 | self._logger.info("Handout written to: {}".format(filename)) 112 | 113 | def _generate(self, source): 114 | content = [] 115 | content.append(blocks.Html([ 116 | '', 117 | '', 118 | '', 119 | '{}'.format(self._title), 120 | '', 121 | '', 122 | '', 123 | '', 124 | '', 125 | '', 126 | '', 127 | MATHJAX_SCRIPTS, 128 | '', 129 | '', 130 | '
    ', 131 | ])) 132 | content.append(blocks.Code()) 133 | excluding = False # Range exclude. 134 | for lineno, line in enumerate(source.split('\n')): 135 | lineno += 1 # Line numbers are 1-based indices. 136 | line = line.rstrip() 137 | if isinstance(content[-1], blocks.Code) and line.startswith('"""'): 138 | line = line[3:] 139 | content.append(blocks.Text()) 140 | if isinstance(content[-1], blocks.Text) and line.endswith('"""'): 141 | line = line[:-3] 142 | content[-1].append(line) 143 | content.append(blocks.Code()) 144 | continue 145 | if isinstance(content[-1], blocks.Text): 146 | content[-1].append(line) 147 | elif line == '# handout: begin-exclude': 148 | excluding = True 149 | elif line == '# handout: end-exclude': 150 | excluding = False 151 | elif excluding: 152 | pass 153 | elif line.endswith('# handout: exclude'): 154 | pass 155 | else: 156 | content[-1].append(line) 157 | blocks_ = self._blocks[lineno] 158 | if blocks_: 159 | for block in blocks_: 160 | content.append(block) 161 | content.append(blocks.Code()) 162 | content.append(blocks.Html([ 163 | '
    ', 164 | '', 165 | '', 166 | ])) 167 | return ''.join(block.render() for block in content) 168 | 169 | def _get_current_line(self): 170 | for info in inspect.stack(): 171 | if info.filename == self._source_name: 172 | return info.lineno 173 | message = ( 174 | "Handout object was created in '{}' and accessed in '{}'. The file in " 175 | "which you create the handout will be rendered. Thus, it only makes " 176 | "sense to add to the handout from this file or functions called from " 177 | "this file. You should not pass the handout object to a parent file.") 178 | raise RuntimeError(message.format(self._source_name, info.filename)) 179 | -------------------------------------------------------------------------------- /handout/tests/test_handout.py: -------------------------------------------------------------------------------- 1 | import handout 2 | 3 | 4 | def test_handout_on_title_arg_inserts_title(tmp_path): 5 | doc = handout.Handout(directory=tmp_path, title='This string') 6 | output = doc._generate(source='') 7 | assert 'This string' in output 8 | -------------------------------------------------------------------------------- /handout/tools.py: -------------------------------------------------------------------------------- 1 | def strip_empty_lines(lines): 2 | output = [] 3 | for line in lines: 4 | if not line and not output: 5 | continue 6 | output.append(line) 7 | lines = reversed(output) 8 | output = [] 9 | for line in lines: 10 | if not line and not output: 11 | continue 12 | output.append(line) 13 | lines = reversed(output) 14 | return list(lines) 15 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | import pathlib 3 | 4 | 5 | setuptools.setup( 6 | name='handout', 7 | version='1.1.2', 8 | description='Turn Python scripts into handouts with Markdown and figures', 9 | url='http://github.com/danijar/handout', 10 | long_description=pathlib.Path('README.md').read_text(), 11 | long_description_content_type='text/markdown', 12 | install_requires=[], 13 | extras_require={'media': ['imageio']}, 14 | packages=['handout'], 15 | package_data={'handout': ['data/*']}, 16 | classifiers=[ 17 | 'Programming Language :: Python :: 3', 18 | 'Topic :: Scientific/Engineering :: Visualization', 19 | 'Topic :: Multimedia :: Graphics :: Presentation', 20 | 'License :: OSI Approved :: Apache Software License', 21 | ], 22 | ) 23 | --------------------------------------------------------------------------------