Git Product home page Git Product logo

python-markdown-math's Introduction

Travis CI status

Math extension for Python-Markdown

This extension adds math formulas support to Python-Markdown.

Installation

Install from PyPI

$ pip install python-markdown-math

Install locally

Use setup.py build and setup.py install to build and install this extension, respectively.

The extension name is mdx_math, so you need to add that name to your list of Python-Markdown extensions. Check Python-Markdown documentation for details on how to load extensions.

Usage

To use this extension, you need to include MathJax library in HTML files, like:

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/mathjax@2/MathJax.js">
</script>

Also, you need to specify a configuration for MathJax. Please note that most of standard configurations include tex2jax extension, which is not needed with this code.

Example of configuration for MathJax 2.x:

<script type="text/x-mathjax-config">
MathJax.Hub.Config({
  config: ["MMLorHTML.js"],
  jax: ["input/TeX", "output/HTML-CSS", "output/NativeMML"],
  extensions: ["MathMenu.js", "MathZoom.js"]
});
</script>

If you want to use MathJax 3.x, you need to teach it to understand 2.x-style <script> tags. See the upgrading documentation on how to do it. Alternatively, you may use the Arithmatex extension which has a generic output mode, that does not require such special configuration.

To pass the extension to Python-Markdown, use mdx_math as extension name. For example:

>>> md = markdown.Markdown(extensions=['mdx_math'])
>>> md.convert('$$e^x$$')
'<p>\n<script type="math/tex; mode=display">e^x</script>\n</p>'

Usage from the command line:

$ echo "\(e^x\)" | python3 -m markdown -x mdx_math
<p>
<script type="math/tex">e^x</script>
</p>

Math Delimiters

For inline math, use \(...\).

For standalone math, use $$...$$, \[...\] or \begin...\end.

The single-dollar delimiter ($...$) for inline math is disabled by default, but can be enabled by passing enable_dollar_delimiter=True in the extension configuration.

If you want to use GitLab-style delimiters ($`...`$ for inline math, and a code block-like ```math...``` syntax for standalone), use use_gitlab_delimiters=True configuration option.

If you want to this extension to generate a preview node (which will be shown when MathJax has not yet processed the node, or when JavaScript is unavailable), use add_preview=True configuration option.

Notes

If you use ReText, this extension is not needed as it is included by default.

This extension also works with Katex. Use the following in your page <head>:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex/dist/katex.min.css" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/katex/dist/katex.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/katex/dist/contrib/mathtex-script-type.min.js" defer></script>

python-markdown-math's People

Contributors

a3nm avatar akshatm avatar blag avatar evidlo avatar mitya57 avatar shahamran avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

python-markdown-math's Issues

python-markdown-math fails to build with Python 3.10.0a2

Hello,
I am packaging python-markdown-math on Fedora Linux.

In Fedora we testing all packages with python 3.10 (alpha release). While testing the 0.7 release we found a test that fails:

======================================================================
FAIL: test_standalone_gitlab (__main__.MathTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/builddir/build/BUILD/python-markdown-math-0.7/test.py", line 17, in
<lambda>
    return lambda self: self.verify(mkd_name, html_name, config=config)
  File "/builddir/build/BUILD/python-markdown-math-0.7/test.py", line 14, in
verify
    self.assertEqual(html, md.convert(mkd) + '\n')
AssertionError: '<scr[97 chars]pt>\n\n<script type="math/tex;
mode=display">\[38 chars]t>\n' != '<scr[97 chars]pt>\n<script type="math/tex;
mode=display">\n [36 chars]t>\n'
  <script type="math/tex; mode=display">
   e^{i \varphi} =
   \cos \varphi + i \sin \varphi
  </script>
- 
  <script type="math/tex; mode=display">
   \text{one more math block}
  </script>

The original bug report can be found here:
https://bugzilla.redhat.com/show_bug.cgi?id=1900512

This is not urgent since python 3.10 is expected to be released in October.

Math in inline mode in Julia packages

Inline mode equations are not rendered in Julia documentation even when I use \(...\) as suggested in the docs. Display mode is working just fine with $$. Can you please help me debug this issue?

The mkdocs file is here and the part of the docs that I am trying to use math notation is the interval [0,1] written here.

Please list LICENSE in the MANIFEST.in

This ensures that PyPI tarballs contain the licensing information, which is important since unlike the GPL, the BSD license contains a unique copyright line and downstream distributors (e.g. Arch Linux) are required to provide the full license text.

render_to_span

Hi.

I can see that the config-option "Render_to_span" making it easier to support users that has disabled js is committed 13 months ago.
Would it be possible to ship a new release anytime soon, so that (large performance change) can get out into the air?

Thanks in advance!
Danni

\begin{} \end{} environment * simble

when using
\begin{equation*} e^{\pi i} + 1 = 0 \end{equation*}
environment, the "*" seems to be eaten and the result will be
Screen Shot 2020-03-10 at 06 49 11
maybe a particular rules is necessary.
Thank you.

Escaping $ when using `enable_dollar_delimiter`

When enable_dollar_delimiter is set to True, you cannot use "$" in text. Would it be possible to add a way to escape it, to be able to use it without its delimiter meaning? Using "$" seems to do only half of the job currently: it disables MathJax, but "\$" renders as "\$", not as "$".

Formula do not display (in wagtail)

Hi, thanks a lot for the amazing extension!

I tried to integrate mathjax into a markdown extension for wagtail and I got to a point where formulas appear in the rendered html as

<script type="math/tex; mode=display"> E = m\cdot c^2 </script>

but the formula does not show up. I followed the instructions on the Readme (especially the settings) and MathJax.Message.Log() on the console shows only the two loaded extensions. The script tag has a display=none property but I have no idea where this can be changed.

'enable_dollar_delimiter' is mandatory

I tried to use the math extension but it ended up with

/usr/local/lib/python2.7/dist-packages/mdx_math.pyc in extendMarkdown(self, md, md_globals)
     45             markdown.inlinepatterns.Pattern(r'(?<!\\)(\\begin{([a-z]+?\*?)})(.+?)(\\end{\3})')
     46         )
