When I write multiple equations in a math directive, they are right-aligned by default.
Proof of concept, full source rst, output PDF. Source rst:
Default behaviour:
.. math::
e^{i \pi} + 1 = 0
x = \frac{-b\pm \sqrt{b^2-4ac}}{2a}
Output:

I would like the maths to be centered, and I think right-aligning is a bad default to choose in this case.
split inside gather.split inside align*. This is useful for if you want to align equations using &.With #2370 and 39396a4 and 3206ccb, we changed it to split in equation* (for single equations) or aligned inside align* (for multiple equations).
The original issue #2370 mentioned right-alignment vs. centering. In the end, the applied fix was to add a negative space to nudge aligned output slightly to the left. But I suspect that the original submitter meant the same problem as my current issue is for.
Sphinx chooses one of two setups for the maths.
\begin{equation*} (or equation).\begin{aligned} and then in \begin{align*} (or align).The latter makes sense when the user has alignment characters & in the maths, but otherwise I don't see a reason to, because without alignment characters, the aligned environment will make everything right-aligned.
I propose to add a third case:
& characters, then we wrap the equations in \begin{gather*}.off-topic but for info: the aligned environment of amsmath has had for years a long-standing bug, which was the reason for the \! negative space. This has now been fixed by the LaTeX team, in a way which maintains backwards compatibility with people using \! in the past. At Sphinx, we need the \! because not all project have up-to-date TeX installations.
a bit less off-topic but for people reading this: if you simply use one math directive per equation you obtain the centering. But a better mark-up is
.. math::
:nowrap:
\begin{gather*}
e^{i \pi} + 1 = 0\\
x = \frac{-b\pm \sqrt{b^2-4ac}}{2a}
\end{gather*}
thus, currently, multiple equations per single math directive is thought out for aligning things with user positioned &.
Your proposal is interesting but has complications: what if the equations contain some matrices using the & ? Sphinx would need to parse the TeX syntax for maths, at least in a minimal way to distinguish this use of & from the one for the alignment of the equations. Not easy.
That's a good point, I didn't consider that some people might want to use & in a centered environment still.
Those people wouldn't be any worse off with my current proposal, but a proposal that would fix that case as well would be even better.
But I would definitely not propose parsing TeX. That would be intrinsically buggy; TeX isn't parseable, only executable.
Let's bounce some more ideas off you. How about these two alternative features? Either of these would be nice for users I think.
:noalign: flag that for multiple equations, switches from aligned/align* (=aligned/right-aligned) to gather (=centered).In addition to the :nowrap: flag, an :env: flag to be used as follows:
.. math::
:env: gather*
e^{i \pi} + 1 = 0
\\
x = \frac{-b\pm \sqrt{b^2-4ac}}{2a}
or perhaps even:
.. math::
:env: aligned/align*
e^{i \pi} + 1 = 0
\\
x = \frac{-b\pm \sqrt{b^2-4ac}}{2a}
This change unfortunately broke my webpage (https://github.com/certik/theoretical-physics/pull/76), so currently I can't upgrade Sphinx until I can figure out how to make the multiline equations not right aligned.
@certik if you add this to your conf.py:
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
'preamble': r'''
\makeatletter
\renewenvironment{aligned}[1][c]{%
\alignedspace@left
\if #1t\vtop \else \if#1b\vbox \else \vcenter \fi\fi \bgroup
\Let@ \chardef\dspbrk@context\@ne \restore@math@cr
\spread@equation
\ialign\bgroup
\hfil\strut@$\m@th\displaystyle##$\hfil
\crcr
}{%
\crcr\egroup
\restorecolumn@
\egroup
}
\makeatother
''',
}
the LaTeX "aligned" environment is redefined to act like "gathered" environment so equations are centered.
This is assuming that your document uses no extra mark-up.
In math typesetting it is not typographically usual to center equations, the norm is rather to align them at equal signs or plus signs etc, ..., using the & marker. This is what Sphinx provides.
If however you have a big document which was created lacking the correct mark-up then the above hack may help. Of course, this is only for PDF output which is the topic of this thread I think.
@certik if your issue is with html, if you use sphinx.ext.imgmath then the above trick can be used too but the LaTeX macros must be moved to imgmath_latex_preamble. If you use MathJax, then i don't know off-hand how to coerce aligned to act as gathered. You could post-process the html files to do the replacement by a script.
@jfbu thanks for the tips. Indeed, in the new sphinx I am using imgmath and pdf. First I am trying the pdf output (the html output will work once I get the pdf working). I am getting:
! Undefined control sequence.
\\aligned [#1]->\alignedspace@left
\if #1t\vtop \else \if #1b\vbox \else \vc...
l.468 \end{aligned}\end{align*}
on the code you sent. I have a custom preamble. To debug this, I modify the generated .tex file. Here is the beginning of the generated tex file:
%% Generated by Sphinx.
\def\sphinxdocclass{report}
\documentclass[letterpaper,10pt,english]{sphinxmanual}
\ifdefined\pdfpxdimen
\let\sphinxpxdimen\pdfpxdimen\else\newdimen\sphinxpxdimen
\fi \sphinxpxdimen=.75bp\relax
\PassOptionsToPackage{warn}{textcomp}
\usepackage[utf8]{inputenc}
\ifdefined\DeclareUnicodeCharacter
\ifdefined\DeclareUnicodeCharacterAsOptional
\DeclareUnicodeCharacter{"00A0}{\nobreakspace}
\DeclareUnicodeCharacter{"2500}{\sphinxunichar{2500}}
\DeclareUnicodeCharacter{"2502}{\sphinxunichar{2502}}
\DeclareUnicodeCharacter{"2514}{\sphinxunichar{2514}}
\DeclareUnicodeCharacter{"251C}{\sphinxunichar{251C}}
\DeclareUnicodeCharacter{"2572}{\textbackslash}
\else
\DeclareUnicodeCharacter{00A0}{\nobreakspace}
\DeclareUnicodeCharacter{2500}{\sphinxunichar{2500}}
\DeclareUnicodeCharacter{2502}{\sphinxunichar{2502}}
\DeclareUnicodeCharacter{2514}{\sphinxunichar{2514}}
\DeclareUnicodeCharacter{251C}{\sphinxunichar{251C}}
\DeclareUnicodeCharacter{2572}{\textbackslash}
\fi
\fi
\usepackage{cmap}
\usepackage[T1]{fontenc}
\usepackage{amsmath,amssymb,amstext}
\usepackage{babel}
\usepackage{times}
\usepackage[Bjarne]{fncychap}
\usepackage{sphinx}
\makeatletter
\renewenvironment{aligned}[1][c]{%
\alignedspace@left
\if #1t\vtop \else \if#1b\vbox \else \vcenter \fi\fi \bgroup
\Let@ \chardef\dspbrk@context\@ne \restore@math@cr
\spread@equation
\ialign\bgroup
\hfil\strut@$\m@th\displaystyle##$\hfil
\crcr
}{%
\crcr\egroup
\restorecolumn@
\egroup
}
\makeatother
\usepackage{geometry}
% Include hyperref last.
\usepackage{hyperref}
% Fix anchor placement for figures with captions.
\usepackage{hypcap}% it must be loaded after hyperref.
% Set up styles of URL: it should be placed after hyperref.
\urlstyle{same}
\addto\captionsenglish{\renewcommand{\figurename}{Fig.}}
\addto\captionsenglish{\renewcommand{\tablename}{Table}}
...
As you can see, I added your code below some of the \usepackage commands. If I add it above them, I get another error:
! LaTeX Error: Environment aligned undefined.
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.31 \renewenvironment{aligned}
[1][c]{%
Do you know what packages I should use to make this work? Do you have some kind of a minimal example? I'll then take it from there.
Thanks again for your help with this. The approach you sent is what I was trying to figure out myself, but I couldn't figure out any latex code to make it work like yours (after we fix it).
Regarding:
In math typesetting it is not typographically usual to center equations, the norm is rather to align them at equal signs or plus signs etc, ..., using the
&marker. This is what Sphinx provides.
Indeed, it's better to use & and I do that at many places, but also at many other places I just have a set of equations one after another, and I just want that to look ok, and the centered equations look much better than right centered ones. In the long run, I would like to format all equations using & probably -- although I need to figure out a format that fits into a book, and it depends on the width of the paper in inches. Once I settle on that, I will reformat all equations to fit.
@certik Ah sorry, I copied pasted from my TeXLive 2018 version of amsmath macros. But they incorporate (since TeXLive 2017 I think) this \alignedspace@left to fix a longstanding amsmath bug.
As your version of amsmath is without this patch, just proceed by defining suitably the macro
\makeatletter
\def\alignedspace@left{\null\,}
\renewenvironment{aligned}[1][c]{%
....
....
\makeatother
If in future you update your TeX installation, the above hack will still work but be as if you had loaded amsmath with option alignedleftspaceyes. As the Sphinx output contains the for many years recommended\! before the \begin{aligned} to fix the \, which was hard-coded in old amsmath, using the \null\, definition for \alignedspace@left is ok even if you update your TeX installation. (I am silencing here that we do something rather radical by obliterating aligned environment to transform it into gathered environment!)
It is normal you get the error if moving the code above the standard packages loaded by Sphinx as the aligned environment is provided by amsmath package.
@certik I am worried my tip will not work due to your remark:
Indeed, it's better to use & and I do that at many places, but also at many other places I just have a set of equations one after another, and I just want that to look ok, and the centered equations look much better than right centered ones. In the long run, I would like to format all equations using & probably -- although I need to figure out a format that fits into a book, and it depends on the width of the paper in inches. Once I settle on that, I will reformat all equations to fit.
Indeed, my tip transforms "aligned" into "gathered" but the latter will not accept & alignment character. Thus if your source contains even a single usage of & within equations, unfortunately my tip will not work. Sorry to waste your time on this...
What would be needed then is new behaviour of our math directive as was asked by @bgeron.
Unfortunately I currently see no obvious way to modify aligned amsmath environment to produce centered equations in absence of & markers and normal aligned behaviour in presence of &.
math directive,:nowrap: and gather*.In both cases this means modifying your sources, which may be too much time time costly. With some script you could do that semi-automatically, but there is the problem I mentioned at top of thread that some & might come from matrix, and not be relevant to the alignment.
@jfbu ok, it looks like I'll have to rework my book to always use the & markers. Thanks for your help.
Aligning multi-line equations seems to be an issue with rendering MathJax as well.
My solution is to set mathjax_config in conf.py as follows:
mathjax_config = {
"jax": ["input/TeX","output/HTML-CSS"],
"displayAlign": "left"
}
Once I do this, all equations are left-aligned, and the number of indents before .. math:: determines how much the equation is indented from the left. This works for both single-line and multi-line. Use & and \\ for additional formatting.
No need for additional LaTeX or :nowrap:
Example:
* We can actually use the gradient-flow graph to get the partial derivative of *any* variable (not just the final output) with respect to any variable it depends on. E.g. if we wanted :math:`\frac{\partial f}{\partial d}`, we would just have to look at the edges along all paths from :math:`f` to :math:`d` and trace the path of gradients accordingly:
.. math::
\frac{\partial f}{\partial d} = \frac{\partial f}{\partial e} \cdot \frac{\partial e}{\partial d}
* Let us now use our knowledge to calculate :math:`\frac{\partial g}{\partial a}`.
* Peeking at the gradient flow graph, we see that there is only one gradient flowing into :math:`a`. This, we can use our basic chain rule:
.. math::
\frac{\partial g}{\partial a} &= \frac{\partial g}{\partial b} \cdot \frac{\partial b}{\partial a} \\
&= (1944 - 900a)(-3) \\
&= 2700a - 5832
* Remember: we store and re-use the values we had already calculated. To obtain any new gradient value, we only have to calculate the gradient on each of the final edge incoming to the target node, on the gradient-flow graph. Here, that is :math:`\frac{\partial b}{\partial a}`. We then reuse the already-computed values of gradients to fill the rest of the chain (here, :math:`\frac{\partial g}{\partial b}`).
(My indents are 2 spaces wide)
Here, I add an extra indentation under the bullet point for the start of the .. math:: directive, to keep it in line with the bullet point text.

References:
Most helpful comment
a bit less off-topic but for people reading this: if you simply use one
mathdirective per equation you obtain the centering. But a better mark-up isthus, currently, multiple equations per single
mathdirective is thought out for aligning things with user positioned&.Your proposal is interesting but has complications: what if the equations contain some matrices using the
&? Sphinx would need to parse the TeX syntax for maths, at least in a minimal way to distinguish this use of&from the one for the alignment of the equations. Not easy.