latex.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. # -*- coding: utf-8 -*-
  2. """
  3. Latex Plugin For Pelican
  4. ========================
  5. This plugin allows you to write mathematical equations in your articles using Latex.
  6. It uses the MathJax Latex JavaScript library to render latex that is embedded in
  7. between `$..$` for inline math and `$$..$$` for displayed math. It also allows for
  8. writing equations in by using `\begin{equation}`...`\end{equation}`. No
  9. alteration to a template is required for this plugin to work, just install and
  10. use.
  11. Typogrify Compatibility
  12. -----------------------
  13. This plugin now plays nicely with typogrify, but it requires
  14. typogrify version 2.07 or above.
  15. User Settings
  16. -------------
  17. Users are also able to pass a dictionary of settings in the settings file which
  18. will control how the mathjax library renders thing. This could be very useful
  19. for template builders that want to adjust look and feel of the math.
  20. See README for more details.
  21. """
  22. from pelican import signals
  23. from pelican import contents
  24. import re
  25. # Global Variables
  26. _WRAP_TAG = None # the tag to wrap mathjax in (needed to play nicely with typogrify or for template designers)
  27. _LATEX_REGEX = re.compile(r'(\$\$|\$|\\begin\{(.+?)\}).*?\1|\\end\{\2\}', re.DOTALL | re.IGNORECASE) # used to detect latex
  28. _LATEX_SUMMARY_REGEX = None # used to match latex in summary
  29. _LATEX_PARTIAL_REGEX = None # used to match latex that has been cut off in summary
  30. _MATHJAX_SETTINGS = {} # Settings that can be specified by the user, used to control mathjax script settings
  31. _MATHJAX_SCRIPT="""
  32. <script type= "text/javascript">
  33. if (!document.getElementById('mathjaxscript_pelican')) {{
  34. var s = document.createElement('script');
  35. s.id = 'mathjaxscript_pelican';
  36. s.type = 'text/javascript'; s.src = 'https:' == document.location.protocol ? 'https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js' : 'http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
  37. s[(window.opera ? "innerHTML" : "text")] =
  38. "MathJax.Hub.Config({{" +
  39. " config: ['MMLorHTML.js']," +
  40. " TeX: {{ extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: {{ autoNumber: 'AMS' }} }}," +
  41. " jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
  42. " extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
  43. " displayAlign: '{align}'," +
  44. " displayIndent: '{indent}'," +
  45. " showMathMenu: {show_menu}," +
  46. " tex2jax: {{ " +
  47. " inlineMath: [ [\'$\',\'$\'] ], " +
  48. " displayMath: [ [\'$$\',\'$$\'] ]," +
  49. " processEscapes: {process_escapes}," +
  50. " preview: '{preview}'," +
  51. " }}, " +
  52. " 'HTML-CSS': {{ " +
  53. " styles: {{ '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {{color: '{color} ! important'}} }}" +
  54. " }} " +
  55. "}}); ";
  56. (document.body || document.getElementsByTagName('head')[0]).appendChild(s);
  57. }}
  58. </script>
  59. """
  60. # Python standard library for binary search, namely bisect is cool but I need
  61. # specific business logic to evaluate my search predicate, so I am using my
  62. # own version
  63. def binary_search(match_tuple, ignore_within):
  64. """Determines if t is within tupleList. Using the fact that tupleList is
  65. ordered, binary search can be performed which is O(logn)
  66. """
  67. ignore = False
  68. if ignore_within == []:
  69. return False
  70. lo = 0
  71. hi = len(ignore_within)-1
  72. # Find first value in array where predicate is False
  73. # predicate function: tupleList[mid][0] < t[index]
  74. while lo < hi:
  75. mid = lo + (hi-lo+1)/2
  76. if ignore_within[mid][0] < match_tuple[0]:
  77. lo = mid
  78. else:
  79. hi = mid-1
  80. if lo >= 0 and lo <= len(ignore_within)-1:
  81. ignore = (ignore_within[lo][0] <= match_tuple[0] and ignore_within[lo][1] >= match_tuple[1])
  82. return ignore
  83. def ignore_content(content):
  84. """Creates a list of match span tuples for which content should be ignored
  85. e.g. <pre> and <code> tags
  86. """
  87. ignore_within = []
  88. # used to detect all <pre> and <code> tags. NOTE: Alter this regex should
  89. # additional tags need to be ignored
  90. ignore_regex = re.compile(r'<(pre|code).*?>.*?</(\1)>', re.DOTALL | re.IGNORECASE)
  91. for match in ignore_regex.finditer(content):
  92. ignore_within.append(match.span())
  93. return ignore_within
  94. def wrap_latex(content, ignore_within):
  95. """Wraps latex in user specified tags.
  96. This is needed for typogrify to play nicely with latex but it can also be
  97. styled by template providers
  98. """
  99. wrap_latex.foundlatex = False
  100. def math_tag_wrap(match):
  101. """function for use in re.sub"""
  102. # determine if the tags are within <pre> and <code> blocks
  103. ignore = binary_search(match.span(1), ignore_within) and binary_search(match.span(2), ignore_within)
  104. if ignore:
  105. return match.group(0)
  106. else:
  107. wrap_latex.foundlatex = True
  108. return '<%s>%s</%s>' % (_WRAP_TAG, match.group(0), _WRAP_TAG)
  109. return (_LATEX_REGEX.sub(math_tag_wrap, content), wrap_latex.foundlatex)
  110. def process_summary(instance, ignore_within):
  111. """Summaries need special care. If Latex is cut off, it must be restored.
  112. In addition, the mathjax script must be included if necessary thereby
  113. making it independent to the template
  114. """
  115. process_summary.altered_summary = False
  116. insert_mathjax_script = False
  117. endtag = '</%s>' % _WRAP_TAG if _WRAP_TAG != None else ''
  118. # use content's _get_summary method to obtain summary
  119. summary = instance._get_summary()
  120. # Determine if there is any math in the summary which are not within the
  121. # ignore_within tags
  122. mathitem = None
  123. for mathitem in _LATEX_SUMMARY_REGEX.finditer(summary):
  124. if binary_search(mathitem.span(), ignore_within):
  125. mathitem = None # In <code> or <pre> tags, so ignore
  126. else:
  127. insert_mathjax_script = True
  128. # Repair the latex if it was cut off mathitem will be the final latex
  129. # code matched that is not within <pre> or <code> tags
  130. if mathitem and mathitem.group(4) == ' ...':
  131. end = r'\end{%s}' % mathitem.group(3) if mathitem.group(3) is not None else mathitem.group(2)
  132. latex_match = re.search('%s.*?%s' % (re.escape(mathitem.group(1)), re.escape(end)), instance._content, re.DOTALL | re.IGNORECASE)
  133. new_summary = summary.replace(mathitem.group(0), latex_match.group(0)+'%s ...' % endtag)
  134. if new_summary != summary:
  135. return new_summary+_MATHJAX_SCRIPT.format(**_MATHJAX_SETTINGS)
  136. def partial_regex(match):
  137. """function for use in re.sub"""
  138. if binary_search(match.span(), ignore_within):
  139. return match.group(0)
  140. process_summary.altered_summary = True
  141. return match.group(1) + match.group(4)
  142. # check for partial latex tags at end. These must be removed
  143. summary = _LATEX_PARTIAL_REGEX.sub(partial_regex, summary)
  144. if process_summary.altered_summary:
  145. return summary+_MATHJAX_SCRIPT.format(**_MATHJAX_SETTINGS) if insert_mathjax_script else summary
  146. return summary+_MATHJAX_SCRIPT.format(**_MATHJAX_SETTINGS) if insert_mathjax_script else None
  147. def process_settings(settings):
  148. """Sets user specified MathJax settings (see README for more details)"""
  149. global _MATHJAX_SETTINGS
  150. # NOTE TO FUTURE DEVELOPERS: Look at the README and what is happening in
  151. # this function if any additional changes to the mathjax settings need to
  152. # be incorporated. Also, please inline comment what the variables
  153. # will be used for
  154. # Default settings
  155. _MATHJAX_SETTINGS['align'] = 'center' # controls alignment of of displayed equations (values can be: left, right, center)
  156. _MATHJAX_SETTINGS['indent'] = '0em' # if above is not set to 'center', then this setting acts as an indent
  157. _MATHJAX_SETTINGS['show_menu'] = 'true' # controls whether to attach mathjax contextual menu
  158. _MATHJAX_SETTINGS['process_escapes'] = 'true' # controls whether escapes are processed
  159. _MATHJAX_SETTINGS['preview'] = 'TeX' # controls what user sees as preview
  160. _MATHJAX_SETTINGS['color'] = 'black' # controls color math is rendered in
  161. if not isinstance(settings, dict):
  162. return
  163. # The following mathjax settings can be set via the settings dictionary
  164. # Iterate over dictionary in a way that is compatible with both version 2
  165. # and 3 of python
  166. for key, value in ((key, settings[key]) for key in settings):
  167. if key == 'align' and isinstance(value, str):
  168. if value == 'left' or value == 'right' or value == 'center':
  169. _MATHJAX_SETTINGS[key] = value
  170. else:
  171. _MATHJAX_SETTINGS[key] = 'center'
  172. if key == 'indent':
  173. _MATHJAX_SETTINGS[key] = value
  174. if key == 'show_menu' and isinstance(value, bool):
  175. _MATHJAX_SETTINGS[key] = 'true' if value else 'false'
  176. if key == 'process_escapes' and isinstance(value, bool):
  177. _MATHJAX_SETTINGS[key] = 'true' if value else 'false'
  178. if key == 'preview' and isinstance(value, str):
  179. _MATHJAX_SETTINGS[key] = value
  180. if key == 'color' and isinstance(value, str):
  181. _MATHJAX_SETTINGS[key] = value
  182. def process_content(instance):
  183. """Processes content, with logic to ensure that typogrify does not clash
  184. with latex.
  185. In addition, mathjax script is inserted at the end of the content thereby
  186. making it independent of the template
  187. """
  188. if not instance._content:
  189. return
  190. ignore_within = ignore_content(instance._content)
  191. if _WRAP_TAG:
  192. instance._content, latex = wrap_latex(instance._content, ignore_within)
  193. else:
  194. latex = True if _LATEX_REGEX.search(instance._content) else False
  195. # The user initially set typogrify to be True, but since it would clash
  196. # with latex, we set it to False. This means that the default reader will
  197. # not call typogrify, so it is called here, where we are able to control
  198. # logic for it ignore latex if necessary
  199. if process_content.typogrify:
  200. # Tell typogrify to ignore the tags that latex has been wrapped in
  201. ignore_tags = [_WRAP_TAG] if _WRAP_TAG else None
  202. # Exact copy of the logic as found in the default reader
  203. from typogrify.filters import typogrify
  204. instance._content = typogrify(instance._content, ignore_tags)
  205. instance.metadata['title'] = typogrify(instance.metadata['title'], ignore_tags)
  206. if latex:
  207. # Mathjax script added to the end of article. Now it does not need to
  208. # be explicitly added to the template
  209. instance._content += _MATHJAX_SCRIPT.format(**_MATHJAX_SETTINGS)
  210. # The summary needs special care because latex math cannot just be cut
  211. # off
  212. summary = process_summary(instance, ignore_within)
  213. if summary != None:
  214. instance._summary = summary
  215. def pelican_init(pelicanobj):
  216. """Intialializes certain global variables and sets typogogrify setting to
  217. False should it be set to True.
  218. """
  219. global _WRAP_TAG
  220. global _LATEX_SUMMARY_REGEX
  221. global _LATEX_PARTIAL_REGEX
  222. try:
  223. settings = pelicanobj.settings['LATEX']
  224. except:
  225. settings = None
  226. process_settings(settings)
  227. # Allows mathjax script to be accessed from template should it be needed
  228. pelicanobj.settings['MATHJAXSCRIPT'] = _MATHJAX_SCRIPT.format(**_MATHJAX_SETTINGS)
  229. # If typogrify set to True, then we need to handle it manually so it does
  230. # not conflict with Latex
  231. try:
  232. if pelicanobj.settings['TYPOGRIFY'] == True:
  233. pelicanobj.settings['TYPOGRIFY'] = False
  234. _WRAP_TAG = 'mathjax' # default to wrap mathjax content inside of
  235. process_content.typogrify = True
  236. except KeyError:
  237. pass
  238. # Set _WRAP_TAG to the settings tag if defined. The idea behind this is
  239. # to give template designers control over how math would be rendered
  240. try:
  241. if pelicanobj.settings['LATEX']['wrap']:
  242. _WRAP_TAG = pelicanobj.settings['LATEX']['wrap']
  243. except (KeyError, TypeError):
  244. pass
  245. # regular expressions that depend on _WRAP_TAG are set here
  246. tagstart = r'<%s>' % _WRAP_TAG if not _WRAP_TAG is None else ''
  247. tagend = r'</%s>' % _WRAP_TAG if not _WRAP_TAG is None else ''
  248. latex_summary_regex = r'((\$\$|\$|\\begin\{(.+?)\}).+?)(\2|\\end\{\3\}|\s?\.\.\.)(%s)?' % tagend
  249. latex_partial_regex = r'(.*)(%s)(\\.*?|\$.*?)(\s?\.\.\.)(%s)' % (tagstart, tagend)
  250. _LATEX_SUMMARY_REGEX = re.compile(latex_summary_regex, re.DOTALL | re.IGNORECASE)
  251. _LATEX_PARTIAL_REGEX = re.compile(latex_partial_regex, re.DOTALL | re.IGNORECASE)
  252. def register():
  253. """Plugin registration"""
  254. signals.initialized.connect(pelican_init)
  255. signals.content_object_init.connect(process_content)