---> 47         if not configs['enable_dollar_delimiter']:
     48             inlinemathpatterns = inlinemathpatterns[1:]
     49         for i, pattern in enumerate(inlinemathpatterns):

KeyError: 'enable_dollar_delimiter'

I guess that a configs.get('enable_dollar_delimiter') would be safer.

Failed loading extension 'mdx_math'

Python 2.7.10 (default, Jul 30 2016, 19:40:32) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import markdown
>>> md = markdown.Markdown(extensions=['mdx_math'])
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/markdown/__init__.py", line 159, in __init__
    configs=kwargs.get('extension_configs', {}))
  File "/Library/Python/2.7/site-packages/markdown/__init__.py", line 185, in registerExtensions
    ext = self.build_extension(ext, configs.get(ext, {}))
  File "/Library/Python/2.7/site-packages/markdown/__init__.py", line 264, in build_extension
    module = importlib.import_module(module_name_old_style)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: Failed loading extension 'mdx_math' from 'mdx_math', 'markdown.extensions.mdx_math' or 'mdx_mdx_math'

Conversion error when there's `\begin...\end` in `\(...\)`

Hi,
I was trying to convert r"\( T(v) = \begin{bmatrix}\alpha & \beta \\ \gamma & \delta \end{bmatrix} \)" but it seemed something wrong happened. I don't know if it's intended so.

In [1]: import markdown

In [2]: from mdx_math import MathExtension

In [3]: md = markdown.Markdown(extensions=[MathExtension()])

In [4]: source = r"\( T(v) = \begin{bmatrix}\alpha & \beta \\ \gamma & \delta \end{bmatrix} \)"

In [5]: print(md.convert(source))
   ...: 
<p>
<script type="math/tex"> T(v) = <script type="math/tex; mode=display">\begin{bmatrix}\alpha & \beta \\ \gamma & \delta \end{bmatrix}</script>
</script>
</p>

There's two layers of <script> while I thought it should be

<p>
<script type="math/tex"> T(v) = \begin{bmatrix}\alpha & \beta \\ \gamma & \delta \end{bmatrix}
</script>
</p>

deprecation warnings

I'm getting the following messages when I initialize it. It works fine.

/home/gb/.local/lib/python3.6/site-packages/markdown/util.py:453: DeprecationWarning: Using the add method to register a processor or pattern is deprecated. Use the register method instead.
'Use the register method instead.', DeprecationWarning
/home/gb/.local/lib/python3.6/site-packages/markdown/core.py:128: DeprecationWarning: The 'md_globals' parameter of 'mdx_math.MathExtension.extendMarkdown' is deprecated.
ext._extendMarkdown(self)

why report 'file failed to load https://cdn.jsdelivr.net/npm/mathjax@2/jax/input/Tex/config.js' after configuration?

I intended to use python-markdown-math to support math formula rendering, so i followed official tutorial to try to make such rendering work. i embeded CDN link 'https://cdn.jsdelivr.net/npm/mathjax@2/MathJax.js' into script tag like this:
{% block scripts %}
{{ super() }}
{{ pagedown.include_pagedown() }}
<script type='text'/javascript' id='MathJax-script' async src='https://cdn.jsdelivr.net/npm/mathjax@2/MathJax.js'>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
config: ["MMLorHTML.js"],
jax: ["input/Tex", "output/HTML-CSS", "output/NativeMML"],
extensions: ["MathMenu.js", "MathZoom.js"]
});
</script>
{% endblock %}

