mathshuttle 0.8.0__tar.gz

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.
Files changed (69) hide show
  1. mathshuttle-0.8.0/LICENSE +21 -0
  2. mathshuttle-0.8.0/PKG-INFO +113 -0
  3. mathshuttle-0.8.0/README.md +91 -0
  4. mathshuttle-0.8.0/mathshuttle/__init__.py +3 -0
  5. mathshuttle-0.8.0/mathshuttle/__main__.py +343 -0
  6. mathshuttle-0.8.0/mathshuttle/_clipboard_macos.py +235 -0
  7. mathshuttle-0.8.0/mathshuttle/_clipboard_win32.py +199 -0
  8. mathshuttle-0.8.0/mathshuttle/_hotkeys_macos.py +137 -0
  9. mathshuttle-0.8.0/mathshuttle/app.py +1483 -0
  10. mathshuttle-0.8.0/mathshuttle/clipboard.py +127 -0
  11. mathshuttle-0.8.0/mathshuttle/compat.py +1537 -0
  12. mathshuttle-0.8.0/mathshuttle/convert.py +496 -0
  13. mathshuttle-0.8.0/mathshuttle/diagnose.py +184 -0
  14. mathshuttle-0.8.0/mathshuttle/documents.py +903 -0
  15. mathshuttle-0.8.0/mathshuttle/hotkeys.py +179 -0
  16. mathshuttle-0.8.0/mathshuttle/latex_wrap.py +333 -0
  17. mathshuttle-0.8.0/mathshuttle/office_html.py +234 -0
  18. mathshuttle-0.8.0/mathshuttle/packs.py +610 -0
  19. mathshuttle-0.8.0/mathshuttle/pandoc_engine.py +1732 -0
  20. mathshuttle-0.8.0/mathshuttle/pandoc_fetch.py +325 -0
  21. mathshuttle-0.8.0/mathshuttle/paths.py +19 -0
  22. mathshuttle-0.8.0/mathshuttle/preview.py +232 -0
  23. mathshuttle-0.8.0/mathshuttle/recall.py +337 -0
  24. mathshuttle-0.8.0/mathshuttle/sv_theme/LICENSE +21 -0
  25. mathshuttle-0.8.0/mathshuttle/sv_theme/sv.tcl +130 -0
  26. mathshuttle-0.8.0/mathshuttle/sv_theme/theme/dark.tcl +465 -0
  27. mathshuttle-0.8.0/mathshuttle/sv_theme/theme/light.tcl +469 -0
  28. mathshuttle-0.8.0/mathshuttle/sv_theme/theme/sprites_dark.tcl +95 -0
  29. mathshuttle-0.8.0/mathshuttle/sv_theme/theme/sprites_light.tcl +95 -0
  30. mathshuttle-0.8.0/mathshuttle/sv_theme/theme/spritesheet_dark.png +0 -0
  31. mathshuttle-0.8.0/mathshuttle/sv_theme/theme/spritesheet_light.png +0 -0
  32. mathshuttle-0.8.0/mathshuttle/theme.py +127 -0
  33. mathshuttle-0.8.0/mathshuttle/tidy.py +830 -0
  34. mathshuttle-0.8.0/mathshuttle/wordexport.py +887 -0
  35. mathshuttle-0.8.0/mathshuttle.egg-info/PKG-INFO +113 -0
  36. mathshuttle-0.8.0/mathshuttle.egg-info/SOURCES.txt +67 -0
  37. mathshuttle-0.8.0/mathshuttle.egg-info/dependency_links.txt +1 -0
  38. mathshuttle-0.8.0/mathshuttle.egg-info/entry_points.txt +5 -0
  39. mathshuttle-0.8.0/mathshuttle.egg-info/top_level.txt +1 -0
  40. mathshuttle-0.8.0/pyproject.toml +47 -0
  41. mathshuttle-0.8.0/setup.cfg +4 -0
  42. mathshuttle-0.8.0/tests/test_app_smoke.py +695 -0
  43. mathshuttle-0.8.0/tests/test_batch_extract.py +86 -0
  44. mathshuttle-0.8.0/tests/test_cli.py +235 -0
  45. mathshuttle-0.8.0/tests/test_clipboard_macos.py +135 -0
  46. mathshuttle-0.8.0/tests/test_compat.py +187 -0
  47. mathshuttle-0.8.0/tests/test_convert.py +650 -0
  48. mathshuttle-0.8.0/tests/test_document_definitions.py +135 -0
  49. mathshuttle-0.8.0/tests/test_documents.py +155 -0
  50. mathshuttle-0.8.0/tests/test_documents_review.py +242 -0
  51. mathshuttle-0.8.0/tests/test_engine_version.py +95 -0
  52. mathshuttle-0.8.0/tests/test_expand_macros.py +241 -0
  53. mathshuttle-0.8.0/tests/test_hotkeys.py +102 -0
  54. mathshuttle-0.8.0/tests/test_latex_wrap.py +134 -0
  55. mathshuttle-0.8.0/tests/test_markdown_input.py +277 -0
  56. mathshuttle-0.8.0/tests/test_office_html.py +407 -0
  57. mathshuttle-0.8.0/tests/test_office_spaces.py +67 -0
  58. mathshuttle-0.8.0/tests/test_packs.py +142 -0
  59. mathshuttle-0.8.0/tests/test_pandoc_fetch.py +371 -0
  60. mathshuttle-0.8.0/tests/test_platform.py +140 -0
  61. mathshuttle-0.8.0/tests/test_preview.py +57 -0
  62. mathshuttle-0.8.0/tests/test_recall.py +169 -0
  63. mathshuttle-0.8.0/tests/test_regressions.py +304 -0
  64. mathshuttle-0.8.0/tests/test_review_080.py +149 -0
  65. mathshuttle-0.8.0/tests/test_review_batch1.py +284 -0
  66. mathshuttle-0.8.0/tests/test_symbol_roundtrip.py +173 -0
  67. mathshuttle-0.8.0/tests/test_tidy.py +123 -0
  68. mathshuttle-0.8.0/tests/test_wordexport.py +145 -0
  69. mathshuttle-0.8.0/tests/test_wordexport_review.py +388 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 infinitr0us
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,113 @@
1
+ Metadata-Version: 2.4
2
+ Name: mathshuttle
3
+ Version: 0.8.0
4
+ Summary: Move equations between LaTeX and Word / PowerPoint, both ways, offline (texmath via pandoc)
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/infinitr0us/MathShuttle
7
+ Project-URL: Documentation, https://github.com/infinitr0us/MathShuttle#documentation
8
+ Project-URL: Changelog, https://github.com/infinitr0us/MathShuttle/blob/main/CHANGELOG.md
9
+ Project-URL: Issues, https://github.com/infinitr0us/MathShuttle/issues
10
+ Keywords: latex,mathml,omml,word,powerpoint,equations,pandoc,texmath
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: Microsoft :: Windows
13
+ Classifier: Operating System :: MacOS
14
+ Classifier: Environment :: Win32 (MS Windows)
15
+ Classifier: Environment :: MacOS X
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: Topic :: Text Processing :: Markup :: LaTeX
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Dynamic: license-file
22
+
23
+ # MathShuttle
24
+
25
+ Move equations between LaTeX and Word / PowerPoint, both ways, offline.
26
+
27
+ ![The MathShuttle window: LaTeX in, Office Math out, with the LaTeX preview below](https://raw.githubusercontent.com/infinitr0us/MathShuttle/main/docs/images/window.png)
28
+
29
+ * **LaTeX to Word and PowerPoint.** Copy LaTeX, with your paper's macros, and paste it into Word or
30
+ PowerPoint as a native, editable equation. Aligned blocks arrive lined up at the `=` signs.
31
+ * **Word and PowerPoint to LaTeX.** Copy an equation in Office and get LaTeX you can put in a paper
32
+ (`\mathrm{OOD}`, `\operatorname{softmax}`, `\boldsymbol{\theta}`, `cases`, `a &= b`). An equation you
33
+ sent and nobody edited comes back as the LaTeX you wrote.
34
+ * **Whole papers to Word.** A `.tex` or Markdown file, or a pasted chat answer, becomes a Word document
35
+ with native equations, numbered as LaTeX numbers them, with references and citations. Every equation of
36
+ a `.docx`, `.pptx`, `.tex` or `.md` file can be listed, filtered and exported.
37
+ * **Other people's LaTeX.** A paper's own definitions, commands of common packages (physics, braket,
38
+ siunitx...) and old TeX font switches are handled. An equation that still fails says why, in plain words.
39
+ * **Also:** LaTeX, MathML and OMML conversion with Typst and eqn output (a local stand-in for the
40
+ [texmath web demo](https://johnmacfarlane.net/texmath.html)), LaTeX with your macros written out, a
41
+ hotkey that works in any program, a LaTeX preview, and a command line.
42
+
43
+ Windows and macOS. Everything runs on your computer; nothing is sent anywhere.
44
+
45
+ ## Install
46
+
47
+ 1. Download the zip for your system from the
48
+ [latest release](https://github.com/infinitr0us/MathShuttle/releases/latest):
49
+ `MathShuttle-<version>-windows-x64.zip` or `MathShuttle-<version>-macos-arm64.zip`.
50
+ 2. **Windows:** unzip it anywhere and run `MathShuttle\MathShuttle.exe`. The exe is not code-signed, so
51
+ SmartScreen may warn the first time: *More info*, then *Run anyway*.
52
+ **macOS:** drag `MathShuttle.app` into Applications. It is not signed by a registered developer, so
53
+ the first time open it with System Settings > Privacy & Security > *Open Anyway*.
54
+ 3. MathShuttle needs [pandoc](https://pandoc.org), the conversion engine. If pandoc is not installed,
55
+ the window offers to download it (pandoc's own release, about 40 MB, checked against its SHA-256). You can
56
+ also install it yourself: `winget install JohnMacFarlane.Pandoc` (Windows) or `brew install pandoc`
57
+ (macOS).
58
+
59
+ With Python 3.9 or later (with tkinter): `pipx install mathshuttle` gives the commands `mathshuttle`
60
+ (the window without arguments, the command line with them) and `mathshuttle-gui`. No other Python
61
+ packages are needed. A LaTeX installation (MiKTeX, TeX Live, MacTeX) turns on the LaTeX preview.
62
+
63
+ ## Use
64
+
65
+ 1. Type or paste LaTeX, click **Copy for Word/PowerPoint** (Ctrl+Shift+C), and press Ctrl+V in Word or
66
+ PowerPoint.
67
+ 2. The other way: select an equation in Word or PowerPoint, press Ctrl+C, and click
68
+ **Paste from Word/PowerPoint** (Ctrl+Shift+V).
69
+ 3. Your macros: **Macros...** takes your paper's macro file or preamble, once.
70
+ 4. A whole paper: **Open file...**, then **Whole file as Word...**, or `mathshuttle word paper.tex -o paper.docx`.
71
+
72
+ On the Mac, Cmd takes the place of Ctrl. The window follows the system's light or dark mode. On
73
+ Windows and Linux you can fix one: set `"theme"` to `"light"`, `"dark"` or `"native"` (Tk's own look) in
74
+ `settings.json` (`%APPDATA%\MathShuttle` on Windows); on the Mac the window keeps the system's look.
75
+
76
+ ### Next to Office's own LaTeX support
77
+
78
+ Microsoft 365 (Version 2606 and later) turns LaTeX pasted with `$…$` / `\[…\]` delimiters into an
79
+ equation itself. It rejects `\newcommand` and `\DeclareMathOperator`, though, and gives back LaTeX in
80
+ its own style. On a 784-equation PhD thesis (Word 16.0.20527), Word's own paste turned 781 into
81
+ equations; MathShuttle converts all 784, and 764 of them come back from Word as the same symbols and
82
+ fonts. MathShuttle also works with Office versions without LaTeX paste (Office 2021 / 2024 LTSC, older
83
+ Mac Office).
84
+
85
+ ## Documentation
86
+
87
+ * [Word and PowerPoint](https://github.com/infinitr0us/MathShuttle/blob/main/docs/word-and-powerpoint.md):
88
+ both directions, what Word changes, your own LaTeX back, the preview, the hotkey
89
+ * [Documents](https://github.com/infinitr0us/MathShuttle/blob/main/docs/documents.md): Open file, Word
90
+ export of passages and papers, equation numbers, references and citations
91
+ * [LaTeX input and output](https://github.com/infinitr0us/MathShuttle/blob/main/docs/latex-input.md):
92
+ modes, chat answers and Markdown, macros, packs, what is rewritten for texmath, the wrapper box
93
+ * [Command line](https://github.com/infinitr0us/MathShuttle/blob/main/docs/command-line.md)
94
+ * [macOS](https://github.com/infinitr0us/MathShuttle/blob/main/docs/macos.md)
95
+ * [Building, testing and how it works](https://github.com/infinitr0us/MathShuttle/blob/main/docs/development.md)
96
+ * [Changelog](https://github.com/infinitr0us/MathShuttle/blob/main/CHANGELOG.md)
97
+
98
+ Found a problem? [Open an issue](https://github.com/infinitr0us/MathShuttle/issues/new/choose); Help >
99
+ *Copy details for a bug report* in the window copies the versions it asks for.
100
+
101
+ ## How it works
102
+
103
+ The conversion engine is texmath, which runs inside pandoc (same author). MathShuttle prepares the LaTeX
104
+ that texmath cannot read (macros, packages, old syntax), tidies the LaTeX that comes back from Office,
105
+ and talks to the Word and PowerPoint clipboard. It needs only Python's standard library and pandoc.
106
+
107
+ ## Licence
108
+
109
+ MIT, see [LICENSE](LICENSE). pandoc (which contains texmath) is a separate program under the GPL
110
+ (version 2 or later); MathShuttle only runs it. A copy downloaded by the window is pandoc's own release,
111
+ with its licence files next to it. A build made with `build_exe.ps1 -BundlePandoc` contains `pandoc.exe`:
112
+ if you pass such a build on, the GPL applies to that copy of pandoc (include its licence and offer its
113
+ source code).
@@ -0,0 +1,91 @@
1
+ # MathShuttle
2
+
3
+ Move equations between LaTeX and Word / PowerPoint, both ways, offline.
4
+
5
+ ![The MathShuttle window: LaTeX in, Office Math out, with the LaTeX preview below](https://raw.githubusercontent.com/infinitr0us/MathShuttle/main/docs/images/window.png)
6
+
7
+ * **LaTeX to Word and PowerPoint.** Copy LaTeX, with your paper's macros, and paste it into Word or
8
+ PowerPoint as a native, editable equation. Aligned blocks arrive lined up at the `=` signs.
9
+ * **Word and PowerPoint to LaTeX.** Copy an equation in Office and get LaTeX you can put in a paper
10
+ (`\mathrm{OOD}`, `\operatorname{softmax}`, `\boldsymbol{\theta}`, `cases`, `a &= b`). An equation you
11
+ sent and nobody edited comes back as the LaTeX you wrote.
12
+ * **Whole papers to Word.** A `.tex` or Markdown file, or a pasted chat answer, becomes a Word document
13
+ with native equations, numbered as LaTeX numbers them, with references and citations. Every equation of
14
+ a `.docx`, `.pptx`, `.tex` or `.md` file can be listed, filtered and exported.
15
+ * **Other people's LaTeX.** A paper's own definitions, commands of common packages (physics, braket,
16
+ siunitx...) and old TeX font switches are handled. An equation that still fails says why, in plain words.
17
+ * **Also:** LaTeX, MathML and OMML conversion with Typst and eqn output (a local stand-in for the
18
+ [texmath web demo](https://johnmacfarlane.net/texmath.html)), LaTeX with your macros written out, a
19
+ hotkey that works in any program, a LaTeX preview, and a command line.
20
+
21
+ Windows and macOS. Everything runs on your computer; nothing is sent anywhere.
22
+
23
+ ## Install
24
+
25
+ 1. Download the zip for your system from the
26
+ [latest release](https://github.com/infinitr0us/MathShuttle/releases/latest):
27
+ `MathShuttle-<version>-windows-x64.zip` or `MathShuttle-<version>-macos-arm64.zip`.
28
+ 2. **Windows:** unzip it anywhere and run `MathShuttle\MathShuttle.exe`. The exe is not code-signed, so
29
+ SmartScreen may warn the first time: *More info*, then *Run anyway*.
30
+ **macOS:** drag `MathShuttle.app` into Applications. It is not signed by a registered developer, so
31
+ the first time open it with System Settings > Privacy & Security > *Open Anyway*.
32
+ 3. MathShuttle needs [pandoc](https://pandoc.org), the conversion engine. If pandoc is not installed,
33
+ the window offers to download it (pandoc's own release, about 40 MB, checked against its SHA-256). You can
34
+ also install it yourself: `winget install JohnMacFarlane.Pandoc` (Windows) or `brew install pandoc`
35
+ (macOS).
36
+
37
+ With Python 3.9 or later (with tkinter): `pipx install mathshuttle` gives the commands `mathshuttle`
38
+ (the window without arguments, the command line with them) and `mathshuttle-gui`. No other Python
39
+ packages are needed. A LaTeX installation (MiKTeX, TeX Live, MacTeX) turns on the LaTeX preview.
40
+
41
+ ## Use
42
+
43
+ 1. Type or paste LaTeX, click **Copy for Word/PowerPoint** (Ctrl+Shift+C), and press Ctrl+V in Word or
44
+ PowerPoint.
45
+ 2. The other way: select an equation in Word or PowerPoint, press Ctrl+C, and click
46
+ **Paste from Word/PowerPoint** (Ctrl+Shift+V).
47
+ 3. Your macros: **Macros...** takes your paper's macro file or preamble, once.
48
+ 4. A whole paper: **Open file...**, then **Whole file as Word...**, or `mathshuttle word paper.tex -o paper.docx`.
49
+
50
+ On the Mac, Cmd takes the place of Ctrl. The window follows the system's light or dark mode. On
51
+ Windows and Linux you can fix one: set `"theme"` to `"light"`, `"dark"` or `"native"` (Tk's own look) in
52
+ `settings.json` (`%APPDATA%\MathShuttle` on Windows); on the Mac the window keeps the system's look.
53
+
54
+ ### Next to Office's own LaTeX support
55
+
56
+ Microsoft 365 (Version 2606 and later) turns LaTeX pasted with `$…$` / `\[…\]` delimiters into an
57
+ equation itself. It rejects `\newcommand` and `\DeclareMathOperator`, though, and gives back LaTeX in
58
+ its own style. On a 784-equation PhD thesis (Word 16.0.20527), Word's own paste turned 781 into
59
+ equations; MathShuttle converts all 784, and 764 of them come back from Word as the same symbols and
60
+ fonts. MathShuttle also works with Office versions without LaTeX paste (Office 2021 / 2024 LTSC, older
61
+ Mac Office).
62
+
63
+ ## Documentation
64
+
65
+ * [Word and PowerPoint](https://github.com/infinitr0us/MathShuttle/blob/main/docs/word-and-powerpoint.md):
66
+ both directions, what Word changes, your own LaTeX back, the preview, the hotkey
67
+ * [Documents](https://github.com/infinitr0us/MathShuttle/blob/main/docs/documents.md): Open file, Word
68
+ export of passages and papers, equation numbers, references and citations
69
+ * [LaTeX input and output](https://github.com/infinitr0us/MathShuttle/blob/main/docs/latex-input.md):
70
+ modes, chat answers and Markdown, macros, packs, what is rewritten for texmath, the wrapper box
71
+ * [Command line](https://github.com/infinitr0us/MathShuttle/blob/main/docs/command-line.md)
72
+ * [macOS](https://github.com/infinitr0us/MathShuttle/blob/main/docs/macos.md)
73
+ * [Building, testing and how it works](https://github.com/infinitr0us/MathShuttle/blob/main/docs/development.md)
74
+ * [Changelog](https://github.com/infinitr0us/MathShuttle/blob/main/CHANGELOG.md)
75
+
76
+ Found a problem? [Open an issue](https://github.com/infinitr0us/MathShuttle/issues/new/choose); Help >
77
+ *Copy details for a bug report* in the window copies the versions it asks for.
78
+
79
+ ## How it works
80
+
81
+ The conversion engine is texmath, which runs inside pandoc (same author). MathShuttle prepares the LaTeX
82
+ that texmath cannot read (macros, packages, old syntax), tidies the LaTeX that comes back from Office,
83
+ and talks to the Word and PowerPoint clipboard. It needs only Python's standard library and pandoc.
84
+
85
+ ## Licence
86
+
87
+ MIT, see [LICENSE](LICENSE). pandoc (which contains texmath) is a separate program under the GPL
88
+ (version 2 or later); MathShuttle only runs it. A copy downloaded by the window is pandoc's own release,
89
+ with its licence files next to it. A build made with `build_exe.ps1 -BundlePandoc` contains `pandoc.exe`:
90
+ if you pass such a build on, the GPL applies to that copy of pandoc (include its licence and offer its
91
+ source code).
@@ -0,0 +1,3 @@
1
+ """MathShuttle - local LaTeX / MathML / OMML equation converter (texmath via pandoc)."""
2
+
3
+ __version__ = "0.8.0"
@@ -0,0 +1,343 @@
1
+ """Open the MathShuttle window without arguments, or run a command."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import os
6
+ import re
7
+ import shlex
8
+ import sys
9
+
10
+ from . import __version__
11
+ from .compat import load_macros, merge_notes
12
+ from .convert import MODES, convert, convert_equations, macro_notes, office_copy
13
+ from .documents import READABLE, read_document
14
+ from .latex_wrap import WRAPPER_KEYS
15
+ from .pandoc_engine import READ_FORMATS, WRITE_FORMATS, ConversionError, PandocNotFound, _mathy, engine_report
16
+
17
+ # how a line of comment (the equation's place in the document) is written in each output format
18
+ _COMMENT = {"latex": "%% %s", "mathml": "<!-- %s -->", "omml": "<!-- %s -->", "typst": "// %s", "eqn": '.\\" %s'}
19
+
20
+
21
+ def _comment(fmt: str, text: str, keep_spacing: bool = False) -> str:
22
+ """A one-line comment in `fmt`; an XML comment may not hold "--" nor end with "-" (a heading "A--B")."""
23
+ text = " ".join(text.splitlines() if keep_spacing else text.split())
24
+ if fmt in ("mathml", "omml"):
25
+ while "--" in text:
26
+ text = text.replace("--", "- -")
27
+ text = text + " " if text.endswith("-") else text
28
+ return _COMMENT[fmt] % text
29
+
30
+
31
+ def _failure_reason(error: ConversionError) -> str:
32
+ """In a texmath parse error the diagnosis follows the source line and its caret."""
33
+ if getattr(error, "short", ""): # the explanation in plain words (diagnose.explained), on one line
34
+ return error.short
35
+ lines = [line.strip() for line in str(error).splitlines() if line.strip()]
36
+ for marker, reason in zip(lines, lines[1:]):
37
+ if marker == "^" and reason != "^":
38
+ return reason
39
+ return lines[0].rstrip(":") if lines else "Unknown conversion error"
40
+
41
+
42
+ class InputError(ValueError):
43
+ """The input file cannot be read; the message is meant for the user."""
44
+
45
+
46
+ def _quote_arg(value: str) -> str:
47
+ """Quote one argument for PowerShell on Windows or a POSIX shell elsewhere."""
48
+ if sys.platform == "win32":
49
+ return value if re.fullmatch(r"[\w./:\\-]+", value) else "'" + value.replace("'", "''") + "'"
50
+ return shlex.quote(value)
51
+
52
+
53
+ def _read_source(path: str | None, expr: str | None, command: str) -> str:
54
+ """The input text: UTF-8 (with or without a BOM), or UTF-16 with a BOM - what `>` writes in
55
+ Windows PowerShell 5.1."""
56
+ if expr is not None:
57
+ return expr
58
+ if path is None or path == "-":
59
+ if sys.stdin.isatty():
60
+ eof = "Ctrl+Z then Enter" if sys.platform == "win32" else "Ctrl+D"
61
+ print(f"Reading input from the keyboard. Press {eof} to finish.", file=sys.stderr, flush=True)
62
+ return sys.stdin.read()
63
+ try:
64
+ with open(path, "rb") as f:
65
+ data = f.read()
66
+ except OSError as e:
67
+ message = f"cannot read {path}: {e.strerror or e}"
68
+ # (a mistyped path - C:\papers\x.tex, notes/eq.md - gets no hint)
69
+ looks_like_path = bool(re.match(r"[A-Za-z]:[\\/]|\.{1,2}[\\/]|~[\\/]|/", path) or
70
+ re.search(r"\.[A-Za-z][A-Za-z0-9]{0,4}$", path))
71
+ if not os.path.exists(path) and not looks_like_path and (
72
+ re.search(r"[\s\\^_{}=+*()$]", path) or _mathy(path)):
73
+ expr_arg = "-e=" if path.startswith("-") else "-e "
74
+ message += ("\nThe argument was taken as a file name. For an equation, "
75
+ f"try mathshuttle {command} {expr_arg}{_quote_arg(path)}")
76
+ raise InputError(message) from e
77
+ try:
78
+ text = data.decode("utf-16") if data[:2] in (b"\xff\xfe", b"\xfe\xff") else data.decode("utf-8-sig")
79
+ except UnicodeDecodeError as e:
80
+ raise InputError("%s is neither UTF-8 nor UTF-16 text (%s)" % (path, e))
81
+ return text.replace("\r\n", "\n").replace("\r", "\n") # as text mode would
82
+
83
+
84
+ def _utf8_stdio() -> None:
85
+ """Pipes and redirections default to the ANSI code page on Windows (cp1252, cp936...):
86
+ UTF-8 input would be misread and MathML output such as <mi>ℝ</mi> fails to encode."""
87
+ for stream, encoding in ((sys.stdin, "utf-8-sig"), (sys.stdout, "utf-8"), (sys.stderr, "utf-8")):
88
+ if hasattr(stream, "reconfigure"):
89
+ stream.reconfigure(encoding=encoding)
90
+
91
+
92
+ class _CommandParser(argparse.ArgumentParser):
93
+ def error(self, message):
94
+ super().error(message + "\nsee mathshuttle --help")
95
+
96
+
97
+ def _get_pandoc(force: bool) -> int:
98
+ from . import pandoc_engine, pandoc_fetch
99
+
100
+ name, override = pandoc_engine._env_pandoc()
101
+ if override and not os.path.isfile(override): # it would still win over a downloaded copy
102
+ print(f"error: {name} is set to {override}, which is not a file. Unset it (or correct it); "
103
+ f"then mathshuttle finds pandoc by itself, and get-pandoc can install one.", file=sys.stderr)
104
+ return 1
105
+ if not force:
106
+ try:
107
+ path = pandoc_engine.find_pandoc()
108
+ except PandocNotFound:
109
+ pass
110
+ else:
111
+ print(f"Pandoc is already available at {path}")
112
+ return 0
113
+
114
+ last = ""
115
+
116
+ def progress(done, total):
117
+ nonlocal last
118
+ amount = f"{done * 100 // total}%" if total else f"{done / 1_000_000:.1f} MB"
119
+ if amount != last:
120
+ print(f"\rDownloading pandoc: {amount}", file=sys.stderr, end="", flush=True)
121
+ last = amount
122
+
123
+ try:
124
+ path = pandoc_fetch.install(progress=progress)
125
+ except (pandoc_fetch.FetchError, KeyboardInterrupt) as exc:
126
+ if last:
127
+ print(file=sys.stderr)
128
+ if isinstance(exc, KeyboardInterrupt):
129
+ print("Pandoc installation cancelled.", file=sys.stderr)
130
+ return 130
131
+ print(f"error: {exc}", file=sys.stderr)
132
+ return 1
133
+ if last:
134
+ print(file=sys.stderr)
135
+ pandoc_engine.reset_pandoc()
136
+ print(f"Installed pandoc {pandoc_fetch.PANDOC_VERSION} at {path}")
137
+ return 0
138
+
139
+
140
+ def _cli(argv: list[str]) -> int:
141
+ _utf8_stdio()
142
+ parser = _CommandParser(
143
+ prog="mathshuttle",
144
+ description="Convert equations between LaTeX, MathML and OMML or exchange them with Office.\n"
145
+ "Running mathshuttle without arguments opens the window.",
146
+ formatter_class=argparse.RawDescriptionHelpFormatter,
147
+ epilog="""Examples:
148
+ mathshuttle convert -e 'x^2' -t mathml
149
+ mathshuttle copy -e 'x^2'
150
+ mathshuttle paste --wrapper bare
151
+ mathshuttle extract paper.tex -t typst
152
+ mathshuttle get-pandoc
153
+ mathshuttle --version""",
154
+ )
155
+ version_help = "Show the MathShuttle, pandoc and texmath versions."
156
+ parser.add_argument("--version", action="store_true", help=version_help)
157
+ sub = parser.add_subparsers(dest="cmd", title="commands", parser_class=argparse.ArgumentParser)
158
+
159
+ def command(name, summary, description=None):
160
+ return sub.add_parser(name, help=summary, description=description or summary)
161
+
162
+ convert_cmd = command(
163
+ "convert", "Convert equations and write them to standard output.",
164
+ description="Convert equations and write them to standard output. The default output (-t omml) "
165
+ "is OMML text for people working with the XML. Use mathshuttle copy to paste into Office.",
166
+ )
167
+ copy_cmd = command("copy", "Copy an equation to paste into Word or PowerPoint.")
168
+ paste_cmd = command("paste", "Convert an equation copied in Office and write it to standard output.")
169
+ extract_cmd = command("extract", "Write each equation in a document with its location.")
170
+ word_cmd = command(
171
+ "word", "Write a passage or a whole .tex / .md document as a Word file with native equations.",
172
+ description="Write a passage (a chat answer, Markdown notes, LaTeX text: a file, -e TEXT or standard "
173
+ "input) or a whole .tex / .md document as a Word file: its prose, headings, lists and tables, "
174
+ "and each equation a native Word equation. A .tex file gets its own definitions, and the "
175
+ "equation numbers of its .aux file at the right margin.")
176
+ command("version", version_help)
177
+ get_cmd = command("get-pandoc", "Download and install pandoc for this user.")
178
+ get_cmd.add_argument("--force", action="store_true", help="download even if pandoc is already available")
179
+
180
+ word_input = word_cmd.add_mutually_exclusive_group()
181
+ word_input.add_argument("-e", "--expr", metavar="TEXT", help="use TEXT instead of a file or standard input")
182
+ word_input.add_argument("file", nargs="?", metavar="FILE",
183
+ help="a .tex or .md document, or a text file with a passage (default: standard input)")
184
+ word_cmd.add_argument("-o", "--output", required=True, metavar="OUT", help="the Word file to write (.docx)")
185
+ word_cmd.add_argument("--macros", action="append", default=[], metavar="FILE",
186
+ help="load LaTeX macro definitions from FILE (repeatable)")
187
+
188
+ for p in (convert_cmd, copy_cmd):
189
+ input_group = p.add_mutually_exclusive_group()
190
+ input_group.add_argument("-e", "--expr", metavar="TEXT", help="use TEXT instead of a file or standard input")
191
+ input_group.add_argument("file", nargs="?", metavar="FILE", help="read input from FILE (default: standard input)")
192
+ p.add_argument("-f", "--from", dest="src", choices=READ_FORMATS, default="latex",
193
+ help="input format (default: %(default)s)")
194
+ for p, default in ((convert_cmd, "omml"), (paste_cmd, "latex"), (extract_cmd, "latex")):
195
+ p.add_argument("-t", "--to", dest="dst", choices=WRITE_FORMATS, default=default,
196
+ help="output format (default: %(default)s)")
197
+ p.add_argument("--wrapper", choices=WRAPPER_KEYS, default="auto", metavar="WRAPPER",
198
+ help="delimiters or environment for LaTeX output (default: auto). Choices: %(choices)s")
199
+ for p in (convert_cmd, copy_cmd, paste_cmd):
200
+ p.add_argument("--mode", choices=[k for k, _ in MODES], default="auto",
201
+ help="use inline or display math (auto keeps the detected mode)")
202
+ for p in (convert_cmd, copy_cmd, extract_cmd):
203
+ p.add_argument("--macros", action="append", default=[], metavar="FILE",
204
+ help="load LaTeX macro definitions from FILE (repeatable)")
205
+ for p in (convert_cmd, extract_cmd):
206
+ p.add_argument("--expand-macros", action="store_true",
207
+ help="write LaTeX with the macros of --macros, the input and the document written out "
208
+ "(only for LaTeX input and -t latex)")
209
+ for p in (convert_cmd, paste_cmd):
210
+ p.add_argument("--no-tidy", dest="tidy", action="store_false",
211
+ help="keep texmath's original LaTeX when reading MathML or OMML")
212
+ convert_cmd.add_argument("--annotate", action="store_true", help="keep the TeX source inside MathML output")
213
+ copy_cmd.add_argument("--index", type=int, default=1, metavar="N",
214
+ help="copy equation N from the input (default: 1, the first equation)")
215
+ extract_cmd.add_argument("file", metavar="FILE", help="document to read (.tex, .md, .docx or .pptx)")
216
+ extract_cmd.add_argument("--display", action="store_true", help="keep only display equations")
217
+ extract_cmd.add_argument("--unique", action="store_true", help="show each distinct LaTeX source once with its count")
218
+ extract_cmd.add_argument("--match", default="", metavar="TEXT", help="match TEXT in the LaTeX or location, ignoring case")
219
+ extract_cmd.add_argument("--docx", metavar="OUT", help="also write the equations to the Word file OUT")
220
+
221
+ if argv and argv[0] not in sub.choices and argv[0] not in ("--help", "-h", "--version"):
222
+ name = argv[0]
223
+ if os.path.isfile(name) or name.lower().endswith(tuple(READABLE)):
224
+ end_options = "-- " if name.startswith("-") else ""
225
+ parser.error(f"to read equations from a document, try mathshuttle extract {end_options}{_quote_arg(name)}")
226
+ args = parser.parse_args(argv)
227
+ errors: tuple = (ConversionError, PandocNotFound, InputError)
228
+ if args.cmd in ("copy", "paste"):
229
+ from . import clipboard
230
+ errors += (clipboard.ClipboardError,)
231
+ try:
232
+ if args.version or args.cmd == "version":
233
+ print(f"MathShuttle {__version__}")
234
+ print(engine_report())
235
+ return 0
236
+ if args.cmd == "get-pandoc":
237
+ return _get_pandoc(args.force)
238
+ if args.cmd in ("convert", "copy", "extract", "word"):
239
+ for path in args.macros:
240
+ if not os.path.isfile(path):
241
+ raise InputError("macro file %s does not exist" % path)
242
+ if args.cmd == "word":
243
+ from . import wordexport
244
+ if args.file and os.path.splitext(args.file)[1].lower() in (".tex", ".md"):
245
+ notes = wordexport.document_to_word(args.file, args.output, load_macros(args.macros))
246
+ else:
247
+ source = _read_source(args.file, args.expr, args.cmd)
248
+ notes = wordexport.passage_to_word(source, args.output, load_macros(args.macros))
249
+ sys.stderr.write("".join(n + "\n" for n in notes) + "written to %s\n" % args.output)
250
+ elif args.cmd == "convert":
251
+ source = _read_source(args.file, args.expr, args.cmd)
252
+ result = convert(source, args.src, args.dst, args.mode, args.wrapper, args.annotate,
253
+ macros=load_macros(args.macros), tidy=args.tidy, expand_macros=args.expand_macros)
254
+ sys.stdout.write(result.text + "\n")
255
+ for note in result.notes:
256
+ sys.stderr.write(note + "\n")
257
+ elif args.cmd == "copy":
258
+ if args.index < 1:
259
+ raise InputError("--index counts from 1")
260
+ source = _read_source(args.file, args.expr, args.cmd)
261
+ copy = office_copy(source, args.src, args.mode, load_macros(args.macros), index=args.index - 1)
262
+ clipboard.copy_mathml_for_office(copy.mathml) # the plain text must be the MathML too (see there)
263
+ copy.remember()
264
+ sys.stderr.write("".join(n + "\n" for n in copy.notes) or "Equation copied. Paste it into Word or PowerPoint.\n")
265
+ elif args.cmd == "paste":
266
+ found = clipboard.read_office_equation()
267
+ if not found:
268
+ sys.stderr.write("No equation on the clipboard (copy one in Word / PowerPoint first).\n")
269
+ return 2
270
+ src, text = found
271
+ from . import recall
272
+ recalled = recall.latex_for(text, args.wrapper, args.mode) if src == "mathml" and args.dst == "latex" \
273
+ and args.tidy else None
274
+ if recalled is not None: # copied from here and unedited: the LaTeX as written
275
+ sys.stdout.write(recalled + "\n")
276
+ sys.stderr.write(recall.NOTE + "\n")
277
+ return 0
278
+ result = convert(text, src, args.dst, args.mode, args.wrapper, tidy=args.tidy)
279
+ sys.stdout.write(result.text + "\n")
280
+ for note in result.notes: # e.g. several equations in the copied text
281
+ sys.stderr.write(note + "\n")
282
+ elif args.cmd == "extract":
283
+ expand = args.expand_macros and args.dst == "latex"
284
+ doc = read_document(args.file, expand_macros=expand)
285
+ macros = load_macros(args.macros)
286
+ notes = list(doc.notes) + macro_notes(macros)
287
+ rows = doc.rows(args.display, args.unique, args.match)
288
+ if args.docx: # first, and said at once: an equation that -t cannot write below does not stop it
289
+ from .documents import write_docx
290
+ word_doc = read_document(args.file) if expand and doc.source == "latex" else doc
291
+ word_rows = rows
292
+ if word_doc is not doc: # the same occurrences (filtered on the LaTeX as written), read as usual
293
+ from .documents import EquationRow
294
+ word_rows = [EquationRow(r.number, word_doc.found[r.number - 1], r.where, r.count)
295
+ if len(word_doc.found) == len(doc.found) else r for r in rows]
296
+ written = write_docx(word_doc, args.docx, macros, word_rows)
297
+ sys.stderr.write("".join(n + "\n" for n in written) + "written to %s\n" % args.docx)
298
+ sys.stderr.flush()
299
+ own = doc.macros(macros) # a document's own LaTeX: the macro files and its own definitions
300
+ failures = []
301
+ equations = [row.found.equation for row in rows]
302
+ if expand and doc.source == "latex":
303
+ converted = convert_equations(equations, args.dst, args.wrapper, own, expand_macros=True)
304
+ else:
305
+ converted = convert_equations(equations, args.dst, args.wrapper, own)
306
+ for row, result in zip(rows, converted):
307
+ # Keep the original one-space comments unless we have a new number or count to show.
308
+ enhanced = bool(row.count or row.where != row.found.where)
309
+ where = row.location if enhanced else " ".join(row.where.split())
310
+ location = f"[{row.number}] {where}"
311
+ if isinstance(result, ConversionError):
312
+ reason = _failure_reason(result)
313
+ text = _comment(args.dst, "Could not be converted: " + reason)
314
+ failures.append(f"{location}: {reason}")
315
+ else:
316
+ text, new = result
317
+ notes += [n for n in new if n not in notes]
318
+ sys.stdout.write(_comment(args.dst, location, keep_spacing=enhanced) + "\n" + text + "\n\n")
319
+ count = f"{len(rows)} equation(s) in {os.path.basename(args.file)}"
320
+ for line in merge_notes(notes) + [count] + failures:
321
+ print(line, file=sys.stderr)
322
+ if failures:
323
+ print(f"{len(failures)} of {count} could not be converted", file=sys.stderr)
324
+ return 1
325
+ else:
326
+ parser.print_help()
327
+ return 2
328
+ except errors as e:
329
+ sys.stderr.write("error: %s\n" % e)
330
+ return 1
331
+ return 0
332
+
333
+
334
+ def main(argv: list[str] | None = None) -> int:
335
+ argv = sys.argv[1:] if argv is None else argv
336
+ if argv:
337
+ return _cli(argv)
338
+ from .app import main as gui_main
339
+ return gui_main()
340
+
341
+
342
+ if __name__ == "__main__":
343
+ sys.exit(main())