math.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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
  27. from . pelican_mathjax_markdown_extension import PelicanMathJaxExtension
  28. def process_settings(pelicanobj):
  29. """Sets user specified MathJax settings (see README for more details)"""
  30. mathjax_settings = {}
  31. # NOTE TO FUTURE DEVELOPERS: Look at the README and what is happening in
  32. # this function if any additional changes to the mathjax settings need to
  33. # be incorporated. Also, please inline comment what the variables
  34. # will be used for
  35. # Default settings
  36. mathjax_settings['align'] = 'center' # controls alignment of of displayed equations (values can be: left, right, center)
  37. mathjax_settings['indent'] = '0em' # if above is not set to 'center', then this setting acts as an indent
  38. mathjax_settings['show_menu'] = 'true' # controls whether to attach mathjax contextual menu
  39. mathjax_settings['process_escapes'] = 'true' # controls whether escapes are processed
  40. mathjax_settings['latex_preview'] = 'TeX' # controls what user sees while waiting for LaTex to render
  41. mathjax_settings['color'] = 'inherit' # controls color math is rendered in
  42. 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)
  43. 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)
  44. # Source for MathJax: Works boths for http and https (see http://docs.mathjax.org/en/latest/start.html#secure-access-to-the-cdn)
  45. mathjax_settings['source'] = "'//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'"
  46. # Get the user specified settings
  47. try:
  48. settings = pelicanobj.settings['MATH_JAX']
  49. except:
  50. settings = None
  51. # If no settings have been specified, then return the defaults
  52. if not isinstance(settings, dict):
  53. return mathjax_settings
  54. # The following mathjax settings can be set via the settings dictionary
  55. for key, value in ((key, settings[key]) for key in settings):
  56. # Iterate over dictionary in a way that is compatible with both version 2
  57. # and 3 of python
  58. if key == 'align' and isinstance(value, basestring):
  59. if value == 'left' or value == 'right' or value == 'center':
  60. mathjax_settings[key] = value
  61. else:
  62. mathjax_settings[key] = 'center'
  63. if key == 'indent':
  64. mathjax_settings[key] = value
  65. if key == 'show_menu' and isinstance(value, bool):
  66. mathjax_settings[key] = 'true' if value else 'false'
  67. if key == 'process_escapes' and isinstance(value, bool):
  68. mathjax_settings[key] = 'true' if value else 'false'
  69. if key == 'latex_preview' and isinstance(value, basestring):
  70. mathjax_settings[key] = value
  71. if key == 'color' and isinstance(value, basestring):
  72. mathjax_settings[key] = value
  73. if key == 'linebreak_automatic' and isinstance(value, bool):
  74. mathjax_settings[key] = 'true' if value else 'false'
  75. if key == 'tex_extensions' and isinstance(value, list):
  76. # filter string values, then add '' to them
  77. value = filter(lambda string: isinstance(string, basestring), value)
  78. value = map(lambda string: "'%s'" % string, value)
  79. mathjax_settings[key] = ',' + ','.join(value)
  80. return mathjax_settings
  81. def configure_typogrify(pelicanobj, mathjax_settings):
  82. """Instructs Typogrify to ignore math tags - which allows Typogfrify
  83. to play nicely with math related content"""
  84. # If Typogrify is not being used, then just exit
  85. if not pelicanobj.settings.get('TYPOGRIFY', False):
  86. return
  87. try:
  88. import typogrify
  89. from distutils.version import LooseVersion
  90. if LooseVersion(typogrify.__version__) < LooseVersion('2.0.7'):
  91. raise TypeError('Incorrect version of Typogrify')
  92. from typogrify.filters import typogrify
  93. # At this point, we are happy to use Typogrify, meaning
  94. # it is installed and it is a recent enough version
  95. # that can be used to ignore all math
  96. # Instantiate markdown extension and append it to the current extensions
  97. pelicanobj.settings['TYPOGRIFY_IGNORE_TAGS'].extend(['.math', 'script']) # ignore math class and script
  98. except (ImportError, TypeError, KeyError) as e:
  99. pelicanobj.settings['TYPOGRIFY'] = False # disable Typogrify
  100. if isinstance(e, ImportError):
  101. print("\nTypogrify is not installed, so it is being ignored.\nIf you want to use it, please install via: pip install typogrify\n")
  102. if isinstance(e, TypeError):
  103. 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")
  104. if isinstance(e, KeyError):
  105. 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")
  106. def process_mathjax_script(mathjax_settings):
  107. """Load the mathjax script template from file, and render with the settings"""
  108. # Read the mathjax javascript template from file
  109. with open (os.path.dirname(os.path.realpath(__file__))+'/mathjax_script_template', 'r') as mathjax_script_template:
  110. mathjax_template = mathjax_script_template.read()
  111. return mathjax_template.format(**mathjax_settings)
  112. def mathjax_for_markdown(pelicanobj, mathjax_settings):
  113. """Instantiates a customized markdown extension for handling mathjax
  114. related content"""
  115. # Create the configuration for the markdown template
  116. config = {}
  117. config['mathjax_script'] = process_mathjax_script(mathjax_settings)
  118. config['math_tag_class'] = 'math'
  119. # Instantiate markdown extension and append it to the current extensions
  120. try:
  121. pelicanobj.settings['MD_EXTENSIONS'].append(PelicanMathJaxExtension(config))
  122. except:
  123. sys.excepthook(*sys.exc_info())
  124. sys.stderr.write("\nError - the pelican mathjax markdown extension failed to configure. MathJax is non-functional.\n")
  125. sys.stderr.flush()
  126. def mathjax_for_rst(pelicanobj, mathjax_settings):
  127. pelicanobj.settings['DOCUTILS_SETTINGS'] = {'math_output': 'MathJax'}
  128. rst_add_mathjax.mathjax_script = process_mathjax_script(mathjax_settings)
  129. def pelican_init(pelicanobj):
  130. """Loads the mathjax script according to the settings. Instantiate the Python
  131. markdown extension, passing in the mathjax script as config parameter
  132. """
  133. # Process settings
  134. mathjax_settings = process_settings(pelicanobj)
  135. # Configure Typogrify
  136. configure_typogrify(pelicanobj, mathjax_settings)
  137. # Configure Mathjax For Markdown
  138. mathjax_for_markdown(pelicanobj, mathjax_settings)
  139. # Configure Mathjax For RST
  140. mathjax_for_rst(pelicanobj, mathjax_settings)
  141. def rst_add_mathjax(instance):
  142. _, ext = os.path.splitext(os.path.basename(instance.source_path))
  143. if ext != '.rst':
  144. return
  145. # If math class is present in text, add the javascript
  146. if 'class="math"' in instance._content:
  147. instance._content += "<script type='text/javascript'>%s</script>" % rst_add_mathjax.mathjax_script
  148. def register():
  149. """Plugin registration"""
  150. signals.initialized.connect(pelican_init)
  151. signals.content_object_init.connect(rst_add_mathjax)