math.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. # -*- coding: utf-8 -*-
  2. """
  3. Math Render Plugin for Pelican
  4. ==============================
  5. This plugin allows your site to render Math. It uses
  6. the MathJax JavaScript engine.
  7. For markdown, the plugin works by creating a Markdown
  8. extension which is used during the markdown compilation stage.
  9. Math therefore gets treated like a "first class citizen" in Pelican
  10. For reStructuredText, the plugin instructs the rst engine
  11. to output Mathjax for for math.
  12. The mathjax script is automatically inserted into the HTML.
  13. Typogrify Compatibility
  14. -----------------------
  15. This plugin now plays nicely with Typogrify, but it requires
  16. Typogrify version 2.04 or above.
  17. User Settings
  18. -------------
  19. Users are also able to pass a dictionary of settings in the settings file which
  20. will control how the MathJax library renders things. This could be very useful
  21. for template builders that want to adjust the look and feel of the math.
  22. See README for more details.
  23. """
  24. import os
  25. import sys
  26. from pelican import signals, generators
  27. try:
  28. from bs4 import BeautifulSoup
  29. except ImportError as e:
  30. BeautifulSoup = None
  31. try:
  32. from . pelican_mathjax_markdown_extension import PelicanMathJaxExtension
  33. except ImportError as e:
  34. PelicanMathJaxExtension = None
  35. def process_settings(pelicanobj):
  36. """Sets user specified MathJax settings (see README for more details)"""
  37. mathjax_settings = {}
  38. # NOTE TO FUTURE DEVELOPERS: Look at the README and what is happening in
  39. # this function if any additional changes to the mathjax settings need to
  40. # be incorporated. Also, please inline comment what the variables
  41. # will be used for
  42. # Default settings
  43. mathjax_settings['auto_insert'] = True # if set to true, it will insert mathjax script automatically into content without needing to alter the template.
  44. mathjax_settings['align'] = 'center' # controls alignment of of displayed equations (values can be: left, right, center)
  45. mathjax_settings['indent'] = '0em' # if above is not set to 'center', then this setting acts as an indent
  46. mathjax_settings['show_menu'] = 'true' # controls whether to attach mathjax contextual menu
  47. mathjax_settings['process_escapes'] = 'true' # controls whether escapes are processed
  48. mathjax_settings['latex_preview'] = 'TeX' # controls what user sees while waiting for LaTex to render
  49. mathjax_settings['color'] = 'inherit' # controls color math is rendered in
  50. mathjax_settings['linebreak_automatic'] = 'false' # Set to false by default for performance reasons (see http://docs.mathjax.org/en/latest/output.html#automatic-line-breaking)
  51. mathjax_settings['tex_extensions'] = '' # latex extensions that can be embedded inside mathjax (see http://docs.mathjax.org/en/latest/tex.html#tex-and-latex-extensions)
  52. mathjax_settings['responsive'] = 'false' # Tries to make displayed math responsive
  53. mathjax_settings['responsive_break'] = '768' # The break point at which it math is responsively aligned (in pixels)
  54. mathjax_settings['mathjax_font'] = 'default' # forces mathjax to use the specified font.
  55. mathjax_settings['process_summary'] = BeautifulSoup is not None # will fix up summaries if math is cut off. Requires beautiful soup
  56. # Source for MathJax: Works boths for http and https (see http://docs.mathjax.org/en/latest/start.html#secure-access-to-the-cdn)
  57. mathjax_settings['source'] = "'//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'"
  58. # Get the user specified settings
  59. try:
  60. settings = pelicanobj.settings['MATH_JAX']
  61. except:
  62. settings = None
  63. # If no settings have been specified, then return the defaults
  64. if not isinstance(settings, dict):
  65. return mathjax_settings
  66. # The following mathjax settings can be set via the settings dictionary
  67. for key, value in ((key, settings[key]) for key in settings):
  68. # Iterate over dictionary in a way that is compatible with both version 2
  69. # and 3 of python
  70. if key == 'align':
  71. try:
  72. typeVal = isinstance(value, basestring)
  73. except NameError:
  74. typeVal = isinstance(value, str)
  75. if not typeVal:
  76. continue
  77. if value == 'left' or value == 'right' or value == 'center':
  78. mathjax_settings[key] = value
  79. else:
  80. mathjax_settings[key] = 'center'
  81. if key == 'indent':
  82. mathjax_settings[key] = value
  83. if key == 'show_menu' and isinstance(value, bool):
  84. mathjax_settings[key] = 'true' if value else 'false'
  85. if key == 'auto_insert' and isinstance(value, bool):
  86. mathjax_settings[key] = value
  87. if key == 'process_escapes' and isinstance(value, bool):
  88. mathjax_settings[key] = 'true' if value else 'false'
  89. if key == 'latex_preview':
  90. try:
  91. typeVal = isinstance(value, basestring)
  92. except NameError:
  93. typeVal = isinstance(value, str)
  94. if not typeVal:
  95. continue
  96. mathjax_settings[key] = value
  97. if key == 'color':
  98. try:
  99. typeVal = isinstance(value, basestring)
  100. except NameError:
  101. typeVal = isinstance(value, str)
  102. if not typeVal:
  103. continue
  104. mathjax_settings[key] = value
  105. if key == 'linebreak_automatic' and isinstance(value, bool):
  106. mathjax_settings[key] = 'true' if value else 'false'
  107. if key == 'process_summary' and isinstance(value, bool):
  108. if value and BeautifulSoup is None:
  109. print("BeautifulSoup4 is needed for summaries to be processed by render_math\nPlease install it")
  110. value = False
  111. mathjax_settings[key] = value
  112. if key == 'responsive' and isinstance(value, bool):
  113. mathjax_settings[key] = 'true' if value else 'false'
  114. if key == 'responsive_break' and isinstance(value, int):
  115. mathjax_settings[key] = str(value)
  116. if key == 'tex_extensions' and isinstance(value, list):
  117. # filter string values, then add '' to them
  118. try:
  119. value = filter(lambda string: isinstance(string, basestring), value)
  120. except NameError:
  121. value = filter(lambda string: isinstance(string, str), value)
  122. value = map(lambda string: "'%s'" % string, value)
  123. mathjax_settings[key] = ',' + ','.join(value)
  124. if key == 'mathjax_font':
  125. try:
  126. typeVal = isinstance(value, basestring)
  127. except NameError:
  128. typeVal = isinstance(value, str)
  129. if not typeVal:
  130. continue
  131. value = value.lower()
  132. if value == 'sanserif':
  133. value = 'SansSerif'
  134. elif value == 'fraktur':
  135. value = 'Fraktur'
  136. elif value == 'typewriter':
  137. value = 'Typewriter'
  138. else:
  139. value = 'default'
  140. mathjax_settings[key] = value
  141. return mathjax_settings
  142. def process_summary(article):
  143. """Ensures summaries are not cut off. Also inserts
  144. mathjax script so that math will be rendered"""
  145. summary = article._get_summary()
  146. summary_parsed = BeautifulSoup(summary, 'html.parser')
  147. math = summary_parsed.find_all(class_='math')
  148. if len(math) > 0:
  149. last_math_text = math[-1].get_text()
  150. if len(last_math_text) > 3 and last_math_text[-3:] == '...':
  151. content_parsed = BeautifulSoup(article._content, 'html.parser')
  152. full_text = content_parsed.find_all(class_='math')[len(math)-1].get_text()
  153. math[-1].string = "%s ..." % full_text
  154. summary = summary_parsed.decode()
  155. article._summary = "%s<script type='text/javascript'>%s</script>" % (summary, process_summary.mathjax_script)
  156. def configure_typogrify(pelicanobj, mathjax_settings):
  157. """Instructs Typogrify to ignore math tags - which allows Typogrify
  158. to play nicely with math related content"""
  159. # If Typogrify is not being used, then just exit
  160. if not pelicanobj.settings.get('TYPOGRIFY', False):
  161. return
  162. try:
  163. import typogrify
  164. from distutils.version import LooseVersion
  165. if LooseVersion(typogrify.__version__) < LooseVersion('2.0.7'):
  166. raise TypeError('Incorrect version of Typogrify')
  167. from typogrify.filters import typogrify
  168. # At this point, we are happy to use Typogrify, meaning
  169. # it is installed and it is a recent enough version
  170. # that can be used to ignore all math
  171. # Instantiate markdown extension and append it to the current extensions
  172. pelicanobj.settings['TYPOGRIFY_IGNORE_TAGS'].extend(['.math', 'script']) # ignore math class and script
  173. except (ImportError, TypeError, KeyError) as e:
  174. pelicanobj.settings['TYPOGRIFY'] = False # disable Typogrify
  175. if isinstance(e, ImportError):
  176. print("\nTypogrify is not installed, so it is being ignored.\nIf you want to use it, please install via: pip install typogrify\n")
  177. if isinstance(e, TypeError):
  178. print("\nA more recent version of Typogrify is needed for the render_math module.\nPlease upgrade Typogrify to the latest version (anything equal or above version 2.0.7 is okay).\nTypogrify will be turned off due to this reason.\n")
  179. if isinstance(e, KeyError):
  180. print("\nA more recent version of Pelican is needed for Typogrify to work with render_math.\nPlease upgrade Pelican to the latest version or clone it directly from the master GitHub branch\nTypogrify will be turned off due to this reason\n")
  181. def process_mathjax_script(mathjax_settings):
  182. """Load the mathjax script template from file, and render with the settings"""
  183. # Read the mathjax javascript template from file
  184. with open (os.path.dirname(os.path.realpath(__file__))
  185. + '/mathjax_script_template', 'r') as mathjax_script_template:
  186. mathjax_template = mathjax_script_template.read()
  187. return mathjax_template.format(**mathjax_settings)
  188. def mathjax_for_markdown(pelicanobj, mathjax_script, mathjax_settings):
  189. """Instantiates a customized markdown extension for handling mathjax
  190. related content"""
  191. # Create the configuration for the markdown template
  192. config = {}
  193. config['mathjax_script'] = mathjax_script
  194. config['math_tag_class'] = 'math'
  195. config['auto_insert'] = mathjax_settings['auto_insert']
  196. # Instantiate markdown extension and append it to the current extensions
  197. try:
  198. pelicanobj.settings['MD_EXTENSIONS'].append(PelicanMathJaxExtension(config))
  199. except:
  200. sys.excepthook(*sys.exc_info())
  201. sys.stderr.write("\nError - the pelican mathjax markdown extension failed to configure. MathJax is non-functional.\n")
  202. sys.stderr.flush()
  203. def mathjax_for_rst(pelicanobj, mathjax_script):
  204. """Setup math for RST"""
  205. pelicanobj.settings['DOCUTILS_SETTINGS'] = {'math_output': 'MathJax'}
  206. rst_add_mathjax.mathjax_script = mathjax_script
  207. def pelican_init(pelicanobj):
  208. """
  209. Loads the mathjax script according to the settings.
  210. Instantiate the Python markdown extension, passing in the mathjax
  211. script as config parameter.
  212. """
  213. # Process settings, and set global var
  214. mathjax_settings = process_settings(pelicanobj)
  215. # Generate mathjax script
  216. mathjax_script = process_mathjax_script(mathjax_settings)
  217. # Configure Typogrify
  218. configure_typogrify(pelicanobj, mathjax_settings)
  219. # Configure Mathjax For Markdown
  220. if PelicanMathJaxExtension:
  221. mathjax_for_markdown(pelicanobj, mathjax_script, mathjax_settings)
  222. # Configure Mathjax For RST
  223. mathjax_for_rst(pelicanobj, mathjax_script)
  224. # Set process_summary's mathjax_script variable
  225. process_summary.mathjax_script = None
  226. if mathjax_settings['process_summary']:
  227. process_summary.mathjax_script = mathjax_script
  228. def rst_add_mathjax(content):
  229. """Adds mathjax script for reStructuredText"""
  230. # This is only value for .rst files
  231. _, ext = os.path.splitext(os.path.basename(content.source_path))
  232. if ext != '.rst':
  233. return
  234. # If math class is present in text, add the javascript
  235. if 'class="math"' in content._content:
  236. content._content += "<script type='text/javascript'>%s</script>" % rst_add_mathjax.mathjax_script
  237. def process_rst_and_summaries(content_generators):
  238. """
  239. Ensure mathjax script is applied to RST and summaries are
  240. corrected if specified in user settings.
  241. Handle content attached to ArticleGenerator and PageGenerator objects,
  242. since we don't know how to handle other Generator types.
  243. For reStructuredText content, examine both articles and pages.
  244. If article or page is reStructuredText and there is math present,
  245. append the mathjax script.
  246. Also process summaries if present (only applies to articles)
  247. and user wants summaries processed (via user settings)
  248. """
  249. for generator in content_generators:
  250. if isinstance(generator, generators.ArticlesGenerator):
  251. for article in generator.articles:
  252. rst_add_mathjax(article)
  253. #optionally fix truncated formulae in summaries.
  254. if process_summary.mathjax_script is not None:
  255. process_summary(article)
  256. elif isinstance(generator, generators.PagesGenerator):
  257. for page in generator.pages:
  258. rst_add_mathjax(page)
  259. def register():
  260. """Plugin registration"""
  261. signals.initialized.connect(pelican_init)
  262. signals.all_generators_finalized.connect(process_rst_and_summaries)