|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +# Copyright © 2017, Chris Warrick. |
| 4 | + |
| 5 | +# Permission is hereby granted, free of charge, to any |
| 6 | +# person obtaining a copy of this software and associated |
| 7 | +# documentation files (the "Software"), to deal in the |
| 8 | +# Software without restriction, including without limitation |
| 9 | +# the rights to use, copy, modify, merge, publish, |
| 10 | +# distribute, sublicense, and/or sell copies of the |
| 11 | +# Software, and to permit persons to whom the Software is |
| 12 | +# furnished to do so, subject to the following conditions: |
| 13 | +# |
| 14 | +# The above copyright notice and this permission notice |
| 15 | +# shall be included in all copies or substantial portions of |
| 16 | +# the Software. |
| 17 | +# |
| 18 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY |
| 19 | +# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE |
| 20 | +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR |
| 21 | +# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS |
| 22 | +# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR |
| 23 | +# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR |
| 24 | +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |
| 25 | +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 26 | + |
| 27 | +from __future__ import unicode_literals |
| 28 | +import subprocess |
| 29 | +import json |
| 30 | +import os.path |
| 31 | + |
| 32 | +from nikola.plugin_categories import ShortcodePlugin |
| 33 | +from nikola import utils |
| 34 | + |
| 35 | +jspath = os.path.join(os.path.split(__file__)[0], 'localkatex.js') |
| 36 | + |
| 37 | + |
| 38 | +class LocalKatex(ShortcodePlugin): |
| 39 | + """Render math using KaTeX while building the site.""" |
| 40 | + |
| 41 | + name = 'localkatex' |
| 42 | + _options_available = {'displayMode': bool, 'throwOnError': bool, 'errorColor': str, 'colorIsTextColor': bool} |
| 43 | + logger = None |
| 44 | + |
| 45 | + def set_site(self, site): |
| 46 | + """Set Nikola site.""" |
| 47 | + site.register_shortcode('lmath', self.handler) |
| 48 | + site.register_shortcode('lmathd', self.handler_display) |
| 49 | + self.logger = utils.get_logger('localkatex') |
| 50 | + return super(LocalKatex, self).set_site(site) |
| 51 | + |
| 52 | + @staticmethod |
| 53 | + def _str_to_bool(v): |
| 54 | + return v.lower() not in ('false', 'no', 'f', 'n') |
| 55 | + |
| 56 | + def handler(self, site, lang, post, data, **options): |
| 57 | + """Render math.""" |
| 58 | + p = subprocess.Popen(['node', jspath], stdin=subprocess.PIPE, stdout=subprocess.PIPE) |
| 59 | + |
| 60 | + if 'display' in options: |
| 61 | + options['displayMode'] = options['display'] |
| 62 | + del options['display'] |
| 63 | + |
| 64 | + for k, v in options.items(): |
| 65 | + if k in self._options_available and self._options_available[k] == bool: |
| 66 | + options[k] = self._str_to_bool(v) |
| 67 | + elif k not in self._options_available: |
| 68 | + raise ValueError("Unknown KaTeX option {0}={1}".format(k, v)) |
| 69 | + |
| 70 | + json_input = json.dumps({'math': data, 'options': options}).encode('utf-8') |
| 71 | + stdout, stderr = p.communicate(json_input) |
| 72 | + output = json.loads(stdout.decode('utf-8').strip()) |
| 73 | + if output['success']: |
| 74 | + return output['output'] |
| 75 | + else: |
| 76 | + if output['input'] is None and output['output'] is None: |
| 77 | + raise Exception("Cannot import KaTeX. Did you run npm install?") |
| 78 | + else: |
| 79 | + self.logger.error("In expression {0}: {1}".format(data, output['output'])) |
| 80 | + return '<span class="problematic"><strong>In expression <code>{0}</code>:</strong> {1}</span>'.format(data, output['output']) |
| 81 | + |
| 82 | + def handler_display(self, site, lang, post, data, **options): |
| 83 | + """Render math in display mode.""" |
| 84 | + return self.handler(site, lang, post, data, displayMode='true', **options) |
0 commit comments