mathshuttle 0.8.0__py3-none-any.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.
@@ -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())
@@ -0,0 +1,235 @@
1
+ """macOS pasteboard (NSPasteboard) through the Objective-C runtime with ctypes; used through :mod:`.clipboard`.
2
+
3
+ No PyObjC: the runtime's C functions (``objc_getClass``, ``sel_registerName``, ``objc_msgSend``) are
4
+ called directly. ``objc_msgSend`` has no signature of its own; every call must go through a function
5
+ pointer of the method's exact argument and result types. On arm64 this is not optional: a variadic
6
+ call passes its arguments on the stack, where the method does not look for them. So each signature
7
+ used here gets its own prototype (which also keeps threads from racing on a shared ``argtypes``).
8
+
9
+ Every public function runs in an autorelease pool of its own, so objects the frameworks hand back
10
+ autoreleased are freed even when called from a thread without a run loop (the hotkey's worker).
11
+
12
+ macOS may ask the user before an app reads pasteboard data that another app wrote without a paste
13
+ command (paste privacy). Listing the types and reading the change count do not read the data itself;
14
+ reading an equation that Word copied (:func:`read_equation_from_office`) does.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import ctypes
19
+ import re
20
+ import threading
21
+ from typing import Dict, List, Optional, Tuple, Union
22
+
23
+ # shared by the platform backends: the exceptions the app catches, the decoding of registered formats
24
+ from .clipboard import _XML_DECL, ClipboardChanged, ClipboardError, _decode_text
25
+
26
+ # The pasteboard types an equation travels under, in the order they are read. Found with Word and
27
+ # PowerPoint 16.115 on macOS 27.2 (tools/mac_office_probe.py, 2026-11-26):
28
+ # * Word copies an equation as MathML (UTF-8, no XML declaration) under both of these, next to RTF,
29
+ # HTML (with the OMML), PDF and OLE types; PowerPoint under public.mathml only, next to HTML (with the
30
+ # OMML), RTF, PDF and TIFF. For a selection with text, or a math paragraph of several aligned lines,
31
+ # Word writes no MathML (the types may be listed with no data): read_office_html().
32
+ # * Word pastes an equation from either type; PowerPoint only from public.mathml. With MathML and no
33
+ # plain text, PowerPoint puts the equation into a new text box of its own instead of the one with the
34
+ # cursor. With the MathML as plain text as well (as on Windows), both paste in place; Word and
35
+ # PowerPoint also turn plain-text MathML, or $...$ LaTeX, into an equation by themselves.
36
+ # Reading also takes any other type whose name contains "mathml" (any case); writing puts the MathML
37
+ # under these and as plain text.
38
+ MATHML_TYPES = (
39
+ "public.mathml",
40
+ "public.mathml.presentation",
41
+ )
42
+ TEXT_TYPE = "public.utf8-plain-text" # NSPasteboardTypeString
43
+ HTML_TYPE = "public.html"
44
+
45
+ _objc = ctypes.CDLL("/usr/lib/libobjc.A.dylib")
46
+ ctypes.CDLL("/System/Library/Frameworks/AppKit.framework/AppKit") # defines NSPasteboard (Tk loads it too)
47
+
48
+ _objc.objc_getClass.argtypes = [ctypes.c_char_p]
49
+ _objc.objc_getClass.restype = ctypes.c_void_p
50
+ _objc.sel_registerName.argtypes = [ctypes.c_char_p]
51
+ _objc.sel_registerName.restype = ctypes.c_void_p
52
+ _objc.objc_autoreleasePoolPush.argtypes = []
53
+ _objc.objc_autoreleasePoolPush.restype = ctypes.c_void_p
54
+ _objc.objc_autoreleasePoolPop.argtypes = [ctypes.c_void_p]
55
+ _objc.objc_autoreleasePoolPop.restype = None
56
+
57
+ _id = ctypes.c_void_p
58
+ _NSInteger = ctypes.c_ssize_t # long on 64-bit macOS
59
+ _NSUInteger = ctypes.c_size_t # unsigned long
60
+ _BOOL = ctypes.c_bool # bool on arm64, signed char (0 / 1) on x86_64: one byte either way
61
+ _MSG_SEND = ctypes.cast(_objc.objc_msgSend, ctypes.c_void_p).value
62
+
63
+
64
+ def _prototype(restype, *argtypes):
65
+ """objc_msgSend as a function (receiver, selector, *argtypes) -> restype."""
66
+ return ctypes.CFUNCTYPE(restype, _id, ctypes.c_void_p, *argtypes)(_MSG_SEND)
67
+
68
+
69
+ _send = _prototype(_id) # -(id)m
70
+ _send_int = _prototype(_NSInteger) # -(NSInteger)m
71
+ _send_uint = _prototype(_NSUInteger) # -(NSUInteger)m
72
+ _send_ptr = _prototype(ctypes.c_void_p) # -(const void *)m
73
+ _send_id = _prototype(_id, _id) # -(id)m:(id)a
74
+ _send_index = _prototype(_id, _NSUInteger) # -(id)m:(NSUInteger)a
75
+ _send_encode = _prototype(_id, _NSUInteger, _BOOL) # -(id)m:(NSUInteger)a b:(BOOL)b
76
+ _send_bytes = _prototype(_id, ctypes.c_void_p, _NSUInteger) # -(id)m:(const void *)a b:(NSUInteger)b
77
+ _send_bytes_enc = _prototype(_id, ctypes.c_void_p, _NSUInteger, _NSUInteger) # ... c:(NSUInteger)c
78
+ _send_set = _prototype(_BOOL, _id, _id) # -(BOOL)m:(id)a b:(id)b
79
+
80
+ _NSUTF8StringEncoding = 4
81
+
82
+
83
+ def _class(name: str) -> int:
84
+ cls = _objc.objc_getClass(name.encode("ascii"))
85
+ if not cls:
86
+ raise ClipboardError("The Objective-C class %s is not available" % name)
87
+ return cls
88
+
89
+
90
+ _SEL = {name: _objc.sel_registerName(name.encode("ascii")) for name in (
91
+ "generalPasteboard", "changeCount", "clearContents", "types", "dataForType:", "stringForType:",
92
+ "setData:forType:", "setString:forType:", "count", "objectAtIndex:", "alloc", "initWithBytes:length:encoding:",
93
+ "autorelease", "dataWithBytes:length:", "dataUsingEncoding:allowLossyConversion:", "length", "bytes")}
94
+ _NSPasteboard, _NSString, _NSData = _class("NSPasteboard"), _class("NSString"), _class("NSData")
95
+
96
+ # Serialises this process's own pasteboard use (the Tk thread and the hotkey's worker), so that the
97
+ # expect_sequence check and the write that follows it are not split by another write of ours. Other
98
+ # apps are not held off: macOS has no clipboard lock like OpenClipboard; the gap is a few calls long.
99
+ _lock = threading.Lock()
100
+
101
+
102
+ class _Pool:
103
+ """An autorelease pool for the duration of a `with` block."""
104
+
105
+ def __enter__(self):
106
+ self._pool = _objc.objc_autoreleasePoolPush()
107
+ return self
108
+
109
+ def __exit__(self, *exc):
110
+ _objc.objc_autoreleasePoolPop(self._pool)
111
+ return False
112
+
113
+
114
+ # --- conversions between Python and Foundation objects (call inside a pool) --------------------
115
+ def _nsstring(text: str) -> int:
116
+ # a lone surrogate (possible in a Python str, not in UTF-8) becomes "?" rather than failing the copy
117
+ data = text.encode("utf-8", "replace")
118
+ obj = _send_bytes_enc(_send(_NSString, _SEL["alloc"]), _SEL["initWithBytes:length:encoding:"],
119
+ data, len(data), _NSUTF8StringEncoding)
120
+ if not obj:
121
+ raise ClipboardError("Could not make an NSString")
122
+ return _send(obj, _SEL["autorelease"])
123
+
124
+
125
+ def _nsdata(data: bytes) -> int:
126
+ obj = _send_bytes(_NSData, _SEL["dataWithBytes:length:"], data, len(data))
127
+ if not obj:
128
+ raise ClipboardError("Could not make an NSData")
129
+ return obj
130
+
131
+
132
+ def _bytes(nsdata: int) -> bytes:
133
+ n = _send_uint(nsdata, _SEL["length"])
134
+ return ctypes.string_at(_send_ptr(nsdata, _SEL["bytes"]), n) if n else b""
135
+
136
+
137
+ def _str(nsstring: int) -> str:
138
+ # dataUsingEncoding: rather than UTF8String: the text may contain NUL characters
139
+ data = _send_encode(nsstring, _SEL["dataUsingEncoding:allowLossyConversion:"], _NSUTF8StringEncoding, True)
140
+ return _bytes(data).decode("utf-8", "replace") if data else ""
141
+
142
+
143
+ def _pasteboard() -> int:
144
+ pb = _send(_NSPasteboard, _SEL["generalPasteboard"])
145
+ if not pb:
146
+ raise ClipboardError("Could not open the pasteboard")
147
+ return pb
148
+
149
+
150
+ # --- the API (see clipboard.py) ---------------------------------------------------------------
151
+ def sequence_number() -> int:
152
+ """The general pasteboard's changeCount: it changes whenever anything is copied."""
153
+ with _Pool():
154
+ return _send_int(_pasteboard(), _SEL["changeCount"])
155
+
156
+
157
+ def set_data(entries: Dict[str, Union[bytes, str]], expect_sequence: Optional[int] = None) -> None:
158
+ """Replace the pasteboard contents with {type: data} (bytes as they are, str as a string), in the
159
+ given order (the first is the richest representation, by the pasteboard's convention)."""
160
+ with _lock, _Pool():
161
+ pb = _pasteboard()
162
+ if expect_sequence is not None and _send_int(pb, _SEL["changeCount"]) != expect_sequence:
163
+ raise ClipboardChanged("The clipboard changed meanwhile (something else was copied): left as it is")
164
+ _send_int(pb, _SEL["clearContents"])
165
+ for fmt, value in entries.items():
166
+ if isinstance(value, str):
167
+ ok = _send_set(pb, _SEL["setString:forType:"], _nsstring(value), _nsstring(fmt))
168
+ else:
169
+ ok = _send_set(pb, _SEL["setData:forType:"], _nsdata(bytes(value)), _nsstring(fmt))
170
+ if not ok:
171
+ raise ClipboardError("Could not put %s on the clipboard" % fmt)
172
+
173
+
174
+ def get_data(fmt: str) -> Optional[bytes]:
175
+ with _lock, _Pool():
176
+ data = _send_id(_pasteboard(), _SEL["dataForType:"], _nsstring(fmt))
177
+ return _bytes(data) if data else None
178
+
179
+
180
+ def available_formats() -> List[Tuple[str, str]]:
181
+ """(type, type) for each type on the pasteboard: the key :func:`get_data` takes, and its name."""
182
+ with _lock, _Pool():
183
+ types = _send(_pasteboard(), _SEL["types"])
184
+ n = _send_uint(types, _SEL["count"]) if types else 0
185
+ names = [_str(_send_index(types, _SEL["objectAtIndex:"], i)) for i in range(n)]
186
+ return [(name, name) for name in names]
187
+
188
+
189
+ def get_text() -> Optional[str]:
190
+ with _lock, _Pool():
191
+ text = _send_id(_pasteboard(), _SEL["stringForType:"], _nsstring(TEXT_TYPE))
192
+ return _str(text) if text else None
193
+
194
+
195
+ def set_text(text: str, expect_sequence: Optional[int] = None) -> None:
196
+ set_data({TEXT_TYPE: text}, expect_sequence)
197
+
198
+
199
+ # --- Office equation exchange -----------------------------------------------------------------
200
+ def _mathml_payload(mathml: str) -> bytes:
201
+ """What goes under each MathML type: UTF-8 with an XML declaration, as Office writes on Windows,
202
+ without the NUL that ends a Windows clipboard string (pasteboard data carries its length)."""
203
+ body = mathml.strip()
204
+ if not body.startswith("<?xml"):
205
+ body = _XML_DECL + body
206
+ return body.encode("utf-8")
207
+
208
+
209
+ def copy_mathml_for_office(mathml: str, plain_text: Optional[str] = None, expect_sequence: Optional[int] = None) -> None:
210
+ """Put MathML under every type of MATHML_TYPES and, as on Windows (where Word pastes from the plain
211
+ text), as the plain text too unless `plain_text` says otherwise."""
212
+ payload = _mathml_payload(mathml)
213
+ entries: Dict[str, Union[bytes, str]] = {t: payload for t in MATHML_TYPES}
214
+ entries[TEXT_TYPE] = plain_text if plain_text is not None else mathml
215
+ set_data(entries, expect_sequence)
216
+
217
+
218
+ def _mathml_types_on(types: List[str]) -> List[str]:
219
+ """The types to look for an equation under: MATHML_TYPES first, then any other "mathml" type."""
220
+ return [t for t in MATHML_TYPES if t in types] + \
221
+ [t for t in types if "mathml" in t.lower() and t not in MATHML_TYPES]
222
+
223
+
224
+ def read_equation_from_office() -> Optional[str]:
225
+ """MathML of an equation on the pasteboard (under one of the MathML types), or None."""
226
+ for fmt in _mathml_types_on([name for _, name in available_formats()]):
227
+ mathml = _decode_text(get_data(fmt))
228
+ if mathml and re.search(r"<(\w+:)?math\b", mathml): # other programs may write <mml:math>
229
+ return mathml
230
+ return None
231
+
232
+
233
+ def read_office_html() -> Optional[str]:
234
+ """The HTML on the pasteboard (Word writes its equations into it as OMML), or None."""
235
+ return _decode_text(get_data(HTML_TYPE))