math.py 13 KB

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