math.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. # -*- coding: utf-8 -*-
  2. """
  3. Math Render Plugin for Pelican
  4. ==============================
  5. This plugin allows your site to render Math. It supports both LaTeX and MathML
  6. using the MathJax JavaScript engine.
  7. Typogrify Compatibility
  8. -----------------------
  9. This plugin now plays nicely with Typogrify, but it requires
  10. Typogrify version 2.04 or above.
  11. User Settings
  12. -------------
  13. Users are also able to pass a dictionary of settings in the settings file which
  14. will control how the MathJax library renders things. This could be very useful
  15. for template builders that want to adjust the look and feel of the math.
  16. See README for more details.
  17. """
  18. import os
  19. import re
  20. from pelican import signals
  21. from pelican import contents
  22. # Global Variables
  23. _TYPOGRIFY = None # if Typogrify is enabled, this is set to the typogrify.filter function
  24. _WRAP_LATEX = None # the tag to wrap LaTeX math in (needed to play nicely with Typogrify or for template designers)
  25. _MATH_REGEX = re.compile(r'(\$\$|\$|\\begin\{(.+?)\}|<(math)(?:\s.*?)?>).*?(\1|\\end\{\2\}|</\3>)', re.DOTALL | re.IGNORECASE) # used to detect math
  26. _MATH_SUMMARY_REGEX = None # used to match math in summary
  27. _MATH_INCOMPLETE_TAG_REGEX = None # used to match math that has been cut off in summary
  28. _MATHJAX_SETTINGS = {} # settings that can be specified by the user, used to control mathjax script settings
  29. with open (os.path.dirname(os.path.realpath(__file__))+'/mathjax_script.txt', 'r') as mathjax_script: # Read the mathjax javascript from file
  30. _MATHJAX_SCRIPT=mathjax_script.read()
  31. # Python standard library for binary search, namely bisect is cool but I need
  32. # specific business logic to evaluate my search predicate, so I am using my
  33. # own version
  34. def binary_search(match_tuple, ignore_within):
  35. """Determines if t is within tupleList. Using the fact that tupleList is
  36. ordered, binary search can be performed which is O(logn)
  37. """
  38. ignore = False
  39. if ignore_within == []:
  40. return False
  41. lo = 0
  42. hi = len(ignore_within)-1
  43. # Find first value in array where predicate is False
  44. # predicate function: tupleList[mid][0] < t[index]
  45. while lo < hi:
  46. mid = lo + (hi-lo+1)//2
  47. if ignore_within[mid][0] < match_tuple[0]:
  48. lo = mid
  49. else:
  50. hi = mid-1
  51. if lo >= 0 and lo <= len(ignore_within)-1:
  52. ignore = (ignore_within[lo][0] <= match_tuple[0] and ignore_within[lo][1] >= match_tuple[1])
  53. return ignore
  54. def ignore_content(content):
  55. """Creates a list of match span tuples for which content should be ignored
  56. e.g. <pre> and <code> tags
  57. """
  58. ignore_within = []
  59. # used to detect all <pre> and <code> tags. NOTE: Alter this regex should
  60. # additional tags need to be ignored
  61. ignore_regex = re.compile(r'<(pre|code)(?:\s.*?)?>.*?</(\1)>', re.DOTALL | re.IGNORECASE)
  62. for match in ignore_regex.finditer(content):
  63. ignore_within.append(match.span())
  64. return ignore_within
  65. def wrap_math(content, ignore_within):
  66. """Wraps math in user specified tags.
  67. This is needed for Typogrify to play nicely with math but it can also be
  68. styled by template providers
  69. """
  70. wrap_math.found_math = False
  71. def math_tag_wrap(match):
  72. """function for use in re.sub"""
  73. # determine if the tags are within <pre> and <code> blocks
  74. ignore = binary_search(match.span(1), ignore_within) or binary_search(match.span(4), ignore_within)
  75. if ignore or match.group(3) == 'math':
  76. if match.group(3) == 'math':
  77. # Will detect mml, but not wrap anything around it
  78. wrap_math.found_math = True
  79. return match.group(0)
  80. else:
  81. wrap_math.found_math = True
  82. return '<%s>%s</%s>' % (_WRAP_LATEX, match.group(0), _WRAP_LATEX)
  83. return (_MATH_REGEX.sub(math_tag_wrap, content), wrap_math.found_math)
  84. def process_summary(instance, ignore_within):
  85. """Summaries need special care. If Latex is cut off, it must be restored.
  86. In addition, the mathjax script must be included if necessary thereby
  87. making it independent to the template
  88. """
  89. process_summary.altered_summary = False
  90. insert_mathjax = False
  91. end_tag = '</%s>' % _WRAP_LATEX if _WRAP_LATEX is not None else ''
  92. # use content's _get_summary method to obtain summary
  93. summary = instance._get_summary()
  94. # Determine if there is any math in the summary which are not within the
  95. # ignore_within tags
  96. math_item = None
  97. for math_item in _MATH_SUMMARY_REGEX.finditer(summary):
  98. ignore = binary_search(math_item.span(2), ignore_within)
  99. if '...' not in math_item.group(5):
  100. ignore = ignore or binary_search(math_item.span(5), ignore_within)
  101. else:
  102. ignore = ignore or binary_search(math_item.span(6), ignore_within)
  103. if ignore:
  104. math_item = None # In <code> or <pre> tags, so ignore
  105. else:
  106. insert_mathjax = True
  107. # Repair the math if it was cut off math_item will be the final math
  108. # code matched that is not within <pre> or <code> tags
  109. if math_item and '...' in math_item.group(5):
  110. if math_item.group(3) is not None:
  111. end = r'\end{%s}' % math_item.group(3)
  112. elif math_item.group(4) is not None:
  113. end = r'</math>'
  114. elif math_item.group(2) is not None:
  115. end = math_item.group(2)
  116. search_regex = r'%s(%s.*?%s)' % (re.escape(instance._content[0:math_item.start(1)]), re.escape(math_item.group(1)), re.escape(end))
  117. math_match = re.search(search_regex, instance._content, re.DOTALL | re.IGNORECASE)
  118. if math_match:
  119. new_summary = summary.replace(math_item.group(0), math_match.group(1)+'%s ...' % end_tag)
  120. if new_summary != summary:
  121. if _MATHJAX_SETTINGS['auto_insert']:
  122. return new_summary+_MATHJAX_SCRIPT.format(**_MATHJAX_SETTINGS)
  123. else:
  124. instance.mathjax = True
  125. return new_summary
  126. def incomplete_end_latex_tag(match):
  127. """function for use in re.sub"""
  128. if binary_search(match.span(3), ignore_within):
  129. return match.group(0)
  130. process_summary.altered_summary = True
  131. return match.group(1) + match.group(4)
  132. # check for partial math tags at end. These must be removed
  133. summary = _MATH_INCOMPLETE_TAG_REGEX.sub(incomplete_end_latex_tag, summary)
  134. if process_summary.altered_summary or insert_mathjax:
  135. if insert_mathjax:
  136. if _MATHJAX_SETTINGS['auto_insert']:
  137. summary+= _MATHJAX_SCRIPT.format(**_MATHJAX_SETTINGS)
  138. else:
  139. instance.mathjax = True
  140. return summary
  141. return None # Making it explicit that summary was not altered
  142. def process_settings(settings):
  143. """Sets user specified MathJax settings (see README for more details)"""
  144. global _MATHJAX_SETTINGS
  145. # NOTE TO FUTURE DEVELOPERS: Look at the README and what is happening in
  146. # this function if any additional changes to the mathjax settings need to
  147. # be incorporated. Also, please inline comment what the variables
  148. # will be used for
  149. # Default settings
  150. _MATHJAX_SETTINGS['align'] = 'center' # controls alignment of of displayed equations (values can be: left, right, center)
  151. _MATHJAX_SETTINGS['indent'] = '0em' # if above is not set to 'center', then this setting acts as an indent
  152. _MATHJAX_SETTINGS['show_menu'] = 'true' # controls whether to attach mathjax contextual menu
  153. _MATHJAX_SETTINGS['process_escapes'] = 'true' # controls whether escapes are processed
  154. _MATHJAX_SETTINGS['latex_preview'] = 'TeX' # controls what user sees while waiting for LaTex to render
  155. _MATHJAX_SETTINGS['color'] = 'black' # controls color math is rendered in
  156. # Source for MathJax: default (below) is to automatically determine what protocol to use
  157. _MATHJAX_SETTINGS['source'] = """'https:' == document.location.protocol
  158. ? 'https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'
  159. : 'http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'"""
  160. # This next setting controls whether the mathjax script should be automatically
  161. # inserted into the content. The mathjax script will not be inserted into
  162. # the content if no math is detected. For summaries that are present in the
  163. # index listings, mathjax script will also be automatically inserted.
  164. # Setting this value to false means the template must be altered if this
  165. # plugin is to work, and so it is only recommended for the template
  166. # designer who wants maximum control.
  167. _MATHJAX_SETTINGS['auto_insert'] = True # controls whether mathjax script is automatically inserted into the content
  168. if not isinstance(settings, dict):
  169. return
  170. # The following mathjax settings can be set via the settings dictionary
  171. # Iterate over dictionary in a way that is compatible with both version 2
  172. # and 3 of python
  173. for key, value in ((key, settings[key]) for key in settings):
  174. if key == 'auto_insert' and isinstance(value, bool):
  175. _MATHJAX_SETTINGS[key] = value
  176. if key == 'align' and isinstance(value, str):
  177. if value == 'left' or value == 'right' or value == 'center':
  178. _MATHJAX_SETTINGS[key] = value
  179. else:
  180. _MATHJAX_SETTINGS[key] = 'center'
  181. if key == 'indent':
  182. _MATHJAX_SETTINGS[key] = value
  183. if key == 'show_menu' and isinstance(value, bool):
  184. _MATHJAX_SETTINGS[key] = 'true' if value else 'false'
  185. if key == 'process_escapes' and isinstance(value, bool):
  186. _MATHJAX_SETTINGS[key] = 'true' if value else 'false'
  187. if key == 'latex_preview' and isinstance(value, str):
  188. _MATHJAX_SETTINGS[key] = value
  189. if key == 'color' and isinstance(value, str):
  190. _MATHJAX_SETTINGS[key] = value
  191. if key == 'ssl' and isinstance(value, str):
  192. if value == 'off':
  193. _MATHJAX_SETTINGS['source'] = "'http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'"
  194. if value == 'force':
  195. _MATHJAX_SETTINGS['source'] = "'https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'"
  196. def process_content(instance):
  197. """Processes content, with logic to ensure that Typogrify does not clash
  198. with math.
  199. In addition, mathjax script is inserted at the end of the content thereby
  200. making it independent of the template
  201. """
  202. if not instance._content:
  203. return
  204. ignore_within = ignore_content(instance._content)
  205. if _WRAP_LATEX:
  206. instance._content, math = wrap_math(instance._content, ignore_within)
  207. else:
  208. math = True if _MATH_REGEX.search(instance._content) else False
  209. # The user initially set Typogrify to be True, but since it would clash
  210. # with math, we set it to False. This means that the default reader will
  211. # not call Typogrify, so it is called here, where we are able to control
  212. # logic for it ignore math if necessary
  213. if _TYPOGRIFY:
  214. # Tell Typogrify to ignore the tags that math has been wrapped in
  215. # also, Typogrify must always ignore mml (math) tags
  216. ignore_tags = [_WRAP_LATEX,'math'] if _WRAP_LATEX else ['math']
  217. # Exact copy of the logic as found in the default reader
  218. instance._content = _TYPOGRIFY(instance._content, ignore_tags)
  219. instance.metadata['title'] = _TYPOGRIFY(instance.metadata['title'], ignore_tags)
  220. if math:
  221. if _MATHJAX_SETTINGS['auto_insert']:
  222. # Mathjax script added to content automatically. Now it
  223. # does not need to be explicitly added to the template
  224. instance._content += _MATHJAX_SCRIPT.format(**_MATHJAX_SETTINGS)
  225. else:
  226. # Place the burden on ensuring mathjax script is available to
  227. # browser on the template designer (see README for more details)
  228. instance.mathjax = True
  229. # The summary needs special care because math math cannot just be cut
  230. # off
  231. summary = process_summary(instance, ignore_within)
  232. if summary is not None:
  233. instance._summary = summary
  234. def pelican_init(pelicanobj):
  235. """Intialializes certain global variables and sets typogogrify setting to
  236. False should it be set to True.
  237. """
  238. global _TYPOGRIFY
  239. global _WRAP_LATEX
  240. global _MATH_SUMMARY_REGEX
  241. global _MATH_INCOMPLETE_TAG_REGEX
  242. try:
  243. settings = pelicanobj.settings['MATH']
  244. except:
  245. settings = None
  246. process_settings(settings)
  247. # Allows MathJax script to be accessed from template should it be needed
  248. pelicanobj.settings['MATHJAXSCRIPT'] = _MATHJAX_SCRIPT.format(**_MATHJAX_SETTINGS)
  249. # If Typogrify set to True, then we need to handle it manually so it does
  250. # not conflict with LaTeX
  251. try:
  252. if pelicanobj.settings['TYPOGRIFY'] is True:
  253. pelicanobj.settings['TYPOGRIFY'] = False
  254. try:
  255. from typogrify.filters import typogrify
  256. # Determine if this is the correct version of Typogrify to use
  257. import inspect
  258. typogrify_args = inspect.getargspec(typogrify).args
  259. if len(typogrify_args) < 2 or 'ignore_tags' not in typogrify_args:
  260. raise TypeError('Incorrect version of Typogrify')
  261. # At this point, we are happy to use Typogrify, meaning
  262. # it is installed and it is a recent enough version
  263. # that can be used to ignore all math
  264. _TYPOGRIFY = typogrify
  265. _WRAP_LATEX = 'mathjax' # default to wrap mathjax content inside of
  266. except ImportError:
  267. print("\nTypogrify is not installed, so it is being ignored.\nIf you want to use it, please install via: pip install typogrify\n")
  268. except TypeError:
  269. print("\nA more recent version of Typogrify is needed for the render_math module.\nPlease upgrade Typogrify to the latest version (anything above version 2.04 is okay).\nTypogrify will be turned off due to this reason.\n")
  270. except KeyError:
  271. pass
  272. # Set _WRAP_LATEX to the settings tag if defined. The idea behind this is
  273. # to give template designers control over how math would be rendered
  274. try:
  275. if pelicanobj.settings['MATH']['wrap_latex']:
  276. _WRAP_LATEX = pelicanobj.settings['MATH']['wrap_latex']
  277. except (KeyError, TypeError):
  278. pass
  279. # regular expressions that depend on _WRAP_LATEX are set here
  280. tag_start= r'<%s>' % _WRAP_LATEX if not _WRAP_LATEX is None else ''
  281. tag_end = r'</%s>' % _WRAP_LATEX if not _WRAP_LATEX is None else ''
  282. math_summary_regex = r'((\$\$|\$|\\begin\{(.+?)\}|<(math)(?:\s.*?)?>).+?)(\2|\\end\{\3\}|</\4>|\s?\.\.\.)(%s|</\4>)?' % tag_end
  283. # NOTE: The logic in _get_summary will handle <math> correctly because it
  284. # is perceived as an html tag. Therefore we are only interested in handling
  285. # non mml (i.e. LaTex)
  286. incomplete_end_latex_tag = r'(.*)(%s)(\\\S*?|\$)\s*?(\s?\.\.\.)(%s)?$' % (tag_start, tag_end)
  287. _MATH_SUMMARY_REGEX = re.compile(math_summary_regex, re.DOTALL | re.IGNORECASE)
  288. _MATH_INCOMPLETE_TAG_REGEX = re.compile(incomplete_end_latex_tag, re.DOTALL | re.IGNORECASE)
  289. def register():
  290. """Plugin registration"""
  291. signals.initialized.connect(pelican_init)
  292. signals.content_object_init.connect(process_content)