marimo-gradescope 0.1.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.
- marimo_gradescope/__init__.py +9 -0
- marimo_gradescope/_assertrewrite.py +44 -0
- marimo_gradescope/_env.py +26 -0
- marimo_gradescope/_run.py +111 -0
- marimo_gradescope/_typst/preview/cmarker/0.1.10/LICENSE +7 -0
- marimo_gradescope/_typst/preview/cmarker/0.1.10/lib.typ +462 -0
- marimo_gradescope/_typst/preview/cmarker/0.1.10/plugin.wasm +0 -0
- marimo_gradescope/_typst/preview/cmarker/0.1.10/typst.toml +11 -0
- marimo_gradescope/_typst/preview/mitex/0.2.7/LICENSE +176 -0
- marimo_gradescope/_typst/preview/mitex/0.2.7/lib.typ +1 -0
- marimo_gradescope/_typst/preview/mitex/0.2.7/mitex.typ +45 -0
- marimo_gradescope/_typst/preview/mitex/0.2.7/mitex.wasm +0 -0
- marimo_gradescope/_typst/preview/mitex/0.2.7/specs/latex/standard.typ +1187 -0
- marimo_gradescope/_typst/preview/mitex/0.2.7/specs/mod.typ +12 -0
- marimo_gradescope/_typst/preview/mitex/0.2.7/specs/prelude.typ +230 -0
- marimo_gradescope/_typst/preview/mitex/0.2.7/typst.toml +12 -0
- marimo_gradescope/build.py +381 -0
- marimo_gradescope/check.py +252 -0
- marimo_gradescope/cli.py +115 -0
- marimo_gradescope/config.py +492 -0
- marimo_gradescope/export.py +450 -0
- marimo_gradescope/grader/__init__.py +1 -0
- marimo_gradescope/grader/_process.py +381 -0
- marimo_gradescope/grader/_user.py +7 -0
- marimo_gradescope/grader/bundle.py +320 -0
- marimo_gradescope/grader/child.py +306 -0
- marimo_gradescope/grader/datafiles.py +54 -0
- marimo_gradescope/grader/main.py +132 -0
- marimo_gradescope/grader/protocol.py +175 -0
- marimo_gradescope/grader/results.py +269 -0
- marimo_gradescope/grader/sandbox.py +419 -0
- marimo_gradescope/grader/templates/__init__.py +38 -0
- marimo_gradescope/grader/templates/run_autograder +3 -0
- marimo_gradescope/grader/templates/setup.sh +28 -0
- marimo_gradescope/loader.py +200 -0
- marimo_gradescope/pdf.py +511 -0
- marimo_gradescope/requirements.py +231 -0
- marimo_gradescope/runner.py +235 -0
- marimo_gradescope/selfcheck.py +126 -0
- marimo_gradescope/source.py +853 -0
- marimo_gradescope/transform.py +495 -0
- marimo_gradescope-0.1.0.dist-info/METADATA +17 -0
- marimo_gradescope-0.1.0.dist-info/RECORD +45 -0
- marimo_gradescope-0.1.0.dist-info/WHEEL +4 -0
- marimo_gradescope-0.1.0.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Gradescope autograding for marimo notebooks."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import version
|
|
4
|
+
|
|
5
|
+
from marimo_gradescope.check import check
|
|
6
|
+
from marimo_gradescope.export import export, export_button
|
|
7
|
+
|
|
8
|
+
__all__ = ["check", "export", "export_button"]
|
|
9
|
+
__version__ = version("marimo-gradescope")
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Compile test source with pytest's assertion rewriting.
|
|
2
|
+
|
|
3
|
+
This is the only module that imports the private `_pytest` package, so a change in pytest's
|
|
4
|
+
internals breaks one place, and `tests/test_assertrewrite_guard.py` catches it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import ast
|
|
8
|
+
import hashlib
|
|
9
|
+
import linecache
|
|
10
|
+
from types import CodeType
|
|
11
|
+
|
|
12
|
+
from _pytest.assertion.rewrite import rewrite_asserts
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def compile_tests(source: str, filename: str) -> CodeType:
|
|
16
|
+
"""Compile test source so failing asserts explain their values.
|
|
17
|
+
|
|
18
|
+
The source is registered in `linecache` under `<mgs-tests-H:filename>`, where `H` is a hash
|
|
19
|
+
of the source, and that name is the code's file name, so tracebacks and failure messages
|
|
20
|
+
show its lines. Different sources get different names, so no other source, and no real
|
|
21
|
+
file, can replace these lines. The same source gets the same name, so compiling it again,
|
|
22
|
+
as a re-run notebook check does, reuses the entry instead of adding one.
|
|
23
|
+
Line numbers count from the first line of `source`.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
source: Module-like source, e.g. one or more `def test_*` functions.
|
|
27
|
+
filename: Label kept inside the generated file name.
|
|
28
|
+
|
|
29
|
+
Returns:
|
|
30
|
+
A module code object to run with `exec`.
|
|
31
|
+
|
|
32
|
+
Raises:
|
|
33
|
+
SyntaxError: The source does not parse.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
digest = hashlib.sha1(source.encode(errors="surrogatepass")).hexdigest()[:12]
|
|
37
|
+
name = f"<mgs-tests-{digest}:{filename}>"
|
|
38
|
+
tree = ast.parse(source, name)
|
|
39
|
+
rewrite_asserts(tree, source.encode())
|
|
40
|
+
|
|
41
|
+
# `mtime=None` keeps the entry through `linecache.checkcache`.
|
|
42
|
+
linecache.cache[name] = (len(source), None, source.splitlines(keepends=True), name)
|
|
43
|
+
|
|
44
|
+
return compile(tree, name, "exec", dont_inherit=True)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Environment of the processes this package starts, and the flag they read."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
GRADING = "MGS_GRADING"
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def clean_env() -> dict[str, str]:
|
|
9
|
+
"""The current environment without `PYTEST_CURRENT_TEST`.
|
|
10
|
+
|
|
11
|
+
marimo acts as if under test when that variable is set.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
return {key: value for key, value in os.environ.items() if key != "PYTEST_CURRENT_TEST"}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def grading_env() -> dict[str, str]:
|
|
18
|
+
"""`clean_env()` plus the flag that turns `check` and `export` into no-ops."""
|
|
19
|
+
|
|
20
|
+
return clean_env() | {GRADING: "1"}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def grading() -> bool:
|
|
24
|
+
"""Whether this process runs tests for a grader or a self-check, not for a student."""
|
|
25
|
+
|
|
26
|
+
return os.environ.get(GRADING) == "1"
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Run a helper command from the student's kernel without risking a hang.
|
|
2
|
+
|
|
3
|
+
Works on Linux, macOS and Windows: no timers, no resource limits.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
import signal
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import tempfile
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import IO
|
|
13
|
+
|
|
14
|
+
from marimo_gradescope._env import grading_env
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def run_capped(
|
|
18
|
+
command: list[str], *, cwd: Path, timeout: float
|
|
19
|
+
) -> subprocess.CompletedProcess[str] | None:
|
|
20
|
+
"""Run `command` and capture its output, killing it after `timeout` seconds.
|
|
21
|
+
|
|
22
|
+
Output goes to temporary files, not pipes, so a grandchild that keeps a pipe open cannot
|
|
23
|
+
block the wait. On a timeout or any exception, `KeyboardInterrupt` included, the process
|
|
24
|
+
is killed before the exception propagates: with its whole process group on Linux and
|
|
25
|
+
macOS, with its process tree (`taskkill /T`) on Windows. The command runs with
|
|
26
|
+
`MGS_GRADING=1`, so `check` and `export` cells do nothing if it runs the notebook.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
command: The command and its arguments.
|
|
30
|
+
cwd: Working directory.
|
|
31
|
+
timeout: Seconds to wait before killing the process.
|
|
32
|
+
|
|
33
|
+
Returns:
|
|
34
|
+
The finished process with decoded output, or `None` when it timed out.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
# Bytecode caches would land next to the student's notebook.
|
|
38
|
+
env = grading_env() | {"PYTHONDONTWRITEBYTECODE": "1", "PYTHONIOENCODING": "utf-8"}
|
|
39
|
+
|
|
40
|
+
with tempfile.TemporaryFile() as out, tempfile.TemporaryFile() as err:
|
|
41
|
+
process = _start(command, cwd, env, out, err)
|
|
42
|
+
|
|
43
|
+
try:
|
|
44
|
+
returncode = process.wait(timeout)
|
|
45
|
+
except subprocess.TimeoutExpired:
|
|
46
|
+
return None
|
|
47
|
+
finally:
|
|
48
|
+
_kill_tree(process)
|
|
49
|
+
|
|
50
|
+
out.seek(0)
|
|
51
|
+
err.seek(0)
|
|
52
|
+
|
|
53
|
+
return subprocess.CompletedProcess(
|
|
54
|
+
command,
|
|
55
|
+
returncode,
|
|
56
|
+
out.read().decode(errors="replace"),
|
|
57
|
+
err.read().decode(errors="replace"),
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _start(
|
|
62
|
+
command: list[str], cwd: Path, env: dict[str, str], out: IO[bytes], err: IO[bytes]
|
|
63
|
+
) -> subprocess.Popen[bytes]:
|
|
64
|
+
"""Start `command` in a process group of its own."""
|
|
65
|
+
|
|
66
|
+
if sys.platform == "win32":
|
|
67
|
+
return subprocess.Popen(
|
|
68
|
+
command,
|
|
69
|
+
cwd=cwd,
|
|
70
|
+
env=env,
|
|
71
|
+
stdin=subprocess.DEVNULL,
|
|
72
|
+
stdout=out,
|
|
73
|
+
stderr=err,
|
|
74
|
+
creationflags=subprocess.CREATE_NEW_PROCESS_GROUP,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
return subprocess.Popen(
|
|
78
|
+
command,
|
|
79
|
+
cwd=cwd,
|
|
80
|
+
env=env,
|
|
81
|
+
stdin=subprocess.DEVNULL,
|
|
82
|
+
stdout=out,
|
|
83
|
+
stderr=err,
|
|
84
|
+
start_new_session=True,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _kill_tree(process: subprocess.Popen[bytes]) -> None:
|
|
89
|
+
"""Kill the process and what it started, then reap it.
|
|
90
|
+
|
|
91
|
+
On Linux and macOS the whole group goes, even after the process itself exited, so a
|
|
92
|
+
grandchild it left behind does not outlive it.
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
if sys.platform == "win32":
|
|
96
|
+
if process.poll() is None:
|
|
97
|
+
subprocess.run(
|
|
98
|
+
["taskkill", "/F", "/T", "/PID", str(process.pid)],
|
|
99
|
+
capture_output=True,
|
|
100
|
+
check=False,
|
|
101
|
+
)
|
|
102
|
+
else:
|
|
103
|
+
try:
|
|
104
|
+
os.killpg(process.pid, signal.SIGKILL)
|
|
105
|
+
except (ProcessLookupError, PermissionError):
|
|
106
|
+
pass
|
|
107
|
+
|
|
108
|
+
if process.poll() is None:
|
|
109
|
+
process.kill()
|
|
110
|
+
|
|
111
|
+
process.wait()
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
Copyright 2023 Sabrina Jewson
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
4
|
+
|
|
5
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
#let _p = plugin("./plugin.wasm")
|
|
2
|
+
#let render-with-metadata(
|
|
3
|
+
markdown,
|
|
4
|
+
smart-punctuation: true,
|
|
5
|
+
math: none,
|
|
6
|
+
task-list-marker: none,
|
|
7
|
+
h1-level: 1,
|
|
8
|
+
set-document-title: true,
|
|
9
|
+
raw-typst: true,
|
|
10
|
+
html: (:),
|
|
11
|
+
label-prefix: "",
|
|
12
|
+
prefix-label-uses: true,
|
|
13
|
+
heading-labels: "github",
|
|
14
|
+
scope: (:),
|
|
15
|
+
show-source: false,
|
|
16
|
+
blockquote: none,
|
|
17
|
+
metadata-block: none,
|
|
18
|
+
) = {
|
|
19
|
+
// A simple system for tagging content with invisible metadata.
|
|
20
|
+
// Used to implement various HTML tags that need some amount of structure.
|
|
21
|
+
let tag-content(content, tag, data: none) = [#metadata((tag, data))#content]
|
|
22
|
+
let is-tagged(content, tag) = (
|
|
23
|
+
content.func() == [].func()
|
|
24
|
+
and content.children.len() == 2
|
|
25
|
+
and content.children.at(0).func() == metadata
|
|
26
|
+
and content.children.at(0).value.len() == 2
|
|
27
|
+
and content.children.at(0).value.at(0) == tag
|
|
28
|
+
)
|
|
29
|
+
let untag-content(content) = (..content.children.at(0).value, content.children.at(1))
|
|
30
|
+
let take-tagged-children(content, tag) = {
|
|
31
|
+
if type(tag) != array {
|
|
32
|
+
tag = (tag,)
|
|
33
|
+
}
|
|
34
|
+
let tagged = ()
|
|
35
|
+
let rest = ()
|
|
36
|
+
if tag.any(t => is-tagged(content, t)) {
|
|
37
|
+
tagged.push(untag-content(content))
|
|
38
|
+
} else if content.func() == [].func() {
|
|
39
|
+
for child in content.children {
|
|
40
|
+
if tag.any(t => is-tagged(child, t)) {
|
|
41
|
+
tagged.push(untag-content(child))
|
|
42
|
+
} else {
|
|
43
|
+
rest.push(child)
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
} else {
|
|
47
|
+
rest.push(content)
|
|
48
|
+
}
|
|
49
|
+
(tagged: tagged, rest: for r in rest { r })
|
|
50
|
+
}
|
|
51
|
+
let untag-children(content, tag) = take-tagged-children(content, tag).tagged
|
|
52
|
+
|
|
53
|
+
if type(markdown) == content and markdown.has("text") {
|
|
54
|
+
markdown = markdown.text
|
|
55
|
+
}
|
|
56
|
+
assert(type(markdown) == str, message: "Markdown must be a string")
|
|
57
|
+
|
|
58
|
+
// Backward compatibility
|
|
59
|
+
if blockquote != none {
|
|
60
|
+
assert(type(blockquote) == function, message: "blockquote must be a function")
|
|
61
|
+
scope += (
|
|
62
|
+
quote: (block: false, ..rest) => if block { blockquote(..rest) } else { quote(..rest) },
|
|
63
|
+
)
|
|
64
|
+
}
|
|
65
|
+
// Backward compatibility
|
|
66
|
+
if "rule" in scope {
|
|
67
|
+
scope += (divider: scope.rule)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
let labelify(content, attrs) = {
|
|
71
|
+
if "id" in attrs {
|
|
72
|
+
[#content #label(label-prefix + attrs.id)]
|
|
73
|
+
} else {
|
|
74
|
+
content
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
assert(type(label-prefix) == str, message: "label-prefix must be a string")
|
|
79
|
+
let label-use-prefix = if prefix-label-uses { label-prefix } else { "" }
|
|
80
|
+
|
|
81
|
+
let heading-fn(level) = (attrs, body) => {
|
|
82
|
+
let level = h1-level + level
|
|
83
|
+
if level < 0 {
|
|
84
|
+
body
|
|
85
|
+
} else if level == 0 {
|
|
86
|
+
if set-document-title {
|
|
87
|
+
set document(title: body)
|
|
88
|
+
title()
|
|
89
|
+
} else {
|
|
90
|
+
title(body)
|
|
91
|
+
}
|
|
92
|
+
} else {
|
|
93
|
+
labelify(scope.at("heading", default: heading)(level: level, body), attrs)
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
html = (
|
|
98
|
+
sub: (attrs, body) => scope.at("sub", default: sub)(body),
|
|
99
|
+
sup: (attrs, body) => scope.at("sup", default: super)(body),
|
|
100
|
+
mark: (attrs, body) => scope.at("highlight", default: highlight)(body),
|
|
101
|
+
h1: heading-fn(0),
|
|
102
|
+
h2: heading-fn(1),
|
|
103
|
+
h3: heading-fn(2),
|
|
104
|
+
h4: heading-fn(3),
|
|
105
|
+
h5: heading-fn(4),
|
|
106
|
+
h6: heading-fn(5),
|
|
107
|
+
|
|
108
|
+
li: (attrs, body) => tag-content(body, "<li>"),
|
|
109
|
+
ul: (attrs, body) => {
|
|
110
|
+
scope.at("list", default: list)(..untag-children(body, "<li>").map(((_, _, c)) => c))
|
|
111
|
+
},
|
|
112
|
+
ol: (attrs, body) => {
|
|
113
|
+
scope.at("enum", default: enum)(..untag-children(body, "<li>").map(((_, _, c)) => c))
|
|
114
|
+
},
|
|
115
|
+
|
|
116
|
+
dt: (attrs, body) => tag-content(body, "<dt>"),
|
|
117
|
+
dd: (attrs, body) => tag-content(body, "<dd>"),
|
|
118
|
+
dl: (attrs, body) => scope.at("terms", default: terms)(..(
|
|
119
|
+
untag-children(body, ("<dt>", "<dd>"))
|
|
120
|
+
.map(((_, _, c)) => c)
|
|
121
|
+
.chunks(2, exact: true)
|
|
122
|
+
)),
|
|
123
|
+
|
|
124
|
+
tr: (attrs, body) => tag-content(body, "<tr>"),
|
|
125
|
+
thead: (attrs, body) => tag-content(body, "<thead>"),
|
|
126
|
+
tfoot: (attrs, body) => tag-content(body, "<tfoot>"),
|
|
127
|
+
th: (attrs, body) => tag-content(body, "<td>", data: attrs),
|
|
128
|
+
td: (attrs, body) => tag-content(body, "<td>", data: attrs),
|
|
129
|
+
table: (attrs, body) => {
|
|
130
|
+
let rows = (header: (), body: (), footer: ())
|
|
131
|
+
for (tag, _, child) in untag-children(body, ("<tr>", "<thead>", "<tfoot>")) {
|
|
132
|
+
if tag == "<thead>" {
|
|
133
|
+
for (_, _, row) in untag-children(child, "<tr>") {
|
|
134
|
+
rows.header.push(untag-children(row, "<td>"))
|
|
135
|
+
}
|
|
136
|
+
} else if tag == "<tfoot>" {
|
|
137
|
+
for (_, _, row) in untag-children(child, "<tr>") {
|
|
138
|
+
rows.footer.push(untag-children(row, "<td>"))
|
|
139
|
+
}
|
|
140
|
+
} else if tag == "<tr>" {
|
|
141
|
+
rows.body.push(untag-children(child, "<td>"))
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if rows.header.len() == 0 and rows.body.len() == 0 and rows.footer.len() == 0 {
|
|
145
|
+
return table()
|
|
146
|
+
}
|
|
147
|
+
// FIXME: This is likely buggy for exotic uses of rowspan and colspan.
|
|
148
|
+
let columns = calc.max(
|
|
149
|
+
..rows.header.map(r => r.len()),
|
|
150
|
+
..rows.body.map(r => r.len()),
|
|
151
|
+
..rows.footer.map(r => r.len()),
|
|
152
|
+
)
|
|
153
|
+
let start-i = 0
|
|
154
|
+
for (k, section) in rows {
|
|
155
|
+
rows.insert(k, section.enumerate().map(((i, row)) => {
|
|
156
|
+
row = row.map(((_, attrs, td)) => {
|
|
157
|
+
let rowspan = int(attrs.at("rowspan", default: "1"))
|
|
158
|
+
let colspan = int(attrs.at("colspan", default: "1"))
|
|
159
|
+
table.cell(rowspan: rowspan, colspan: colspan, y: start-i + i, td)
|
|
160
|
+
})
|
|
161
|
+
row
|
|
162
|
+
}))
|
|
163
|
+
start-i += section.len()
|
|
164
|
+
}
|
|
165
|
+
let args = ()
|
|
166
|
+
if rows.header.len() != 0 {
|
|
167
|
+
args.push(table.header(..rows.header.flatten()))
|
|
168
|
+
}
|
|
169
|
+
args += rows.body.flatten()
|
|
170
|
+
if rows.footer.len() != 0 {
|
|
171
|
+
args.push(table.footer(..rows.footer.flatten()))
|
|
172
|
+
}
|
|
173
|
+
scope.at("table", default: table)(columns: columns, ..args)
|
|
174
|
+
},
|
|
175
|
+
|
|
176
|
+
figcaption: (attrs, body) => tag-content(body, "<figcaption>"),
|
|
177
|
+
figure: (attrs, body) => {
|
|
178
|
+
let (tagged: captions, rest) = take-tagged-children(body, "<figcaption>")
|
|
179
|
+
let caption = if captions.len() >= 1 { captions.at(0).at(2) } else { none }
|
|
180
|
+
labelify(figure(caption: caption, rest), attrs)
|
|
181
|
+
},
|
|
182
|
+
|
|
183
|
+
hr: ("void", (attrs) => (scope.at("divider", default: divider))()),
|
|
184
|
+
a: (attrs, body) => scope.at("link", default: link)(
|
|
185
|
+
if attrs.href.starts-with("#") {
|
|
186
|
+
label(label-use-prefix + attrs.href.slice(1))
|
|
187
|
+
} else {
|
|
188
|
+
attrs.href
|
|
189
|
+
},
|
|
190
|
+
body,
|
|
191
|
+
),
|
|
192
|
+
em: (attrs, body) => scope.at("emph", default: emph)(body),
|
|
193
|
+
strong: (attrs, body) => scope.at("strong", default: strong)(body),
|
|
194
|
+
s: (attrs, body) => scope.at("strike", default: strike)(body),
|
|
195
|
+
// Although we stringify the body, <code> cannot be a raw text element because raw text elements
|
|
196
|
+
// - have their content ignored by heading ID generation and
|
|
197
|
+
// - include nested HTML in the string,
|
|
198
|
+
// both of which are undesirable for <code>.
|
|
199
|
+
code: (attrs, body) => {
|
|
200
|
+
// https://github.com/typst/typst/issues/2196#issuecomment-1728135476
|
|
201
|
+
let to-string(it) = {
|
|
202
|
+
if type(it) == str {
|
|
203
|
+
it
|
|
204
|
+
} else if type(it) != content {
|
|
205
|
+
str(it)
|
|
206
|
+
} else if it.has("text") {
|
|
207
|
+
it.text
|
|
208
|
+
} else if it.has("children") {
|
|
209
|
+
it.children.map(to-string).join()
|
|
210
|
+
} else if it.has("body") {
|
|
211
|
+
to-string(it.body)
|
|
212
|
+
} else if it == [ ] {
|
|
213
|
+
" "
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
scope.at("raw", default: raw)(to-string(body))
|
|
217
|
+
},
|
|
218
|
+
br: ("void", (attrs) => scope.at("linebreak", default: linebreak)()),
|
|
219
|
+
img: ("void", (attrs) => {
|
|
220
|
+
let args = (:)
|
|
221
|
+
|
|
222
|
+
let parse-dim(dim) = {
|
|
223
|
+
if dim.ends-with("%") {
|
|
224
|
+
int(dim.slice(0, -1)) * 1%
|
|
225
|
+
} else {
|
|
226
|
+
// When exporting as PDF, the inherent size of the image is converted into `pt` for its
|
|
227
|
+
// default size. HTML uses `px` instead, meaning this gives wrong results:
|
|
228
|
+
// https://github.com/typst/typst/issues/8136
|
|
229
|
+
int(dim) * 1pt
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
let width = attrs.at("width", default: none)
|
|
234
|
+
if width != none {
|
|
235
|
+
args += (width: parse-dim(width))
|
|
236
|
+
}
|
|
237
|
+
let height = attrs.at("height", default: none)
|
|
238
|
+
if height != none {
|
|
239
|
+
args += (height: parse-dim(height))
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
scope.at("image", default: image)(attrs.src, alt: attrs.at("alt", default: none), ..args)
|
|
243
|
+
}),
|
|
244
|
+
blockquote: (attrs, body) => scope.at("quote", default: quote)(block: true, body),
|
|
245
|
+
|
|
246
|
+
svg: ("raw-text", (attrs, body) => {
|
|
247
|
+
let escape(s) = {
|
|
248
|
+
for c in s {
|
|
249
|
+
if c == "\"" {
|
|
250
|
+
"""
|
|
251
|
+
} else if c == "&" {
|
|
252
|
+
"&"
|
|
253
|
+
} else {
|
|
254
|
+
c
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
let attrs = attrs.pairs().map(((k, v)) => k + "=\"" + escape(v) + "\"").join(" ")
|
|
260
|
+
let svg = "<svg " + attrs + ">" + body + "</svg>"
|
|
261
|
+
scope.at("image", default: image)(bytes(svg), format: "svg")
|
|
262
|
+
}),
|
|
263
|
+
|
|
264
|
+
..html,
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
let flags = 0
|
|
268
|
+
if smart-punctuation {
|
|
269
|
+
flags += 0b00000001
|
|
270
|
+
}
|
|
271
|
+
if raw-typst {
|
|
272
|
+
flags += 0b00000010
|
|
273
|
+
}
|
|
274
|
+
if math != none {
|
|
275
|
+
assert(type(math) == function, message: "math must be a function")
|
|
276
|
+
flags += 0b00000100
|
|
277
|
+
scope += (math: math)
|
|
278
|
+
}
|
|
279
|
+
if set-document-title {
|
|
280
|
+
flags += 0b00001000
|
|
281
|
+
}
|
|
282
|
+
if task-list-marker != none {
|
|
283
|
+
assert(type(task-list-marker) == function, message: "task-list-marker must be a function")
|
|
284
|
+
flags += 0b00010000
|
|
285
|
+
|
|
286
|
+
// We use manual counters even for `enum`s, even though they could use numberings. This is
|
|
287
|
+
// because in certain edge cases, numberings are not unique: a reversed list may have several
|
|
288
|
+
// items numbered at zero.
|
|
289
|
+
let list-counter = counter("cmarker-list")
|
|
290
|
+
let enum-counter = counter("cmarker-enum")
|
|
291
|
+
|
|
292
|
+
scope += (
|
|
293
|
+
list-helper: data => depth => {
|
|
294
|
+
list-counter.step(level: depth + 1)
|
|
295
|
+
context {
|
|
296
|
+
let i = list-counter.get().last()
|
|
297
|
+
let v = data.at(i - 1)
|
|
298
|
+
if v > 0 {
|
|
299
|
+
task-list-marker(v == 2)
|
|
300
|
+
} else if type(list.marker) == content {
|
|
301
|
+
list.marker
|
|
302
|
+
} else if type(list.marker) == array {
|
|
303
|
+
list.marker.at(calc.rem(depth, list.marker.len()))
|
|
304
|
+
} else {
|
|
305
|
+
(list.marker)(depth)
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
list-counter.update((..c, i) => if i < data.len() { (..c.pos(), i) } else { c.pos() })
|
|
309
|
+
},
|
|
310
|
+
enum-helper: data => (..numbers) => {
|
|
311
|
+
enum-counter.step(level: numbers.len())
|
|
312
|
+
context {
|
|
313
|
+
let i = enum-counter.get().last()
|
|
314
|
+
let v = data.at(i - 1)
|
|
315
|
+
if v > 0 {
|
|
316
|
+
task-list-marker(v == 2)
|
|
317
|
+
} else if enum.full {
|
|
318
|
+
numbering(enum.numbering, ..numbers)
|
|
319
|
+
} else {
|
|
320
|
+
numbering(enum.numbering, numbers.pos().last())
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
enum-counter.update((..c, i) => if i < data.len() { (..c.pos(), i) } else { c.pos() })
|
|
324
|
+
},
|
|
325
|
+
)
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
let heading-labels = {
|
|
329
|
+
if heading-labels == none { 0 }
|
|
330
|
+
else if heading-labels == "github" { 1 }
|
|
331
|
+
else if heading-labels == "jupyter" { 2 }
|
|
332
|
+
else { assert(false, message: "invalid heading-labels") }
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
assert(type(h1-level) == int, message: "h1-level must be an integer")
|
|
336
|
+
assert(-128 <= h1-level and h1-level <= 127, message: "h1-level must be in the range [-128, 127]")
|
|
337
|
+
// Reinterpret 8-bit 2’s complement (i8) as a u8
|
|
338
|
+
h1-level = if h1-level < 0 { 256 + h1-level } else { h1-level }
|
|
339
|
+
|
|
340
|
+
let options-bytes = (flags, h1-level, heading-labels)
|
|
341
|
+
|
|
342
|
+
options-bytes += array(bytes(label-prefix)) + (0xFF,)
|
|
343
|
+
options-bytes += array(bytes(label-use-prefix)) + (0xFF,)
|
|
344
|
+
|
|
345
|
+
scope.html = (:)
|
|
346
|
+
for (tag-name, value) in html {
|
|
347
|
+
let (kind, callback) = if type(value) == function { ("normal", value) } else { value }
|
|
348
|
+
assert(type(callback) == function, message: "HTML callback must be a function")
|
|
349
|
+
scope.html.insert(tag-name, callback)
|
|
350
|
+
options-bytes += array(bytes(tag-name))
|
|
351
|
+
options-bytes.push(if kind == "void" {
|
|
352
|
+
0xFC
|
|
353
|
+
} else if kind == "raw-text" {
|
|
354
|
+
0xFD
|
|
355
|
+
} else if kind == "escapable-raw-text" {
|
|
356
|
+
0xFE
|
|
357
|
+
} else if kind == "normal" {
|
|
358
|
+
0xFF
|
|
359
|
+
} else {
|
|
360
|
+
assert(false, message: "invalid HTML tag kind for <" + tag-name + "> (expected void, raw-text, escapable-raw-text or normal)")
|
|
361
|
+
})
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// Transforms the following:
|
|
365
|
+
// ```md
|
|
366
|
+
// ---
|
|
367
|
+
// frontmatter
|
|
368
|
+
// ---
|
|
369
|
+
// content
|
|
370
|
+
// ```
|
|
371
|
+
// into the tuple (frontmatter, content) of type (str, str).
|
|
372
|
+
//
|
|
373
|
+
// The frontmatter is left as a string to let the user
|
|
374
|
+
// decide the metadata format i.e. yaml, toml, etc.
|
|
375
|
+
//
|
|
376
|
+
// A YAML metadata block is a valid YAML object,
|
|
377
|
+
// [1] delimited by a line of three hyphens (---) at the top
|
|
378
|
+
// [2] and a line of three hyphens (---) or three dots (...) at the bottom.
|
|
379
|
+
// [3] The initial line --- must not be followed by a blank line.
|
|
380
|
+
//
|
|
381
|
+
// Reference: https://pandoc.org/demo/example33/8.10-metadata-blocks.html
|
|
382
|
+
let extract-frontmatter(s) = {
|
|
383
|
+
let original = s
|
|
384
|
+
|
|
385
|
+
let start-match = s.match(regex("^---[ \t\r]*\n"))
|
|
386
|
+
if start-match == none {
|
|
387
|
+
return ("", original)
|
|
388
|
+
}
|
|
389
|
+
s = s.slice(start-match.end)
|
|
390
|
+
|
|
391
|
+
if s.starts-with(regex("[ \t\r]*\n")) {
|
|
392
|
+
return ("", original)
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
let end-match = s.match(regex("\n(---|\.\.\.)[ \t\r]*(\n|$)"))
|
|
396
|
+
if end-match == none {
|
|
397
|
+
return ("", original)
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
return (s.slice(0, end-match.start), s.slice(end-match.end))
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
let (markdown-frontmatter, markdown) = if metadata-block != none {
|
|
404
|
+
extract-frontmatter(markdown)
|
|
405
|
+
} else {
|
|
406
|
+
(none, markdown)
|
|
407
|
+
}
|
|
408
|
+
let rendered = str(_p.render(bytes(markdown), bytes(options-bytes)))
|
|
409
|
+
|
|
410
|
+
let body = if show-source {
|
|
411
|
+
raw(rendered, block: true, lang: "typ")
|
|
412
|
+
} else {
|
|
413
|
+
eval(rendered, mode: "markup", scope: scope)
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
let metadata-block-content = if metadata-block == "frontmatter-raw" {
|
|
417
|
+
markdown-frontmatter
|
|
418
|
+
} else if metadata-block == "frontmatter-yaml" {
|
|
419
|
+
yaml(bytes(markdown-frontmatter))
|
|
420
|
+
} else if metadata-block != none {
|
|
421
|
+
let message = "invalid metadata-block value `" + metadata-block + "` (expected `frontmatter-raw` or `frontmatter-yaml`)"
|
|
422
|
+
assert(false, message: message)
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
(metadata-block-content, body)
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
#let render(
|
|
429
|
+
markdown,
|
|
430
|
+
smart-punctuation: true,
|
|
431
|
+
math: none,
|
|
432
|
+
task-list-marker: none,
|
|
433
|
+
h1-level: 1,
|
|
434
|
+
set-document-title: true,
|
|
435
|
+
raw-typst: true,
|
|
436
|
+
html: (:),
|
|
437
|
+
label-prefix: "",
|
|
438
|
+
prefix-label-uses: true,
|
|
439
|
+
heading-labels: "github",
|
|
440
|
+
scope: (:),
|
|
441
|
+
show-source: false,
|
|
442
|
+
blockquote: none,
|
|
443
|
+
) = {
|
|
444
|
+
let (meta, body) = render-with-metadata(
|
|
445
|
+
markdown,
|
|
446
|
+
smart-punctuation: smart-punctuation,
|
|
447
|
+
math: math,
|
|
448
|
+
task-list-marker: task-list-marker,
|
|
449
|
+
h1-level: h1-level,
|
|
450
|
+
set-document-title: set-document-title,
|
|
451
|
+
raw-typst: raw-typst,
|
|
452
|
+
html: html,
|
|
453
|
+
label-prefix: label-prefix,
|
|
454
|
+
prefix-label-uses: prefix-label-uses,
|
|
455
|
+
heading-labels: heading-labels,
|
|
456
|
+
scope: scope,
|
|
457
|
+
show-source: show-source,
|
|
458
|
+
blockquote: blockquote,
|
|
459
|
+
metadata-block: none,
|
|
460
|
+
)
|
|
461
|
+
body
|
|
462
|
+
}
|
|
Binary file
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "cmarker"
|
|
3
|
+
version = "0.1.10"
|
|
4
|
+
entrypoint = "lib.typ"
|
|
5
|
+
authors = ["Sabrina Jewson"]
|
|
6
|
+
license = "MIT"
|
|
7
|
+
description = "Transpile CommonMark Markdown to Typst, from within Typst!"
|
|
8
|
+
repository = "https://github.com/SabrinaJewson/cmarker.typ"
|
|
9
|
+
keywords = ["Markdown", "CommonMark"]
|
|
10
|
+
compiler = "0.15.0"
|
|
11
|
+
exclude = ["examples", "README.pdf"]
|