Giter Club home page Giter Club logo

sphinxcontrib-katex's Introduction

sphinxcontrib-katex

sphinxcontrib.katex's documentation on Read the Docs sphinxcontrib-katex's supported Python versions sphinxcontrib.katex's MIT license

A Sphinx extension for rendering math in HTML pages.

The extension uses KaTeX for rendering of math in HTML pages. It is designed as a replacement for the built-in extension sphinx.ext.mathjax, which uses MathJax for rendering.

Installation

To install sphinxcontrib.katex into your Python virtual environment run:

$ pip install sphinxcontrib-katex

If you want to pre-render the math by running Javascript on your server instead of running it in the browsers of the users, you have to install nodejs.

Usage

In conf.py of your Sphinx project, add the extension with:

extensions = ['sphinxcontrib.katex']

To enable server side pre-rendering add in addition (nodejs installation needed):

katex_prerender = True

See the Configuration section for all available settings.

Configuration

The behavior of sphinxcontrib.katex can be changed by configuration entries in conf.py of your documentation project. In the following all configuration entries are listed and their default values are shown.

katex_css_path = \
    'https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css'
katex_js_path = 'katex.min.js'
katex_autorender_path = 'auto-render.min.js'
katex_inline = [r'\(', r'\)']
katex_display = [r'\[', r'\]']
katex_prerender = False
katex_options = ''

The specific delimiters written to HTML when math mode is encountered are controlled by the two lists katex_inline and katex_display.

If katex_prerender is set to True the equations will be pre-rendered on the server and loading of the page in the browser will be faster. On your server you must have a katex executable installed and in your PATH as described in the Installation section.

The string variable katex_options allows you to change all available official KaTeX rendering options, e.g.

katex_options = r'''{
    displayMode: true,
    macros: {
        "\\RR": "\\mathbb{R}"
    }
}'''

You can also add KaTeX auto-rendering options to katex_options, but be aware that the delimiters entry should contain the entries of katex_inline and katex_display.

LaTeX Macros

Most probably you want to add some of your LaTeX math commands for the rendering. In KaTeX this is supported by LaTeX macros (\def). You can use the katex_options configuration setting to add those:

katex_options = r'''macros: {
        "\\i": "\\mathrm{i}",
        "\\e": "\\mathrm{e}^{#1}",
        "\\vec": "\\mathbf{#1}",
        "\\x": "\\vec{x}",
        "\\d": "\\operatorname{d}\\!{}",
        "\\dirac": "\\operatorname{\\delta}\\left(#1\\right)",
        "\\scalarprod": "\\left\\langle#1,#2\\right\\rangle",
    }'''

The disadvantage of this option is that those macros will be only available in the HTML based Sphinx builders. If you want to use them in the LaTeX based builders as well you have to add them as the latex_macros setting in your conf.py and specify them using proper LaTeX syntax. Afterwards you can include them via the sphinxcontrib.katex.latex_defs_to_katex_macros function into katex_options and add them to the LaTeX preamble:

import sphinxcontrib.katex as katex

latex_macros = r"""
    \def \i                {\mathrm{i}}
    \def \e              #1{\mathrm{e}^{#1}}
    \def \vec            #1{\mathbf{#1}}
    \def \x                {\vec{x}}
    \def \d                {\operatorname{d}\!}
    \def \dirac          #1{\operatorname{\delta}\left(#1\right)}
    \def \scalarprod   #1#2{\left\langle#1,#2\right\rangle}
"""

# Translate LaTeX macros to KaTeX and add to options for HTML builder
katex_macros = katex.latex_defs_to_katex_macros(latex_macros)
katex_options = 'macros: {' + katex_macros + '}'

# Add LaTeX macros for LATEX builder
latex_elements = {'preamble': latex_macros}

sphinxcontrib-katex's People

Contributors

bryanwweber avatar ezyang avatar felerius avatar hagenw avatar shivshankardayal avatar speth avatar w08r 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

Watchers

 avatar  avatar  avatar  avatar

sphinxcontrib-katex's Issues

Add a script for updating the KaTeX version

Every time we want to update to a new KaTeX version we need to change the version at a few places, namely

katex_version = '0.16.0'

https://github.com/hagenw/sphinxcontrib-katex/blame/e643524b34edddb30517f77eadea2d5c614b9957/README.rst#L85-L89

and after merging #69 we also need to download a new version of sphinxcontrib/katex.js from https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.js

It would be nice, if we can automate all of this by just calling a script and providing the version number as argument.

offline css and fonts

I found out that even with katex_prerender=True the generated documentation wants to fetch katex.min.css from the Internet. I've solved it by installing libjs-katex Ubuntu package and added the following to my conf.py:

html_static_path = ["/usr/share/javascript/katex"]
katex_prerender = True
katex_css_path = "katex.min.css"

