diff --git a/latex/Readme.md b/latex/Readme.md index 51424ce..49888b8 100644 --- a/latex/Readme.md +++ b/latex/Readme.md @@ -3,73 +3,73 @@ Latex Plugin For Pelican This plugin allows you to write mathematical equations in your articles using Latex. It uses the MathJax Latex JavaScript library to render latex that is embedded in -between `$..$` for inline math and `$$..$$` for displayed math. It also allows for +between `$..$` for inline math and `$$..$$` for displayed math. It also allows for writing equations in by using `\begin{equation}`...`\end{equation}`. Installation ------------ - To enable, ensure that `latex.py` is put somewhere that is accessible. Then use as follows by adding the following to your settings.py: PLUGINS = ["latex"] -Be careful: Not loading the plugin is easy to do, and difficult to detect. To -make life easier, find where pelican is installed, and then copy the plugin -there. An easy way to find where pelican is installed is to verbose list the -available themes by typing `pelican-themes -l -v`. +Your site is now capable of rendering latex math using the mathjax JavaScript +library. No alterations to the template file is needed. -Once the pelican folder is found, copy `latex.py` to the `plugins` folder. Then -add to settings.py like this: - - PLUGINS = ["pelican.plugins.latex"] - -Now all that is left to do is to embed the following to your template file -between the `
` parameters (for the NotMyIdea template, this file is base.html) - - {% if article and article.latex %} - {{ article.latex }} - {% endif %} - {% if page and page.latex %} - {{ page.latex }} - {% endif %} +### Typogrify +Typogrify will now play nicely with Latex (i.e. typogrify can be enabled +and Latex will be rendered correctly). In order for this to happen, +version 2.07 (or above) of typogrify is required. In fact, this plugin expects +that at least version 2.07 is present and will fail without it. Usage ----- -Latex will be embedded in every article. If however you want latex only for -selected articles, then in settings.py, add +### Backward Compatibility +This plugin is backward compatible in the sense that it +accompishes what previous versions did without needing any setup in the +metadata or settings files. - LATEX = 'article' +### Settings File +Extra options regarding how mathjax renders latex can be set in the settings +file. These options are in a dictionary variable called `LATEX` in the pelican +settings file. -And in each article, add the metadata key `latex:`. For example, with the above -settings, creating an article that I want to render latex math, I would just -include 'Latex' as part of the metadata without any value: +The dictionary can be set with the following keys: - Date: 1 sep 2012 - Status: draft - Latex: + * `wrap`: controls the tags that math is wrapped with inside the resulting +html. For example, setting `wrap` to `'mathjax'` would wrap all math inside +` and tags
"""
- if 'LATEX' in gen.settings.keys() and gen.settings['LATEX'] == 'article':
- if 'latex' in metadata.keys():
- metadata['latex'] = latexScript
+ ignore_within = []
+
+ # used to detect all and tags. NOTE: Alter this regex should
+ # additional tags need to be ignored
+ ignore_regex = re.compile(r'<(pre|code).*?>.*?(\1)>', re.DOTALL | re.IGNORECASE)
+
+ for match in ignore_regex.finditer(content):
+ ignore_within.append(match.span())
+
+ return ignore_within
+
+
+def wrap_latex(content, ignore_within):
+ """Wraps latex in user specified tags.
+
+ This is needed for typogrify to play nicely with latex but it can also be
+ styled by template providers
+ """
+ wrap_latex.foundlatex = False
+
+ def math_tag_wrap(match):
+ """function for use in re.sub"""
+
+ # determine if the tags are within and blocks
+ ignore = binary_search(match.span(1), ignore_within) and binary_search(match.span(2), ignore_within)
+
+ if ignore:
+ return match.group(0)
+ else:
+ wrap_latex.foundlatex = True
+ return '<%s>%s%s>' % (_WRAP_TAG, match.group(0), _WRAP_TAG)
+
+ return (_LATEX_REGEX.sub(math_tag_wrap, content), wrap_latex.foundlatex)
+
+
+def process_summary(instance, ignore_within):
+ """Summaries need special care. If Latex is cut off, it must be restored.
+
+ In addition, the mathjax script must be included if necessary thereby
+ making it independent to the template
+ """
+
+ process_summary.altered_summary = False
+ insert_mathjax_script = False
+ endtag = '%s>' % _WRAP_TAG if _WRAP_TAG != None else ''
+
+ # use content's _get_summary method to obtain summary
+ summary = instance._get_summary()
+
+ # Determine if there is any math in the summary which are not within the
+ # ignore_within tags
+ mathitem = None
+ for mathitem in _LATEX_SUMMARY_REGEX.finditer(summary):
+ if binary_search(mathitem.span(), ignore_within):
+ mathitem = None # In or tags, so ignore
+ else:
+ insert_mathjax_script = True
+
+ # Repair the latex if it was cut off mathitem will be the final latex
+ # code matched that is not within or tags
+ if mathitem and mathitem.group(4) == ' ...':
+ end = r'\end{%s}' % mathitem.group(3) if mathitem.group(3) is not None else mathitem.group(2)
+ latex_match = re.search('%s.*?%s' % (re.escape(mathitem.group(1)), re.escape(end)), instance._content, re.DOTALL | re.IGNORECASE)
+ new_summary = summary.replace(mathitem.group(0), latex_match.group(0)+'%s ...' % endtag)
+
+ if new_summary != summary:
+ return new_summary+_MATHJAX_SCRIPT.format(**_MATHJAX_SETTINGS)
+
+ def partial_regex(match):
+ """function for use in re.sub"""
+ if binary_search(match.span(), ignore_within):
+ return match.group(0)
+
+ process_summary.altered_summary = True
+ return match.group(1) + match.group(4)
+
+ # check for partial latex tags at end. These must be removed
+ summary = _LATEX_PARTIAL_REGEX.sub(partial_regex, summary)
+
+ if process_summary.altered_summary:
+ return summary+_MATHJAX_SCRIPT.format(**_MATHJAX_SETTINGS) if insert_mathjax_script else summary
+
+ return summary+_MATHJAX_SCRIPT.format(**_MATHJAX_SETTINGS) if insert_mathjax_script else None
+
+
+def process_settings(settings):
+ """Sets user specified MathJax settings (see README for more details)"""
+
+ global _MATHJAX_SETTINGS
+
+ # NOTE TO FUTURE DEVELOPERS: Look at the README and what is happening in
+ # this function if any additional changes to the mathjax settings need to
+ # be incorporated. Also, please inline comment what the variables
+ # will be used for
+
+ # Default settings
+ _MATHJAX_SETTINGS['align'] = 'center' # controls alignment of of displayed equations (values can be: left, right, center)
+ _MATHJAX_SETTINGS['indent'] = '0em' # if above is not set to 'center', then this setting acts as an indent
+ _MATHJAX_SETTINGS['show_menu'] = 'true' # controls whether to attach mathjax contextual menu
+ _MATHJAX_SETTINGS['process_escapes'] = 'true' # controls whether escapes are processed
+ _MATHJAX_SETTINGS['preview'] = 'TeX' # controls what user sees as preview
+ _MATHJAX_SETTINGS['color'] = 'black' # controls color math is rendered in
+
+ if not isinstance(settings, dict):
+ return
+
+ # The following mathjax settings can be set via the settings dictionary
+ # Iterate over dictionary in a way that is compatible with both version 2
+ # and 3 of python
+ for key, value in ((key, settings[key]) for key in settings):
+ if key == 'align' and isinstance(value, str):
+ if value == 'left' or value == 'right' or value == 'center':
+ _MATHJAX_SETTINGS[key] = value
+ else:
+ _MATHJAX_SETTINGS[key] = 'center'
+
+ if key == 'indent':
+ _MATHJAX_SETTINGS[key] = value
+
+ if key == 'show_menu' and isinstance(value, bool):
+ _MATHJAX_SETTINGS[key] = 'true' if value else 'false'
+
+ if key == 'process_escapes' and isinstance(value, bool):
+ _MATHJAX_SETTINGS[key] = 'true' if value else 'false'
+
+ if key == 'preview' and isinstance(value, str):
+ _MATHJAX_SETTINGS[key] = value
+
+ if key == 'color' and isinstance(value, str):
+ _MATHJAX_SETTINGS[key] = value
+
+
+def process_content(instance):
+ """Processes content, with logic to ensure that typogrify does not clash
+ with latex.
+
+ In addition, mathjax script is inserted at the end of the content thereby
+ making it independent of the template
+ """
+
+ if not instance._content:
+ return
+
+ ignore_within = ignore_content(instance._content)
+
+ if _WRAP_TAG:
+ instance._content, latex = wrap_latex(instance._content, ignore_within)
else:
- metadata['latex'] = latexScript
+ latex = True if _LATEX_REGEX.search(instance._content) else False
+
+ # The user initially set typogrify to be True, but since it would clash
+ # with latex, we set it to False. This means that the default reader will
+ # not call typogrify, so it is called here, where we are able to control
+ # logic for it ignore latex if necessary
+ if process_content.typogrify:
+ # Tell typogrify to ignore the tags that latex has been wrapped in
+ ignore_tags = [_WRAP_TAG] if _WRAP_TAG else None
+
+ # Exact copy of the logic as found in the default reader
+ from typogrify.filters import typogrify
+ instance._content = typogrify(instance._content, ignore_tags)
+ instance.metadata['title'] = typogrify(instance.metadata['title'], ignore_tags)
+
+ if latex:
+ # Mathjax script added to the end of article. Now it does not need to
+ # be explicitly added to the template
+ instance._content += _MATHJAX_SCRIPT.format(**_MATHJAX_SETTINGS)
+
+ # The summary needs special care because latex math cannot just be cut
+ # off
+ summary = process_summary(instance, ignore_within)
+ if summary != None:
+ instance._summary = summary
+
+
+def pelican_init(pelicanobj):
+ """Intialializes certain global variables and sets typogogrify setting to
+ False should it be set to True.
+ """
+
+ global _WRAP_TAG
+ global _LATEX_SUMMARY_REGEX
+ global _LATEX_PARTIAL_REGEX
+
+ try:
+ settings = pelicanobj.settings['LATEX']
+ except:
+ settings = None
+
+ process_settings(settings)
+
+ # Allows mathjax script to be accessed from template should it be needed
+ pelicanobj.settings['MATHJAXSCRIPT'] = _MATHJAX_SCRIPT.format(**_MATHJAX_SETTINGS)
+
+ # If typogrify set to True, then we need to handle it manually so it does
+ # not conflict with Latex
+ try:
+ if pelicanobj.settings['TYPOGRIFY'] == True:
+ pelicanobj.settings['TYPOGRIFY'] = False
+ _WRAP_TAG = 'mathjax' # default to wrap mathjax content inside of
+ process_content.typogrify = True
+ except KeyError:
+ pass
+
+ # Set _WRAP_TAG to the settings tag if defined. The idea behind this is
+ # to give template designers control over how math would be rendered
+ try:
+ if pelicanobj.settings['LATEX']['wrap']:
+ _WRAP_TAG = pelicanobj.settings['LATEX']['wrap']
+ except (KeyError, TypeError):
+ pass
+
+ # regular expressions that depend on _WRAP_TAG are set here
+ tagstart = r'<%s>' % _WRAP_TAG if not _WRAP_TAG is None else ''
+ tagend = r'%s>' % _WRAP_TAG if not _WRAP_TAG is None else ''
+ latex_summary_regex = r'((\$\$|\$|\\begin\{(.+?)\}).+?)(\2|\\end\{\3\}|\s?\.\.\.)(%s)?' % tagend
+ latex_partial_regex = r'(.*)(%s)(\\.*?|\$.*?)(\s?\.\.\.)(%s)' % (tagstart, tagend)
+
+ _LATEX_SUMMARY_REGEX = re.compile(latex_summary_regex, re.DOTALL | re.IGNORECASE)
+ _LATEX_PARTIAL_REGEX = re.compile(latex_partial_regex, re.DOTALL | re.IGNORECASE)
+
def register():
- """
- Plugin registration
- """
- signals.article_generator_context.connect(addLatex)
- signals.page_generator_context.connect(addLatex)
+ """Plugin registration"""
+
+ signals.initialized.connect(pelican_init)
+ signals.content_object_init.connect(process_content)