matplotlib-rs 0.0.8__cp315-cp315-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- docs/releases/0.0.1.md +268 -0
- docs/releases/0.0.2.md +69 -0
- docs/releases/0.0.3.md +80 -0
- docs/releases/0.0.4.md +73 -0
- docs/releases/0.0.5.md +24 -0
- docs/releases/0.0.6.md +24 -0
- docs/releases/0.0.7.md +24 -0
- docs/releases/0.0.8.md +16 -0
- licenses/LICENSE_CONTOURPY +29 -0
- licenses/LICENSE_CYCLER +27 -0
- licenses/LICENSE_DATEUTIL +54 -0
- licenses/LICENSE_KIWISOLVER +71 -0
- licenses/LICENSE_LIBWEBP +56 -0
- licenses/LICENSE_MATPLOTLIB +1253 -0
- licenses/LICENSE_PYPARSING +20 -0
- licenses/LICENSE_QHULL +39 -0
- licenses/LICENSE_SIX +18 -0
- matplotlib_rs/__init__.py +1683 -0
- matplotlib_rs/__main__.py +27 -0
- matplotlib_rs/_afm.py +500 -0
- matplotlib_rs/_animation_data.py +263 -0
- matplotlib_rs/_api/__init__.py +495 -0
- matplotlib_rs/_api/deprecation.py +534 -0
- matplotlib_rs/_axis_py.py +2991 -0
- matplotlib_rs/_blocking_input.py +31 -0
- matplotlib_rs/_cm.py +1500 -0
- matplotlib_rs/_cm_bivar.py +1289 -0
- matplotlib_rs/_cm_listed.py +2848 -0
- matplotlib_rs/_cm_multivar.py +167 -0
- matplotlib_rs/_color_data.py +1142 -0
- matplotlib_rs/_colormap.py +132 -0
- matplotlib_rs/_constrained_layout.py +825 -0
- matplotlib_rs/_contour.py +108 -0
- matplotlib_rs/_doc_cache.py +12214 -0
- matplotlib_rs/_docstring.py +142 -0
- matplotlib_rs/_enums.py +178 -0
- matplotlib_rs/_figure_rs.py +294 -0
- matplotlib_rs/_fontconfig_pattern.py +129 -0
- matplotlib_rs/_foreign.py +220 -0
- matplotlib_rs/_hook.py +94 -0
- matplotlib_rs/_image.py +160 -0
- matplotlib_rs/_imageio.py +229 -0
- matplotlib_rs/_internal_utils.py +65 -0
- matplotlib_rs/_kiwi.py +484 -0
- matplotlib_rs/_layoutgrid.py +549 -0
- matplotlib_rs/_live.py +192 -0
- matplotlib_rs/_mathtext.py +3103 -0
- matplotlib_rs/_mathtext_data.py +1811 -0
- matplotlib_rs/_mplrs.cp315-win_amd64.pyd +0 -0
- matplotlib_rs/_path.py +25 -0
- matplotlib_rs/_png.py +162 -0
- matplotlib_rs/_pylab_helpers.py +137 -0
- matplotlib_rs/_qhull.py +66 -0
- matplotlib_rs/_rcpush.py +84 -0
- matplotlib_rs/_spines_rs.py +108 -0
- matplotlib_rs/_style_helpers.py +52 -0
- matplotlib_rs/_text_helpers.py +51 -0
- matplotlib_rs/_tight_bbox.py +85 -0
- matplotlib_rs/_tight_layout.py +302 -0
- matplotlib_rs/_tri.py +140 -0
- matplotlib_rs/_type1font.py +1228 -0
- matplotlib_rs/_vendor/__init__.py +8 -0
- matplotlib_rs/_vendor/cycler.py +574 -0
- matplotlib_rs/_vendor/dateutil/__init__.py +27 -0
- matplotlib_rs/_vendor/dateutil/_common.py +44 -0
- matplotlib_rs/_vendor/dateutil/_tzdata_impl.py +148 -0
- matplotlib_rs/_vendor/dateutil/_version.py +5 -0
- matplotlib_rs/_vendor/dateutil/easter.py +90 -0
- matplotlib_rs/_vendor/dateutil/parser/__init__.py +62 -0
- matplotlib_rs/_vendor/dateutil/parser/_parser.py +1614 -0
- matplotlib_rs/_vendor/dateutil/parser/isoparser.py +417 -0
- matplotlib_rs/_vendor/dateutil/relativedelta.py +597 -0
- matplotlib_rs/_vendor/dateutil/rrule.py +1765 -0
- matplotlib_rs/_vendor/dateutil/tz/__init__.py +61 -0
- matplotlib_rs/_vendor/dateutil/tz/_common.py +420 -0
- matplotlib_rs/_vendor/dateutil/tz/_factories.py +81 -0
- matplotlib_rs/_vendor/dateutil/tz/_tzfile.py +1429 -0
- matplotlib_rs/_vendor/dateutil/tz/_tzpath.py +105 -0
- matplotlib_rs/_vendor/dateutil/tz/tz.py +1473 -0
- matplotlib_rs/_vendor/dateutil/tz/win.py +371 -0
- matplotlib_rs/_vendor/dateutil/tzwin.py +3 -0
- matplotlib_rs/_vendor/dateutil/utils.py +72 -0
- matplotlib_rs/_vendor/dateutil/zoneinfo/__init__.py +234 -0
- matplotlib_rs/_vendor/pyparsing/__init__.py +414 -0
- matplotlib_rs/_vendor/pyparsing/actions.py +265 -0
- matplotlib_rs/_vendor/pyparsing/common.py +571 -0
- matplotlib_rs/_vendor/pyparsing/core.py +6973 -0
- matplotlib_rs/_vendor/pyparsing/exceptions.py +354 -0
- matplotlib_rs/_vendor/pyparsing/helpers.py +1770 -0
- matplotlib_rs/_vendor/pyparsing/results.py +929 -0
- matplotlib_rs/_vendor/pyparsing/testing.py +399 -0
- matplotlib_rs/_vendor/pyparsing/unicode.py +357 -0
- matplotlib_rs/_vendor/pyparsing/util.py +515 -0
- matplotlib_rs/_vendor/pyparsing/warnings.py +11 -0
- matplotlib_rs/_vendor/six.py +1004 -0
- matplotlib_rs/animation.py +1843 -0
- matplotlib_rs/artist.py +2302 -0
- matplotlib_rs/axes/__init__.py +19 -0
- matplotlib_rs/axes/_axes.py +9402 -0
- matplotlib_rs/axes/_bar.py +185 -0
- matplotlib_rs/axes/_base.py +5236 -0
- matplotlib_rs/axes/_base_rs.py +727 -0
- matplotlib_rs/axes/_boxplot.py +391 -0
- matplotlib_rs/axes/_hist.py +99 -0
- matplotlib_rs/axes/_secondary_axes.py +357 -0
- matplotlib_rs/axis.py +1963 -0
- matplotlib_rs/backend_bases.py +3760 -0
- matplotlib_rs/backend_managers.py +388 -0
- matplotlib_rs/backend_tools.py +1002 -0
- matplotlib_rs/backends/__init__.py +6 -0
- matplotlib_rs/backends/_backend_pdf_ps.py +451 -0
- matplotlib_rs/backends/backend_agg.py +552 -0
- matplotlib_rs/backends/backend_mixed.py +123 -0
- matplotlib_rs/backends/backend_pdf.py +2711 -0
- matplotlib_rs/backends/backend_pgf.py +1031 -0
- matplotlib_rs/backends/backend_ps.py +1491 -0
- matplotlib_rs/backends/backend_svg.py +1395 -0
- matplotlib_rs/backends/backend_template.py +214 -0
- matplotlib_rs/backends/registry.py +423 -0
- matplotlib_rs/bezier.py +691 -0
- matplotlib_rs/category.py +236 -0
- matplotlib_rs/cbook.py +2762 -0
- matplotlib_rs/cm.py +251 -0
- matplotlib_rs/collections.py +2711 -0
- matplotlib_rs/colorbar.py +1586 -0
- matplotlib_rs/colorizer.py +909 -0
- matplotlib_rs/colors.py +4278 -0
- matplotlib_rs/container.py +256 -0
- matplotlib_rs/contour.py +1756 -0
- matplotlib_rs/dates.py +1847 -0
- matplotlib_rs/dviread.py +1386 -0
- matplotlib_rs/figure.py +3815 -0
- matplotlib_rs/font_manager.py +1855 -0
- matplotlib_rs/ft2font.py +515 -0
- matplotlib_rs/gridspec.py +808 -0
- matplotlib_rs/hatch.py +244 -0
- matplotlib_rs/image.py +1863 -0
- matplotlib_rs/inset.py +291 -0
- matplotlib_rs/layout_engine.py +310 -0
- matplotlib_rs/legend.py +1480 -0
- matplotlib_rs/legend_handler.py +812 -0
- matplotlib_rs/lines.py +1886 -0
- matplotlib_rs/markers.py +908 -0
- matplotlib_rs/mathtext.py +141 -0
- matplotlib_rs/mlab.py +959 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Bold.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-BoldOblique.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Oblique.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansDisplay.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Bold.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-BoldOblique.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Oblique.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Bold.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-BoldItalic.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Italic.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerifDisplay.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/LICENSE_DEJAVU +99 -0
- matplotlib_rs/mpl-data/fonts/ttf/LICENSE_STIX +124 -0
- matplotlib_rs/mpl-data/fonts/ttf/LastResortHE-Regular.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXGeneral.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralItalic.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXNonUni.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBolIta.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniIta.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizFiveSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmb10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmex10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmmi10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmr10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmss10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmsy10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmti10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmtt10.ttf +0 -0
- matplotlib_rs/mpl-data/images/back-symbolic.svg +46 -0
- matplotlib_rs/mpl-data/images/back.pdf +0 -0
- matplotlib_rs/mpl-data/images/back.png +0 -0
- matplotlib_rs/mpl-data/images/back.svg +46 -0
- matplotlib_rs/mpl-data/images/back_large.png +0 -0
- matplotlib_rs/mpl-data/images/filesave-symbolic.svg +68 -0
- matplotlib_rs/mpl-data/images/filesave.pdf +72 -0
- matplotlib_rs/mpl-data/images/filesave.png +0 -0
- matplotlib_rs/mpl-data/images/filesave.svg +68 -0
- matplotlib_rs/mpl-data/images/filesave_large.png +0 -0
- matplotlib_rs/mpl-data/images/forward-symbolic.svg +46 -0
- matplotlib_rs/mpl-data/images/forward.pdf +0 -0
- matplotlib_rs/mpl-data/images/forward.png +0 -0
- matplotlib_rs/mpl-data/images/forward.svg +46 -0
- matplotlib_rs/mpl-data/images/forward_large.png +0 -0
- matplotlib_rs/mpl-data/images/hand.pdf +0 -0
- matplotlib_rs/mpl-data/images/hand.png +0 -0
- matplotlib_rs/mpl-data/images/hand.svg +130 -0
- matplotlib_rs/mpl-data/images/help-symbolic.svg +52 -0
- matplotlib_rs/mpl-data/images/help.pdf +71 -0
- matplotlib_rs/mpl-data/images/help.png +0 -0
- matplotlib_rs/mpl-data/images/help.svg +52 -0
- matplotlib_rs/mpl-data/images/help_large.png +0 -0
- matplotlib_rs/mpl-data/images/home-symbolic.svg +59 -0
- matplotlib_rs/mpl-data/images/home.pdf +0 -0
- matplotlib_rs/mpl-data/images/home.png +0 -0
- matplotlib_rs/mpl-data/images/home.svg +59 -0
- matplotlib_rs/mpl-data/images/home_large.png +0 -0
- matplotlib_rs/mpl-data/images/matplotlib.pdf +0 -0
- matplotlib_rs/mpl-data/images/matplotlib.png +0 -0
- matplotlib_rs/mpl-data/images/matplotlib.svg +3171 -0
- matplotlib_rs/mpl-data/images/matplotlib_large.png +0 -0
- matplotlib_rs/mpl-data/images/move-symbolic.svg +73 -0
- matplotlib_rs/mpl-data/images/move.pdf +0 -0
- matplotlib_rs/mpl-data/images/move.png +0 -0
- matplotlib_rs/mpl-data/images/move.svg +73 -0
- matplotlib_rs/mpl-data/images/move_large.png +0 -0
- matplotlib_rs/mpl-data/images/qt4_editor_options.pdf +0 -0
- matplotlib_rs/mpl-data/images/qt4_editor_options.png +0 -0
- matplotlib_rs/mpl-data/images/qt4_editor_options.svg +48 -0
- matplotlib_rs/mpl-data/images/qt4_editor_options_large.png +0 -0
- matplotlib_rs/mpl-data/images/subplots-symbolic.svg +81 -0
- matplotlib_rs/mpl-data/images/subplots.pdf +0 -0
- matplotlib_rs/mpl-data/images/subplots.png +0 -0
- matplotlib_rs/mpl-data/images/subplots.svg +81 -0
- matplotlib_rs/mpl-data/images/subplots_large.png +0 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect-symbolic.svg +40 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect.pdf +69 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect.png +0 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect.svg +40 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect_large.png +0 -0
- matplotlib_rs/mpl-data/kpsewhich.lua +4 -0
- matplotlib_rs/mpl-data/matplotlibrc +849 -0
- matplotlib_rs/mpl-data/plot_directive/plot_directive.css +16 -0
- matplotlib_rs/mpl-data/sample_data/Minduka_Present_Blue_Pack.png +0 -0
- matplotlib_rs/mpl-data/sample_data/README.txt +2 -0
- matplotlib_rs/mpl-data/sample_data/Stocks.csv +526 -0
- matplotlib_rs/mpl-data/sample_data/axes_grid/bivariate_normal.npy +0 -0
- matplotlib_rs/mpl-data/sample_data/data_x_x2_x3.csv +11 -0
- matplotlib_rs/mpl-data/sample_data/eeg.dat +0 -0
- matplotlib_rs/mpl-data/sample_data/embedding_in_wx3.xrc +65 -0
- matplotlib_rs/mpl-data/sample_data/goog.npz +0 -0
- matplotlib_rs/mpl-data/sample_data/grace_hopper.jpg +0 -0
- matplotlib_rs/mpl-data/sample_data/jacksboro_fault_dem.npz +0 -0
- matplotlib_rs/mpl-data/sample_data/logo2.png +0 -0
- matplotlib_rs/mpl-data/sample_data/membrane.dat +0 -0
- matplotlib_rs/mpl-data/sample_data/msft.csv +66 -0
- matplotlib_rs/mpl-data/sample_data/s1045.ima.gz +0 -0
- matplotlib_rs/mpl-data/sample_data/topobathy.npz +0 -0
- matplotlib_rs/mpl-data/stylelib/Solarize_Light2.mplstyle +53 -0
- matplotlib_rs/mpl-data/stylelib/_classic_test_patch.mplstyle +8 -0
- matplotlib_rs/mpl-data/stylelib/_mpl-gallery-nogrid.mplstyle +19 -0
- matplotlib_rs/mpl-data/stylelib/_mpl-gallery.mplstyle +19 -0
- matplotlib_rs/mpl-data/stylelib/bmh.mplstyle +27 -0
- matplotlib_rs/mpl-data/stylelib/classic.mplstyle +491 -0
- matplotlib_rs/mpl-data/stylelib/dark_background.mplstyle +26 -0
- matplotlib_rs/mpl-data/stylelib/fast.mplstyle +11 -0
- matplotlib_rs/mpl-data/stylelib/fivethirtyeight.mplstyle +37 -0
- matplotlib_rs/mpl-data/stylelib/ggplot.mplstyle +39 -0
- matplotlib_rs/mpl-data/stylelib/grayscale.mplstyle +29 -0
- matplotlib_rs/mpl-data/stylelib/petroff10.mplstyle +5 -0
- matplotlib_rs/mpl-data/stylelib/petroff6.mplstyle +5 -0
- matplotlib_rs/mpl-data/stylelib/petroff8.mplstyle +5 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-bright.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-colorblind.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark-palette.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-darkgrid.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-deep.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-muted.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-notebook.mplstyle +21 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-paper.mplstyle +21 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-pastel.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-poster.mplstyle +21 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-talk.mplstyle +21 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-ticks.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-white.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-whitegrid.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8.mplstyle +57 -0
- matplotlib_rs/mpl-data/stylelib/tableau-colorblind10.mplstyle +3 -0
- matplotlib_rs/mpl_toolkits/__init__.py +3 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/__init__.py +11 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/anchored_artists.py +415 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/axes_divider.py +619 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/axes_grid.py +565 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/axes_rgb.py +158 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/axes_size.py +272 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/inset_locator.py +525 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/mpl_axes.py +129 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/parasite_axes.py +261 -0
- matplotlib_rs/mpl_toolkits/axisartist/__init__.py +15 -0
- matplotlib_rs/mpl_toolkits/axisartist/angle_helper.py +396 -0
- matplotlib_rs/mpl_toolkits/axisartist/axes_divider.py +3 -0
- matplotlib_rs/mpl_toolkits/axisartist/axis_artist.py +1148 -0
- matplotlib_rs/mpl_toolkits/axisartist/axisline_style.py +193 -0
- matplotlib_rs/mpl_toolkits/axisartist/axislines.py +475 -0
- matplotlib_rs/mpl_toolkits/axisartist/floating_axes.py +265 -0
- matplotlib_rs/mpl_toolkits/axisartist/grid_finder.py +329 -0
- matplotlib_rs/mpl_toolkits/axisartist/grid_helper_curvelinear.py +353 -0
- matplotlib_rs/mpl_toolkits/axisartist/parasite_axes.py +8 -0
- matplotlib_rs/mpl_toolkits/mplot3d/__init__.py +4 -0
- matplotlib_rs/mpl_toolkits/mplot3d/art3d.py +1758 -0
- matplotlib_rs/mpl_toolkits/mplot3d/axes3d.py +4462 -0
- matplotlib_rs/mpl_toolkits/mplot3d/axis3d.py +807 -0
- matplotlib_rs/mpl_toolkits/mplot3d/proj3d.py +270 -0
- matplotlib_rs/offsetbox.py +1726 -0
- matplotlib_rs/patches.py +5049 -0
- matplotlib_rs/path.py +1147 -0
- matplotlib_rs/patheffects.py +512 -0
- matplotlib_rs/projections/__init__.py +126 -0
- matplotlib_rs/projections/geo.py +512 -0
- matplotlib_rs/projections/polar.py +1518 -0
- matplotlib_rs/pylab.py +68 -0
- matplotlib_rs/pyplot.py +4834 -0
- matplotlib_rs/quiver.py +1236 -0
- matplotlib_rs/rcsetup.py +3435 -0
- matplotlib_rs/sankey.py +815 -0
- matplotlib_rs/scale.py +1002 -0
- matplotlib_rs/spines.py +618 -0
- matplotlib_rs/stackplot.py +144 -0
- matplotlib_rs/streamplot.py +768 -0
- matplotlib_rs/style/__init__.py +269 -0
- matplotlib_rs/style/core.py +28 -0
- matplotlib_rs/table.py +860 -0
- matplotlib_rs/texmanager.py +375 -0
- matplotlib_rs/text.py +2412 -0
- matplotlib_rs/textpath.py +377 -0
- matplotlib_rs/ticker.py +3111 -0
- matplotlib_rs/transforms.py +3069 -0
- matplotlib_rs/tri/__init__.py +24 -0
- matplotlib_rs/tri/_triangulation.py +248 -0
- matplotlib_rs/tri/_tricontour.py +271 -0
- matplotlib_rs/tri/_trifinder.py +97 -0
- matplotlib_rs/tri/_triinterpolate.py +1575 -0
- matplotlib_rs/tri/_tripcolor.py +170 -0
- matplotlib_rs/tri/_triplot.py +87 -0
- matplotlib_rs/tri/_trirefine.py +308 -0
- matplotlib_rs/tri/_tritools.py +264 -0
- matplotlib_rs/typing.py +597 -0
- matplotlib_rs/units.py +196 -0
- matplotlib_rs/widgets.py +4455 -0
- matplotlib_rs-0.0.8.dist-info/METADATA +392 -0
- matplotlib_rs-0.0.8.dist-info/RECORD +352 -0
- matplotlib_rs-0.0.8.dist-info/WHEEL +4 -0
- matplotlib_rs-0.0.8.dist-info/sboms/matplotlib-rs.cyclonedx.json +4390 -0
|
@@ -0,0 +1,3103 @@
|
|
|
1
|
+
# Vendored from matplotlib 3.11 (see licenses/LICENSE_MATPLOTLIB), adapted for matplotlib_rs.
|
|
2
|
+
"""
|
|
3
|
+
Implementation details for :mod:`.mathtext`.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import abc
|
|
9
|
+
import copy
|
|
10
|
+
import enum
|
|
11
|
+
import functools
|
|
12
|
+
import itertools
|
|
13
|
+
import logging
|
|
14
|
+
import math
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import types
|
|
18
|
+
import unicodedata
|
|
19
|
+
import string
|
|
20
|
+
import textwrap
|
|
21
|
+
import typing as T
|
|
22
|
+
from typing import NamedTuple
|
|
23
|
+
|
|
24
|
+
import numpy as np
|
|
25
|
+
from numpy.typing import NDArray
|
|
26
|
+
from ._vendor.pyparsing import (
|
|
27
|
+
Empty, Forward, Literal, Group, NotAny, OneOrMore, Optional,
|
|
28
|
+
ParseBaseException, ParseException, ParseExpression, ParseFatalException,
|
|
29
|
+
ParserElement, ParseResults, QuotedString, Regex, StringEnd, Token,
|
|
30
|
+
ZeroOrMore, pyparsing_common, nested_expr, one_of)
|
|
31
|
+
|
|
32
|
+
import matplotlib_rs as mpl
|
|
33
|
+
from . import cbook
|
|
34
|
+
from ._mathtext_data import (
|
|
35
|
+
latex_to_bakoma, stix_glyph_fixes, stix_virtual_fonts, tex2uni)
|
|
36
|
+
from .font_manager import FontProperties, findfont, get_font
|
|
37
|
+
from .ft2font import FT2Font, Kerning, LoadFlags
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
if T.TYPE_CHECKING:
|
|
41
|
+
from collections.abc import Iterable
|
|
42
|
+
from .ft2font import CharacterCodeType, Glyph, GlyphIndexType
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
ParserElement.enable_packrat()
|
|
46
|
+
_log = logging.getLogger("matplotlib.mathtext")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
##############################################################################
|
|
50
|
+
# FONTS
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def get_unicode_index(symbol: str) -> CharacterCodeType: # Publicly exported.
|
|
54
|
+
r"""
|
|
55
|
+
Return the integer index (from the Unicode table) of *symbol*.
|
|
56
|
+
|
|
57
|
+
Parameters
|
|
58
|
+
----------
|
|
59
|
+
symbol : str
|
|
60
|
+
A single (Unicode) character, a TeX command (e.g. r'\pi') or a Type1
|
|
61
|
+
symbol name (e.g. 'phi').
|
|
62
|
+
"""
|
|
63
|
+
try: # This will succeed if symbol is a single Unicode char
|
|
64
|
+
return ord(symbol)
|
|
65
|
+
except TypeError:
|
|
66
|
+
pass
|
|
67
|
+
try: # Is symbol a TeX symbol (i.e. \alpha)
|
|
68
|
+
return tex2uni[symbol.strip("\\")]
|
|
69
|
+
except KeyError as err:
|
|
70
|
+
raise ValueError(
|
|
71
|
+
f"{symbol!r} is not a valid Unicode character or TeX/Type1 symbol"
|
|
72
|
+
) from err
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class VectorParse(NamedTuple):
|
|
76
|
+
"""
|
|
77
|
+
The namedtuple type returned by ``MathTextParser("path").parse(...)``.
|
|
78
|
+
|
|
79
|
+
Attributes
|
|
80
|
+
----------
|
|
81
|
+
width, height, depth : float
|
|
82
|
+
The global metrics.
|
|
83
|
+
glyphs : list
|
|
84
|
+
The glyphs including their positions.
|
|
85
|
+
rect : list
|
|
86
|
+
The list of rectangles.
|
|
87
|
+
"""
|
|
88
|
+
width: float
|
|
89
|
+
height: float
|
|
90
|
+
depth: float
|
|
91
|
+
glyphs: list[tuple[FT2Font, float, CharacterCodeType, GlyphIndexType, float, float]]
|
|
92
|
+
rects: list[tuple[float, float, float, float]]
|
|
93
|
+
|
|
94
|
+
VectorParse.__module__ = "matplotlib.mathtext"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class RasterParse(NamedTuple):
|
|
98
|
+
"""
|
|
99
|
+
The namedtuple type returned by ``MathTextParser("agg").parse(...)``.
|
|
100
|
+
|
|
101
|
+
Attributes
|
|
102
|
+
----------
|
|
103
|
+
ox, oy : float
|
|
104
|
+
The offsets are always zero.
|
|
105
|
+
width, height, depth : float
|
|
106
|
+
The global metrics.
|
|
107
|
+
image : 2D array of uint8
|
|
108
|
+
A raster image.
|
|
109
|
+
"""
|
|
110
|
+
ox: float
|
|
111
|
+
oy: float
|
|
112
|
+
width: float
|
|
113
|
+
height: float
|
|
114
|
+
depth: float
|
|
115
|
+
image: NDArray[np.uint8]
|
|
116
|
+
|
|
117
|
+
RasterParse.__module__ = "matplotlib.mathtext"
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class Output:
|
|
121
|
+
r"""
|
|
122
|
+
Result of `ship`\ping a box: lists of positioned glyphs and rectangles.
|
|
123
|
+
|
|
124
|
+
This class is not exposed to end users, but converted to a `VectorParse` or
|
|
125
|
+
a `RasterParse` by `.MathTextParser.parse`.
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
def __init__(self, box: Box):
|
|
129
|
+
self.box = box
|
|
130
|
+
self.glyphs: list[tuple[float, float, FontInfo]] = [] # (ox, oy, info)
|
|
131
|
+
self.rects: list[tuple[float, float, float, float]] = [] # (x, y, w, h)
|
|
132
|
+
|
|
133
|
+
def to_vector(self) -> VectorParse:
|
|
134
|
+
w, h, d = map(
|
|
135
|
+
np.ceil, [self.box.width, self.box.height, self.box.depth])
|
|
136
|
+
gs = [(info.font, info.fontsize, info.num, info.glyph_index,
|
|
137
|
+
ox, h - oy + info.offset)
|
|
138
|
+
for ox, oy, info in self.glyphs]
|
|
139
|
+
rs = [(bx, h - (by + bh), bw, bh)
|
|
140
|
+
for bx, by, bw, bh in self.rects]
|
|
141
|
+
# Output.rects has downwards ys, VectorParse.rects has upwards ys.
|
|
142
|
+
return VectorParse(w, h + d, d, gs, rs)
|
|
143
|
+
|
|
144
|
+
def to_raster(self, *, antialiased: bool) -> RasterParse:
|
|
145
|
+
# Metrics y's and mathtext y's are oriented in opposite directions,
|
|
146
|
+
# hence the switch between ymin and ymax.
|
|
147
|
+
xmin = min([*[ox + info.metrics.xmin for ox, oy, info in self.glyphs],
|
|
148
|
+
*[x for x, y, w, h in self.rects], 0]) - 1
|
|
149
|
+
ymin = min([*[oy - info.metrics.ymax for ox, oy, info in self.glyphs],
|
|
150
|
+
*[y for x, y, w, h in self.rects], 0]) - 1
|
|
151
|
+
xmax = max([*[ox + info.metrics.xmax for ox, oy, info in self.glyphs],
|
|
152
|
+
*[x + w for x, y, w, h in self.rects], 0]) + 1
|
|
153
|
+
ymax = max([*[oy - info.metrics.ymin for ox, oy, info in self.glyphs],
|
|
154
|
+
*[y + h for x, y, w, h in self.rects], 0]) + 1
|
|
155
|
+
w = xmax - xmin
|
|
156
|
+
h = ymax - ymin - self.box.depth
|
|
157
|
+
d = ymax - ymin - self.box.height
|
|
158
|
+
image = np.zeros((math.ceil(h + max(d, 0)), math.ceil(w)), np.uint8)
|
|
159
|
+
|
|
160
|
+
# Ideally, we could just use self.glyphs and self.rects here, shifting
|
|
161
|
+
# their coordinates by (-xmin, -ymin), but this yields slightly
|
|
162
|
+
# different results due to floating point slop; shipping twice is the
|
|
163
|
+
# old approach and keeps baseline images backcompat.
|
|
164
|
+
shifted = ship(self.box, (-xmin, -ymin))
|
|
165
|
+
|
|
166
|
+
for ox, oy, info in shifted.glyphs:
|
|
167
|
+
info.font.draw_glyph_to_bitmap(
|
|
168
|
+
image, int(ox), int(oy - info.metrics.iceberg), info.glyph,
|
|
169
|
+
antialiased=antialiased)
|
|
170
|
+
for x, y, bw, bh in shifted.rects:
|
|
171
|
+
height = max(int(bh) - 1, 0)
|
|
172
|
+
if height == 0:
|
|
173
|
+
center = y + bh / 2
|
|
174
|
+
y = int(center - (height + 1) / 2)
|
|
175
|
+
else:
|
|
176
|
+
y = int(y)
|
|
177
|
+
x1 = math.floor(x)
|
|
178
|
+
x2 = math.ceil(x + bw)
|
|
179
|
+
image[y:y+height+1, x1:x2+1] = 0xff
|
|
180
|
+
return RasterParse(0, 0, w, h + d, d, image)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class FontMetrics(NamedTuple):
|
|
184
|
+
"""
|
|
185
|
+
Metrics of a font.
|
|
186
|
+
|
|
187
|
+
Attributes
|
|
188
|
+
----------
|
|
189
|
+
advance : float
|
|
190
|
+
The advance distance (in points) of the glyph.
|
|
191
|
+
height : float
|
|
192
|
+
The height of the glyph in points.
|
|
193
|
+
width : float
|
|
194
|
+
The width of the glyph in points.
|
|
195
|
+
xmin, xmax, ymin, ymax : float
|
|
196
|
+
The ink rectangle of the glyph.
|
|
197
|
+
iceberg : float
|
|
198
|
+
The distance from the baseline to the top of the glyph. (This corresponds to
|
|
199
|
+
TeX's definition of "height".)
|
|
200
|
+
slanted : bool
|
|
201
|
+
Whether the glyph should be considered as "slanted" (currently used for kerning
|
|
202
|
+
sub/superscripts).
|
|
203
|
+
"""
|
|
204
|
+
advance: float
|
|
205
|
+
height: float
|
|
206
|
+
width: float
|
|
207
|
+
xmin: float
|
|
208
|
+
xmax: float
|
|
209
|
+
ymin: float
|
|
210
|
+
ymax: float
|
|
211
|
+
iceberg: float
|
|
212
|
+
slanted: bool
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
class FontInfo(NamedTuple):
|
|
216
|
+
font: FT2Font
|
|
217
|
+
fontsize: float
|
|
218
|
+
postscript_name: str
|
|
219
|
+
metrics: FontMetrics
|
|
220
|
+
num: CharacterCodeType
|
|
221
|
+
glyph_index: GlyphIndexType
|
|
222
|
+
glyph: Glyph
|
|
223
|
+
offset: float
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
class Fonts(abc.ABC):
|
|
227
|
+
"""
|
|
228
|
+
An abstract base class for a system of fonts to use for mathtext.
|
|
229
|
+
|
|
230
|
+
The class must be able to take symbol keys and font file names and
|
|
231
|
+
return the character metrics. It also delegates to a backend class
|
|
232
|
+
to do the actual drawing.
|
|
233
|
+
"""
|
|
234
|
+
|
|
235
|
+
def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlags):
|
|
236
|
+
"""
|
|
237
|
+
Parameters
|
|
238
|
+
----------
|
|
239
|
+
default_font_prop : `~.font_manager.FontProperties`
|
|
240
|
+
The default non-math font, or the base font for Unicode (generic)
|
|
241
|
+
font rendering.
|
|
242
|
+
load_glyph_flags : `.ft2font.LoadFlags`
|
|
243
|
+
Flags passed to the glyph loader (e.g. ``FT_Load_Glyph`` and
|
|
244
|
+
``FT_Load_Char`` for FreeType-based fonts).
|
|
245
|
+
"""
|
|
246
|
+
self.default_font_prop = default_font_prop
|
|
247
|
+
self.load_glyph_flags = load_glyph_flags
|
|
248
|
+
|
|
249
|
+
def get_kern(self, font1: str, fontclass1: str, sym1: str, fontsize1: float,
|
|
250
|
+
font2: str, fontclass2: str, sym2: str, fontsize2: float,
|
|
251
|
+
dpi: float) -> float:
|
|
252
|
+
"""
|
|
253
|
+
Get the kerning distance for font between *sym1* and *sym2*.
|
|
254
|
+
|
|
255
|
+
See `~.Fonts.get_metrics` for a detailed description of the parameters.
|
|
256
|
+
"""
|
|
257
|
+
return 0.
|
|
258
|
+
|
|
259
|
+
def _get_font(self, font: str) -> FT2Font:
|
|
260
|
+
raise NotImplementedError
|
|
261
|
+
|
|
262
|
+
def _get_info(self, font: str, font_class: str, sym: str, fontsize: float,
|
|
263
|
+
dpi: float) -> FontInfo:
|
|
264
|
+
raise NotImplementedError
|
|
265
|
+
|
|
266
|
+
def get_metrics(self, font: str, font_class: str, sym: str, fontsize: float,
|
|
267
|
+
dpi: float) -> FontMetrics:
|
|
268
|
+
r"""
|
|
269
|
+
Parameters
|
|
270
|
+
----------
|
|
271
|
+
font : str
|
|
272
|
+
One of the TeX font names: "tt", "it", "rm", "cal", "sf", "bf",
|
|
273
|
+
"default", "regular", "normal", "bb", "frak", "scr". "default"
|
|
274
|
+
and "regular" are synonyms and use the non-math font.
|
|
275
|
+
"normal" denotes the normal math font.
|
|
276
|
+
font_class : str
|
|
277
|
+
One of the TeX font names (as for *font*), but **not** "bb",
|
|
278
|
+
"frak", or "scr". This is used to combine two font classes. The
|
|
279
|
+
only supported combination currently is ``get_metrics("frak", "bf",
|
|
280
|
+
...)``.
|
|
281
|
+
sym : str
|
|
282
|
+
A symbol in raw TeX form, e.g., "1", "x", or "\sigma".
|
|
283
|
+
fontsize : float
|
|
284
|
+
Font size in points.
|
|
285
|
+
dpi : float
|
|
286
|
+
Rendering dots-per-inch.
|
|
287
|
+
|
|
288
|
+
Returns
|
|
289
|
+
-------
|
|
290
|
+
FontMetrics
|
|
291
|
+
"""
|
|
292
|
+
info = self._get_info(font, font_class, sym, fontsize, dpi)
|
|
293
|
+
return info.metrics
|
|
294
|
+
|
|
295
|
+
def render_glyph(self, output: Output, ox: float, oy: float, font: str,
|
|
296
|
+
font_class: str, sym: str, fontsize: float, dpi: float) -> None:
|
|
297
|
+
"""
|
|
298
|
+
At position (*ox*, *oy*), draw the glyph specified by the remaining
|
|
299
|
+
parameters (see `get_metrics` for their detailed description).
|
|
300
|
+
"""
|
|
301
|
+
info = self._get_info(font, font_class, sym, fontsize, dpi)
|
|
302
|
+
output.glyphs.append((ox, oy, info))
|
|
303
|
+
|
|
304
|
+
def render_rect_filled(self, output: Output,
|
|
305
|
+
x: float, y: float, w: float, h: float) -> None:
|
|
306
|
+
"""
|
|
307
|
+
Draw a filled rectangle at (*x*, *y*) with size (*w*, *h*).
|
|
308
|
+
"""
|
|
309
|
+
output.rects.append((x, y, w, h))
|
|
310
|
+
|
|
311
|
+
def get_axis_height(self, font: str, fontsize: float, dpi: float) -> float:
|
|
312
|
+
"""
|
|
313
|
+
Get the axis height for the given *font* and *fontsize*.
|
|
314
|
+
"""
|
|
315
|
+
raise NotImplementedError()
|
|
316
|
+
|
|
317
|
+
def get_quad(self, font: str, fontsize: float, dpi: float) -> float:
|
|
318
|
+
"""
|
|
319
|
+
Get the size of a quad for the given *font* and *fontsize*.
|
|
320
|
+
"""
|
|
321
|
+
raise NotImplementedError()
|
|
322
|
+
|
|
323
|
+
def get_xheight(self, font: str, fontsize: float, dpi: float) -> float:
|
|
324
|
+
"""
|
|
325
|
+
Get the xheight for the given *font* and *fontsize*.
|
|
326
|
+
"""
|
|
327
|
+
raise NotImplementedError()
|
|
328
|
+
|
|
329
|
+
def get_underline_thickness(self, font: str, fontsize: float, dpi: float) -> float:
|
|
330
|
+
"""
|
|
331
|
+
Get the line thickness that matches the given font. Used as a
|
|
332
|
+
base unit for drawing lines such as in a fraction or radical.
|
|
333
|
+
"""
|
|
334
|
+
raise NotImplementedError()
|
|
335
|
+
|
|
336
|
+
def get_sized_alternatives_for_symbol(self, fontname: str,
|
|
337
|
+
sym: str) -> list[tuple[str, str]]:
|
|
338
|
+
"""
|
|
339
|
+
Override if your font provides multiple sizes of the same
|
|
340
|
+
symbol. Should return a list of symbols matching *sym* in
|
|
341
|
+
various sizes. The expression renderer will select the most
|
|
342
|
+
appropriate size for a given situation from this list.
|
|
343
|
+
"""
|
|
344
|
+
return [(fontname, sym)]
|
|
345
|
+
|
|
346
|
+
def get_font_constants(self) -> type[FontConstantsBase]:
|
|
347
|
+
return FontConstantsBase
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
class TruetypeFonts(Fonts, metaclass=abc.ABCMeta):
|
|
351
|
+
"""
|
|
352
|
+
A generic base class for all font setups that use Truetype fonts
|
|
353
|
+
(through FT2Font).
|
|
354
|
+
"""
|
|
355
|
+
|
|
356
|
+
def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlags):
|
|
357
|
+
super().__init__(default_font_prop, load_glyph_flags)
|
|
358
|
+
# Per-instance cache.
|
|
359
|
+
self._get_info = functools.cache(self._get_info) # type: ignore[method-assign]
|
|
360
|
+
self._fonts = {}
|
|
361
|
+
self.fontmap: dict[str, str] = {}
|
|
362
|
+
|
|
363
|
+
filename = findfont(self.default_font_prop)
|
|
364
|
+
default_font = get_font(filename)
|
|
365
|
+
self._fonts['default'] = default_font
|
|
366
|
+
self._fonts['regular'] = default_font
|
|
367
|
+
|
|
368
|
+
def _get_font(self, font: str) -> FT2Font:
|
|
369
|
+
basename = self.fontmap.get(font, font)
|
|
370
|
+
cached_font = self._fonts.get(basename)
|
|
371
|
+
if cached_font is None and os.path.exists(basename):
|
|
372
|
+
cached_font = get_font(basename)
|
|
373
|
+
self._fonts[basename] = cached_font
|
|
374
|
+
self._fonts[cached_font.postscript_name] = cached_font
|
|
375
|
+
self._fonts[cached_font.postscript_name.lower()] = cached_font
|
|
376
|
+
return T.cast(FT2Font, cached_font) # FIXME: Not sure this is guaranteed.
|
|
377
|
+
|
|
378
|
+
def _get_offset(self, font: FT2Font, glyph: Glyph, fontsize: float,
|
|
379
|
+
dpi: float) -> float:
|
|
380
|
+
if font.postscript_name == 'Cmex10':
|
|
381
|
+
return (glyph.height / 64 / 2) + (fontsize/3 * dpi/72)
|
|
382
|
+
return 0.
|
|
383
|
+
|
|
384
|
+
def _get_glyph(self, fontname: str, font_class: str,
|
|
385
|
+
sym: str) -> tuple[FT2Font, CharacterCodeType, bool]:
|
|
386
|
+
raise NotImplementedError
|
|
387
|
+
|
|
388
|
+
# The return value of _get_info is cached per-instance.
|
|
389
|
+
def _get_info(self, fontname: str, font_class: str, sym: str, fontsize: float,
|
|
390
|
+
dpi: float) -> FontInfo:
|
|
391
|
+
font, num, slanted = self._get_glyph(fontname, font_class, sym)
|
|
392
|
+
font.set_size(fontsize, dpi)
|
|
393
|
+
glyph_index = font.get_char_index(num)
|
|
394
|
+
glyph = font.load_glyph(glyph_index, flags=self.load_glyph_flags)
|
|
395
|
+
|
|
396
|
+
xmin, ymin, xmax, ymax = (val / 64 for val in glyph.bbox)
|
|
397
|
+
offset = self._get_offset(font, glyph, fontsize, dpi)
|
|
398
|
+
metrics = FontMetrics(
|
|
399
|
+
advance=glyph.linearHoriAdvance / 65536,
|
|
400
|
+
height=glyph.height / 64,
|
|
401
|
+
width=glyph.width / 64,
|
|
402
|
+
xmin=xmin,
|
|
403
|
+
xmax=xmax,
|
|
404
|
+
ymin=ymin + offset,
|
|
405
|
+
ymax=ymax + offset,
|
|
406
|
+
# iceberg is the equivalent of TeX's "height"
|
|
407
|
+
iceberg=glyph.horiBearingY / 64 + offset,
|
|
408
|
+
slanted=slanted
|
|
409
|
+
)
|
|
410
|
+
|
|
411
|
+
return FontInfo(
|
|
412
|
+
font=font,
|
|
413
|
+
fontsize=fontsize,
|
|
414
|
+
postscript_name=font.postscript_name,
|
|
415
|
+
metrics=metrics,
|
|
416
|
+
num=num,
|
|
417
|
+
glyph_index=glyph_index,
|
|
418
|
+
glyph=glyph,
|
|
419
|
+
offset=offset
|
|
420
|
+
)
|
|
421
|
+
|
|
422
|
+
def get_axis_height(self, fontname: str, fontsize: float, dpi: float) -> float:
|
|
423
|
+
consts = self.get_font_constants()
|
|
424
|
+
if consts.axis_height is not None:
|
|
425
|
+
return consts.axis_height * fontsize * dpi / 72
|
|
426
|
+
else:
|
|
427
|
+
# The fraction line (if present) must be aligned with the minus sign.
|
|
428
|
+
# Therefore, the height of the latter from the baseline is the axis height.
|
|
429
|
+
metrics = self.get_metrics(
|
|
430
|
+
fontname, mpl.rcParams['mathtext.default'], '\u2212', fontsize, dpi)
|
|
431
|
+
return (metrics.ymax + metrics.ymin) / 2
|
|
432
|
+
|
|
433
|
+
def get_quad(self, fontname: str, fontsize: float, dpi: float) -> float:
|
|
434
|
+
consts = self.get_font_constants()
|
|
435
|
+
if consts.quad is not None:
|
|
436
|
+
return consts.quad * fontsize * dpi / 72
|
|
437
|
+
else:
|
|
438
|
+
# With no other option, we measure the size of an 'm'.
|
|
439
|
+
metrics = self.get_metrics(
|
|
440
|
+
fontname, mpl.rcParams['mathtext.default'], 'm', fontsize, dpi)
|
|
441
|
+
return metrics.advance
|
|
442
|
+
|
|
443
|
+
def get_xheight(self, fontname: str, fontsize: float, dpi: float) -> float:
|
|
444
|
+
consts = self.get_font_constants()
|
|
445
|
+
if consts.x_height is not None:
|
|
446
|
+
return consts.x_height * fontsize * dpi / 72
|
|
447
|
+
else:
|
|
448
|
+
# Some fonts report the wrong x-height, while some don't store it, so
|
|
449
|
+
# we do a poor man's x-height.
|
|
450
|
+
metrics = self.get_metrics(
|
|
451
|
+
fontname, mpl.rcParams['mathtext.default'], 'x', fontsize, dpi)
|
|
452
|
+
return metrics.iceberg
|
|
453
|
+
|
|
454
|
+
def get_underline_thickness(self, font: str, fontsize: float, dpi: float) -> float:
|
|
455
|
+
# This function used to grab underline thickness from the font
|
|
456
|
+
# metrics, but that information is just too un-reliable, so it
|
|
457
|
+
# is now hardcoded.
|
|
458
|
+
return ((0.75 / 12) * fontsize * dpi) / 72
|
|
459
|
+
|
|
460
|
+
def get_kern(self, font1: str, fontclass1: str, sym1: str, fontsize1: float,
|
|
461
|
+
font2: str, fontclass2: str, sym2: str, fontsize2: float,
|
|
462
|
+
dpi: float) -> float:
|
|
463
|
+
if font1 == font2 and fontsize1 == fontsize2:
|
|
464
|
+
info1 = self._get_info(font1, fontclass1, sym1, fontsize1, dpi)
|
|
465
|
+
info2 = self._get_info(font2, fontclass2, sym2, fontsize2, dpi)
|
|
466
|
+
font = info1.font
|
|
467
|
+
return font.get_kerning(info1.glyph_index, info2.glyph_index,
|
|
468
|
+
Kerning.DEFAULT) / 64
|
|
469
|
+
return super().get_kern(font1, fontclass1, sym1, fontsize1,
|
|
470
|
+
font2, fontclass2, sym2, fontsize2, dpi)
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
class BakomaFonts(TruetypeFonts):
|
|
474
|
+
"""
|
|
475
|
+
Use the Bakoma TrueType fonts for rendering.
|
|
476
|
+
|
|
477
|
+
Symbols are strewn about a number of font files, each of which has
|
|
478
|
+
its own proprietary 8-bit encoding.
|
|
479
|
+
"""
|
|
480
|
+
_fontmap = {
|
|
481
|
+
'normal': 'cmmi10',
|
|
482
|
+
'cal': 'cmsy10',
|
|
483
|
+
'rm': 'cmr10',
|
|
484
|
+
'tt': 'cmtt10',
|
|
485
|
+
'it': 'cmti10',
|
|
486
|
+
'bf': 'cmb10',
|
|
487
|
+
'sf': 'cmss10',
|
|
488
|
+
'ex': 'cmex10',
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlags):
|
|
492
|
+
self._stix_fallback = StixFonts(default_font_prop, load_glyph_flags)
|
|
493
|
+
|
|
494
|
+
super().__init__(default_font_prop, load_glyph_flags)
|
|
495
|
+
for key, val in self._fontmap.items():
|
|
496
|
+
fullpath = findfont(val)
|
|
497
|
+
self.fontmap[key] = fullpath
|
|
498
|
+
self.fontmap[val] = fullpath
|
|
499
|
+
|
|
500
|
+
_slanted_symbols = set(r"\int \oint".split())
|
|
501
|
+
|
|
502
|
+
def _get_glyph(self, fontname: str, font_class: str,
|
|
503
|
+
sym: str) -> tuple[FT2Font, CharacterCodeType, bool]:
|
|
504
|
+
font = None
|
|
505
|
+
|
|
506
|
+
if fontname in self.fontmap and sym in latex_to_bakoma:
|
|
507
|
+
basename, num = latex_to_bakoma[sym]
|
|
508
|
+
slanted = (basename in ("cmmi10", "cmti10")) or sym in self._slanted_symbols
|
|
509
|
+
font = self._get_font(basename)
|
|
510
|
+
elif len(sym) == 1:
|
|
511
|
+
slanted = (fontname in ("it", "normal"))
|
|
512
|
+
if fontname == "normal" and sym.isdigit():
|
|
513
|
+
# use digits from cmr (roman alphabet) instead of cmm (math alphabet),
|
|
514
|
+
# same as LaTeX does.
|
|
515
|
+
fontname = "rm"
|
|
516
|
+
slanted = False
|
|
517
|
+
font = self._get_font(fontname)
|
|
518
|
+
if font is not None:
|
|
519
|
+
num = ord(sym)
|
|
520
|
+
if font is not None and font.get_char_index(num) != 0:
|
|
521
|
+
return font, num, slanted
|
|
522
|
+
else:
|
|
523
|
+
return self._stix_fallback._get_glyph(fontname, font_class, sym)
|
|
524
|
+
|
|
525
|
+
# The Bakoma fonts contain many pre-sized alternatives for the delimiters. The
|
|
526
|
+
# Auto(Height|Width)Char classes will use these alternatives and select the best
|
|
527
|
+
# (closest sized) glyph.
|
|
528
|
+
_latex_sizes = ('big', 'Big', 'bigg', 'Bigg')
|
|
529
|
+
_size_alternatives = {
|
|
530
|
+
'(': [('rm', '('), *[('ex', fr'\__parenleft{s}__') for s in _latex_sizes]],
|
|
531
|
+
')': [('rm', ')'), *[('ex', fr'\__parenright{s}__') for s in _latex_sizes]],
|
|
532
|
+
'{': [('ex', fr'\__braceleft{s}__') for s in _latex_sizes],
|
|
533
|
+
'}': [('ex', fr'\__braceright{s}__') for s in _latex_sizes],
|
|
534
|
+
'[': [('rm', '['), *[('ex', fr'\__bracketleft{s}__') for s in _latex_sizes]],
|
|
535
|
+
']': [('rm', ']'), *[('ex', fr'\__bracketright{s}__') for s in _latex_sizes]],
|
|
536
|
+
'<': [('cal', r'\__angbracketleft__'),
|
|
537
|
+
*[('ex', fr'\__angbracketleft{s}__') for s in _latex_sizes]],
|
|
538
|
+
'>': [('cal', r'\__angbracketright__'),
|
|
539
|
+
*[('ex', fr'\__angbracketright{s}__') for s in _latex_sizes]],
|
|
540
|
+
r'\lfloor': [('ex', fr'\__floorleft{s}__') for s in _latex_sizes],
|
|
541
|
+
r'\rfloor': [('ex', fr'\__floorright{s}__') for s in _latex_sizes],
|
|
542
|
+
r'\lceil': [('ex', fr'\__ceilingleft{s}__') for s in _latex_sizes],
|
|
543
|
+
r'\rceil': [('ex', fr'\__ceilingright{s}__') for s in _latex_sizes],
|
|
544
|
+
r'\__sqrt__': [('ex', fr'\__radical{s}__') for s in _latex_sizes],
|
|
545
|
+
r'\backslash': [('ex', fr'\__backslash{s}__') for s in _latex_sizes],
|
|
546
|
+
r'/': [('rm', '/'), *[('ex', fr'\__slash{s}__') for s in _latex_sizes]],
|
|
547
|
+
r'\widehat': [('rm', '\x5e'), ('ex', r'\__hatwide__'), ('ex', r'\__hatwider__'),
|
|
548
|
+
('ex', r'\__hatwidest__')],
|
|
549
|
+
r'\widetilde': [('rm', '\x7e'), ('ex', r'\__tildewide__'),
|
|
550
|
+
('ex', r'\__tildewider__'), ('ex', r'\__tildewidest__')],
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
for alias, target in [(r'\leftparen', '('), (r'\rightparen', ')'),
|
|
554
|
+
(r'\leftbrace', '{'), (r'\rightbrace', '}'),
|
|
555
|
+
(r'\leftbracket', '['), (r'\rightbracket', ']'),
|
|
556
|
+
(r'\langle', '<'), (r'\rangle', '>'),
|
|
557
|
+
(r'\{', '{'), (r'\}', '}'),
|
|
558
|
+
(r'\[', '['), (r'\]', ']')]:
|
|
559
|
+
_size_alternatives[alias] = _size_alternatives[target]
|
|
560
|
+
|
|
561
|
+
def get_sized_alternatives_for_symbol(self, fontname: str,
|
|
562
|
+
sym: str) -> list[tuple[str, str]]:
|
|
563
|
+
return self._size_alternatives.get(sym, [(fontname, sym)])
|
|
564
|
+
|
|
565
|
+
def get_font_constants(self) -> type[FontConstantsBase]:
|
|
566
|
+
return ComputerModernFontConstants
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
class UnicodeFonts(TruetypeFonts):
|
|
570
|
+
"""
|
|
571
|
+
An abstract base class for handling Unicode fonts.
|
|
572
|
+
|
|
573
|
+
While some reasonably complete Unicode fonts (such as DejaVu) may
|
|
574
|
+
work in some situations, the only Unicode font I'm aware of with a
|
|
575
|
+
complete set of math symbols is STIX.
|
|
576
|
+
|
|
577
|
+
This class will "fallback" on the Bakoma fonts when a required
|
|
578
|
+
symbol cannot be found in the font.
|
|
579
|
+
"""
|
|
580
|
+
|
|
581
|
+
# Some glyphs are not present in the `cmr10` font, and must be brought in
|
|
582
|
+
# from `cmsy10`. Map the Unicode indices of those glyphs to the indices at
|
|
583
|
+
# which they are found in `cmsy10`.
|
|
584
|
+
_cmr10_substitutions: dict[CharacterCodeType, CharacterCodeType] = {
|
|
585
|
+
0x00D7: 0x00A3, # Multiplication sign.
|
|
586
|
+
0x2212: 0x00A1, # Minus sign.
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlags):
|
|
590
|
+
# This must come first so the backend's owner is set correctly
|
|
591
|
+
fallback_rc = mpl.rcParams['mathtext.fallback']
|
|
592
|
+
font_cls: type[TruetypeFonts] | None = {
|
|
593
|
+
'stix': StixFonts,
|
|
594
|
+
'stixsans': StixSansFonts,
|
|
595
|
+
'cm': BakomaFonts
|
|
596
|
+
}.get(fallback_rc)
|
|
597
|
+
self._fallback_font = (font_cls(default_font_prop, load_glyph_flags)
|
|
598
|
+
if font_cls else None)
|
|
599
|
+
|
|
600
|
+
super().__init__(default_font_prop, load_glyph_flags)
|
|
601
|
+
for texfont in "cal rm tt it bf sf bfit".split():
|
|
602
|
+
prop = mpl.rcParams['mathtext.' + texfont] # type: ignore[index]
|
|
603
|
+
font = findfont(prop)
|
|
604
|
+
self.fontmap[texfont] = font
|
|
605
|
+
prop = FontProperties('cmex10')
|
|
606
|
+
font = findfont(prop)
|
|
607
|
+
self.fontmap['ex'] = font
|
|
608
|
+
|
|
609
|
+
# include STIX sized alternatives for glyphs if fallback is STIX
|
|
610
|
+
if isinstance(self._fallback_font, StixFonts):
|
|
611
|
+
stixsizedaltfonts = {
|
|
612
|
+
'0': 'STIXGeneral',
|
|
613
|
+
'1': 'STIXSizeOneSym',
|
|
614
|
+
'2': 'STIXSizeTwoSym',
|
|
615
|
+
'3': 'STIXSizeThreeSym',
|
|
616
|
+
'4': 'STIXSizeFourSym',
|
|
617
|
+
'5': 'STIXSizeFiveSym',
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
for size, name in stixsizedaltfonts.items():
|
|
621
|
+
fullpath = findfont(name)
|
|
622
|
+
self.fontmap[size] = fullpath
|
|
623
|
+
self.fontmap[name] = fullpath
|
|
624
|
+
|
|
625
|
+
_slanted_symbols = set(r"\int \oint".split())
|
|
626
|
+
|
|
627
|
+
def _map_virtual_font(self, fontname: str, font_class: str,
|
|
628
|
+
uniindex: CharacterCodeType) -> tuple[str, CharacterCodeType]:
|
|
629
|
+
return fontname, uniindex
|
|
630
|
+
|
|
631
|
+
def _get_glyph(self, fontname: str, font_class: str,
|
|
632
|
+
sym: str) -> tuple[FT2Font, CharacterCodeType, bool]:
|
|
633
|
+
try:
|
|
634
|
+
uniindex = get_unicode_index(sym)
|
|
635
|
+
found_symbol = True
|
|
636
|
+
except ValueError:
|
|
637
|
+
uniindex = ord('?')
|
|
638
|
+
found_symbol = False
|
|
639
|
+
_log.warning("No TeX to Unicode mapping for %a.", sym)
|
|
640
|
+
|
|
641
|
+
fontname, uniindex = self._map_virtual_font(fontname, font_class, uniindex)
|
|
642
|
+
|
|
643
|
+
new_fontname = fontname
|
|
644
|
+
|
|
645
|
+
# Only characters in the "Letter" class should be italicized in 'it'
|
|
646
|
+
# mode. Greek capital letters should be Roman.
|
|
647
|
+
if found_symbol:
|
|
648
|
+
if fontname == 'normal' and uniindex < 0x10000:
|
|
649
|
+
# normal mathematics font
|
|
650
|
+
char = chr(uniindex)
|
|
651
|
+
if (unicodedata.category(char)[0] != "L"
|
|
652
|
+
or unicodedata.name(char).startswith("GREEK CAPITAL")):
|
|
653
|
+
new_fontname = 'rm'
|
|
654
|
+
else:
|
|
655
|
+
new_fontname = 'it'
|
|
656
|
+
|
|
657
|
+
slanted = (new_fontname == 'it') or sym in self._slanted_symbols
|
|
658
|
+
found_symbol = False
|
|
659
|
+
font = self._get_font(new_fontname)
|
|
660
|
+
if font is not None:
|
|
661
|
+
if (uniindex in self._cmr10_substitutions
|
|
662
|
+
and font.family_name == "cmr10"):
|
|
663
|
+
font = get_font(
|
|
664
|
+
cbook._get_data_path("fonts/ttf/cmsy10.ttf"))
|
|
665
|
+
uniindex = self._cmr10_substitutions[uniindex]
|
|
666
|
+
glyphindex = font.get_char_index(uniindex)
|
|
667
|
+
if glyphindex != 0:
|
|
668
|
+
found_symbol = True
|
|
669
|
+
|
|
670
|
+
if not found_symbol:
|
|
671
|
+
if self._fallback_font:
|
|
672
|
+
if (fontname in ('it', 'regular', 'normal')
|
|
673
|
+
and isinstance(self._fallback_font, StixFonts)):
|
|
674
|
+
fontname = 'rm'
|
|
675
|
+
|
|
676
|
+
g = self._fallback_font._get_glyph(fontname, font_class, sym)
|
|
677
|
+
family = g[0].family_name
|
|
678
|
+
if family in BakomaFonts._fontmap.values():
|
|
679
|
+
family = "Computer Modern"
|
|
680
|
+
_log.info("Substituting symbol %s from %s", sym, family)
|
|
681
|
+
return g
|
|
682
|
+
|
|
683
|
+
else:
|
|
684
|
+
if (fontname in ('it', 'regular', 'normal')
|
|
685
|
+
and isinstance(self, StixFonts)):
|
|
686
|
+
return self._get_glyph('rm', font_class, sym)
|
|
687
|
+
_log.warning("Font %r does not have a glyph for %a [U+%x], "
|
|
688
|
+
"substituting with a dummy symbol.",
|
|
689
|
+
new_fontname, sym, uniindex)
|
|
690
|
+
font = self._get_font('rm')
|
|
691
|
+
uniindex = 0xA4 # currency char, for lack of anything better
|
|
692
|
+
slanted = False
|
|
693
|
+
|
|
694
|
+
return font, uniindex, slanted
|
|
695
|
+
|
|
696
|
+
def get_sized_alternatives_for_symbol(self, fontname: str,
|
|
697
|
+
sym: str) -> list[tuple[str, str]]:
|
|
698
|
+
if self._fallback_font:
|
|
699
|
+
return self._fallback_font.get_sized_alternatives_for_symbol(fontname, sym)
|
|
700
|
+
return [(fontname, sym)]
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
class DejaVuFonts(UnicodeFonts, metaclass=abc.ABCMeta):
|
|
704
|
+
_fontmap: dict[str, str] = {}
|
|
705
|
+
|
|
706
|
+
def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlags):
|
|
707
|
+
# This must come first so the backend's owner is set correctly
|
|
708
|
+
if isinstance(self, DejaVuSerifFonts):
|
|
709
|
+
self._fallback_font = StixFonts(default_font_prop, load_glyph_flags)
|
|
710
|
+
else:
|
|
711
|
+
self._fallback_font = StixSansFonts(default_font_prop, load_glyph_flags)
|
|
712
|
+
self.bakoma = BakomaFonts(default_font_prop, load_glyph_flags)
|
|
713
|
+
TruetypeFonts.__init__(self, default_font_prop, load_glyph_flags)
|
|
714
|
+
# Include Stix sized alternatives for glyphs
|
|
715
|
+
self._fontmap.update({
|
|
716
|
+
'1': 'STIXSizeOneSym',
|
|
717
|
+
'2': 'STIXSizeTwoSym',
|
|
718
|
+
'3': 'STIXSizeThreeSym',
|
|
719
|
+
'4': 'STIXSizeFourSym',
|
|
720
|
+
'5': 'STIXSizeFiveSym',
|
|
721
|
+
})
|
|
722
|
+
for key, name in self._fontmap.items():
|
|
723
|
+
fullpath = findfont(name)
|
|
724
|
+
self.fontmap[key] = fullpath
|
|
725
|
+
self.fontmap[name] = fullpath
|
|
726
|
+
|
|
727
|
+
def _get_glyph(self, fontname: str, font_class: str,
|
|
728
|
+
sym: str) -> tuple[FT2Font, CharacterCodeType, bool]:
|
|
729
|
+
# Override prime symbol to use Bakoma.
|
|
730
|
+
if sym == r'\prime':
|
|
731
|
+
return self.bakoma._get_glyph(fontname, font_class, sym)
|
|
732
|
+
else:
|
|
733
|
+
# check whether the glyph is available in the display font
|
|
734
|
+
uniindex = get_unicode_index(sym)
|
|
735
|
+
font = self._get_font('ex')
|
|
736
|
+
if font is not None:
|
|
737
|
+
glyphindex = font.get_char_index(uniindex)
|
|
738
|
+
if glyphindex != 0:
|
|
739
|
+
return super()._get_glyph('ex', font_class, sym)
|
|
740
|
+
# otherwise return regular glyph
|
|
741
|
+
return super()._get_glyph(fontname, font_class, sym)
|
|
742
|
+
|
|
743
|
+
|
|
744
|
+
class DejaVuSerifFonts(DejaVuFonts):
|
|
745
|
+
"""
|
|
746
|
+
A font handling class for the DejaVu Serif fonts
|
|
747
|
+
|
|
748
|
+
If a glyph is not found it will fallback to Stix Serif
|
|
749
|
+
"""
|
|
750
|
+
_fontmap = {
|
|
751
|
+
'rm': 'DejaVu Serif',
|
|
752
|
+
'it': 'DejaVu Serif:italic',
|
|
753
|
+
'bf': 'DejaVu Serif:weight=bold',
|
|
754
|
+
'bfit': 'DejaVu Serif:italic:bold',
|
|
755
|
+
'sf': 'DejaVu Sans',
|
|
756
|
+
'tt': 'DejaVu Sans Mono',
|
|
757
|
+
'ex': 'DejaVu Serif Display',
|
|
758
|
+
'0': 'DejaVu Serif',
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
def get_font_constants(self) -> type[FontConstantsBase]:
|
|
762
|
+
return DejaVuSerifFontConstants
|
|
763
|
+
|
|
764
|
+
|
|
765
|
+
class DejaVuSansFonts(DejaVuFonts):
|
|
766
|
+
"""
|
|
767
|
+
A font handling class for the DejaVu Sans fonts
|
|
768
|
+
|
|
769
|
+
If a glyph is not found it will fallback to Stix Sans
|
|
770
|
+
"""
|
|
771
|
+
_fontmap = {
|
|
772
|
+
'rm': 'DejaVu Sans',
|
|
773
|
+
'it': 'DejaVu Sans:italic',
|
|
774
|
+
'bf': 'DejaVu Sans:weight=bold',
|
|
775
|
+
'bfit': 'DejaVu Sans:italic:bold',
|
|
776
|
+
'sf': 'DejaVu Sans',
|
|
777
|
+
'tt': 'DejaVu Sans Mono',
|
|
778
|
+
'ex': 'DejaVu Sans Display',
|
|
779
|
+
'0': 'DejaVu Sans',
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
def get_font_constants(self) -> type[FontConstantsBase]:
|
|
783
|
+
return DejaVuSansFontConstants
|
|
784
|
+
|
|
785
|
+
|
|
786
|
+
class StixFonts(UnicodeFonts):
|
|
787
|
+
"""
|
|
788
|
+
A font handling class for the STIX fonts.
|
|
789
|
+
|
|
790
|
+
In addition to what UnicodeFonts provides, this class:
|
|
791
|
+
|
|
792
|
+
- supports "virtual fonts" which are complete alpha numeric
|
|
793
|
+
character sets with different font styles at special Unicode
|
|
794
|
+
code points, such as "Blackboard".
|
|
795
|
+
|
|
796
|
+
- handles sized alternative characters for the STIXSizeX fonts.
|
|
797
|
+
"""
|
|
798
|
+
_fontmap = {
|
|
799
|
+
'rm': 'STIXGeneral',
|
|
800
|
+
'it': 'STIXGeneral:italic',
|
|
801
|
+
'bf': 'STIXGeneral:weight=bold',
|
|
802
|
+
'bfit': 'STIXGeneral:italic:bold',
|
|
803
|
+
'nonunirm': 'STIXNonUnicode',
|
|
804
|
+
'nonuniit': 'STIXNonUnicode:italic',
|
|
805
|
+
'nonunibf': 'STIXNonUnicode:weight=bold',
|
|
806
|
+
'0': 'STIXGeneral',
|
|
807
|
+
'1': 'STIXSizeOneSym',
|
|
808
|
+
'2': 'STIXSizeTwoSym',
|
|
809
|
+
'3': 'STIXSizeThreeSym',
|
|
810
|
+
'4': 'STIXSizeFourSym',
|
|
811
|
+
'5': 'STIXSizeFiveSym',
|
|
812
|
+
}
|
|
813
|
+
_fallback_font = None
|
|
814
|
+
_sans = False
|
|
815
|
+
|
|
816
|
+
def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlags):
|
|
817
|
+
TruetypeFonts.__init__(self, default_font_prop, load_glyph_flags)
|
|
818
|
+
for key, name in self._fontmap.items():
|
|
819
|
+
fullpath = findfont(name)
|
|
820
|
+
self.fontmap[key] = fullpath
|
|
821
|
+
self.fontmap[name] = fullpath
|
|
822
|
+
|
|
823
|
+
def _map_virtual_font(self, fontname: str, font_class: str,
|
|
824
|
+
uniindex: CharacterCodeType) -> tuple[str, CharacterCodeType]:
|
|
825
|
+
# Handle these "fonts" that are actually embedded in
|
|
826
|
+
# other fonts.
|
|
827
|
+
font_mapping = stix_virtual_fonts.get(fontname)
|
|
828
|
+
if (self._sans and font_mapping is None
|
|
829
|
+
and fontname not in ('regular', 'default')):
|
|
830
|
+
font_mapping = stix_virtual_fonts['sf']
|
|
831
|
+
doing_sans_conversion = True
|
|
832
|
+
else:
|
|
833
|
+
doing_sans_conversion = False
|
|
834
|
+
|
|
835
|
+
if isinstance(font_mapping, dict):
|
|
836
|
+
try:
|
|
837
|
+
mapping = font_mapping[font_class]
|
|
838
|
+
except KeyError:
|
|
839
|
+
mapping = font_mapping['rm']
|
|
840
|
+
elif isinstance(font_mapping, list):
|
|
841
|
+
mapping = font_mapping
|
|
842
|
+
else:
|
|
843
|
+
mapping = None
|
|
844
|
+
|
|
845
|
+
if mapping is not None:
|
|
846
|
+
# Binary search for the source glyph
|
|
847
|
+
lo = 0
|
|
848
|
+
hi = len(mapping)
|
|
849
|
+
while lo < hi:
|
|
850
|
+
mid = (lo+hi)//2
|
|
851
|
+
range = mapping[mid]
|
|
852
|
+
if uniindex < range[0]:
|
|
853
|
+
hi = mid
|
|
854
|
+
elif uniindex <= range[1]:
|
|
855
|
+
break
|
|
856
|
+
else:
|
|
857
|
+
lo = mid + 1
|
|
858
|
+
|
|
859
|
+
if range[0] <= uniindex <= range[1]:
|
|
860
|
+
uniindex = uniindex - range[0] + range[3]
|
|
861
|
+
fontname = range[2]
|
|
862
|
+
elif not doing_sans_conversion:
|
|
863
|
+
# This will generate a dummy character
|
|
864
|
+
uniindex = 0x1
|
|
865
|
+
fontname = mpl.rcParams['mathtext.default']
|
|
866
|
+
|
|
867
|
+
# Fix some incorrect glyphs.
|
|
868
|
+
if fontname in ('rm', 'it', 'normal'):
|
|
869
|
+
uniindex = stix_glyph_fixes.get(uniindex, uniindex)
|
|
870
|
+
|
|
871
|
+
# Handle private use area glyphs
|
|
872
|
+
if fontname in ('it', 'rm', 'bf', 'bfit') and 0xe000 <= uniindex <= 0xf8ff:
|
|
873
|
+
fontname = 'nonuni' + fontname
|
|
874
|
+
|
|
875
|
+
return fontname, uniindex
|
|
876
|
+
|
|
877
|
+
@functools.cache
|
|
878
|
+
def get_sized_alternatives_for_symbol(self, fontname: str,
|
|
879
|
+
sym: str) -> list[tuple[str, str]]:
|
|
880
|
+
fixes = {
|
|
881
|
+
'\\{': '{', '\\}': '}', '\\[': '[', '\\]': ']',
|
|
882
|
+
'<': '\N{MATHEMATICAL LEFT ANGLE BRACKET}',
|
|
883
|
+
'>': '\N{MATHEMATICAL RIGHT ANGLE BRACKET}',
|
|
884
|
+
}
|
|
885
|
+
sym = fixes.get(sym, sym)
|
|
886
|
+
try:
|
|
887
|
+
uniindex = get_unicode_index(sym)
|
|
888
|
+
except ValueError:
|
|
889
|
+
return [(fontname, sym)]
|
|
890
|
+
alternatives = [(str(i), chr(uniindex)) for i in range(6)
|
|
891
|
+
if self._get_font(str(i)).get_char_index(uniindex) != 0]
|
|
892
|
+
# The largest size of the radical symbol in STIX has incorrect
|
|
893
|
+
# metrics that cause it to be disconnected from the stem.
|
|
894
|
+
if sym == r'\__sqrt__':
|
|
895
|
+
alternatives = alternatives[:-1]
|
|
896
|
+
return alternatives
|
|
897
|
+
|
|
898
|
+
def get_font_constants(self) -> type[FontConstantsBase]:
|
|
899
|
+
if self._sans:
|
|
900
|
+
return STIXSansFontConstants
|
|
901
|
+
else:
|
|
902
|
+
return STIXFontConstants
|
|
903
|
+
|
|
904
|
+
|
|
905
|
+
class StixSansFonts(StixFonts):
|
|
906
|
+
"""
|
|
907
|
+
A font handling class for the STIX fonts (that uses sans-serif
|
|
908
|
+
characters by default).
|
|
909
|
+
"""
|
|
910
|
+
_sans = True
|
|
911
|
+
|
|
912
|
+
|
|
913
|
+
##############################################################################
|
|
914
|
+
# TeX-LIKE BOX MODEL
|
|
915
|
+
|
|
916
|
+
# The following is based directly on the document 'woven' from the
|
|
917
|
+
# TeX82 source code. This information is also available in printed
|
|
918
|
+
# form:
|
|
919
|
+
#
|
|
920
|
+
# Knuth, Donald E.. 1986. Computers and Typesetting, Volume B:
|
|
921
|
+
# TeX: The Program. Addison-Wesley Professional.
|
|
922
|
+
#
|
|
923
|
+
# The most relevant "chapters" are:
|
|
924
|
+
# Data structures for boxes and their friends
|
|
925
|
+
# Shipping pages out (ship())
|
|
926
|
+
# Packaging (hpack() and vpack())
|
|
927
|
+
# Data structures for math mode
|
|
928
|
+
# Subroutines for math mode
|
|
929
|
+
# Typesetting math formulas
|
|
930
|
+
#
|
|
931
|
+
# Many of the docstrings below refer to a numbered "node" in that
|
|
932
|
+
# book, e.g., node123
|
|
933
|
+
#
|
|
934
|
+
# Note that (as TeX) y increases downward, unlike many other parts of
|
|
935
|
+
# matplotlib.
|
|
936
|
+
|
|
937
|
+
# How much text shrinks when going to the next-smallest level.
|
|
938
|
+
SHRINK_FACTOR = 0.7
|
|
939
|
+
# The number of different sizes of chars to use, beyond which they will not
|
|
940
|
+
# get any smaller
|
|
941
|
+
NUM_SIZE_LEVELS = 6
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
class FontConstantsBase:
|
|
945
|
+
"""
|
|
946
|
+
A set of constants that controls how certain things, such as sub-
|
|
947
|
+
and superscripts are laid out. These are all metrics that can't
|
|
948
|
+
be reliably retrieved from the font metrics in the font itself.
|
|
949
|
+
"""
|
|
950
|
+
# Percentage of x-height of additional horiz. space after sub/superscripts
|
|
951
|
+
script_space: T.ClassVar[float] = 0.05
|
|
952
|
+
|
|
953
|
+
# Percentage of x-height that superscripts drop below the top of large box
|
|
954
|
+
supdrop: T.ClassVar[float] = 0.4
|
|
955
|
+
|
|
956
|
+
# Percentage of x-height that subscripts drop below the bottom of large box
|
|
957
|
+
subdrop: T.ClassVar[float] = 0.4
|
|
958
|
+
|
|
959
|
+
# Percentage of x-height that superscripts are raised from the baseline
|
|
960
|
+
sup1: T.ClassVar[float] = 0.7
|
|
961
|
+
|
|
962
|
+
# Percentage of x-height that subscripts drop below the baseline
|
|
963
|
+
sub1: T.ClassVar[float] = 0.3
|
|
964
|
+
|
|
965
|
+
# Percentage of x-height that subscripts drop below the baseline when a
|
|
966
|
+
# superscript is present
|
|
967
|
+
sub2: T.ClassVar[float] = 0.5
|
|
968
|
+
|
|
969
|
+
# Percentage of x-height that sub/superscripts are offset relative to the
|
|
970
|
+
# nucleus edge for non-slanted nuclei
|
|
971
|
+
delta: T.ClassVar[float] = 0.025
|
|
972
|
+
|
|
973
|
+
# Additional percentage of last character height above 2/3 of the
|
|
974
|
+
# x-height that superscripts are offset relative to the subscript
|
|
975
|
+
# for slanted nuclei
|
|
976
|
+
delta_slanted: T.ClassVar[float] = 0.2
|
|
977
|
+
|
|
978
|
+
# Percentage of x-height that superscripts and subscripts are offset for
|
|
979
|
+
# integrals
|
|
980
|
+
delta_integral: T.ClassVar[float] = 0.1
|
|
981
|
+
|
|
982
|
+
# Percentage of x-height the numerator is shifted up in display style.
|
|
983
|
+
num1: T.ClassVar[float] = 1.4
|
|
984
|
+
|
|
985
|
+
# Percentage of x-height the numerator is shifted up in text, script and
|
|
986
|
+
# scriptscript styles if there is a fraction line.
|
|
987
|
+
num2: T.ClassVar[float] = 1.5
|
|
988
|
+
|
|
989
|
+
# Percentage of x-height the numerator is shifted up in text, script and
|
|
990
|
+
# scriptscript styles if there is no fraction line.
|
|
991
|
+
num3: T.ClassVar[float] = 1.3
|
|
992
|
+
|
|
993
|
+
# Percentage of x-height the denominator is shifted down in display style.
|
|
994
|
+
denom1: T.ClassVar[float] = 1.3
|
|
995
|
+
|
|
996
|
+
# Percentage of x-height the denominator is shifted down in text, script
|
|
997
|
+
# and scriptscript styles.
|
|
998
|
+
denom2: T.ClassVar[float] = 1.1
|
|
999
|
+
|
|
1000
|
+
# The height of a horizontal reference line used for positioning elements in a
|
|
1001
|
+
# formula, similar to a baseline, as a multiple of design size.
|
|
1002
|
+
axis_height: T.ClassVar[float | None] = None
|
|
1003
|
+
|
|
1004
|
+
# The size of a quad space in LaTeX, as a multiple of design size.
|
|
1005
|
+
quad: T.ClassVar[float | None] = None
|
|
1006
|
+
|
|
1007
|
+
# The size of x-height in font design units (i.e., divided by units-per-em). If not
|
|
1008
|
+
# provided, then this will be measured from the font itself.
|
|
1009
|
+
x_height: T.ClassVar[float | None] = None
|
|
1010
|
+
|
|
1011
|
+
|
|
1012
|
+
class ComputerModernFontConstants(FontConstantsBase):
|
|
1013
|
+
# Previously, the x-height of Computer Modern was obtained from the font
|
|
1014
|
+
# table. However, that x-height was greater than the actual (rendered)
|
|
1015
|
+
# x-height by a factor of 1.771484375 (at font size 12, DPI 100 and hinting
|
|
1016
|
+
# type 32). Now that we're using the rendered x-height, some font constants
|
|
1017
|
+
# have been increased by the same factor to compensate.
|
|
1018
|
+
script_space = 0.132861328125
|
|
1019
|
+
delta = 0.132861328125
|
|
1020
|
+
delta_slanted = 0.3
|
|
1021
|
+
delta_integral = 0.3
|
|
1022
|
+
_x_height = 451470
|
|
1023
|
+
# These all come from the cmsy10.tfm metrics, divided by the design xheight from
|
|
1024
|
+
# there, since we multiply these values by the scaled xheight later.
|
|
1025
|
+
supdrop = 404864 / _x_height
|
|
1026
|
+
subdrop = 52429 / _x_height
|
|
1027
|
+
sup1 = 432949 / _x_height
|
|
1028
|
+
sub1 = 157286 / _x_height
|
|
1029
|
+
sub2 = 259226 / _x_height
|
|
1030
|
+
num1 = 709370 / _x_height
|
|
1031
|
+
num2 = 412858 / _x_height
|
|
1032
|
+
num3 = 465286 / _x_height
|
|
1033
|
+
denom1 = 719272 / _x_height
|
|
1034
|
+
denom2 = 361592 / _x_height
|
|
1035
|
+
# These come from the cmsy10.tfm metrics, scaled so they are in multiples of design
|
|
1036
|
+
# size.
|
|
1037
|
+
axis_height = 262144 / 2**20
|
|
1038
|
+
quad = 1048579 / 2**20
|
|
1039
|
+
x_height = _x_height / 2**20
|
|
1040
|
+
|
|
1041
|
+
|
|
1042
|
+
class STIXFontConstants(FontConstantsBase):
|
|
1043
|
+
script_space = 0.1
|
|
1044
|
+
delta = 0.05
|
|
1045
|
+
delta_slanted = 0.3
|
|
1046
|
+
delta_integral = 0.3
|
|
1047
|
+
_x_height = 450
|
|
1048
|
+
x_height = _x_height / 1000
|
|
1049
|
+
# These values are extracted from the TeX table of STIXGeneral.ttf using FontForge,
|
|
1050
|
+
# and then divided by design xheight, since we multiply these values by the scaled
|
|
1051
|
+
# xheight later.
|
|
1052
|
+
supdrop = 386 / _x_height
|
|
1053
|
+
subdrop = 50.0002 / _x_height
|
|
1054
|
+
sup1 = 413 / _x_height
|
|
1055
|
+
sub1 = 150 / _x_height
|
|
1056
|
+
sub2 = 309 / _x_height
|
|
1057
|
+
num1 = 747 / _x_height
|
|
1058
|
+
num2 = 424 / _x_height
|
|
1059
|
+
num3 = 474 / _x_height
|
|
1060
|
+
denom1 = 756 / _x_height
|
|
1061
|
+
denom2 = 375 / _x_height
|
|
1062
|
+
# These come from the same TeX table, scaled by Em size so they are in multiples of
|
|
1063
|
+
# design size.
|
|
1064
|
+
axis_height = 250 / 1000
|
|
1065
|
+
quad = 1000 / 1000
|
|
1066
|
+
|
|
1067
|
+
|
|
1068
|
+
class STIXSansFontConstants(STIXFontConstants):
|
|
1069
|
+
script_space = 0.05
|
|
1070
|
+
delta_slanted = 0.6
|
|
1071
|
+
delta_integral = 0.3
|
|
1072
|
+
|
|
1073
|
+
|
|
1074
|
+
class DejaVuSerifFontConstants(FontConstantsBase):
|
|
1075
|
+
_x_height = 1063
|
|
1076
|
+
x_height = _x_height / 2048
|
|
1077
|
+
# These values are extracted from the TeX table of DejaVuSerif.ttf using FontForge,
|
|
1078
|
+
# and then divided by design xheight, since we multiply these values by the scaled
|
|
1079
|
+
# xheight later.
|
|
1080
|
+
supdrop = 790.527 / _x_height
|
|
1081
|
+
subdrop = 102.4 / _x_height
|
|
1082
|
+
sup1 = 845.824 / _x_height
|
|
1083
|
+
sub1 = 307.199 / _x_height
|
|
1084
|
+
sub2 = 632.832 / _x_height
|
|
1085
|
+
num1 = 1529.86 / _x_height
|
|
1086
|
+
num2 = 868.352 / _x_height
|
|
1087
|
+
num3 = 970.752 / _x_height
|
|
1088
|
+
denom1 = 1548.29 / _x_height
|
|
1089
|
+
denom2 = 768 / _x_height
|
|
1090
|
+
# These come from the same TeX table, scaled by Em size so they are in multiples of
|
|
1091
|
+
# design size.
|
|
1092
|
+
axis_height = 512 / 2048
|
|
1093
|
+
|
|
1094
|
+
|
|
1095
|
+
class DejaVuSansFontConstants(FontConstantsBase):
|
|
1096
|
+
_x_height = 1120
|
|
1097
|
+
x_height = _x_height / 2048
|
|
1098
|
+
# These values are extracted from the TeX table of DejaVuSans.ttf using FontForge,
|
|
1099
|
+
# and then divided by design xheight, since we multiply these values by the scaled
|
|
1100
|
+
# xheight later.
|
|
1101
|
+
supdrop = 790.527 / _x_height
|
|
1102
|
+
subdrop = 102.4 / _x_height
|
|
1103
|
+
sup1 = 845.824 / _x_height
|
|
1104
|
+
sub1 = 307.199 / _x_height
|
|
1105
|
+
sub2 = 632.832 / _x_height
|
|
1106
|
+
num1 = 1529.86 / _x_height
|
|
1107
|
+
num2 = 868.352 / _x_height
|
|
1108
|
+
num3 = 970.752 / _x_height
|
|
1109
|
+
denom1 = 1548.29 / _x_height
|
|
1110
|
+
denom2 = 768 / _x_height
|
|
1111
|
+
# These come from the same TeX table, scaled by Em size so they are in multiples of
|
|
1112
|
+
# design size.
|
|
1113
|
+
axis_height = 512 / 2048
|
|
1114
|
+
|
|
1115
|
+
|
|
1116
|
+
class Node:
|
|
1117
|
+
"""A node in the TeX box model."""
|
|
1118
|
+
|
|
1119
|
+
def __init__(self) -> None:
|
|
1120
|
+
self.size = 0
|
|
1121
|
+
|
|
1122
|
+
def __repr__(self) -> str:
|
|
1123
|
+
return type(self).__name__
|
|
1124
|
+
|
|
1125
|
+
def get_kerning(self, next: Node | None) -> float:
|
|
1126
|
+
return 0.0
|
|
1127
|
+
|
|
1128
|
+
def shrink(self) -> None:
|
|
1129
|
+
"""
|
|
1130
|
+
Shrinks one level smaller. There are only three levels of
|
|
1131
|
+
sizes, after which things will no longer get smaller.
|
|
1132
|
+
"""
|
|
1133
|
+
self.size += 1
|
|
1134
|
+
|
|
1135
|
+
def render(self, output: Output, x: float, y: float) -> None:
|
|
1136
|
+
"""Render this node."""
|
|
1137
|
+
|
|
1138
|
+
def is_char_node(self) -> bool:
|
|
1139
|
+
# TeX defines a `char_node` as one which represents a single character,
|
|
1140
|
+
# but also states that a `char_node` will never appear in a `Vlist`
|
|
1141
|
+
# (node134). Further, nuclei made of one `Char` and nuclei made of
|
|
1142
|
+
# multiple `Char`s have their superscripts and subscripts shifted by
|
|
1143
|
+
# the same amount. In order to make Mathtext behave similarly, just
|
|
1144
|
+
# check whether this node is a `Vlist` or has any `Vlist` descendants.
|
|
1145
|
+
return True
|
|
1146
|
+
|
|
1147
|
+
|
|
1148
|
+
class Box(Node):
|
|
1149
|
+
"""A node with a physical location."""
|
|
1150
|
+
|
|
1151
|
+
def __init__(self, width: float, height: float, depth: float) -> None:
|
|
1152
|
+
super().__init__()
|
|
1153
|
+
self.width = width
|
|
1154
|
+
self.height = height
|
|
1155
|
+
self.depth = depth
|
|
1156
|
+
|
|
1157
|
+
def shrink(self) -> None:
|
|
1158
|
+
super().shrink()
|
|
1159
|
+
if self.size < NUM_SIZE_LEVELS:
|
|
1160
|
+
self.width *= SHRINK_FACTOR
|
|
1161
|
+
self.height *= SHRINK_FACTOR
|
|
1162
|
+
self.depth *= SHRINK_FACTOR
|
|
1163
|
+
|
|
1164
|
+
def render(self, output: Output, # type: ignore[override]
|
|
1165
|
+
x1: float, y1: float, x2: float, y2: float) -> None:
|
|
1166
|
+
pass
|
|
1167
|
+
|
|
1168
|
+
|
|
1169
|
+
class Vbox(Box):
|
|
1170
|
+
"""A box with only height (zero width)."""
|
|
1171
|
+
|
|
1172
|
+
def __init__(self, height: float, depth: float):
|
|
1173
|
+
super().__init__(0., height, depth)
|
|
1174
|
+
|
|
1175
|
+
|
|
1176
|
+
class Hbox(Box):
|
|
1177
|
+
"""A box with only width (zero height and depth)."""
|
|
1178
|
+
|
|
1179
|
+
def __init__(self, width: float):
|
|
1180
|
+
super().__init__(width, 0., 0.)
|
|
1181
|
+
|
|
1182
|
+
|
|
1183
|
+
class Char(Node):
|
|
1184
|
+
"""
|
|
1185
|
+
A single character.
|
|
1186
|
+
|
|
1187
|
+
Unlike TeX, the font information and metrics are stored with each `Char`
|
|
1188
|
+
to make it easier to lookup the font metrics when needed. Note that TeX
|
|
1189
|
+
boxes have a width, height, and depth, unlike Type1 and TrueType which use
|
|
1190
|
+
a full bounding box and an advance in the x-direction. The metrics must
|
|
1191
|
+
be converted to the TeX model, and the advance (if different from width)
|
|
1192
|
+
must be converted into a `Kern` node when the `Char` is added to its parent
|
|
1193
|
+
`Hlist`.
|
|
1194
|
+
"""
|
|
1195
|
+
|
|
1196
|
+
def __init__(self, c: str, state: ParserState):
|
|
1197
|
+
super().__init__()
|
|
1198
|
+
self.c = c
|
|
1199
|
+
self.fontset = state.fontset
|
|
1200
|
+
self.font = state.font
|
|
1201
|
+
self.font_class = state.font_class
|
|
1202
|
+
self.fontsize = state.fontsize
|
|
1203
|
+
self.dpi = state.dpi
|
|
1204
|
+
# The real width, height and depth will be set during the
|
|
1205
|
+
# pack phase, after we know the real fontsize
|
|
1206
|
+
self._update_metrics()
|
|
1207
|
+
|
|
1208
|
+
def __repr__(self) -> str:
|
|
1209
|
+
return '`%s`' % self.c
|
|
1210
|
+
|
|
1211
|
+
def _update_metrics(self) -> None:
|
|
1212
|
+
metrics = self._metrics = self.fontset.get_metrics(
|
|
1213
|
+
self.font, self.font_class, self.c, self.fontsize, self.dpi)
|
|
1214
|
+
if self.c == ' ':
|
|
1215
|
+
self.width = metrics.advance
|
|
1216
|
+
else:
|
|
1217
|
+
self.width = metrics.width
|
|
1218
|
+
self.height = metrics.iceberg
|
|
1219
|
+
self.depth = -(metrics.iceberg - metrics.height)
|
|
1220
|
+
|
|
1221
|
+
def is_slanted(self) -> bool:
|
|
1222
|
+
return self._metrics.slanted
|
|
1223
|
+
|
|
1224
|
+
def get_kerning(self, next: Node | None) -> float:
|
|
1225
|
+
"""
|
|
1226
|
+
Return the amount of kerning between this and the given character.
|
|
1227
|
+
|
|
1228
|
+
This method is called when characters are strung together into `Hlist`
|
|
1229
|
+
to create `Kern` nodes.
|
|
1230
|
+
"""
|
|
1231
|
+
advance = self._metrics.advance - self.width
|
|
1232
|
+
kern = 0.
|
|
1233
|
+
if isinstance(next, Char):
|
|
1234
|
+
kern = self.fontset.get_kern(
|
|
1235
|
+
self.font, self.font_class, self.c, self.fontsize,
|
|
1236
|
+
next.font, next.font_class, next.c, next.fontsize,
|
|
1237
|
+
self.dpi)
|
|
1238
|
+
return advance + kern
|
|
1239
|
+
|
|
1240
|
+
def render(self, output: Output, x: float, y: float) -> None:
|
|
1241
|
+
self.fontset.render_glyph(
|
|
1242
|
+
output, x, y,
|
|
1243
|
+
self.font, self.font_class, self.c, self.fontsize, self.dpi)
|
|
1244
|
+
|
|
1245
|
+
def shrink(self) -> None:
|
|
1246
|
+
super().shrink()
|
|
1247
|
+
if self.size < NUM_SIZE_LEVELS:
|
|
1248
|
+
self.fontsize *= SHRINK_FACTOR
|
|
1249
|
+
self.width *= SHRINK_FACTOR
|
|
1250
|
+
self.height *= SHRINK_FACTOR
|
|
1251
|
+
self.depth *= SHRINK_FACTOR
|
|
1252
|
+
|
|
1253
|
+
|
|
1254
|
+
class Accent(Char):
|
|
1255
|
+
"""
|
|
1256
|
+
The font metrics need to be dealt with differently for accents,
|
|
1257
|
+
since they are already offset correctly from the baseline in
|
|
1258
|
+
TrueType fonts.
|
|
1259
|
+
"""
|
|
1260
|
+
def _update_metrics(self) -> None:
|
|
1261
|
+
metrics = self._metrics = self.fontset.get_metrics(
|
|
1262
|
+
self.font, self.font_class, self.c, self.fontsize, self.dpi)
|
|
1263
|
+
self.width = metrics.xmax - metrics.xmin
|
|
1264
|
+
self.height = metrics.ymax - metrics.ymin
|
|
1265
|
+
self.depth = 0
|
|
1266
|
+
|
|
1267
|
+
def shrink(self) -> None:
|
|
1268
|
+
super().shrink()
|
|
1269
|
+
self._update_metrics()
|
|
1270
|
+
|
|
1271
|
+
def render(self, output: Output, x: float, y: float) -> None:
|
|
1272
|
+
self.fontset.render_glyph(
|
|
1273
|
+
output, x - self._metrics.xmin, y + self._metrics.ymin,
|
|
1274
|
+
self.font, self.font_class, self.c, self.fontsize, self.dpi)
|
|
1275
|
+
|
|
1276
|
+
|
|
1277
|
+
class List(Box):
|
|
1278
|
+
"""A list of nodes (either horizontal or vertical)."""
|
|
1279
|
+
|
|
1280
|
+
def __init__(self, elements: T.Sequence[Node]):
|
|
1281
|
+
super().__init__(0., 0., 0.)
|
|
1282
|
+
self.shift_amount = 0. # An arbitrary offset
|
|
1283
|
+
self.children = [*elements] # The child nodes of this list
|
|
1284
|
+
# The following parameters are set in the vpack and hpack functions
|
|
1285
|
+
self.glue_set = 0. # The glue setting of this list
|
|
1286
|
+
self.glue_sign = 0 # 0: normal, -1: shrinking, 1: stretching
|
|
1287
|
+
self.glue_order = 0 # The order of infinity (0 - 3) for the glue
|
|
1288
|
+
|
|
1289
|
+
def __repr__(self) -> str:
|
|
1290
|
+
return "{}<w={:.02f} h={:.02f} d={:.02f} s={:.02f}>[{}]".format(
|
|
1291
|
+
super().__repr__(),
|
|
1292
|
+
self.width, self.height,
|
|
1293
|
+
self.depth, self.shift_amount,
|
|
1294
|
+
"\n" + textwrap.indent(
|
|
1295
|
+
"\n".join(map("{!r},".format, self.children)),
|
|
1296
|
+
" ") + "\n"
|
|
1297
|
+
if self.children else ""
|
|
1298
|
+
)
|
|
1299
|
+
|
|
1300
|
+
def _set_glue(self, x: float, sign: int, totals: list[float],
|
|
1301
|
+
error_type: str) -> None:
|
|
1302
|
+
self.glue_order = o = next(
|
|
1303
|
+
# Highest order of glue used by the members of this list.
|
|
1304
|
+
(i for i in range(len(totals))[::-1] if totals[i] != 0), 0)
|
|
1305
|
+
self.glue_sign = sign
|
|
1306
|
+
if totals[o] != 0.:
|
|
1307
|
+
self.glue_set = x / totals[o]
|
|
1308
|
+
else:
|
|
1309
|
+
self.glue_sign = 0
|
|
1310
|
+
self.glue_ratio = 0.
|
|
1311
|
+
if o == 0:
|
|
1312
|
+
if len(self.children):
|
|
1313
|
+
_log.warning("%s %s: %r",
|
|
1314
|
+
error_type, type(self).__name__, self)
|
|
1315
|
+
|
|
1316
|
+
def shrink(self) -> None:
|
|
1317
|
+
for child in self.children:
|
|
1318
|
+
child.shrink()
|
|
1319
|
+
super().shrink()
|
|
1320
|
+
if self.size < NUM_SIZE_LEVELS:
|
|
1321
|
+
self.shift_amount *= SHRINK_FACTOR
|
|
1322
|
+
self.glue_set *= SHRINK_FACTOR
|
|
1323
|
+
|
|
1324
|
+
|
|
1325
|
+
class Hlist(List):
|
|
1326
|
+
"""A horizontal list of boxes."""
|
|
1327
|
+
|
|
1328
|
+
def __init__(self, elements: T.Sequence[Node], w: float = 0.0,
|
|
1329
|
+
m: T.Literal['additional', 'exactly'] = 'additional',
|
|
1330
|
+
do_kern: bool = True):
|
|
1331
|
+
super().__init__(elements)
|
|
1332
|
+
if do_kern:
|
|
1333
|
+
self.kern()
|
|
1334
|
+
self.hpack(w=w, m=m)
|
|
1335
|
+
self.is_phantom = False
|
|
1336
|
+
|
|
1337
|
+
def is_char_node(self) -> bool:
|
|
1338
|
+
# See description in Node.is_char_node.
|
|
1339
|
+
return all(map(lambda node: node.is_char_node(), self.children))
|
|
1340
|
+
|
|
1341
|
+
def kern(self) -> None:
|
|
1342
|
+
"""
|
|
1343
|
+
Insert `Kern` nodes between `Char` nodes to set kerning.
|
|
1344
|
+
|
|
1345
|
+
The `Char` nodes themselves determine the amount of kerning they need
|
|
1346
|
+
(in `~Char.get_kerning`), and this function just creates the correct
|
|
1347
|
+
linked list.
|
|
1348
|
+
"""
|
|
1349
|
+
new_children = []
|
|
1350
|
+
for elem0, elem1 in itertools.zip_longest(self.children, self.children[1:]):
|
|
1351
|
+
new_children.append(elem0)
|
|
1352
|
+
kerning_distance = elem0.get_kerning(elem1)
|
|
1353
|
+
if kerning_distance != 0.:
|
|
1354
|
+
kern = Kern(kerning_distance)
|
|
1355
|
+
new_children.append(kern)
|
|
1356
|
+
self.children = new_children
|
|
1357
|
+
|
|
1358
|
+
def hpack(self, w: float = 0.0,
|
|
1359
|
+
m: T.Literal['additional', 'exactly'] = 'additional') -> None:
|
|
1360
|
+
r"""
|
|
1361
|
+
Compute the dimensions of the resulting boxes, and adjust the glue if
|
|
1362
|
+
one of those dimensions is pre-specified. The computed sizes normally
|
|
1363
|
+
enclose all of the material inside the new box; but some items may
|
|
1364
|
+
stick out if negative glue is used, if the box is overfull, or if a
|
|
1365
|
+
``\vbox`` includes other boxes that have been shifted left.
|
|
1366
|
+
|
|
1367
|
+
Parameters
|
|
1368
|
+
----------
|
|
1369
|
+
w : float, default: 0
|
|
1370
|
+
A width.
|
|
1371
|
+
m : {'exactly', 'additional'}, default: 'additional'
|
|
1372
|
+
Whether to produce a box whose width is 'exactly' *w*; or a box
|
|
1373
|
+
with the natural width of the contents, plus *w* ('additional').
|
|
1374
|
+
|
|
1375
|
+
Notes
|
|
1376
|
+
-----
|
|
1377
|
+
The defaults produce a box with the natural width of the contents.
|
|
1378
|
+
"""
|
|
1379
|
+
# I don't know why these get reset in TeX. Shift_amount is pretty
|
|
1380
|
+
# much useless if we do.
|
|
1381
|
+
# self.shift_amount = 0.
|
|
1382
|
+
h = 0.
|
|
1383
|
+
d = 0.
|
|
1384
|
+
x = 0.
|
|
1385
|
+
total_stretch = [0.] * 4
|
|
1386
|
+
total_shrink = [0.] * 4
|
|
1387
|
+
for p in self.children:
|
|
1388
|
+
if isinstance(p, Char):
|
|
1389
|
+
x += p.width
|
|
1390
|
+
h = max(h, p.height)
|
|
1391
|
+
d = max(d, p.depth)
|
|
1392
|
+
elif isinstance(p, Box):
|
|
1393
|
+
x += p.width
|
|
1394
|
+
if not np.isinf(p.height) and not np.isinf(p.depth):
|
|
1395
|
+
s = getattr(p, 'shift_amount', 0.)
|
|
1396
|
+
h = max(h, p.height - s)
|
|
1397
|
+
d = max(d, p.depth + s)
|
|
1398
|
+
elif isinstance(p, Glue):
|
|
1399
|
+
glue_spec = p.glue_spec
|
|
1400
|
+
x += glue_spec.width
|
|
1401
|
+
total_stretch[glue_spec.stretch_order] += glue_spec.stretch
|
|
1402
|
+
total_shrink[glue_spec.shrink_order] += glue_spec.shrink
|
|
1403
|
+
elif isinstance(p, Kern):
|
|
1404
|
+
x += p.width
|
|
1405
|
+
self.height = h
|
|
1406
|
+
self.depth = d
|
|
1407
|
+
|
|
1408
|
+
if m == 'additional':
|
|
1409
|
+
w += x
|
|
1410
|
+
self.width = w
|
|
1411
|
+
x = w - x
|
|
1412
|
+
|
|
1413
|
+
if x == 0.:
|
|
1414
|
+
self.glue_sign = 0
|
|
1415
|
+
self.glue_order = 0
|
|
1416
|
+
self.glue_ratio = 0.
|
|
1417
|
+
return
|
|
1418
|
+
if x > 0.:
|
|
1419
|
+
self._set_glue(x, 1, total_stretch, "Overful")
|
|
1420
|
+
else:
|
|
1421
|
+
self._set_glue(x, -1, total_shrink, "Underful")
|
|
1422
|
+
|
|
1423
|
+
|
|
1424
|
+
class Vlist(List):
|
|
1425
|
+
"""A vertical list of boxes."""
|
|
1426
|
+
|
|
1427
|
+
def __init__(self, elements: T.Sequence[Node], h: float = 0.0,
|
|
1428
|
+
m: T.Literal['additional', 'exactly'] = 'additional'):
|
|
1429
|
+
super().__init__(elements)
|
|
1430
|
+
self.vpack(h=h, m=m)
|
|
1431
|
+
|
|
1432
|
+
def is_char_node(self) -> bool:
|
|
1433
|
+
# See description in Node.is_char_node.
|
|
1434
|
+
return False
|
|
1435
|
+
|
|
1436
|
+
def vpack(self, h: float = 0.0,
|
|
1437
|
+
m: T.Literal['additional', 'exactly'] = 'additional',
|
|
1438
|
+
l: float = np.inf) -> None:
|
|
1439
|
+
"""
|
|
1440
|
+
Compute the dimensions of the resulting boxes, and to adjust the glue
|
|
1441
|
+
if one of those dimensions is pre-specified.
|
|
1442
|
+
|
|
1443
|
+
Parameters
|
|
1444
|
+
----------
|
|
1445
|
+
h : float, default: 0
|
|
1446
|
+
A height.
|
|
1447
|
+
m : {'exactly', 'additional'}, default: 'additional'
|
|
1448
|
+
Whether to produce a box whose height is 'exactly' *h*; or a box
|
|
1449
|
+
with the natural height of the contents, plus *h* ('additional').
|
|
1450
|
+
l : float, default: np.inf
|
|
1451
|
+
The maximum height.
|
|
1452
|
+
|
|
1453
|
+
Notes
|
|
1454
|
+
-----
|
|
1455
|
+
The defaults produce a box with the natural height of the contents.
|
|
1456
|
+
"""
|
|
1457
|
+
# I don't know why these get reset in TeX. Shift_amount is pretty
|
|
1458
|
+
# much useless if we do.
|
|
1459
|
+
# self.shift_amount = 0.
|
|
1460
|
+
w = 0.
|
|
1461
|
+
d = 0.
|
|
1462
|
+
x = 0.
|
|
1463
|
+
total_stretch = [0.] * 4
|
|
1464
|
+
total_shrink = [0.] * 4
|
|
1465
|
+
for p in self.children:
|
|
1466
|
+
if isinstance(p, Box):
|
|
1467
|
+
x += d + p.height
|
|
1468
|
+
d = p.depth
|
|
1469
|
+
if not np.isinf(p.width):
|
|
1470
|
+
s = getattr(p, 'shift_amount', 0.)
|
|
1471
|
+
w = max(w, p.width + s)
|
|
1472
|
+
elif isinstance(p, Glue):
|
|
1473
|
+
x += d
|
|
1474
|
+
d = 0.
|
|
1475
|
+
glue_spec = p.glue_spec
|
|
1476
|
+
x += glue_spec.width
|
|
1477
|
+
total_stretch[glue_spec.stretch_order] += glue_spec.stretch
|
|
1478
|
+
total_shrink[glue_spec.shrink_order] += glue_spec.shrink
|
|
1479
|
+
elif isinstance(p, Kern):
|
|
1480
|
+
x += d + p.width
|
|
1481
|
+
d = 0.
|
|
1482
|
+
elif isinstance(p, Char):
|
|
1483
|
+
raise RuntimeError(
|
|
1484
|
+
"Internal mathtext error: Char node found in Vlist")
|
|
1485
|
+
|
|
1486
|
+
self.width = w
|
|
1487
|
+
if d > l:
|
|
1488
|
+
x += d - l
|
|
1489
|
+
self.depth = l
|
|
1490
|
+
else:
|
|
1491
|
+
self.depth = d
|
|
1492
|
+
|
|
1493
|
+
if m == 'additional':
|
|
1494
|
+
h += x
|
|
1495
|
+
self.height = h
|
|
1496
|
+
x = h - x
|
|
1497
|
+
|
|
1498
|
+
if x == 0:
|
|
1499
|
+
self.glue_sign = 0
|
|
1500
|
+
self.glue_order = 0
|
|
1501
|
+
self.glue_ratio = 0.
|
|
1502
|
+
return
|
|
1503
|
+
|
|
1504
|
+
if x > 0.:
|
|
1505
|
+
self._set_glue(x, 1, total_stretch, "Overful")
|
|
1506
|
+
else:
|
|
1507
|
+
self._set_glue(x, -1, total_shrink, "Underful")
|
|
1508
|
+
|
|
1509
|
+
|
|
1510
|
+
class Rule(Box):
|
|
1511
|
+
"""
|
|
1512
|
+
A solid black rectangle.
|
|
1513
|
+
|
|
1514
|
+
It has *width*, *depth*, and *height* fields just as in an `Hlist`.
|
|
1515
|
+
However, if any of these dimensions is inf, the actual value will be
|
|
1516
|
+
determined by running the rule up to the boundary of the innermost
|
|
1517
|
+
enclosing box. This is called a "running dimension". The width is never
|
|
1518
|
+
running in an `Hlist`; the height and depth are never running in a `Vlist`.
|
|
1519
|
+
"""
|
|
1520
|
+
|
|
1521
|
+
def __init__(self, width: float, height: float, depth: float, state: ParserState):
|
|
1522
|
+
super().__init__(width, height, depth)
|
|
1523
|
+
self.fontset = state.fontset
|
|
1524
|
+
|
|
1525
|
+
def render(self, output: Output, # type: ignore[override]
|
|
1526
|
+
x: float, y: float, w: float, h: float) -> None:
|
|
1527
|
+
self.fontset.render_rect_filled(output, x, y - h, w, h)
|
|
1528
|
+
|
|
1529
|
+
|
|
1530
|
+
class Hrule(Rule):
|
|
1531
|
+
"""Convenience class to create a horizontal rule."""
|
|
1532
|
+
|
|
1533
|
+
def __init__(self, state: ParserState, thickness: float | None = None):
|
|
1534
|
+
if thickness is None:
|
|
1535
|
+
thickness = state.get_current_underline_thickness()
|
|
1536
|
+
height = depth = thickness * 0.5
|
|
1537
|
+
super().__init__(np.inf, height, depth, state)
|
|
1538
|
+
|
|
1539
|
+
|
|
1540
|
+
class Vrule(Rule):
|
|
1541
|
+
"""Convenience class to create a vertical rule."""
|
|
1542
|
+
|
|
1543
|
+
def __init__(self, state: ParserState):
|
|
1544
|
+
thickness = state.get_current_underline_thickness()
|
|
1545
|
+
super().__init__(thickness, np.inf, np.inf, state)
|
|
1546
|
+
|
|
1547
|
+
|
|
1548
|
+
class _GlueSpec(NamedTuple):
|
|
1549
|
+
width: float
|
|
1550
|
+
stretch: float
|
|
1551
|
+
stretch_order: int
|
|
1552
|
+
shrink: float
|
|
1553
|
+
shrink_order: int
|
|
1554
|
+
|
|
1555
|
+
|
|
1556
|
+
_GlueSpec._named = { # type: ignore[attr-defined]
|
|
1557
|
+
'fil': _GlueSpec(0., 1., 1, 0., 0),
|
|
1558
|
+
'fill': _GlueSpec(0., 1., 2, 0., 0),
|
|
1559
|
+
'filll': _GlueSpec(0., 1., 3, 0., 0),
|
|
1560
|
+
'neg_fil': _GlueSpec(0., 0., 0, 1., 1),
|
|
1561
|
+
'neg_fill': _GlueSpec(0., 0., 0, 1., 2),
|
|
1562
|
+
'neg_filll': _GlueSpec(0., 0., 0, 1., 3),
|
|
1563
|
+
'empty': _GlueSpec(0., 0., 0, 0., 0),
|
|
1564
|
+
'ss': _GlueSpec(0., 1., 1, -1., 1),
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
|
|
1568
|
+
class Glue(Node):
|
|
1569
|
+
"""
|
|
1570
|
+
Most of the information in this object is stored in the underlying
|
|
1571
|
+
``_GlueSpec`` class, which is shared between multiple glue objects.
|
|
1572
|
+
(This is a memory optimization which probably doesn't matter anymore, but
|
|
1573
|
+
it's easier to stick to what TeX does.)
|
|
1574
|
+
"""
|
|
1575
|
+
|
|
1576
|
+
def __init__(self,
|
|
1577
|
+
glue_type: _GlueSpec | T.Literal["fil", "fill", "filll",
|
|
1578
|
+
"neg_fil", "neg_fill", "neg_filll",
|
|
1579
|
+
"empty", "ss"]):
|
|
1580
|
+
super().__init__()
|
|
1581
|
+
if isinstance(glue_type, str):
|
|
1582
|
+
glue_spec = _GlueSpec._named[glue_type] # type: ignore[attr-defined]
|
|
1583
|
+
elif isinstance(glue_type, _GlueSpec):
|
|
1584
|
+
glue_spec = glue_type
|
|
1585
|
+
else:
|
|
1586
|
+
raise ValueError("glue_type must be a glue spec name or instance")
|
|
1587
|
+
self.glue_spec = glue_spec
|
|
1588
|
+
|
|
1589
|
+
def shrink(self) -> None:
|
|
1590
|
+
super().shrink()
|
|
1591
|
+
if self.size < NUM_SIZE_LEVELS:
|
|
1592
|
+
g = self.glue_spec
|
|
1593
|
+
self.glue_spec = g._replace(width=g.width * SHRINK_FACTOR)
|
|
1594
|
+
|
|
1595
|
+
|
|
1596
|
+
class HCentered(Hlist):
|
|
1597
|
+
"""
|
|
1598
|
+
A convenience class to create an `Hlist` whose contents are
|
|
1599
|
+
centered within its enclosing box.
|
|
1600
|
+
"""
|
|
1601
|
+
|
|
1602
|
+
def __init__(self, elements: list[Node]):
|
|
1603
|
+
super().__init__([Glue('ss'), *elements, Glue('ss')], do_kern=False)
|
|
1604
|
+
|
|
1605
|
+
|
|
1606
|
+
class VCentered(Vlist):
|
|
1607
|
+
"""
|
|
1608
|
+
A convenience class to create a `Vlist` whose contents are
|
|
1609
|
+
centered within its enclosing box.
|
|
1610
|
+
"""
|
|
1611
|
+
|
|
1612
|
+
def __init__(self, elements: list[Node]):
|
|
1613
|
+
super().__init__([Glue('ss'), *elements, Glue('ss')])
|
|
1614
|
+
|
|
1615
|
+
|
|
1616
|
+
class Kern(Node):
|
|
1617
|
+
"""
|
|
1618
|
+
A `Kern` node has a width field to specify a (normally
|
|
1619
|
+
negative) amount of spacing. This spacing correction appears in
|
|
1620
|
+
horizontal lists between letters like A and V when the font
|
|
1621
|
+
designer said that it looks better to move them closer together or
|
|
1622
|
+
further apart. A kern node can also appear in a vertical list,
|
|
1623
|
+
when its *width* denotes additional spacing in the vertical
|
|
1624
|
+
direction.
|
|
1625
|
+
"""
|
|
1626
|
+
|
|
1627
|
+
height = 0
|
|
1628
|
+
depth = 0
|
|
1629
|
+
|
|
1630
|
+
def __init__(self, width: float):
|
|
1631
|
+
super().__init__()
|
|
1632
|
+
self.width = width
|
|
1633
|
+
|
|
1634
|
+
def __repr__(self) -> str:
|
|
1635
|
+
return "k%.02f" % self.width
|
|
1636
|
+
|
|
1637
|
+
def shrink(self) -> None:
|
|
1638
|
+
super().shrink()
|
|
1639
|
+
if self.size < NUM_SIZE_LEVELS:
|
|
1640
|
+
self.width *= SHRINK_FACTOR
|
|
1641
|
+
|
|
1642
|
+
|
|
1643
|
+
class AutoHeightChar(Hlist):
|
|
1644
|
+
"""
|
|
1645
|
+
A character as close to the given height and depth as possible.
|
|
1646
|
+
|
|
1647
|
+
When using a font with multiple height versions of some characters (such as
|
|
1648
|
+
the BaKoMa fonts), the correct glyph will be selected, otherwise this will
|
|
1649
|
+
always just return a scaled version of the glyph.
|
|
1650
|
+
"""
|
|
1651
|
+
|
|
1652
|
+
def __init__(self, c: str, height: float, depth: float, state: ParserState,
|
|
1653
|
+
factor: float | None = None):
|
|
1654
|
+
alternatives = state.fontset.get_sized_alternatives_for_symbol(state.font, c)
|
|
1655
|
+
|
|
1656
|
+
x_height = state.fontset.get_xheight(state.font, state.fontsize, state.dpi)
|
|
1657
|
+
|
|
1658
|
+
state = state.copy()
|
|
1659
|
+
target_total = height + depth
|
|
1660
|
+
for fontname, sym in alternatives:
|
|
1661
|
+
state.font = fontname
|
|
1662
|
+
char = Char(sym, state)
|
|
1663
|
+
# Ensure that size 0 is chosen when the text is regular sized but
|
|
1664
|
+
# with descender glyphs by subtracting 0.2 * x_height
|
|
1665
|
+
if char.height + char.depth >= target_total - 0.2 * x_height:
|
|
1666
|
+
break
|
|
1667
|
+
|
|
1668
|
+
shift = 0.0
|
|
1669
|
+
if state.font != '0' or len(alternatives) == 1:
|
|
1670
|
+
if factor is None:
|
|
1671
|
+
factor = target_total / (char.height + char.depth)
|
|
1672
|
+
state.fontsize *= factor
|
|
1673
|
+
char = Char(sym, state)
|
|
1674
|
+
|
|
1675
|
+
shift = (depth - char.depth)
|
|
1676
|
+
|
|
1677
|
+
super().__init__([char])
|
|
1678
|
+
self.shift_amount = shift
|
|
1679
|
+
|
|
1680
|
+
|
|
1681
|
+
class AutoWidthChar(Hlist):
|
|
1682
|
+
"""
|
|
1683
|
+
A character as close to the given width as possible.
|
|
1684
|
+
|
|
1685
|
+
When using a font with multiple width versions of some characters (such as
|
|
1686
|
+
the BaKoMa fonts), the correct glyph will be selected, otherwise this will
|
|
1687
|
+
always just return a scaled version of the glyph.
|
|
1688
|
+
"""
|
|
1689
|
+
|
|
1690
|
+
def __init__(self, c: str, width: float, state: ParserState,
|
|
1691
|
+
char_class: type[Char] = Char):
|
|
1692
|
+
alternatives = state.fontset.get_sized_alternatives_for_symbol(state.font, c)
|
|
1693
|
+
|
|
1694
|
+
state = state.copy()
|
|
1695
|
+
for fontname, sym in alternatives:
|
|
1696
|
+
state.font = fontname
|
|
1697
|
+
char = char_class(sym, state)
|
|
1698
|
+
if char.width >= width:
|
|
1699
|
+
break
|
|
1700
|
+
|
|
1701
|
+
factor = width / char.width
|
|
1702
|
+
state.fontsize *= factor
|
|
1703
|
+
char = char_class(sym, state)
|
|
1704
|
+
|
|
1705
|
+
super().__init__([char])
|
|
1706
|
+
self.width = char.width
|
|
1707
|
+
|
|
1708
|
+
|
|
1709
|
+
def ship(box: Box, xy: tuple[float, float] = (0, 0)) -> Output:
|
|
1710
|
+
"""
|
|
1711
|
+
Ship out *box* at offset *xy*, converting it to an `Output`.
|
|
1712
|
+
|
|
1713
|
+
Since boxes can be inside of boxes inside of boxes, the main work of `ship`
|
|
1714
|
+
is done by two mutually recursive routines, `hlist_out` and `vlist_out`,
|
|
1715
|
+
which traverse the `Hlist` nodes and `Vlist` nodes inside of horizontal
|
|
1716
|
+
and vertical boxes. The global variables used in TeX to store state as it
|
|
1717
|
+
processes have become local variables here.
|
|
1718
|
+
"""
|
|
1719
|
+
ox, oy = xy
|
|
1720
|
+
cur_v = 0.
|
|
1721
|
+
cur_h = 0.
|
|
1722
|
+
off_h = ox
|
|
1723
|
+
off_v = oy + box.height
|
|
1724
|
+
output = Output(box)
|
|
1725
|
+
phantom: list[bool] = []
|
|
1726
|
+
|
|
1727
|
+
def render(node, *args):
|
|
1728
|
+
if not any(phantom):
|
|
1729
|
+
node.render(*args)
|
|
1730
|
+
|
|
1731
|
+
def clamp(value: float) -> float:
|
|
1732
|
+
return -1e9 if value < -1e9 else +1e9 if value > +1e9 else value
|
|
1733
|
+
|
|
1734
|
+
def hlist_out(box: Hlist) -> None:
|
|
1735
|
+
nonlocal cur_v, cur_h
|
|
1736
|
+
|
|
1737
|
+
cur_g = 0
|
|
1738
|
+
cur_glue = 0.
|
|
1739
|
+
glue_order = box.glue_order
|
|
1740
|
+
glue_sign = box.glue_sign
|
|
1741
|
+
base_line = cur_v
|
|
1742
|
+
left_edge = cur_h
|
|
1743
|
+
|
|
1744
|
+
phantom.append(box.is_phantom)
|
|
1745
|
+
|
|
1746
|
+
for p in box.children:
|
|
1747
|
+
if isinstance(p, Char):
|
|
1748
|
+
render(p, output, cur_h + off_h, cur_v + off_v)
|
|
1749
|
+
cur_h += p.width
|
|
1750
|
+
elif isinstance(p, Kern):
|
|
1751
|
+
cur_h += p.width
|
|
1752
|
+
elif isinstance(p, List):
|
|
1753
|
+
# node623
|
|
1754
|
+
if len(p.children) == 0:
|
|
1755
|
+
cur_h += p.width
|
|
1756
|
+
else:
|
|
1757
|
+
edge = cur_h
|
|
1758
|
+
cur_v = base_line + p.shift_amount
|
|
1759
|
+
if isinstance(p, Hlist):
|
|
1760
|
+
hlist_out(p)
|
|
1761
|
+
elif isinstance(p, Vlist):
|
|
1762
|
+
# p.vpack(box.height + box.depth, 'exactly')
|
|
1763
|
+
vlist_out(p)
|
|
1764
|
+
else:
|
|
1765
|
+
assert False, "unreachable code"
|
|
1766
|
+
cur_h = edge + p.width
|
|
1767
|
+
cur_v = base_line
|
|
1768
|
+
elif isinstance(p, Box):
|
|
1769
|
+
# node624
|
|
1770
|
+
rule_height = p.height
|
|
1771
|
+
rule_depth = p.depth
|
|
1772
|
+
rule_width = p.width
|
|
1773
|
+
if np.isinf(rule_height):
|
|
1774
|
+
rule_height = box.height
|
|
1775
|
+
if np.isinf(rule_depth):
|
|
1776
|
+
rule_depth = box.depth
|
|
1777
|
+
if rule_height > 0 and rule_width > 0:
|
|
1778
|
+
cur_v = base_line + rule_depth
|
|
1779
|
+
render(p, output,
|
|
1780
|
+
cur_h + off_h, cur_v + off_v,
|
|
1781
|
+
rule_width, rule_height)
|
|
1782
|
+
cur_v = base_line
|
|
1783
|
+
cur_h += rule_width
|
|
1784
|
+
elif isinstance(p, Glue):
|
|
1785
|
+
# node625
|
|
1786
|
+
glue_spec = p.glue_spec
|
|
1787
|
+
rule_width = glue_spec.width - cur_g
|
|
1788
|
+
if glue_sign != 0: # normal
|
|
1789
|
+
if glue_sign == 1: # stretching
|
|
1790
|
+
if glue_spec.stretch_order == glue_order:
|
|
1791
|
+
cur_glue += glue_spec.stretch
|
|
1792
|
+
cur_g = round(clamp(box.glue_set * cur_glue))
|
|
1793
|
+
elif glue_spec.shrink_order == glue_order:
|
|
1794
|
+
cur_glue += glue_spec.shrink
|
|
1795
|
+
cur_g = round(clamp(box.glue_set * cur_glue))
|
|
1796
|
+
rule_width += cur_g
|
|
1797
|
+
cur_h += rule_width
|
|
1798
|
+
|
|
1799
|
+
phantom.pop()
|
|
1800
|
+
|
|
1801
|
+
def vlist_out(box: Vlist) -> None:
|
|
1802
|
+
nonlocal cur_v, cur_h
|
|
1803
|
+
|
|
1804
|
+
cur_g = 0
|
|
1805
|
+
cur_glue = 0.
|
|
1806
|
+
glue_order = box.glue_order
|
|
1807
|
+
glue_sign = box.glue_sign
|
|
1808
|
+
left_edge = cur_h
|
|
1809
|
+
cur_v -= box.height
|
|
1810
|
+
top_edge = cur_v
|
|
1811
|
+
|
|
1812
|
+
for p in box.children:
|
|
1813
|
+
if isinstance(p, Kern):
|
|
1814
|
+
cur_v += p.width
|
|
1815
|
+
elif isinstance(p, List):
|
|
1816
|
+
if len(p.children) == 0:
|
|
1817
|
+
cur_v += p.height + p.depth
|
|
1818
|
+
else:
|
|
1819
|
+
cur_v += p.height
|
|
1820
|
+
cur_h = left_edge + p.shift_amount
|
|
1821
|
+
save_v = cur_v
|
|
1822
|
+
p.width = box.width
|
|
1823
|
+
if isinstance(p, Hlist):
|
|
1824
|
+
hlist_out(p)
|
|
1825
|
+
elif isinstance(p, Vlist):
|
|
1826
|
+
vlist_out(p)
|
|
1827
|
+
else:
|
|
1828
|
+
assert False, "unreachable code"
|
|
1829
|
+
cur_v = save_v + p.depth
|
|
1830
|
+
cur_h = left_edge
|
|
1831
|
+
elif isinstance(p, Box):
|
|
1832
|
+
rule_height = p.height
|
|
1833
|
+
rule_depth = p.depth
|
|
1834
|
+
rule_width = p.width
|
|
1835
|
+
if np.isinf(rule_width):
|
|
1836
|
+
rule_width = box.width
|
|
1837
|
+
rule_height += rule_depth
|
|
1838
|
+
if rule_height > 0 and rule_depth > 0:
|
|
1839
|
+
cur_v += rule_height
|
|
1840
|
+
render(p, output,
|
|
1841
|
+
cur_h + off_h, cur_v + off_v,
|
|
1842
|
+
rule_width, rule_height)
|
|
1843
|
+
elif isinstance(p, Glue):
|
|
1844
|
+
glue_spec = p.glue_spec
|
|
1845
|
+
rule_height = glue_spec.width - cur_g
|
|
1846
|
+
if glue_sign != 0: # normal
|
|
1847
|
+
if glue_sign == 1: # stretching
|
|
1848
|
+
if glue_spec.stretch_order == glue_order:
|
|
1849
|
+
cur_glue += glue_spec.stretch
|
|
1850
|
+
cur_g = round(clamp(box.glue_set * cur_glue))
|
|
1851
|
+
elif glue_spec.shrink_order == glue_order: # shrinking
|
|
1852
|
+
cur_glue += glue_spec.shrink
|
|
1853
|
+
cur_g = round(clamp(box.glue_set * cur_glue))
|
|
1854
|
+
rule_height += cur_g
|
|
1855
|
+
cur_v += rule_height
|
|
1856
|
+
elif isinstance(p, Char):
|
|
1857
|
+
raise RuntimeError(
|
|
1858
|
+
"Internal mathtext error: Char node found in vlist")
|
|
1859
|
+
|
|
1860
|
+
assert isinstance(box, Hlist)
|
|
1861
|
+
hlist_out(box)
|
|
1862
|
+
return output
|
|
1863
|
+
|
|
1864
|
+
|
|
1865
|
+
##############################################################################
|
|
1866
|
+
# PARSER
|
|
1867
|
+
|
|
1868
|
+
|
|
1869
|
+
def Error(msg: str) -> ParserElement:
|
|
1870
|
+
"""Helper class to raise parser errors."""
|
|
1871
|
+
def raise_error(s: str, loc: int, toks: ParseResults) -> T.Any:
|
|
1872
|
+
raise ParseFatalException(s, loc, msg)
|
|
1873
|
+
|
|
1874
|
+
return Empty().set_parse_action(raise_error)
|
|
1875
|
+
|
|
1876
|
+
|
|
1877
|
+
class _BracedText(Token):
|
|
1878
|
+
r"""
|
|
1879
|
+
Match a brace-delimited literal string, allowing nested braces.
|
|
1880
|
+
|
|
1881
|
+
This is similar to ``QuotedString("{", "\\", end_quote_char="}")``, except
|
|
1882
|
+
that brace depth is tracked, so that the string does not end at the first
|
|
1883
|
+
``}``. As in TeX, nested unescaped braces only group, and are not
|
|
1884
|
+
rendered; a literal brace is written as ``\{`` or ``\}``. A backslash
|
|
1885
|
+
escapes the following character, which therefore does not affect depth.
|
|
1886
|
+
"""
|
|
1887
|
+
|
|
1888
|
+
_escapes = {"t": "\t", "n": "\n", "f": "\f", "r": "\r"}
|
|
1889
|
+
|
|
1890
|
+
def __init__(self) -> None:
|
|
1891
|
+
super().__init__()
|
|
1892
|
+
self.mayReturnEmpty = True
|
|
1893
|
+
self.mayIndexError = False
|
|
1894
|
+
|
|
1895
|
+
def parseImpl(self, instring: str, loc: int,
|
|
1896
|
+
do_actions: bool = True) -> tuple[int, str]:
|
|
1897
|
+
if loc >= len(instring) or instring[loc] != "{":
|
|
1898
|
+
raise ParseException(instring, loc, "Expected '{'", self)
|
|
1899
|
+
chars = []
|
|
1900
|
+
depth = 0
|
|
1901
|
+
while loc < len(instring):
|
|
1902
|
+
char = instring[loc]
|
|
1903
|
+
if char == "\\" and loc + 1 < len(instring):
|
|
1904
|
+
escaped = instring[loc + 1]
|
|
1905
|
+
chars.append(self._escapes.get(escaped, escaped))
|
|
1906
|
+
loc += 2
|
|
1907
|
+
continue
|
|
1908
|
+
loc += 1
|
|
1909
|
+
if char == "{":
|
|
1910
|
+
depth += 1
|
|
1911
|
+
continue
|
|
1912
|
+
elif char == "}":
|
|
1913
|
+
depth -= 1
|
|
1914
|
+
if depth == 0:
|
|
1915
|
+
return loc, "".join(chars)
|
|
1916
|
+
continue
|
|
1917
|
+
chars.append(char)
|
|
1918
|
+
raise ParseException(instring, loc, "Expected '}'", self)
|
|
1919
|
+
|
|
1920
|
+
|
|
1921
|
+
class ParserState:
|
|
1922
|
+
"""
|
|
1923
|
+
Parser state.
|
|
1924
|
+
|
|
1925
|
+
States are pushed and popped from a stack as necessary, and the "current"
|
|
1926
|
+
state is always at the top of the stack.
|
|
1927
|
+
|
|
1928
|
+
Upon entering and leaving a group { } or math/non-math, the stack is pushed
|
|
1929
|
+
and popped accordingly.
|
|
1930
|
+
"""
|
|
1931
|
+
|
|
1932
|
+
def __init__(self, fontset: Fonts, font: str, font_class: str, fontsize: float,
|
|
1933
|
+
dpi: float):
|
|
1934
|
+
self.fontset = fontset
|
|
1935
|
+
self._font = font
|
|
1936
|
+
self.font_class = font_class
|
|
1937
|
+
self.fontsize = fontsize
|
|
1938
|
+
self.dpi = dpi
|
|
1939
|
+
|
|
1940
|
+
def copy(self) -> ParserState:
|
|
1941
|
+
return copy.copy(self)
|
|
1942
|
+
|
|
1943
|
+
@property
|
|
1944
|
+
def font(self) -> str:
|
|
1945
|
+
return self._font
|
|
1946
|
+
|
|
1947
|
+
@font.setter
|
|
1948
|
+
def font(self, name: str) -> None:
|
|
1949
|
+
if name in ('normal', 'rm', 'it', 'bf', 'bfit'):
|
|
1950
|
+
self.font_class = name
|
|
1951
|
+
self._font = name
|
|
1952
|
+
|
|
1953
|
+
def get_current_underline_thickness(self) -> float:
|
|
1954
|
+
"""Return the underline thickness for this state."""
|
|
1955
|
+
return self.fontset.get_underline_thickness(
|
|
1956
|
+
self.font, self.fontsize, self.dpi)
|
|
1957
|
+
|
|
1958
|
+
|
|
1959
|
+
def cmd(expr: str, args: ParserElement) -> ParserElement:
|
|
1960
|
+
r"""
|
|
1961
|
+
Helper to define TeX commands.
|
|
1962
|
+
|
|
1963
|
+
``cmd("\cmd", args)`` is equivalent to
|
|
1964
|
+
``"\cmd" - (args | Error("Expected \cmd{arg}{...}"))`` where the names in
|
|
1965
|
+
the error message are taken from element names in *args*. If *expr*
|
|
1966
|
+
already includes arguments (e.g. "\cmd{arg}{...}"), then they are stripped
|
|
1967
|
+
when constructing the parse element, but kept (and *expr* is used as is) in
|
|
1968
|
+
the error message.
|
|
1969
|
+
"""
|
|
1970
|
+
|
|
1971
|
+
def names(elt: ParserElement) -> T.Generator[str, None, None]:
|
|
1972
|
+
if isinstance(elt, ParseExpression):
|
|
1973
|
+
for expr in elt.exprs:
|
|
1974
|
+
yield from names(expr)
|
|
1975
|
+
elif elt.resultsName:
|
|
1976
|
+
yield elt.resultsName
|
|
1977
|
+
|
|
1978
|
+
csname = expr.split("{", 1)[0]
|
|
1979
|
+
err = (csname + "".join("{%s}" % name for name in names(args))
|
|
1980
|
+
if expr == csname else expr)
|
|
1981
|
+
return csname - (args | Error(f"Expected {err}"))
|
|
1982
|
+
|
|
1983
|
+
|
|
1984
|
+
class Parser:
|
|
1985
|
+
"""
|
|
1986
|
+
A pyparsing-based parser for strings containing math expressions.
|
|
1987
|
+
|
|
1988
|
+
Raw text may also appear outside of pairs of ``$``.
|
|
1989
|
+
|
|
1990
|
+
The grammar is based directly on that in TeX, though it cuts a few corners.
|
|
1991
|
+
"""
|
|
1992
|
+
|
|
1993
|
+
class _MathStyle(enum.Enum):
|
|
1994
|
+
DISPLAYSTYLE = 0
|
|
1995
|
+
TEXTSTYLE = 1
|
|
1996
|
+
SCRIPTSTYLE = 2
|
|
1997
|
+
SCRIPTSCRIPTSTYLE = 3
|
|
1998
|
+
|
|
1999
|
+
_binary_operators = set(
|
|
2000
|
+
'+ * - \N{MINUS SIGN}'
|
|
2001
|
+
r'''
|
|
2002
|
+
\pm \sqcap \rhd
|
|
2003
|
+
\mp \sqcup \unlhd
|
|
2004
|
+
\times \vee \unrhd
|
|
2005
|
+
\div \wedge \oplus
|
|
2006
|
+
\ast \setminus \ominus
|
|
2007
|
+
\star \wr \otimes
|
|
2008
|
+
\circ \diamond \oslash
|
|
2009
|
+
\bullet \bigtriangleup \odot
|
|
2010
|
+
\cdot \bigtriangledown \bigcirc
|
|
2011
|
+
\cap \triangleleft \dagger
|
|
2012
|
+
\cup \triangleright \ddagger
|
|
2013
|
+
\uplus \lhd \amalg
|
|
2014
|
+
\dotplus \dotminus \Cap
|
|
2015
|
+
\Cup \barwedge \boxdot
|
|
2016
|
+
\boxminus \boxplus \boxtimes
|
|
2017
|
+
\curlyvee \curlywedge \divideontimes
|
|
2018
|
+
\doublebarwedge \leftthreetimes \rightthreetimes
|
|
2019
|
+
\slash \veebar \barvee
|
|
2020
|
+
\cupdot \intercal \amalg
|
|
2021
|
+
\circledcirc \circleddash \circledast
|
|
2022
|
+
\boxbar \obar \merge
|
|
2023
|
+
\minuscolon \dotsminusdots
|
|
2024
|
+
'''.split())
|
|
2025
|
+
|
|
2026
|
+
_relation_symbols = set(r'''
|
|
2027
|
+
= < > :
|
|
2028
|
+
\leq \geq \equiv \models
|
|
2029
|
+
\prec \succ \sim \perp
|
|
2030
|
+
\preceq \succeq \simeq \mid
|
|
2031
|
+
\ll \gg \asymp \parallel
|
|
2032
|
+
\subset \supset \approx \bowtie
|
|
2033
|
+
\subseteq \supseteq \cong \Join
|
|
2034
|
+
\sqsubset \sqsupset \neq \smile
|
|
2035
|
+
\sqsubseteq \sqsupseteq \doteq \frown
|
|
2036
|
+
\in \ni \propto \vdash
|
|
2037
|
+
\dashv \dots \doteqdot \leqq
|
|
2038
|
+
\geqq \lneqq \gneqq \lessgtr
|
|
2039
|
+
\leqslant \geqslant \eqgtr \eqless
|
|
2040
|
+
\eqslantless \eqslantgtr \lesseqgtr \backsim
|
|
2041
|
+
\backsimeq \lesssim \gtrsim \precsim
|
|
2042
|
+
\precnsim \gnsim \lnsim \succsim
|
|
2043
|
+
\succnsim \nsim \lesseqqgtr \gtreqqless
|
|
2044
|
+
\gtreqless \subseteqq \supseteqq \subsetneqq
|
|
2045
|
+
\supsetneqq \lessapprox \approxeq \gtrapprox
|
|
2046
|
+
\precapprox \succapprox \precnapprox \succnapprox
|
|
2047
|
+
\npreccurlyeq \nsucccurlyeq \nsqsubseteq \nsqsupseteq
|
|
2048
|
+
\sqsubsetneq \sqsupsetneq \nlesssim \ngtrsim
|
|
2049
|
+
\nlessgtr \ngtrless \lnapprox \gnapprox
|
|
2050
|
+
\napprox \approxeq \approxident \lll
|
|
2051
|
+
\ggg \nparallel \Vdash \Vvdash
|
|
2052
|
+
\nVdash \nvdash \vDash \nvDash
|
|
2053
|
+
\nVDash \oequal \simneqq \triangle
|
|
2054
|
+
\triangleq \triangleeq \triangleleft
|
|
2055
|
+
\triangleright \ntriangleleft \ntriangleright
|
|
2056
|
+
\trianglelefteq \ntrianglelefteq \trianglerighteq
|
|
2057
|
+
\ntrianglerighteq \blacktriangleleft \blacktriangleright
|
|
2058
|
+
\equalparallel \measuredrightangle \varlrtriangle
|
|
2059
|
+
\Doteq \Bumpeq \Subset \Supset
|
|
2060
|
+
\backepsilon \because \therefore \bot
|
|
2061
|
+
\top \bumpeq \circeq \coloneq
|
|
2062
|
+
\curlyeqprec \curlyeqsucc \eqcirc \eqcolon
|
|
2063
|
+
\eqsim \fallingdotseq \gtrdot \gtrless
|
|
2064
|
+
\ltimes \rtimes \lessdot \ne
|
|
2065
|
+
\ncong \nequiv \ngeq \ngtr
|
|
2066
|
+
\nleq \nless \nmid \notin
|
|
2067
|
+
\nprec \nsubset \nsubseteq \nsucc
|
|
2068
|
+
\nsupset \nsupseteq \pitchfork \preccurlyeq
|
|
2069
|
+
\risingdotseq \subsetneq \succcurlyeq \supsetneq
|
|
2070
|
+
\varpropto \vartriangleleft \scurel
|
|
2071
|
+
\vartriangleright \rightangle \equal \backcong
|
|
2072
|
+
\eqdef \wedgeq \questeq \between
|
|
2073
|
+
\veeeq \disin \varisins \isins
|
|
2074
|
+
\isindot \varisinobar \isinobar \isinvb
|
|
2075
|
+
\isinE \nisd \varnis \nis
|
|
2076
|
+
\varniobar \niobar \bagmember \ratio
|
|
2077
|
+
\Equiv \stareq \measeq \arceq
|
|
2078
|
+
\rightassert \rightModels \smallin \smallowns
|
|
2079
|
+
\notsmallowns \nsimeq'''.split())
|
|
2080
|
+
|
|
2081
|
+
_arrow_symbols = set(r"""
|
|
2082
|
+
\leftarrow \longleftarrow \uparrow \Leftarrow \Longleftarrow
|
|
2083
|
+
\Uparrow \rightarrow \longrightarrow \downarrow \Rightarrow
|
|
2084
|
+
\Longrightarrow \Downarrow \leftrightarrow \updownarrow
|
|
2085
|
+
\longleftrightarrow \updownarrow \Leftrightarrow
|
|
2086
|
+
\Longleftrightarrow \Updownarrow \mapsto \longmapsto \nearrow
|
|
2087
|
+
\hookleftarrow \hookrightarrow \searrow \leftharpoonup
|
|
2088
|
+
\rightharpoonup \swarrow \leftharpoondown \rightharpoondown
|
|
2089
|
+
\nwarrow \rightleftharpoons \leadsto \dashrightarrow
|
|
2090
|
+
\dashleftarrow \leftleftarrows \leftrightarrows \Lleftarrow
|
|
2091
|
+
\Rrightarrow \twoheadleftarrow \leftarrowtail \looparrowleft
|
|
2092
|
+
\leftrightharpoons \curvearrowleft \circlearrowleft \Lsh
|
|
2093
|
+
\upuparrows \upharpoonleft \downharpoonleft \multimap
|
|
2094
|
+
\leftrightsquigarrow \rightrightarrows \rightleftarrows
|
|
2095
|
+
\rightrightarrows \rightleftarrows \twoheadrightarrow
|
|
2096
|
+
\rightarrowtail \looparrowright \rightleftharpoons
|
|
2097
|
+
\curvearrowright \circlearrowright \Rsh \downdownarrows
|
|
2098
|
+
\upharpoonright \downharpoonright \rightsquigarrow \nleftarrow
|
|
2099
|
+
\nrightarrow \nLeftarrow \nRightarrow \nleftrightarrow
|
|
2100
|
+
\nLeftrightarrow \to \Swarrow \Searrow \Nwarrow \Nearrow
|
|
2101
|
+
\leftsquigarrow \overleftarrow \overleftrightarrow \cwopencirclearrow
|
|
2102
|
+
\downzigzagarrow \cupleftarrow \rightzigzagarrow \twoheaddownarrow
|
|
2103
|
+
\updownarrowbar \twoheaduparrow \rightarrowbar \updownarrows
|
|
2104
|
+
\barleftarrow \mapsfrom \mapsdown \mapsup \Ldsh \Rdsh
|
|
2105
|
+
""".split())
|
|
2106
|
+
|
|
2107
|
+
_spaced_symbols = _binary_operators | _relation_symbols | _arrow_symbols
|
|
2108
|
+
|
|
2109
|
+
_punctuation_symbols = set(r', ; . ! \ldotp \cdotp'.split())
|
|
2110
|
+
|
|
2111
|
+
_overunder_symbols = set(r'''
|
|
2112
|
+
\sum \prod \coprod \bigcap \bigcup \bigsqcup \bigvee
|
|
2113
|
+
\bigwedge \bigodot \bigotimes \bigoplus \biguplus
|
|
2114
|
+
'''.split())
|
|
2115
|
+
|
|
2116
|
+
_overunder_functions = set("lim liminf limsup sup max min".split())
|
|
2117
|
+
|
|
2118
|
+
_dropsub_symbols = set(r'\int \oint \iint \oiint \iiint \oiiint \iiiint'.split())
|
|
2119
|
+
|
|
2120
|
+
_fontnames = set("rm cal it tt sf bf bfit "
|
|
2121
|
+
"default bb frak scr regular normal".split())
|
|
2122
|
+
|
|
2123
|
+
_function_names = set("""
|
|
2124
|
+
arccos csc ker min arcsin deg lg Pr arctan det lim sec arg dim
|
|
2125
|
+
liminf sin cos exp limsup sinh cosh gcd ln sup cot hom log tan
|
|
2126
|
+
coth inf max tanh""".split())
|
|
2127
|
+
|
|
2128
|
+
_ambi_delims = set(r"""
|
|
2129
|
+
| \| / \backslash \uparrow \downarrow \updownarrow \Uparrow
|
|
2130
|
+
\Downarrow \Updownarrow . \vert \Vert""".split())
|
|
2131
|
+
_left_delims = set(r"""
|
|
2132
|
+
( [ \{ < \lfloor \langle \lceil \lbrace \leftbrace \lbrack \leftparen \lgroup
|
|
2133
|
+
""".split())
|
|
2134
|
+
_right_delims = set(r"""
|
|
2135
|
+
) ] \} > \rfloor \rangle \rceil \rbrace \rightbrace \rbrack \rightparen \rgroup
|
|
2136
|
+
""".split())
|
|
2137
|
+
_delims = _left_delims | _right_delims | _ambi_delims
|
|
2138
|
+
|
|
2139
|
+
_small_greek = set([unicodedata.name(chr(i)).split()[-1].lower() for i in
|
|
2140
|
+
range(ord('\N{GREEK SMALL LETTER ALPHA}'),
|
|
2141
|
+
ord('\N{GREEK SMALL LETTER OMEGA}') + 1)])
|
|
2142
|
+
_latin_alphabets = set(string.ascii_letters)
|
|
2143
|
+
|
|
2144
|
+
def __init__(self) -> None:
|
|
2145
|
+
p = types.SimpleNamespace()
|
|
2146
|
+
|
|
2147
|
+
def set_names_and_parse_actions() -> None:
|
|
2148
|
+
for key, val in vars(p).items():
|
|
2149
|
+
if not key.startswith('_'):
|
|
2150
|
+
# Set names on (almost) everything -- very useful for debugging
|
|
2151
|
+
# token, placeable, and auto_delim are forward references which
|
|
2152
|
+
# are left without names to ensure useful error messages
|
|
2153
|
+
if key not in ("token", "placeable", "auto_delim"):
|
|
2154
|
+
val.set_name(key)
|
|
2155
|
+
# Set actions
|
|
2156
|
+
if hasattr(self, key):
|
|
2157
|
+
val.set_parse_action(getattr(self, key))
|
|
2158
|
+
|
|
2159
|
+
# Root definitions.
|
|
2160
|
+
|
|
2161
|
+
# In TeX parlance, a csname is a control sequence name (a "\foo").
|
|
2162
|
+
def csnames(group: str, names: Iterable[str]) -> Regex:
|
|
2163
|
+
ends_with_alpha = []
|
|
2164
|
+
ends_with_nonalpha = []
|
|
2165
|
+
for name in names:
|
|
2166
|
+
if name[-1].isalpha():
|
|
2167
|
+
ends_with_alpha.append(name)
|
|
2168
|
+
else:
|
|
2169
|
+
ends_with_nonalpha.append(name)
|
|
2170
|
+
return Regex(
|
|
2171
|
+
r"\\(?P<{group}>(?:{alpha})(?![A-Za-z]){additional}{nonalpha})".format(
|
|
2172
|
+
group=group,
|
|
2173
|
+
alpha="|".join(map(re.escape, ends_with_alpha)),
|
|
2174
|
+
additional="|" if ends_with_nonalpha else "",
|
|
2175
|
+
nonalpha="|".join(map(re.escape, ends_with_nonalpha)),
|
|
2176
|
+
)
|
|
2177
|
+
)
|
|
2178
|
+
|
|
2179
|
+
p.float_literal = Regex(r"[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)")
|
|
2180
|
+
p.space = one_of(self._space_widths)("space")
|
|
2181
|
+
|
|
2182
|
+
p.style_literal = one_of(
|
|
2183
|
+
[str(e.value) for e in self._MathStyle])("style_literal")
|
|
2184
|
+
|
|
2185
|
+
p.symbol = Regex(
|
|
2186
|
+
r"[a-zA-Z0-9 +\-*/<>=:,.;!\?&'@()\[\]|\U00000080-\U0001ffff]"
|
|
2187
|
+
r"|\\[%${}\[\]_|]"
|
|
2188
|
+
+ r"|\\(?:{})(?![A-Za-z])".format(
|
|
2189
|
+
"|".join(map(re.escape, tex2uni)))
|
|
2190
|
+
)("sym").leave_whitespace()
|
|
2191
|
+
p.unknown_symbol = Regex(r"\\[A-Za-z]+")("name")
|
|
2192
|
+
|
|
2193
|
+
p.font = csnames("font", self._fontnames)
|
|
2194
|
+
p.start_group = Optional(r"\math" + one_of(self._fontnames)("font")) + "{"
|
|
2195
|
+
p.end_group = Literal("}")
|
|
2196
|
+
|
|
2197
|
+
p.delim = one_of(self._delims)
|
|
2198
|
+
|
|
2199
|
+
# Mutually recursive definitions. (Minimizing the number of Forward
|
|
2200
|
+
# elements is important for speed.)
|
|
2201
|
+
p.auto_delim = Forward()
|
|
2202
|
+
p.placeable = Forward()
|
|
2203
|
+
p.named_placeable = Forward()
|
|
2204
|
+
p.required_group = Forward()
|
|
2205
|
+
p.optional_group = Forward()
|
|
2206
|
+
p.token = Forward()
|
|
2207
|
+
|
|
2208
|
+
# Workaround for placable being part of a cycle of definitions
|
|
2209
|
+
# calling `p.placeable("name")` results in a copy, so not guaranteed
|
|
2210
|
+
# to get the definition added after it is used.
|
|
2211
|
+
# ref https://github.com/matplotlib/matplotlib/issues/25204
|
|
2212
|
+
# xref https://github.com/pyparsing/pyparsing/issues/95
|
|
2213
|
+
p.named_placeable <<= p.placeable
|
|
2214
|
+
|
|
2215
|
+
set_names_and_parse_actions() # for mutually recursive definitions.
|
|
2216
|
+
|
|
2217
|
+
p.optional_group <<= "{" + ZeroOrMore(p.token)("group") + "}"
|
|
2218
|
+
p.required_group <<= "{" + OneOrMore(p.token)("group") + "}"
|
|
2219
|
+
|
|
2220
|
+
p.customspace = cmd(r"\hspace", "{" + p.float_literal("space") + "}")
|
|
2221
|
+
|
|
2222
|
+
p.phantom = cmd(r"\phantom", p.optional_group("value"))
|
|
2223
|
+
p.llap = cmd(r"\llap", p.optional_group("value"))
|
|
2224
|
+
p.rlap = cmd(r"\rlap", p.optional_group("value"))
|
|
2225
|
+
|
|
2226
|
+
p.accent = (
|
|
2227
|
+
csnames("accent", [*self._accent_map, *self._wide_accents])
|
|
2228
|
+
- p.named_placeable("sym"))
|
|
2229
|
+
|
|
2230
|
+
p.function = csnames("name", self._function_names)
|
|
2231
|
+
|
|
2232
|
+
p.group = p.start_group + ZeroOrMore(p.token)("group") + p.end_group
|
|
2233
|
+
p.unclosed_group = (p.start_group + ZeroOrMore(p.token)("group") + StringEnd())
|
|
2234
|
+
|
|
2235
|
+
p.frac = cmd(r"\frac", p.required_group("num") + p.required_group("den"))
|
|
2236
|
+
p.dfrac = cmd(r"\dfrac", p.required_group("num") + p.required_group("den"))
|
|
2237
|
+
p.binom = cmd(r"\binom", p.required_group("num") + p.required_group("den"))
|
|
2238
|
+
|
|
2239
|
+
p.genfrac = cmd(
|
|
2240
|
+
r"\genfrac",
|
|
2241
|
+
"{" + Optional(p.delim)("ldelim") + "}"
|
|
2242
|
+
+ "{" + Optional(p.delim)("rdelim") + "}"
|
|
2243
|
+
+ "{" + p.float_literal("rulesize") + "}"
|
|
2244
|
+
+ "{" + Optional(p.style_literal)("style") + "}"
|
|
2245
|
+
+ p.required_group("num")
|
|
2246
|
+
+ p.required_group("den"))
|
|
2247
|
+
|
|
2248
|
+
p.sqrt = cmd(
|
|
2249
|
+
r"\sqrt{value}",
|
|
2250
|
+
Optional("[" + OneOrMore(NotAny("]") + p.token)("root") + "]")
|
|
2251
|
+
+ p.required_group("value"))
|
|
2252
|
+
|
|
2253
|
+
p.overline = cmd(r"\overline", p.required_group("body"))
|
|
2254
|
+
|
|
2255
|
+
p.underline = cmd(r"\underline", p.required_group("body"))
|
|
2256
|
+
|
|
2257
|
+
p.overset = cmd(
|
|
2258
|
+
r"\overset",
|
|
2259
|
+
p.optional_group("annotation") + p.optional_group("body"))
|
|
2260
|
+
p.underset = cmd(
|
|
2261
|
+
r"\underset",
|
|
2262
|
+
p.optional_group("annotation") + p.optional_group("body"))
|
|
2263
|
+
|
|
2264
|
+
p.text = cmd(r"\text", _BracedText())
|
|
2265
|
+
|
|
2266
|
+
p.substack = cmd(r"\substack",
|
|
2267
|
+
nested_expr(opener="{", closer="}",
|
|
2268
|
+
content=Group(OneOrMore(p.token)) +
|
|
2269
|
+
ZeroOrMore(Literal("\\\\").suppress()))("parts"))
|
|
2270
|
+
|
|
2271
|
+
p.subsuper = (
|
|
2272
|
+
(Optional(p.placeable)("nucleus")
|
|
2273
|
+
+ OneOrMore(one_of(["_", "^"]) - p.placeable)("subsuper")
|
|
2274
|
+
+ Regex("'*")("apostrophes"))
|
|
2275
|
+
| Regex("'+")("apostrophes")
|
|
2276
|
+
| (p.named_placeable("nucleus") + Regex("'*")("apostrophes"))
|
|
2277
|
+
)
|
|
2278
|
+
|
|
2279
|
+
p.simple = p.space | p.customspace | p.font | p.subsuper
|
|
2280
|
+
|
|
2281
|
+
p.token <<= (
|
|
2282
|
+
p.simple
|
|
2283
|
+
| p.auto_delim
|
|
2284
|
+
| p.unclosed_group
|
|
2285
|
+
| p.unknown_symbol # Must be last
|
|
2286
|
+
)
|
|
2287
|
+
|
|
2288
|
+
p.operatorname = cmd(r"\operatorname", "{" + ZeroOrMore(p.simple)("name") + "}")
|
|
2289
|
+
|
|
2290
|
+
p.boldsymbol = cmd(
|
|
2291
|
+
r"\boldsymbol", "{" + ZeroOrMore(p.simple)("value") + "}")
|
|
2292
|
+
|
|
2293
|
+
p.placeable <<= (
|
|
2294
|
+
p.phantom | p.llap | p.rlap
|
|
2295
|
+
| p.accent # Must be before symbol as all accents are symbols
|
|
2296
|
+
| p.symbol # Must be second to catch all named symbols and single
|
|
2297
|
+
# chars not in a group
|
|
2298
|
+
| p.function
|
|
2299
|
+
| p.operatorname
|
|
2300
|
+
| p.group
|
|
2301
|
+
| p.frac
|
|
2302
|
+
| p.dfrac
|
|
2303
|
+
| p.binom
|
|
2304
|
+
| p.genfrac
|
|
2305
|
+
| p.overset
|
|
2306
|
+
| p.underset
|
|
2307
|
+
| p.sqrt
|
|
2308
|
+
| p.overline
|
|
2309
|
+
| p.underline
|
|
2310
|
+
| p.text
|
|
2311
|
+
| p.boldsymbol
|
|
2312
|
+
| p.substack
|
|
2313
|
+
| p.auto_delim
|
|
2314
|
+
)
|
|
2315
|
+
|
|
2316
|
+
mdelim = r"\middle" - (p.delim("mdelim") | Error("Expected a delimiter"))
|
|
2317
|
+
p.auto_delim <<= (
|
|
2318
|
+
r"\left" - (p.delim("left") | Error("Expected a delimiter"))
|
|
2319
|
+
+ ZeroOrMore(p.simple | p.auto_delim | mdelim)("mid")
|
|
2320
|
+
+ r"\right" - (p.delim("right") | Error("Expected a delimiter"))
|
|
2321
|
+
)
|
|
2322
|
+
|
|
2323
|
+
# Leaf definitions.
|
|
2324
|
+
p.math = OneOrMore(p.token)
|
|
2325
|
+
p.math_string = QuotedString('$', '\\', unquote_results=False)
|
|
2326
|
+
p.non_math = Regex(r"(?:(?:\\[$])|[^$])*").leave_whitespace()
|
|
2327
|
+
p.main = (
|
|
2328
|
+
p.non_math + ZeroOrMore(p.math_string + p.non_math) + StringEnd()
|
|
2329
|
+
)
|
|
2330
|
+
set_names_and_parse_actions() # for leaf definitions.
|
|
2331
|
+
|
|
2332
|
+
self._expression = p.main
|
|
2333
|
+
self._math_expression = p.math
|
|
2334
|
+
|
|
2335
|
+
# To add space to nucleus operators after sub/superscripts
|
|
2336
|
+
self._needs_space_after_subsuper = False
|
|
2337
|
+
|
|
2338
|
+
def parse(self, s: str, fonts_object: Fonts, fontsize: float, dpi: float) -> Hlist:
|
|
2339
|
+
"""
|
|
2340
|
+
Parse expression *s* using the given *fonts_object* for
|
|
2341
|
+
output, at the given *fontsize* and *dpi*.
|
|
2342
|
+
|
|
2343
|
+
Returns the parse tree of `Node` instances.
|
|
2344
|
+
"""
|
|
2345
|
+
self._state_stack = [
|
|
2346
|
+
ParserState(fonts_object, 'default', 'rm', fontsize, dpi)]
|
|
2347
|
+
self._em_width_cache: dict[tuple[str, float, float], float] = {}
|
|
2348
|
+
try:
|
|
2349
|
+
result = self._expression.parse_string(s)
|
|
2350
|
+
except ParseBaseException as err:
|
|
2351
|
+
raise ValueError("\n" + err.explain(0)) from None
|
|
2352
|
+
self._state_stack = []
|
|
2353
|
+
self._needs_space_after_subsuper = False
|
|
2354
|
+
# prevent operator spacing from leaking into a new expression
|
|
2355
|
+
self._em_width_cache = {}
|
|
2356
|
+
ParserElement.reset_cache()
|
|
2357
|
+
return T.cast(Hlist, result[0]) # Known return type from main.
|
|
2358
|
+
|
|
2359
|
+
def get_state(self) -> ParserState:
|
|
2360
|
+
"""Get the current `State` of the parser."""
|
|
2361
|
+
return self._state_stack[-1]
|
|
2362
|
+
|
|
2363
|
+
def pop_state(self) -> None:
|
|
2364
|
+
"""Pop a `State` off of the stack."""
|
|
2365
|
+
self._state_stack.pop()
|
|
2366
|
+
|
|
2367
|
+
def push_state(self) -> None:
|
|
2368
|
+
"""Push a new `State` onto the stack, copying the current state."""
|
|
2369
|
+
self._state_stack.append(self.get_state().copy())
|
|
2370
|
+
|
|
2371
|
+
def main(self, toks: ParseResults) -> list[Hlist]:
|
|
2372
|
+
return [Hlist(toks.as_list())]
|
|
2373
|
+
|
|
2374
|
+
def math_string(self, toks: ParseResults) -> ParseResults:
|
|
2375
|
+
return self._math_expression.parse_string(toks[0][1:-1], parse_all=True)
|
|
2376
|
+
|
|
2377
|
+
def math(self, toks: ParseResults) -> T.Any:
|
|
2378
|
+
hlist = Hlist(toks.as_list())
|
|
2379
|
+
self.pop_state()
|
|
2380
|
+
return [hlist]
|
|
2381
|
+
|
|
2382
|
+
def non_math(self, toks: ParseResults) -> T.Any:
|
|
2383
|
+
s = toks[0].replace(r'\$', '$')
|
|
2384
|
+
symbols = [Char(c, self.get_state()) for c in s]
|
|
2385
|
+
hlist = Hlist(symbols)
|
|
2386
|
+
# We're going into math now, so set font to 'normal'
|
|
2387
|
+
self.push_state()
|
|
2388
|
+
self.get_state().font = mpl.rcParams['mathtext.default']
|
|
2389
|
+
return [hlist]
|
|
2390
|
+
|
|
2391
|
+
float_literal = staticmethod(pyparsing_common.convert_to_float)
|
|
2392
|
+
|
|
2393
|
+
def text(self, toks: ParseResults) -> T.Any:
|
|
2394
|
+
self.push_state()
|
|
2395
|
+
state = self.get_state()
|
|
2396
|
+
state.font = 'rm'
|
|
2397
|
+
hlist = Hlist([Char(c, state) for c in toks[1]])
|
|
2398
|
+
self.pop_state()
|
|
2399
|
+
return [hlist]
|
|
2400
|
+
|
|
2401
|
+
def _make_space(self, percentage: float) -> Kern:
|
|
2402
|
+
# In TeX, an em (the unit usually used to measure horizontal lengths)
|
|
2403
|
+
# is not the width of the character 'm'; it is the same in different
|
|
2404
|
+
# font styles (e.g. roman or italic). Mathtext, however, uses 'm' in
|
|
2405
|
+
# the normal style so that horizontal spaces don't depend on the
|
|
2406
|
+
# current font style.
|
|
2407
|
+
# TODO: this should be read from the font file
|
|
2408
|
+
state = self.get_state()
|
|
2409
|
+
key = (state.font, state.fontsize, state.dpi)
|
|
2410
|
+
width = self._em_width_cache.get(key)
|
|
2411
|
+
if width is None:
|
|
2412
|
+
width = state.fontset.get_quad('normal', state.fontsize, state.dpi)
|
|
2413
|
+
self._em_width_cache[key] = width
|
|
2414
|
+
return Kern(width * percentage)
|
|
2415
|
+
|
|
2416
|
+
_space_widths = {
|
|
2417
|
+
r'\,': 0.16667, # 3/18 em = 3 mu
|
|
2418
|
+
r'\thinspace': 0.16667, # 3/18 em = 3 mu
|
|
2419
|
+
r'\/': 0.16667, # 3/18 em = 3 mu
|
|
2420
|
+
r'\>': 0.22222, # 4/18 em = 4 mu
|
|
2421
|
+
r'\:': 0.22222, # 4/18 em = 4 mu
|
|
2422
|
+
r'\;': 0.27778, # 5/18 em = 5 mu
|
|
2423
|
+
r'\ ': 0.33333, # 6/18 em = 6 mu
|
|
2424
|
+
r'~': 0.33333, # 6/18 em = 6 mu, nonbreakable
|
|
2425
|
+
r'\enspace': 0.5, # 9/18 em = 9 mu
|
|
2426
|
+
r'\quad': 1, # 1 em = 18 mu
|
|
2427
|
+
r'\qquad': 2, # 2 em = 36 mu
|
|
2428
|
+
r'\!': -0.16667, # -3/18 em = -3 mu
|
|
2429
|
+
}
|
|
2430
|
+
|
|
2431
|
+
def space(self, toks: ParseResults) -> T.Any:
|
|
2432
|
+
num = self._space_widths[toks["space"]]
|
|
2433
|
+
box = self._make_space(num)
|
|
2434
|
+
return [box]
|
|
2435
|
+
|
|
2436
|
+
def customspace(self, toks: ParseResults) -> T.Any:
|
|
2437
|
+
return [self._make_space(toks["space"])]
|
|
2438
|
+
|
|
2439
|
+
def symbol(self, s: str, loc: int,
|
|
2440
|
+
toks: ParseResults | dict[str, str]) -> T.Any:
|
|
2441
|
+
c = toks["sym"]
|
|
2442
|
+
if c == "-":
|
|
2443
|
+
# "U+2212 minus sign is the preferred representation of the unary
|
|
2444
|
+
# and binary minus sign rather than the ASCII-derived U+002D
|
|
2445
|
+
# hyphen-minus, because minus sign is unambiguous and because it
|
|
2446
|
+
# is rendered with a more desirable length, usually longer than a
|
|
2447
|
+
# hyphen." (https://www.unicode.org/reports/tr25/)
|
|
2448
|
+
c = "\N{MINUS SIGN}"
|
|
2449
|
+
try:
|
|
2450
|
+
char = Char(c, self.get_state())
|
|
2451
|
+
except ValueError as err:
|
|
2452
|
+
raise ParseFatalException(s, loc,
|
|
2453
|
+
"Unknown symbol: %s" % c) from err
|
|
2454
|
+
|
|
2455
|
+
if c in self._spaced_symbols:
|
|
2456
|
+
# iterate until we find previous character, needed for cases
|
|
2457
|
+
# such as $=-2$, ${ -2}$, $ -2$, or $ -2$.
|
|
2458
|
+
prev_char = next((c for c in s[:loc][::-1] if c != ' '), '')
|
|
2459
|
+
# Binary operators at start of string should not be spaced
|
|
2460
|
+
# Also, operators in sub- or superscripts should not be spaced
|
|
2461
|
+
if (self._needs_space_after_subsuper or (
|
|
2462
|
+
c in self._binary_operators and (
|
|
2463
|
+
len(s[:loc].split()) == 0 or prev_char in {
|
|
2464
|
+
'{', *self._left_delims, *self._relation_symbols}))):
|
|
2465
|
+
return [char]
|
|
2466
|
+
else:
|
|
2467
|
+
return [Hlist([self._make_space(0.2),
|
|
2468
|
+
char,
|
|
2469
|
+
self._make_space(0.2)],
|
|
2470
|
+
do_kern=True)]
|
|
2471
|
+
elif c in self._punctuation_symbols:
|
|
2472
|
+
prev_char = next((c for c in s[:loc][::-1] if c != ' '), '')
|
|
2473
|
+
next_char = next((c for c in s[loc + 1:] if c != ' '), '')
|
|
2474
|
+
|
|
2475
|
+
# Do not space commas between brackets
|
|
2476
|
+
if c == ',':
|
|
2477
|
+
if prev_char == '{' and next_char == '}':
|
|
2478
|
+
return [char]
|
|
2479
|
+
|
|
2480
|
+
# Do not space dots as decimal separators
|
|
2481
|
+
if c == '.' and prev_char.isdigit() and next_char.isdigit():
|
|
2482
|
+
return [char]
|
|
2483
|
+
else:
|
|
2484
|
+
return [Hlist([char, self._make_space(0.2)], do_kern=True)]
|
|
2485
|
+
return [char]
|
|
2486
|
+
|
|
2487
|
+
def unknown_symbol(self, s: str, loc: int, toks: ParseResults) -> T.Any:
|
|
2488
|
+
raise ParseFatalException(s, loc, f"Unknown symbol: {toks['name']}")
|
|
2489
|
+
|
|
2490
|
+
def phantom(self, toks: ParseResults) -> T.Any:
|
|
2491
|
+
toks["value"].is_phantom = True
|
|
2492
|
+
return toks["value"]
|
|
2493
|
+
|
|
2494
|
+
def llap(self, toks: ParseResults) -> T.Any:
|
|
2495
|
+
return [Hlist([Kern(-toks["value"].width), toks["value"]])]
|
|
2496
|
+
|
|
2497
|
+
def rlap(self, toks: ParseResults) -> T.Any:
|
|
2498
|
+
return [Hlist([toks["value"], Kern(-toks["value"].width)])]
|
|
2499
|
+
|
|
2500
|
+
_accent_map = {
|
|
2501
|
+
r'hat': r'\circumflexaccent',
|
|
2502
|
+
r'breve': r'\combiningbreve',
|
|
2503
|
+
r'bar': r'\combiningoverline',
|
|
2504
|
+
r'grave': r'\combininggraveaccent',
|
|
2505
|
+
r'acute': r'\combiningacuteaccent',
|
|
2506
|
+
r'tilde': r'\combiningtilde',
|
|
2507
|
+
r'dot': r'\combiningdotabove',
|
|
2508
|
+
r'ddot': r'\combiningdiaeresis',
|
|
2509
|
+
r'dddot': r'\combiningthreedotsabove',
|
|
2510
|
+
r'ddddot': r'\combiningfourdotsabove',
|
|
2511
|
+
r'vec': r'\combiningrightarrowabove',
|
|
2512
|
+
r'"': r'\combiningdiaeresis',
|
|
2513
|
+
r"`": r'\combininggraveaccent',
|
|
2514
|
+
r"'": r'\combiningacuteaccent',
|
|
2515
|
+
r'~': r'\combiningtilde',
|
|
2516
|
+
r'.': r'\combiningdotabove',
|
|
2517
|
+
r'^': r'\circumflexaccent',
|
|
2518
|
+
r'overrightarrow': r'\rightarrow',
|
|
2519
|
+
r'overleftarrow': r'\leftarrow',
|
|
2520
|
+
r'mathring': r'\circ',
|
|
2521
|
+
}
|
|
2522
|
+
|
|
2523
|
+
_wide_accents = set(r"widehat widetilde widebar".split())
|
|
2524
|
+
|
|
2525
|
+
def accent(self, toks: ParseResults) -> T.Any:
|
|
2526
|
+
state = self.get_state()
|
|
2527
|
+
thickness = state.get_current_underline_thickness()
|
|
2528
|
+
accent = toks["accent"]
|
|
2529
|
+
sym = toks["sym"]
|
|
2530
|
+
accent_box: Node
|
|
2531
|
+
if accent in self._wide_accents:
|
|
2532
|
+
accent_box = AutoWidthChar(
|
|
2533
|
+
'\\' + accent, sym.width, state, char_class=Accent)
|
|
2534
|
+
centered = HCentered([accent_box])
|
|
2535
|
+
else:
|
|
2536
|
+
accent_box = Accent(self._accent_map[accent], state)
|
|
2537
|
+
if accent == 'mathring':
|
|
2538
|
+
accent_box.shrink()
|
|
2539
|
+
accent_box.shrink()
|
|
2540
|
+
centered = HCentered([Hbox(sym.width / 4.0), accent_box])
|
|
2541
|
+
centered.hpack(sym.width, 'exactly')
|
|
2542
|
+
return Vlist([
|
|
2543
|
+
centered,
|
|
2544
|
+
Vbox(0., thickness * 2.0),
|
|
2545
|
+
Hlist([sym])
|
|
2546
|
+
])
|
|
2547
|
+
|
|
2548
|
+
def function(self, s: str, loc: int, toks: ParseResults) -> T.Any:
|
|
2549
|
+
hlist = self.operatorname(s, loc, toks)
|
|
2550
|
+
hlist.function_name = toks["name"]
|
|
2551
|
+
return hlist
|
|
2552
|
+
|
|
2553
|
+
def operatorname(self, s: str, loc: int, toks: ParseResults) -> T.Any:
|
|
2554
|
+
self.push_state()
|
|
2555
|
+
state = self.get_state()
|
|
2556
|
+
state.font = 'rm'
|
|
2557
|
+
hlist_list: list[Node] = []
|
|
2558
|
+
# Change the font of Chars, but leave Kerns alone
|
|
2559
|
+
name = toks["name"]
|
|
2560
|
+
for c in name:
|
|
2561
|
+
if isinstance(c, Char):
|
|
2562
|
+
c.font = 'rm'
|
|
2563
|
+
c._update_metrics()
|
|
2564
|
+
hlist_list.append(c)
|
|
2565
|
+
elif isinstance(c, str):
|
|
2566
|
+
hlist_list.append(Char(c, state))
|
|
2567
|
+
else:
|
|
2568
|
+
hlist_list.append(c)
|
|
2569
|
+
next_char_loc = loc + len(name) + 1
|
|
2570
|
+
if isinstance(name, ParseResults):
|
|
2571
|
+
next_char_loc += len('operatorname{}')
|
|
2572
|
+
next_char = next((c for c in s[next_char_loc:] if c != ' '), '')
|
|
2573
|
+
delimiters = self._delims | {'^', '_'}
|
|
2574
|
+
if next_char not in delimiters:
|
|
2575
|
+
# Add thin space except when followed by parenthesis, bracket, etc.
|
|
2576
|
+
hlist_list += [self._make_space(self._space_widths[r'\,'])]
|
|
2577
|
+
self.pop_state()
|
|
2578
|
+
# If followed by a sub/superscript, set flag to true to tell subsuper
|
|
2579
|
+
# to add space after this operator.
|
|
2580
|
+
self._needs_space_after_subsuper = next_char in {'^', '_'}
|
|
2581
|
+
return Hlist(hlist_list)
|
|
2582
|
+
|
|
2583
|
+
def start_group(self, toks: ParseResults) -> T.Any:
|
|
2584
|
+
self.push_state()
|
|
2585
|
+
# Deal with LaTeX-style font tokens
|
|
2586
|
+
if toks.get("font"):
|
|
2587
|
+
self.get_state().font = toks.get("font")
|
|
2588
|
+
return []
|
|
2589
|
+
|
|
2590
|
+
def group(self, toks: ParseResults) -> T.Any:
|
|
2591
|
+
grp = Hlist(toks.get("group", []))
|
|
2592
|
+
return [grp]
|
|
2593
|
+
|
|
2594
|
+
def required_group(self, toks: ParseResults) -> T.Any:
|
|
2595
|
+
return Hlist(toks.get("group", []))
|
|
2596
|
+
|
|
2597
|
+
optional_group = required_group
|
|
2598
|
+
|
|
2599
|
+
def end_group(self) -> T.Any:
|
|
2600
|
+
self.pop_state()
|
|
2601
|
+
return []
|
|
2602
|
+
|
|
2603
|
+
def unclosed_group(self, s: str, loc: int, toks: ParseResults) -> T.Any:
|
|
2604
|
+
raise ParseFatalException(s, len(s), "Expected '}'")
|
|
2605
|
+
|
|
2606
|
+
def font(self, toks: ParseResults) -> T.Any:
|
|
2607
|
+
self.get_state().font = toks["font"]
|
|
2608
|
+
return []
|
|
2609
|
+
|
|
2610
|
+
def is_overunder(self, nucleus: Node) -> bool:
|
|
2611
|
+
if isinstance(nucleus, Char):
|
|
2612
|
+
return nucleus.c in self._overunder_symbols
|
|
2613
|
+
elif isinstance(nucleus, Hlist) and hasattr(nucleus, 'function_name'):
|
|
2614
|
+
return nucleus.function_name in self._overunder_functions
|
|
2615
|
+
return False
|
|
2616
|
+
|
|
2617
|
+
def is_dropsub(self, nucleus: Node) -> bool:
|
|
2618
|
+
if isinstance(nucleus, Char):
|
|
2619
|
+
return nucleus.c in self._dropsub_symbols
|
|
2620
|
+
return False
|
|
2621
|
+
|
|
2622
|
+
def is_slanted(self, nucleus: Node) -> bool:
|
|
2623
|
+
if isinstance(nucleus, Char):
|
|
2624
|
+
return nucleus.is_slanted()
|
|
2625
|
+
return False
|
|
2626
|
+
|
|
2627
|
+
def subsuper(self, s: str, loc: int, toks: ParseResults) -> T.Any:
|
|
2628
|
+
nucleus = toks.get("nucleus", Hbox(0))
|
|
2629
|
+
subsuper = toks.get("subsuper", [])
|
|
2630
|
+
napostrophes = len(toks.get("apostrophes", []))
|
|
2631
|
+
|
|
2632
|
+
if not subsuper and not napostrophes:
|
|
2633
|
+
return nucleus
|
|
2634
|
+
|
|
2635
|
+
sub = super = None
|
|
2636
|
+
while subsuper:
|
|
2637
|
+
op, arg, *subsuper = subsuper
|
|
2638
|
+
if op == '_':
|
|
2639
|
+
if sub is not None:
|
|
2640
|
+
raise ParseFatalException("Double subscript")
|
|
2641
|
+
sub = arg
|
|
2642
|
+
else:
|
|
2643
|
+
if super is not None:
|
|
2644
|
+
raise ParseFatalException("Double superscript")
|
|
2645
|
+
super = arg
|
|
2646
|
+
|
|
2647
|
+
state = self.get_state()
|
|
2648
|
+
rule_thickness = state.fontset.get_underline_thickness(
|
|
2649
|
+
state.font, state.fontsize, state.dpi)
|
|
2650
|
+
x_height = state.fontset.get_xheight(state.font, state.fontsize, state.dpi)
|
|
2651
|
+
|
|
2652
|
+
if napostrophes:
|
|
2653
|
+
if super is None:
|
|
2654
|
+
super = Hlist([])
|
|
2655
|
+
elif not isinstance(super, Hlist):
|
|
2656
|
+
# A single-char superscript is a bare Char; wrap it so the
|
|
2657
|
+
# prime glyphs can be appended.
|
|
2658
|
+
super = Hlist([super])
|
|
2659
|
+
for i in range(napostrophes):
|
|
2660
|
+
super.children.extend(self.symbol(s, loc, {"sym": "\\prime"}))
|
|
2661
|
+
# kern() and hpack() needed to get the metrics right after
|
|
2662
|
+
# extending
|
|
2663
|
+
super.kern()
|
|
2664
|
+
super.hpack()
|
|
2665
|
+
|
|
2666
|
+
# Handle over/under symbols, such as sum or prod
|
|
2667
|
+
if self.is_overunder(nucleus):
|
|
2668
|
+
vlist = []
|
|
2669
|
+
shift = 0.
|
|
2670
|
+
width = nucleus.width
|
|
2671
|
+
if super is not None:
|
|
2672
|
+
super.shrink()
|
|
2673
|
+
width = max(width, super.width)
|
|
2674
|
+
if sub is not None:
|
|
2675
|
+
sub.shrink()
|
|
2676
|
+
width = max(width, sub.width)
|
|
2677
|
+
|
|
2678
|
+
vgap = rule_thickness * 3.0
|
|
2679
|
+
if super is not None:
|
|
2680
|
+
hlist = HCentered([super])
|
|
2681
|
+
hlist.hpack(width, 'exactly')
|
|
2682
|
+
vlist.extend([hlist, Vbox(0, vgap)])
|
|
2683
|
+
hlist = HCentered([nucleus])
|
|
2684
|
+
hlist.hpack(width, 'exactly')
|
|
2685
|
+
vlist.append(hlist)
|
|
2686
|
+
if sub is not None:
|
|
2687
|
+
hlist = HCentered([sub])
|
|
2688
|
+
hlist.hpack(width, 'exactly')
|
|
2689
|
+
vlist.extend([Vbox(0, vgap), hlist])
|
|
2690
|
+
shift = hlist.height + vgap + nucleus.depth
|
|
2691
|
+
vlt = Vlist(vlist)
|
|
2692
|
+
vlt.shift_amount = shift
|
|
2693
|
+
optional_spacing = ([self._make_space(self._space_widths[r'\,'])]
|
|
2694
|
+
if self._needs_space_after_subsuper else [])
|
|
2695
|
+
self._needs_space_after_subsuper = False
|
|
2696
|
+
result = Hlist([vlt, *optional_spacing])
|
|
2697
|
+
return [result]
|
|
2698
|
+
|
|
2699
|
+
# We remove kerning on the last character for consistency (otherwise
|
|
2700
|
+
# it will compute kerning based on non-shrunk characters and may put
|
|
2701
|
+
# them too close together when superscripted)
|
|
2702
|
+
# We change the width of the last character to match the advance to
|
|
2703
|
+
# consider some fonts with weird metrics: e.g. stix's f has a width of
|
|
2704
|
+
# 7.75 and a kerning of -4.0 for an advance of 3.72, and we want to put
|
|
2705
|
+
# the superscript at the advance
|
|
2706
|
+
last_char = nucleus
|
|
2707
|
+
if isinstance(nucleus, Hlist):
|
|
2708
|
+
new_children = nucleus.children
|
|
2709
|
+
if len(new_children):
|
|
2710
|
+
# remove last kern
|
|
2711
|
+
if (isinstance(new_children[-1], Kern) and
|
|
2712
|
+
isinstance(new_children[-2], Char)):
|
|
2713
|
+
new_children = new_children[:-1]
|
|
2714
|
+
last_char = new_children[-1]
|
|
2715
|
+
if isinstance(last_char, Char):
|
|
2716
|
+
last_char.width = last_char._metrics.advance
|
|
2717
|
+
# create new Hlist without kerning
|
|
2718
|
+
nucleus = Hlist(new_children, do_kern=False)
|
|
2719
|
+
else:
|
|
2720
|
+
if isinstance(nucleus, Char):
|
|
2721
|
+
last_char.width = last_char._metrics.advance
|
|
2722
|
+
nucleus = Hlist([nucleus])
|
|
2723
|
+
|
|
2724
|
+
# Handle regular sub/superscripts
|
|
2725
|
+
consts = state.fontset.get_font_constants()
|
|
2726
|
+
lc_height = last_char.height
|
|
2727
|
+
lc_baseline = 0.0
|
|
2728
|
+
if self.is_dropsub(last_char):
|
|
2729
|
+
lc_baseline = last_char.depth
|
|
2730
|
+
|
|
2731
|
+
# Compute kerning for sub and super
|
|
2732
|
+
superkern = consts.delta * x_height
|
|
2733
|
+
subkern = consts.delta * x_height
|
|
2734
|
+
if self.is_slanted(last_char):
|
|
2735
|
+
superkern += consts.delta * x_height
|
|
2736
|
+
superkern += consts.delta_slanted * (lc_height - x_height * 2 / 3)
|
|
2737
|
+
if self.is_dropsub(last_char):
|
|
2738
|
+
subkern = (3 * consts.delta - consts.delta_integral) * lc_height
|
|
2739
|
+
superkern = (3 * consts.delta + consts.delta_integral) * lc_height
|
|
2740
|
+
else:
|
|
2741
|
+
subkern = 0
|
|
2742
|
+
|
|
2743
|
+
# Set the minimum shifts for the superscript and subscript (node756).
|
|
2744
|
+
if nucleus.is_char_node():
|
|
2745
|
+
shift_up = 0.0
|
|
2746
|
+
shift_down = 0.0
|
|
2747
|
+
else:
|
|
2748
|
+
shrunk_x_height = state.fontset.get_xheight(
|
|
2749
|
+
state.font, state.fontsize * SHRINK_FACTOR, state.dpi)
|
|
2750
|
+
shift_up = nucleus.height - consts.supdrop * shrunk_x_height
|
|
2751
|
+
shift_down = nucleus.depth + consts.subdrop * shrunk_x_height
|
|
2752
|
+
|
|
2753
|
+
x: List
|
|
2754
|
+
if super is None:
|
|
2755
|
+
# Align subscript without superscript (node757).
|
|
2756
|
+
# Note: One of super or sub must be a Node if we're in this function, but
|
|
2757
|
+
# mypy can't know this, since it can't interpret pyparsing expressions,
|
|
2758
|
+
# hence the cast.
|
|
2759
|
+
x = Hlist([Kern(subkern), T.cast(Node, sub)])
|
|
2760
|
+
x.shrink()
|
|
2761
|
+
if self.is_dropsub(last_char):
|
|
2762
|
+
shift_down = lc_baseline + consts.subdrop * x_height
|
|
2763
|
+
else:
|
|
2764
|
+
shift_down = max(shift_down, consts.sub1 * x_height,
|
|
2765
|
+
x.height - x_height * 4 / 5)
|
|
2766
|
+
x.shift_amount = shift_down
|
|
2767
|
+
else:
|
|
2768
|
+
# Align superscript (node758).
|
|
2769
|
+
x = Hlist([Kern(superkern), super])
|
|
2770
|
+
x.shrink()
|
|
2771
|
+
if self.is_dropsub(last_char):
|
|
2772
|
+
shift_up = lc_height - consts.subdrop * x_height
|
|
2773
|
+
else:
|
|
2774
|
+
shift_up = max(shift_up, consts.sup1 * x_height, x.depth + x_height / 4)
|
|
2775
|
+
if sub is None:
|
|
2776
|
+
x.shift_amount = -shift_up
|
|
2777
|
+
else:
|
|
2778
|
+
# Align subscript with superscript (node759).
|
|
2779
|
+
y = Hlist([Kern(subkern), sub])
|
|
2780
|
+
y.shrink()
|
|
2781
|
+
if self.is_dropsub(last_char):
|
|
2782
|
+
shift_down = lc_baseline + consts.subdrop * x_height
|
|
2783
|
+
else:
|
|
2784
|
+
shift_down = max(shift_down, consts.sub2 * x_height)
|
|
2785
|
+
# If the subscript and superscript are too close to each other,
|
|
2786
|
+
# move the subscript down.
|
|
2787
|
+
clr = (4 * rule_thickness -
|
|
2788
|
+
((shift_up - x.depth) - (y.height - shift_down)))
|
|
2789
|
+
if clr > 0.:
|
|
2790
|
+
shift_down += clr
|
|
2791
|
+
clr = x_height * 4 / 5 - shift_up + x.depth
|
|
2792
|
+
if clr > 0:
|
|
2793
|
+
shift_up += clr
|
|
2794
|
+
shift_down -= clr
|
|
2795
|
+
x = Vlist([
|
|
2796
|
+
x,
|
|
2797
|
+
Kern((shift_up - x.depth) - (y.height - shift_down)),
|
|
2798
|
+
y])
|
|
2799
|
+
x.shift_amount = shift_down
|
|
2800
|
+
|
|
2801
|
+
if not self.is_dropsub(last_char):
|
|
2802
|
+
x.width += consts.script_space * x_height
|
|
2803
|
+
|
|
2804
|
+
# Do we need to add a space after the nucleus?
|
|
2805
|
+
# To find out, check the flag set by operatorname
|
|
2806
|
+
optional_spacing = ([self._make_space(self._space_widths[r'\,'])]
|
|
2807
|
+
if self._needs_space_after_subsuper else [])
|
|
2808
|
+
self._needs_space_after_subsuper = False
|
|
2809
|
+
result = Hlist([nucleus, x, *optional_spacing])
|
|
2810
|
+
return [result]
|
|
2811
|
+
|
|
2812
|
+
def _genfrac(self, ldelim: str, rdelim: str, rule: float | None, style: _MathStyle,
|
|
2813
|
+
num: Hlist, den: Hlist) -> T.Any:
|
|
2814
|
+
state = self.get_state()
|
|
2815
|
+
thickness = state.get_current_underline_thickness()
|
|
2816
|
+
|
|
2817
|
+
axis_height = state.fontset.get_axis_height(
|
|
2818
|
+
state.font, state.fontsize, state.dpi)
|
|
2819
|
+
consts = state.fontset.get_font_constants()
|
|
2820
|
+
x_height = state.fontset.get_xheight(state.font, state.fontsize, state.dpi)
|
|
2821
|
+
|
|
2822
|
+
for _ in range(style.value):
|
|
2823
|
+
x_height *= SHRINK_FACTOR
|
|
2824
|
+
num.shrink()
|
|
2825
|
+
den.shrink()
|
|
2826
|
+
cnum = HCentered([num])
|
|
2827
|
+
cden = HCentered([den])
|
|
2828
|
+
width = max(num.width, den.width)
|
|
2829
|
+
cnum.hpack(width, 'exactly')
|
|
2830
|
+
cden.hpack(width, 'exactly')
|
|
2831
|
+
|
|
2832
|
+
# Align the fraction with a fraction line (node743, node744 and node746).
|
|
2833
|
+
if rule:
|
|
2834
|
+
if style is self._MathStyle.DISPLAYSTYLE:
|
|
2835
|
+
num_shift_up = consts.num1 * x_height
|
|
2836
|
+
den_shift_down = consts.denom1 * x_height
|
|
2837
|
+
clr = 3 * rule # The minimum clearance.
|
|
2838
|
+
else:
|
|
2839
|
+
num_shift_up = consts.num2 * x_height
|
|
2840
|
+
den_shift_down = consts.denom2 * x_height
|
|
2841
|
+
clr = rule # The minimum clearance.
|
|
2842
|
+
delta = rule / 2
|
|
2843
|
+
num_clr = max((num_shift_up - cnum.depth) - (axis_height + delta), clr)
|
|
2844
|
+
den_clr = max((axis_height - delta) - (cden.height - den_shift_down), clr)
|
|
2845
|
+
vlist = Vlist([cnum, # numerator
|
|
2846
|
+
Vbox(0, num_clr), # space
|
|
2847
|
+
Hrule(state, rule), # rule
|
|
2848
|
+
Vbox(0, den_clr), # space
|
|
2849
|
+
cden # denominator
|
|
2850
|
+
])
|
|
2851
|
+
vlist.shift_amount = cden.height + den_clr + delta - axis_height
|
|
2852
|
+
|
|
2853
|
+
# Align the fraction without a fraction line (node743, node744 and node745).
|
|
2854
|
+
else:
|
|
2855
|
+
if style is self._MathStyle.DISPLAYSTYLE:
|
|
2856
|
+
num_shift_up = consts.num1 * x_height
|
|
2857
|
+
den_shift_down = consts.denom1 * x_height
|
|
2858
|
+
min_clr = 7 * thickness # The minimum clearance.
|
|
2859
|
+
else:
|
|
2860
|
+
num_shift_up = consts.num3 * x_height
|
|
2861
|
+
den_shift_down = consts.denom2 * x_height
|
|
2862
|
+
min_clr = 3 * thickness # The minimum clearance.
|
|
2863
|
+
def_clr = (num_shift_up - cnum.depth) - (cden.height - den_shift_down)
|
|
2864
|
+
clr = max(def_clr, min_clr)
|
|
2865
|
+
vlist = Vlist([cnum, # numerator
|
|
2866
|
+
Vbox(0, clr), # space
|
|
2867
|
+
cden # denominator
|
|
2868
|
+
])
|
|
2869
|
+
vlist.shift_amount = den_shift_down
|
|
2870
|
+
if def_clr < min_clr:
|
|
2871
|
+
vlist.shift_amount += (min_clr - def_clr) / 2
|
|
2872
|
+
|
|
2873
|
+
result: list[Box | Char | str] = [Hlist([
|
|
2874
|
+
Hbox(thickness),
|
|
2875
|
+
vlist,
|
|
2876
|
+
Hbox(thickness)
|
|
2877
|
+
])]
|
|
2878
|
+
if ldelim or rdelim:
|
|
2879
|
+
return self._auto_sized_delimiter(ldelim or ".", result, rdelim or ".")
|
|
2880
|
+
return result
|
|
2881
|
+
|
|
2882
|
+
def style_literal(self, toks: ParseResults) -> T.Any:
|
|
2883
|
+
return self._MathStyle(int(toks["style_literal"]))
|
|
2884
|
+
|
|
2885
|
+
def genfrac(self, toks: ParseResults) -> T.Any:
|
|
2886
|
+
return self._genfrac(
|
|
2887
|
+
toks.get("ldelim", ""), toks.get("rdelim", ""),
|
|
2888
|
+
toks["rulesize"], toks.get("style", self._MathStyle.TEXTSTYLE),
|
|
2889
|
+
toks["num"], toks["den"])
|
|
2890
|
+
|
|
2891
|
+
def frac(self, toks: ParseResults) -> T.Any:
|
|
2892
|
+
return self._genfrac(
|
|
2893
|
+
"", "", self.get_state().get_current_underline_thickness(),
|
|
2894
|
+
self._MathStyle.TEXTSTYLE, toks["num"], toks["den"])
|
|
2895
|
+
|
|
2896
|
+
def dfrac(self, toks: ParseResults) -> T.Any:
|
|
2897
|
+
return self._genfrac(
|
|
2898
|
+
"", "", self.get_state().get_current_underline_thickness(),
|
|
2899
|
+
self._MathStyle.DISPLAYSTYLE, toks["num"], toks["den"])
|
|
2900
|
+
|
|
2901
|
+
def binom(self, toks: ParseResults) -> T.Any:
|
|
2902
|
+
return self._genfrac(
|
|
2903
|
+
"(", ")", 0,
|
|
2904
|
+
self._MathStyle.TEXTSTYLE, toks["num"], toks["den"])
|
|
2905
|
+
|
|
2906
|
+
def _genset(self, s: str, loc: int, toks: ParseResults) -> T.Any:
|
|
2907
|
+
annotation = toks["annotation"]
|
|
2908
|
+
body = toks["body"]
|
|
2909
|
+
thickness = self.get_state().get_current_underline_thickness()
|
|
2910
|
+
|
|
2911
|
+
annotation.shrink()
|
|
2912
|
+
centered_annotation = HCentered([annotation])
|
|
2913
|
+
centered_body = HCentered([body])
|
|
2914
|
+
width = max(centered_annotation.width, centered_body.width)
|
|
2915
|
+
centered_annotation.hpack(width, 'exactly')
|
|
2916
|
+
centered_body.hpack(width, 'exactly')
|
|
2917
|
+
|
|
2918
|
+
vgap = thickness * 3
|
|
2919
|
+
if s[loc + 1] == "u": # \underset
|
|
2920
|
+
vlist = Vlist([
|
|
2921
|
+
centered_body, # body
|
|
2922
|
+
Vbox(0, vgap), # space
|
|
2923
|
+
centered_annotation # annotation
|
|
2924
|
+
])
|
|
2925
|
+
# Shift so the body sits in the same vertical position
|
|
2926
|
+
vlist.shift_amount = centered_body.depth + centered_annotation.height + vgap
|
|
2927
|
+
else: # \overset
|
|
2928
|
+
vlist = Vlist([
|
|
2929
|
+
centered_annotation, # annotation
|
|
2930
|
+
Vbox(0, vgap), # space
|
|
2931
|
+
centered_body # body
|
|
2932
|
+
])
|
|
2933
|
+
|
|
2934
|
+
# To add horizontal gap between symbols: wrap the Vlist into
|
|
2935
|
+
# an Hlist and extend it with an Hbox(0, horizontal_gap)
|
|
2936
|
+
return vlist
|
|
2937
|
+
|
|
2938
|
+
overset = underset = _genset
|
|
2939
|
+
|
|
2940
|
+
def sqrt(self, toks: ParseResults) -> T.Any:
|
|
2941
|
+
root = toks.get("root")
|
|
2942
|
+
body = toks["value"]
|
|
2943
|
+
state = self.get_state()
|
|
2944
|
+
thickness = state.get_current_underline_thickness()
|
|
2945
|
+
|
|
2946
|
+
# Determine the height of the body, and add a little extra to
|
|
2947
|
+
# the height so it doesn't seem cramped
|
|
2948
|
+
height = body.height - body.shift_amount + 5 * thickness
|
|
2949
|
+
depth = body.depth + body.shift_amount
|
|
2950
|
+
check = AutoHeightChar(r'\__sqrt__', height, depth, state)
|
|
2951
|
+
height = check.height - check.shift_amount
|
|
2952
|
+
depth = check.depth + check.shift_amount
|
|
2953
|
+
|
|
2954
|
+
# Put a little extra space to the left and right of the body
|
|
2955
|
+
padded_body = Hlist([Hbox(2 * thickness), body, Hbox(2 * thickness)])
|
|
2956
|
+
rightside = Vlist([Hrule(state), Glue('fill'), padded_body])
|
|
2957
|
+
# Stretch the glue between the hrule and the body
|
|
2958
|
+
rightside.vpack(height + (state.fontsize * state.dpi) / (100 * 12),
|
|
2959
|
+
'exactly', depth)
|
|
2960
|
+
|
|
2961
|
+
# Add the root and shift it upward so it is above the tick.
|
|
2962
|
+
# The value of 0.6 is a hard-coded hack ;)
|
|
2963
|
+
if not root:
|
|
2964
|
+
root = Box(0.5 * check.width, 0., 0.)
|
|
2965
|
+
else:
|
|
2966
|
+
root = Hlist(root)
|
|
2967
|
+
root.shrink()
|
|
2968
|
+
root.shrink()
|
|
2969
|
+
|
|
2970
|
+
root_vlist = Vlist([Hlist([root])])
|
|
2971
|
+
root_vlist.shift_amount = -height * 0.6
|
|
2972
|
+
|
|
2973
|
+
hlist = Hlist([
|
|
2974
|
+
root_vlist, # Root
|
|
2975
|
+
Kern(-0.5 * check.width), # Negative kerning to put root over tick
|
|
2976
|
+
check, # Check
|
|
2977
|
+
rightside, # Body
|
|
2978
|
+
])
|
|
2979
|
+
return [hlist]
|
|
2980
|
+
|
|
2981
|
+
def overline(self, toks: ParseResults) -> T.Any:
|
|
2982
|
+
body = toks["body"]
|
|
2983
|
+
|
|
2984
|
+
state = self.get_state()
|
|
2985
|
+
thickness = state.get_current_underline_thickness()
|
|
2986
|
+
|
|
2987
|
+
height = body.height - body.shift_amount + 3 * thickness
|
|
2988
|
+
depth = body.depth + body.shift_amount
|
|
2989
|
+
|
|
2990
|
+
# Place overline above body
|
|
2991
|
+
rightside = Vlist([Hrule(state), Glue('fill'), Hlist([body])])
|
|
2992
|
+
|
|
2993
|
+
# Stretch the glue between the hrule and the body
|
|
2994
|
+
rightside.vpack(height + (state.fontsize * state.dpi) / (100 * 12),
|
|
2995
|
+
'exactly', depth)
|
|
2996
|
+
|
|
2997
|
+
hlist = Hlist([rightside])
|
|
2998
|
+
return [hlist]
|
|
2999
|
+
|
|
3000
|
+
def underline(self, toks: ParseResults) -> T.Any:
|
|
3001
|
+
body = toks["body"]
|
|
3002
|
+
state = self.get_state()
|
|
3003
|
+
thickness = state.get_current_underline_thickness()
|
|
3004
|
+
# Place the underline below `body` (node735).
|
|
3005
|
+
vlist = Vlist([
|
|
3006
|
+
Hlist([body]),
|
|
3007
|
+
Kern(3 * thickness),
|
|
3008
|
+
Hrule(state, thickness),
|
|
3009
|
+
])
|
|
3010
|
+
delta = vlist.height + vlist.depth + thickness
|
|
3011
|
+
vlist.height = body.height
|
|
3012
|
+
vlist.depth = delta - vlist.height
|
|
3013
|
+
return [Hlist([vlist])]
|
|
3014
|
+
|
|
3015
|
+
def _auto_sized_delimiter(self, front: str,
|
|
3016
|
+
middle: list[Box | Char | str],
|
|
3017
|
+
back: str) -> T.Any:
|
|
3018
|
+
state = self.get_state()
|
|
3019
|
+
if len(middle):
|
|
3020
|
+
height = max([x.height for x in middle if not isinstance(x, str)])
|
|
3021
|
+
depth = max([x.depth for x in middle if not isinstance(x, str)])
|
|
3022
|
+
factor = None
|
|
3023
|
+
for idx, el in enumerate(middle):
|
|
3024
|
+
if el == r'\middle':
|
|
3025
|
+
c = T.cast(str, middle[idx + 1]) # Should be one of p.delims.
|
|
3026
|
+
if c != '.':
|
|
3027
|
+
middle[idx + 1] = AutoHeightChar(
|
|
3028
|
+
c, height, depth, state, factor=factor)
|
|
3029
|
+
else:
|
|
3030
|
+
middle.remove(c)
|
|
3031
|
+
del middle[idx]
|
|
3032
|
+
# There should only be \middle and its delimiter as str, which have
|
|
3033
|
+
# just been removed.
|
|
3034
|
+
middle_part = T.cast(list[Box | Char], middle)
|
|
3035
|
+
else:
|
|
3036
|
+
height = 0
|
|
3037
|
+
depth = 0
|
|
3038
|
+
factor = 1.0
|
|
3039
|
+
middle_part = []
|
|
3040
|
+
|
|
3041
|
+
parts: list[Node] = []
|
|
3042
|
+
# \left. and \right. aren't supposed to produce any symbols
|
|
3043
|
+
if front != '.':
|
|
3044
|
+
parts.append(
|
|
3045
|
+
AutoHeightChar(front, height, depth, state, factor=factor))
|
|
3046
|
+
parts.extend(middle_part)
|
|
3047
|
+
if back != '.':
|
|
3048
|
+
parts.append(
|
|
3049
|
+
AutoHeightChar(back, height, depth, state, factor=factor))
|
|
3050
|
+
hlist = Hlist(parts)
|
|
3051
|
+
return hlist
|
|
3052
|
+
|
|
3053
|
+
def auto_delim(self, toks: ParseResults) -> T.Any:
|
|
3054
|
+
return self._auto_sized_delimiter(
|
|
3055
|
+
toks["left"], toks["mid"].as_list(), toks["right"])
|
|
3056
|
+
|
|
3057
|
+
def boldsymbol(self, toks: ParseResults) -> T.Any:
|
|
3058
|
+
self.push_state()
|
|
3059
|
+
state = self.get_state()
|
|
3060
|
+
hlist: list[Node] = []
|
|
3061
|
+
name = toks["value"]
|
|
3062
|
+
for c in name:
|
|
3063
|
+
if isinstance(c, Hlist):
|
|
3064
|
+
k = c.children[1]
|
|
3065
|
+
if isinstance(k, Char):
|
|
3066
|
+
k.font = "bf"
|
|
3067
|
+
k._update_metrics()
|
|
3068
|
+
hlist.append(c)
|
|
3069
|
+
elif isinstance(c, Char):
|
|
3070
|
+
c.font = "bf"
|
|
3071
|
+
if (c.c in self._latin_alphabets or
|
|
3072
|
+
c.c[1:] in self._small_greek):
|
|
3073
|
+
c.font = "bfit"
|
|
3074
|
+
c._update_metrics()
|
|
3075
|
+
c._update_metrics()
|
|
3076
|
+
hlist.append(c)
|
|
3077
|
+
else:
|
|
3078
|
+
hlist.append(c)
|
|
3079
|
+
self.pop_state()
|
|
3080
|
+
|
|
3081
|
+
return Hlist(hlist)
|
|
3082
|
+
|
|
3083
|
+
def substack(self, toks: ParseResults) -> T.Any:
|
|
3084
|
+
parts = toks["parts"]
|
|
3085
|
+
state = self.get_state()
|
|
3086
|
+
thickness = state.get_current_underline_thickness()
|
|
3087
|
+
|
|
3088
|
+
hlist = [Hlist(k) for k in parts[0]]
|
|
3089
|
+
max_width = max(map(lambda c: c.width, hlist))
|
|
3090
|
+
|
|
3091
|
+
vlist = []
|
|
3092
|
+
for sub in hlist:
|
|
3093
|
+
cp = HCentered([sub])
|
|
3094
|
+
cp.hpack(max_width, 'exactly')
|
|
3095
|
+
vlist.append(cp)
|
|
3096
|
+
|
|
3097
|
+
stack = [val
|
|
3098
|
+
for pair in zip(vlist, [Vbox(0, thickness * 2)] * len(vlist))
|
|
3099
|
+
for val in pair]
|
|
3100
|
+
del stack[-1]
|
|
3101
|
+
vlt = Vlist(stack)
|
|
3102
|
+
result = [Hlist([vlt])]
|
|
3103
|
+
return result
|