The problem is now that the css comes from a different katex version than what was used to render the HTML. I seek advice here how we should solve the problem:

  1. Bundle all katex static resources into sphinxcontrib-katex,
  2. Make the katex.min.js path configurable in katex-server.js so I can point it to /usr/share/javascript/katex/katex.js, or
  3. Don't do anything and leave it to the user to make sure katex_css_path points to the same version as bundled with sphinxcontrib-katex.

[bug] compatibility for windows 10

I suffer from this bug when compiling Pytorch Documents on Windows System.

p = subprocess.Popen(
('katex', ) + options,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE
)

leads to the Exception:
FileNotFoundError: [WinError 2] The system cannot find the file specified

This code doesn't work for Windows System because 'katex' can't be found even though it is in $PATH$ and can be executed in command line.

You can view the solution here: https://stackoverflow.com/questions/5658622/python-subprocess-popen-environment-path

A simple way that should work on Windows too is to explicitly give os.environ['PATH'] as the argument env to subprocess.Popen

Example Solution (The program is katex.cmd on Windows rather than katex on Linux. Might need to deal with that for compatibility.)

    p = subprocess.Popen(
        ('katex.cmd', ) + options,
        stdout=subprocess.PIPE,
        stdin=subprocess.PIPE,
        env=os.environ.copy()
    )

No render equations with nbsphinx

Hello, it is good to know that MathJax is disabled by default in Sphinx. My issue report is the following:

I installed in two python 3.8.2 environment the packages sphinx==2.4.4, sphinxcontrib-katex==0.6.0 and nbsphinx==0.5.1, indeed, the last versions of each one.

I did an experiment and isolated two Sphinx projects called 1 and 2 with the packages mentioned above, the only difference between these is conf.py.
DeepinScreenshot_select-area_20200316112602
DeepinScreenshot_select-area_20200316112634
i.e, 1 load sphinxcontrib-katex and 2 load sphinxcontrib-katex and nbsphinx. Then, when I build both projects and put some math in the front page:
DeepinScreenshot_select-area_20200316114439
Whose sources HTML generated by Sphinx are
DeepinScreenshot_select-area_20200316121745
Hence, there are similar, the difference match on line 17 on 2.
DeepinScreenshot_select-area_20200316110719
And render the math (if I comment the line 17 in index.html from 2):
DeepinScreenshot_select-area_20200316110801
DeepinScreenshot_select-area_20200316114124

Please, could you review this behavior? Maybe the issue will be on nbsphinx and not in sphinxcontrib-katex.

Thank you.

Option to pre-render?

According to the KaTeX documentation, it supports prerendering HTML server side so that no JS has to run on client. Is this supported by sphinxcontrib-katex? If it is not, do you have any idea how difficult it would be to add support?

Question about docs directory installation.

Hi, I do not know if is an unexpected behaviour
image
when I run the following command below

$ python setup.py build
$ python setup.py install --prefix=/usr --root=/some/path

I am expecting that will not belong docs subdirectory over python -c "import site; print(site.getsitepackages()[0])".

Could be done inside sphinxcontrib/docs.

Speed up pre-rendering?

Hi Dr. Wierstorf,

Thank you very much for your creation of this package! It is incredibly useful and speeds up page loads a ton.

I was recently looking to speed up page loads even more (I use a lot of equations in my documentation. I found the pre-rendering option of your project, and was able to use it locally quite successfully. The savings in load time is 30-40% for many pages; the original speed improvement from using katex in the first places was 200-400%.

When I went to use that option with readthedocs however, it turns out they have a 15-minute time limit and the servers aren't quite as a fast as even a slow laptop. Because of the number of equations I use, the build time went from 300 s to 2200 s; over their time limit. They suggested the performance of the extension might be the issue, so I took a look and wanted to share my findings.

I believe the slowdown comes because a new katex process is started for every single equation. Their is a lot of overhead to loading a new node process and having it read and run katex. I looked around to see if there were other Python projects calling katex, and I was able to find one. The approach it takes is to start up a node process, which runs some custom javascript, and operates as a server to process requests.

I was able to macgyver sphinxcontrib-katex into using the same approach with their code and using their Python wrapper. The timing table with the new approach is as follows:

68.5 - no pre-rendering
346.8 s - pre-rendering with currently included approach
77.3 - pre-rendering with server approach

I understand that this approach is substantially more complicated than the current implementation. It is also based around GPL licensed code. I am not an expert in javascript either, and I would have a hard time debugging issues with the javacsript wrapper. I don't think I can offer a pull request with this implemented, and for now it looks like the solution I can afford is to just turn prerendering off.

I though I would share my experience for any future people who ran into this issue.

Have a happy new year and thanks again for this project!

Configuration of delimiters

This is a follow up on #3 as the current solution is not perfect as indicated in #5.

The current situation is as follows:
We introduce the special config variables katex_inline and katex_display. Those are then added to the delimiters entry inside the string variable katex_options.

Possible improvements:

1.) Add the entries of katex_inline and katex_display only to delimiters if the string 'delimiters' cannot be found inside katex_options.
Con: If the custom user setting of delimiters doesn't contain the delimiters specified in katex_inline and katex_display the math will not be rendered at all. This could happen, if a user decides after some time to change for example the katex_inline setting, but forgets to adjust the custom delimiters setting.
Pro: We don't have to add something to the katex_options string.