when i typed some math formula, the Edge browser reported message on web as follows :
' start to load [MathJax]input/Tex/config.js' ,
'file failed to load https://cdn.jsdelivr.net/npm/mathjax@2/jax/input/Tex/config.js'

i have checked each step and code carefully, use search engine, but can't figure it out. It really muddles me, so i presume to ask for help.

MathJAX v3

With MathJAX v3, the <script type='text/math'> tags are not used anymore. I updated this extension to drop that. While doing it, I realized it can be done much simpler now since the only job of the extension is to prevent the markdown parser from parsing text in math regions. This led to essentially a complete rewrite.

It's in my fork here. Feel free to use it, or parts of it as you need.

Support for label and references

This might not be the correct place to ask this however python markdown math fails to render \label and \ref.

A simple example given by Mathjax is,

In equation \eqref{eq:sample}, we find the value of an
interesting integral:

\begin{equation}
  \int_0^\infty \frac{x^3}{e^x-1}\,dx = \frac{\pi^4}{15}
  \label{eq:sample}
\end{equation}

Interestingly \tag works perfectly but it's not so useful to me when I want to reference.

As a motivation my idea of markdown math is to be able to render everything seen in the Feynman Lectures. The use of MathJax here simple but amazing which some features are missing in every Markdown math extension I've used so far.

Inline Tex inside image annotation

I have some Tex that I'd like to put inside an image annotation, like so

![Hello world $3x + 2$](foo.jpg)

I dug down a bit and it seems that handle_match_inline is correctly substituting the script tag, but this is getting stripped off in a later stage.

def handle_match_inline(m):
    node = etree.Element('script')
    node.set('type', self._get_content_type())
    node.text = AtomicString(m.group(3))
    result = _wrap_node(node, ''.join(m.group(2, 3, 4)), 'span')
    print(etree.tostring(result))
    return result
In [22]: md.convert('![$3x + 2$](a.jpg)')                                                 
b'<script type="math/tex">3x + 2</script>'
Out[22]: '<p><img alt="3x + 2" src="a.jpg" /></p>'

Can I modify the inline tex delimiters?

I tried using tex2jax but it doesn't seem to modify the $$ delimiter, which I want to switch to inline. I also tried upgrading to MathJax3 but that seems to cause no rendered text to display. Is there an effective way to make the $$ an inline delimiter? Thanks!

Can you provide more details in documentation?

I installed the package via sudo pip install python-markdown-math in Mac and run the markdown via html = markdown.markdown(text,extensions=['markdown.extensions.extra','markdown.extensions.mdx_math'])

Got the error bellow:

ImportError: Failed loading extension 'markdown.extensions.mdx_math' from 'markdown.extensions.mdx_math', 'markdown.extensions.markdown.extensions.mdx_math' or 'mdx_markdown.extensions.mdx_math'

I am very much appreciated if you can provide more details in installation.

successful use with ReadTheDocs.org

Not an issue, just a big thank you that your markdown extension works on readthedocs. I've described my setup in an issue over there. This is just for cross reference.

getConfig will not run

First of all, thank you very much for sharing this code.

I have a problem with line 37.

  File "C:\Coding\Anaconda3\lib\site-packages\markdown\extensions\math.py", line
 37, in extendMarkdown
    configs = self.getConfigs()
  File "C:\Coding\Anaconda3\lib\site-packages\markdown\extensions\__init__.py",
line 28, in getConfigs
    return dict([(key, self.getConfig(key)) for key in self.config.keys()])
AttributeError: 'dict_items' object has no attribute 'keys'

If I comment out this line and lines 47-48 then mkdocs works fine and displays mathjax.
I'm on python 3.4.1.

Parsing clash with underscore emphasis

Hi, thanks for this plugin, and thanks for going to the effort to release it on pypi, it really makes things easier.

I've been using it to write some technical documentation, and have found what seems to be a clash with underscore emphasis. I haven't had the time to get to the bottom of it yet, so I thought I'd report it here. Simple test case:

In [3]: import markdown
In [4]: md = markdown.Markdown(extensions=['math'])
In [5]: md.convert(r'${a}_{b}$ ${c}_{d}$')
Out[5]: u'<p>${a}<em>{b}$ ${c}</em>{d}$</p>'

Obviously the emphasis tags which have been inserted here across the boundaries of the math notation are bogus...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.