math.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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 = False # used to determine if we should process typogrify
  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. # This next setting controls whether the mathjax script should be automatically
  156. # inserted into the content. The mathjax script will not be inserted into
  157. # the content if no math is detected. For summaries that are present in the
  158. # index listings, mathjax script will also be automatically inserted.
  159. # Setting this value to false means the template must be altered if this
  160. # plugin is to work, and so it is only recommended for the template
  161. # designer who wants maximum control.
  162. _MATHJAX_SETTINGS['auto_insert'] = True # controls whether mathjax script is automatically inserted into the content
  163. if not isinstance(settings, dict):
  164. return
  165. # The following mathjax settings can be set via the settings dictionary
  166. # Iterate over dictionary in a way that is compatible with both version 2
  167. # and 3 of python
  168. for key, value in ((key, settings[key]) for key in settings):
  169. if key == 'auto_insert' and isinstance(value, bool):
  170. _MATHJAX_SETTINGS[key] = value
  171. if key == 'align' and isinstance(value, str):
  172. if value == 'left' or value == 'right' or value == 'center':
  173. _MATHJAX_SETTINGS[key] = value
  174. else:
  175. _MATHJAX_SETTINGS[key] = 'center'
  176. if key == 'indent':
  177. _MATHJAX_SETTINGS[key] = value
  178. if key == 'show_menu' and isinstance(value, bool):
  179. _MATHJAX_SETTINGS[key] = 'true' if value else 'false'
  180. if key == 'process_escapes' and isinstance(value, bool):
  181. _MATHJAX_SETTINGS[key] = 'true' if value else 'false'
  182. if key == 'latex_preview' and isinstance(value, str):
  183. _MATHJAX_SETTINGS[key] = value
  184. if key == 'color' and isinstance(value, str):
  185. _MATHJAX_SETTINGS[key] = value
  186. def process_content(instance):
  187. """Processes content, with logic to ensure that typogrify does not clash
  188. with math.
  189. In addition, mathjax script is inserted at the end of the content thereby
  190. making it independent of the template
  191. """
  192. if not instance._content:
  193. return
  194. ignore_within = ignore_content(instance._content)
  195. if _WRAP_LATEX:
  196. instance._content, math = wrap_math(instance._content, ignore_within)
  197. else:
  198. math = True if _MATH_REGEX.search(instance._content) else False
  199. # The user initially set typogrify to be True, but since it would clash
  200. # with math, we set it to False. This means that the default reader will
  201. # not call typogrify, so it is called here, where we are able to control
  202. # logic for it ignore math if necessary
  203. if _TYPOGRIFY:
  204. # Tell typogrify to ignore the tags that math has been wrapped in
  205. # also, typogrify must always ignore mml (math) tags
  206. ignore_tags = [_WRAP_LATEX,'math'] if _WRAP_LATEX else ['math']
  207. # Exact copy of the logic as found in the default reader
  208. from typogrify.filters import typogrify
  209. instance._content = typogrify(instance._content, ignore_tags)
  210. instance.metadata['title'] = typogrify(instance.metadata['title'], ignore_tags)
  211. if math:
  212. if _MATHJAX_SETTINGS['auto_insert']:
  213. # Mathjax script added to content automatically. Now it
  214. # does not need to be explicitly added to the template
  215. instance._content += _MATHJAX_SCRIPT.format(**_MATHJAX_SETTINGS)
  216. else:
  217. # Place the burden on ensuring mathjax script is available to
  218. # browser on the template designer (see README for more details)
  219. instance.mathjax = True
  220. # The summary needs special care because math math cannot just be cut
  221. # off
  222. summary = process_summary(instance, ignore_within)
  223. if summary != None:
  224. instance._summary = summary
  225. def pelican_init(pelicanobj):
  226. """Intialializes certain global variables and sets typogogrify setting to
  227. False should it be set to True.
  228. """
  229. global _TYPOGRIFY
  230. global _WRAP_LATEX
  231. global _MATH_SUMMARY_REGEX
  232. global _MATH_INCOMPLETE_TAG_REGEX
  233. try:
  234. settings = pelicanobj.settings['MATH']
  235. except:
  236. settings = None
  237. process_settings(settings)
  238. # Allows mathjax script to be accessed from template should it be needed
  239. pelicanobj.settings['MATHJAXSCRIPT'] = _MATHJAX_SCRIPT.format(**_MATHJAX_SETTINGS)
  240. # If typogrify set to True, then we need to handle it manually so it does
  241. # not conflict with Latex
  242. try:
  243. if pelicanobj.settings['TYPOGRIFY'] == True:
  244. pelicanobj.settings['TYPOGRIFY'] = False
  245. _WRAP_LATEX = 'mathjax' # default to wrap mathjax content inside of
  246. _TYPOGRIFY = True
  247. except KeyError:
  248. pass
  249. # Set _WRAP_LATEX to the settings tag if defined. The idea behind this is
  250. # to give template designers control over how math would be rendered
  251. try:
  252. if pelicanobj.settings['MATH']['wrap_latex']:
  253. _WRAP_LATEX = pelicanobj.settings['MATH']['wrap_latex']
  254. except (KeyError, TypeError):
  255. pass
  256. # regular expressions that depend on _WRAP_LATEX are set here
  257. tag_start= r'<%s>' % _WRAP_LATEX if not _WRAP_LATEX is None else ''
  258. tag_end = r'</%s>' % _WRAP_LATEX if not _WRAP_LATEX is None else ''
  259. math_summary_regex = r'((\$\$|\$|\\begin\{(.+?)\}|<(math)(?:\s.*?)?>).+?)(\2|\\end\{\3\}|</\4>|\s?\.\.\.)(%s|</\4>)?' % tag_end
  260. # NOTE: The logic in _get_summary will handle <math> correctly because it
  261. # is perceived as an html tag. Therefore we are only interested in handling
  262. # non mml (i.e. LaTex)
  263. incomplete_end_latex_tag = r'(.*)(%s)(\\\S*?|\$)\s*?(\s?\.\.\.)(%s)?$' % (tag_start, tag_end)
  264. _MATH_SUMMARY_REGEX = re.compile(math_summary_regex, re.DOTALL | re.IGNORECASE)
  265. _MATH_INCOMPLETE_TAG_REGEX = re.compile(incomplete_end_latex_tag, re.DOTALL | re.IGNORECASE)
  266. def register():
  267. """Plugin registration"""
  268. signals.initialized.connect(pelican_init)
  269. signals.content_object_init.connect(process_content)