2.) Allow for katex_inline, katex_display and delimiters settings and simply merge them together.
Con: As the delimiters setting is inside the string variable katex_options it might be complicated to find the right positions for adding the contents of katex_inline and katex_display. In addition, we have to check what happens with duplicated entries.
Pro: This should be bullet proof from a user perspective as you cannot break it, but also gives you maximum flexibility in configuring it.

3.) Abandon katex_inline and katex_display and only use the delimiters entry in katex_options. The default inline and default display delimiters will be automatically extracted from there.
Con: It will be not obvious to a user which of the display: true entries in delimiters will be used as the display delimiter in KaTeX. It might be complicated to extract the delimiters from the string variable katex_options.
Pro: Only one setting for the used delimiters, which is in addition compatible with the way it is described in the KaTeX documentation. If the user is used to KaTeX it should be easy to use this plugin.

4.) Abandon katex_inline and katex_display and add the new config variable delimiters. The same as in 3.) applies, but now we don't have to extract the variable from the katex_options string.
Con: Beside the same issue that it might be not obvious to a user which delimiter is used internally, it is inconsistent with the KaTeX documentation as we allow for all settings inside katex_options, but the delimiters one.
Pro: We don't have to add something to the katex_options string and have again only one setting for the delimiters as in 3.).

@bryanwweber: any thoughts on which might be the best solution, or if there are more pro and cons?

Support macros when prerendering

Macros aren't passed to the katex command line if katex_prerender=True.

They could be written to a file and passed using the --macro-file CLI option.

Example macro file

\abc: 123
\xyz: \mathbf{XYZ}

Gitlab math markdown rendered in sphinx

I bumped into this project as gitlab mentions that they use KaTeX to render math in markdown. And it looks very promising for what i have in mind.

However, i bump into the problem, that gitlab uses dollar_sign+backtick for inline math rendering (https://docs.gitlab.com/ee/user/markdown.html#math). The issue is that even if i configure

katex_inline = ['$`', '`$']

When i generate sphinx html from markdown I still get formula from rendered as $code_block$. As if markdown translation kicks in before sphinxcontrib.katex and there is no expected pattern left for KaTeX to render.

Do you have a hint on how one can overcome it? Thanks in advance

Error with Sphinx 4.0.0b1

Looks like the removal of add_stylesheet in Sphinx 4.0.0 has broken this extension. I get this error when building a project with Sphinx 4.0.0 and this extension:

Extension error (sphinxcontrib.katex):
Handler <function builder_inited at 0x7fa28fa17700> for event 'builder-inited' threw an exception (exception: 'Sphinx' object has no attribute 'add_stylesheet')

I believe the problem is probably this line:

    add_css = getattr(app, 'add_css_file', getattr(app, 'add_stylesheet'))

This doesn't work if add_stylesheet doesn't exist as an attribute of app, which is the case from Sphinx 4.0.0.

Configuration error with Sphinx 5.0.0 or later

Hi, thanks for the nice package. The following behavior starts when python-sphinx upgrade to 5.0.0-1.

When we run this lines

$ python -m sphinx docs docs/_build/ -c docs/ -b html -W
$ python -m sphinx docs docs/_build/ -c docs/ -b latex -W

we see

==> Starting check()...
Running Sphinx v5.0.0
Configuration error:
There is a programmable error in your configuration file:
Traceback (most recent call last):
  File "/usr/lib/python3.10/site-packages/sphinx/config.py", line 343, in eval_config_file
    exec(code, namespace)
  File "/tmp/makepkg/python-sphinxcontrib-katex/src/sphinxcontrib-katex-0.8.6/docs/conf.py", line 5, in <module>
    import sphinxcontrib.katex as katex
ModuleNotFoundError: No module named 'sphinxcontrib.katex'
==> ERROR: A failure occurred in check().

OS: Arch Linux.
Package: python-sphinxcontrib-katex 0.8.6

PR to sphinx?

Are there any plans for submitting this work as an official extension to sphinx?
(thanks for this project btw)

Math delimiter option

At the moment the math delimiters for the produced HTML code are defined by the config options katex_inline and katex_display. In addition, there is the delimiters option for the KaTeX renderer, which can also be configured by the user. As a consequence the user has to make sure that both fit together, which is not an ideal situation.

Other possible solutions are:
1.) We automatically add the katex_inline and katex_display settings to the delimiters entries.
2.) We extract the first entries for display: true and display: false from delimiters and use those to set katex_inline and katex_display automatically.

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.