math.py 15 KB

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