khors 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.
- khors/__init__.py +3 -0
- khors/__main__.py +44 -0
- khors/assist.py +265 -0
- khors/html.py +85 -0
- khors/mdparse.py +371 -0
- khors/odp.py +295 -0
- khors/odt.py +431 -0
- khors/static/editor.html +21 -0
- khors/static/khors.css +118 -0
- khors/static/khors.js +1109 -0
- khors/themes/beach.json +17 -0
- khors/themes/dark.json +17 -0
- khors/themes/light.json +17 -0
- khors/themes/mono-dark.json +17 -0
- khors/themes/mono-light.json +17 -0
- khors/themes/ocean.json +17 -0
- khors/themes/paper.json +18 -0
- khors/themes/soft.json +17 -0
- khors/themes/strict.json +18 -0
- khors/themes/summer.json +17 -0
- khors/themes.py +125 -0
- khors/web.py +292 -0
- khors-0.1.0.dist-info/METADATA +201 -0
- khors-0.1.0.dist-info/RECORD +28 -0
- khors-0.1.0.dist-info/WHEEL +5 -0
- khors-0.1.0.dist-info/entry_points.txt +2 -0
- khors-0.1.0.dist-info/licenses/LICENSE +21 -0
- khors-0.1.0.dist-info/top_level.txt +1 -0
khors/__init__.py
ADDED
khors/__main__.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""khors export doc.md [--odt] [--odp] [--theme NAME] [--numbered] -> doc.odt / doc.odp beside it
|
|
2
|
+
khors themes -> the themes, your folder, the files not read
|
|
3
|
+
|
|
4
|
+
From the console formulas and diagrams stay as text (they are drawn by the page: KaTeX, mermaid)."""
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from . import odp, odt, themes
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main(argv=None):
|
|
13
|
+
ap = argparse.ArgumentParser(prog="khors")
|
|
14
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
15
|
+
e = sub.add_parser("export", help="markdown -> .odt / .odp beside it")
|
|
16
|
+
e.add_argument("md")
|
|
17
|
+
e.add_argument("--odt", action="store_true")
|
|
18
|
+
e.add_argument("--odp", action="store_true")
|
|
19
|
+
e.add_argument("--theme", default="strict")
|
|
20
|
+
e.add_argument("--numbered", action="store_true", help="number the headings")
|
|
21
|
+
sub.add_parser("themes", help="list the themes")
|
|
22
|
+
a = ap.parse_args(argv)
|
|
23
|
+
if a.cmd == "themes":
|
|
24
|
+
data = themes.listing()
|
|
25
|
+
for th in data["themes"]:
|
|
26
|
+
print(f"{th['name']:12} {'own ' if th['own'] else ' '}{themes.about_text(th['about'])}")
|
|
27
|
+
print(f"\nyour own themes: {data['folder']}")
|
|
28
|
+
for p in data["problems"]:
|
|
29
|
+
print(f"not read: {p['file']}: {p['error']}")
|
|
30
|
+
return 0
|
|
31
|
+
if a.theme not in themes.names():
|
|
32
|
+
print(f"no theme {a.theme!r}; see: khors themes", file=sys.stderr)
|
|
33
|
+
return 2
|
|
34
|
+
text = open(a.md, encoding="utf-8-sig").read()
|
|
35
|
+
base = os.path.splitext(a.md)[0]
|
|
36
|
+
for fmt in [f for f in ("odt", "odp") if getattr(a, f)] or ["odt"]:
|
|
37
|
+
make = odt.write_odt if fmt == "odt" else odp.write_odp
|
|
38
|
+
make(text, f"{base}.{fmt}", theme=a.theme, numbered=a.numbered)
|
|
39
|
+
print(f"{base}.{fmt}")
|
|
40
|
+
return 0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
if __name__ == "__main__":
|
|
44
|
+
sys.exit(main())
|
khors/assist.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
"""khors — the model writes one piece of the document; Python does the rest (concepts/DOCUMENT_EDITOR.md §3a).
|
|
2
|
+
|
|
3
|
+
The model never sees the whole document. A call holds (≈ 0.5–1.5k tokens, fits a 4k context and gpt-oss's
|
|
4
|
+
thinking): the plan of the document (its headings, the one we are under marked), the sentences just before and
|
|
5
|
+
after the place, the selected text (when there is one), the request, and — when the host gives it — a few last
|
|
6
|
+
messages of the chat. Two forms, both tried in an idea test (simrgl DOCUMENT_EDITOR.md, R2) as the ones small models can do:
|
|
7
|
+
|
|
8
|
+
selection -> "rewrite": the model writes the new text for the selection, whole (W)
|
|
9
|
+
cursor -> "insert": the model writes the text that goes between "before" and "after"
|
|
10
|
+
|
|
11
|
+
The answer is a proposal: the person sees it, may edit it, accepts or drops it. Numbers are never the model's
|
|
12
|
+
business (the export numbers headings and lists).
|
|
13
|
+
|
|
14
|
+
context(text, start, end, request, chat) -> {"mode", "messages", "chars", "where"}
|
|
15
|
+
clean(answer) -> the text to put in (a fence around the whole answer, a "Here is…" line, <think> removed)
|
|
16
|
+
"""
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import urllib.error
|
|
21
|
+
import urllib.request
|
|
22
|
+
|
|
23
|
+
from .mdparse import blocks
|
|
24
|
+
|
|
25
|
+
MAX_SELECTION = 6000 # characters; more -> ask for a smaller selection (a 4k context)
|
|
26
|
+
AROUND = 450 # characters of text before / after the place
|
|
27
|
+
OUTLINE_CHARS = 1400
|
|
28
|
+
CHAT_CHARS = 1500
|
|
29
|
+
CHAT_LAST = 3
|
|
30
|
+
|
|
31
|
+
SENT_END = re.compile(r"(?<=[.!?…:;])\s+|\n\s*\n")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _tail(s, n):
|
|
35
|
+
"""The last ~n characters of s, cut at a sentence or line start."""
|
|
36
|
+
if len(s) <= n:
|
|
37
|
+
return s
|
|
38
|
+
cut = s[-n:]
|
|
39
|
+
m = SENT_END.search(cut)
|
|
40
|
+
return cut[m.end():] if m and m.end() < len(cut) - 20 else cut
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _head(s, n):
|
|
44
|
+
if len(s) <= n:
|
|
45
|
+
return s
|
|
46
|
+
cut = s[:n]
|
|
47
|
+
ends = list(SENT_END.finditer(cut))
|
|
48
|
+
return cut[:ends[-1].start() + 1] if ends and ends[-1].start() > 20 else cut
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def outline(text, pos):
|
|
52
|
+
"""The document's headings, one per line, indented by level; the section holding `pos` marked."""
|
|
53
|
+
line_no = text.count("\n", 0, pos)
|
|
54
|
+
at_line_start = pos == 0 or text[pos - 1] == "\n"
|
|
55
|
+
heads = [b for b in blocks(text) if b["k"] == "h"]
|
|
56
|
+
here = None
|
|
57
|
+
for i, h in enumerate(heads):
|
|
58
|
+
# the cursor at the start of a heading's line is before that heading: the end of the section above
|
|
59
|
+
if h["line"] < line_no or (h["line"] == line_no and not at_line_start):
|
|
60
|
+
here = i
|
|
61
|
+
lines = []
|
|
62
|
+
for i, h in enumerate(heads):
|
|
63
|
+
t = h["text"] if len(h["text"]) <= 80 else h["text"][:77] + "…"
|
|
64
|
+
lines.append(" " * (h["level"] - 1) + t + (" <-- HERE" if i == here else ""))
|
|
65
|
+
if here is None and heads:
|
|
66
|
+
lines.insert(0, "(HERE: before the first heading)")
|
|
67
|
+
out = "\n".join(lines)
|
|
68
|
+
if len(out) > OUTLINE_CHARS: # a long plan: keep the part around HERE
|
|
69
|
+
k = here or 0
|
|
70
|
+
lo, hi = max(0, k - 12), min(len(lines), k + 12)
|
|
71
|
+
out = "\n".join((["…"] if lo else []) + lines[lo:hi] + (["…"] if hi < len(lines) else []))
|
|
72
|
+
return out, (heads[here]["text"] if here is not None else "")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _chat_text(chat):
|
|
76
|
+
if not chat:
|
|
77
|
+
return ""
|
|
78
|
+
out, total = [], 0
|
|
79
|
+
for m in chat[-CHAT_LAST:]:
|
|
80
|
+
if not isinstance(m, dict) or m.get("role") not in ("user", "assistant"):
|
|
81
|
+
continue
|
|
82
|
+
c = str(m.get("content") or "").strip()
|
|
83
|
+
c = re.sub(r"<think>.*?</think>", "", c, flags=re.S).strip()
|
|
84
|
+
if len(c) > 600:
|
|
85
|
+
c = c[:600] + " …"
|
|
86
|
+
out.append(f"{m['role']}: {c}")
|
|
87
|
+
total += len(c)
|
|
88
|
+
if total > CHAT_CHARS:
|
|
89
|
+
break
|
|
90
|
+
return "\n".join(out)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
SYSTEM = ("You help write a document in markdown. You write only the text asked for — no explanations, no "
|
|
94
|
+
"notes, no quotes around it. Write in the language of the document unless the request says otherwise. "
|
|
95
|
+
"Do not number headings or list items by hand where the document does not.")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def context(text, start, end, request, chat=None):
|
|
99
|
+
start, end = max(0, min(start, len(text))), max(0, min(end, len(text)))
|
|
100
|
+
if end < start:
|
|
101
|
+
start, end = end, start
|
|
102
|
+
sel = text[start:end]
|
|
103
|
+
if len(sel) > MAX_SELECTION:
|
|
104
|
+
raise ValueError(f"the selection is {len(sel)} characters; select at most {MAX_SELECTION}")
|
|
105
|
+
request = (request or "").strip()
|
|
106
|
+
if not request:
|
|
107
|
+
raise ValueError("write what to do")
|
|
108
|
+
before, after = _tail(text[:start], AROUND), _head(text[end:], AROUND)
|
|
109
|
+
plan, section = outline(text, start)
|
|
110
|
+
parts = []
|
|
111
|
+
if plan:
|
|
112
|
+
parts.append(f"The plan of the document (its headings):\n{plan}")
|
|
113
|
+
chat_part = _chat_text(chat)
|
|
114
|
+
if chat_part:
|
|
115
|
+
parts.append(f"From the conversation beside the document (for background):\n{chat_part}")
|
|
116
|
+
if sel.strip():
|
|
117
|
+
mode = "rewrite"
|
|
118
|
+
parts.append(f"Text just before the selection:\n<<<\n{before.strip() or '(the start of the document)'}\n>>>")
|
|
119
|
+
parts.append(f"THE SELECTED TEXT:\n<<<\n{sel}\n>>>")
|
|
120
|
+
parts.append(f"Text just after the selection:\n<<<\n{after.strip() or '(the end of the document)'}\n>>>")
|
|
121
|
+
parts.append(f"Request: {request}\n\nWrite only the new text that replaces THE SELECTED TEXT, whole, in "
|
|
122
|
+
"markdown. Keep what the request does not ask to change.")
|
|
123
|
+
else:
|
|
124
|
+
mode = "insert"
|
|
125
|
+
parts.append(f"Text before the place:\n<<<\n{before.strip() or '(the start of the document)'}\n>>>")
|
|
126
|
+
parts.append(f"Text after the place:\n<<<\n{after.strip() or '(the end of the document)'}\n>>>")
|
|
127
|
+
parts.append(f"Request: {request}\n\nWrite only the new text that goes at the place between them, in "
|
|
128
|
+
"markdown. Do not repeat the text before or after.")
|
|
129
|
+
user = "\n\n".join(parts)
|
|
130
|
+
messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": user}]
|
|
131
|
+
return {"mode": mode, "messages": messages, "chars": len(SYSTEM) + len(user),
|
|
132
|
+
"where": section, "selection": len(sel)}
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
CHATTER = re.compile(r"^(here(?:'s| is)[^\n]*:|sure[^\n]*[:.!]|certainly[^\n]*[:.!]|ось[^\n]*:|звісно[^\n]*[:.!])\s*\n",
|
|
136
|
+
re.I)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def clean(answer):
|
|
140
|
+
a = re.sub(r"<think>.*?</think>", "", answer or "", flags=re.S).strip("\n")
|
|
141
|
+
a = CHATTER.sub("", a.lstrip(), count=1)
|
|
142
|
+
m = re.match(r"^\s*```[\w-]*\s*\n(.*)\n\s*```\s*$", a, re.S) # one fence around the whole answer
|
|
143
|
+
if m and "```" not in m.group(1):
|
|
144
|
+
a = m.group(1)
|
|
145
|
+
a = re.sub(r"^<<<\s*\n|\n\s*>>>\s*$", "", a.strip("\n"))
|
|
146
|
+
return a.strip("\n")
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
# ── the default model: Ollama on this machine (a host passes its own `chat` / `models`) ──
|
|
150
|
+
|
|
151
|
+
def ollama_host():
|
|
152
|
+
return (os.environ.get("KHORS_OLLAMA") or os.environ.get("OLLAMA_HOST") or "http://127.0.0.1:11434").rstrip("/")
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _url(h):
|
|
156
|
+
return h if h.startswith("http") else "http://" + h
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def ollama_models(host=None):
|
|
160
|
+
with urllib.request.urlopen(_url(host or ollama_host()) + "/api/tags", timeout=10) as r:
|
|
161
|
+
return [m["name"] for m in json.load(r).get("models", [])]
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
_LAST = {"model": None}
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _unload(model, host=None):
|
|
168
|
+
"""Ollama keeps a model loaded 5 min after its last call: switching models in the drawer would pile them up
|
|
169
|
+
in memory (simrgl DOCUMENT_EDITOR.md, R2) — the previous one is unloaded when the model changes."""
|
|
170
|
+
req = urllib.request.Request(_url(host or ollama_host()) + "/api/generate",
|
|
171
|
+
json.dumps({"model": model, "keep_alive": 0}).encode(),
|
|
172
|
+
{"Content-Type": "application/json"})
|
|
173
|
+
try:
|
|
174
|
+
urllib.request.urlopen(req, timeout=30).read()
|
|
175
|
+
except Exception: # noqa: BLE001 — best effort
|
|
176
|
+
pass
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def ollama_chat(messages, model, num_ctx=4096, host=None, think=False, num_predict=None, info=None):
|
|
180
|
+
"""Stream the answer's text. think: ask the model to think (the drawer's "Thinking"); else thinking is
|
|
181
|
+
turned off where the model allows it. Whatever thinking comes (a model that always thinks) is streamed too,
|
|
182
|
+
as <think>…</think> — the same form as vyrii's stream_chat, so the drawer shows it as the chat does.
|
|
183
|
+
host: an Ollama address (a host app's own setting, e.g. alkonost's), else ollama_host().
|
|
184
|
+
num_predict: the answer's limit in tokens (None: the model's own). info: a dict that gets Ollama's
|
|
185
|
+
done_reason ("length" = cut by num_ctx / num_predict)."""
|
|
186
|
+
if _LAST["model"] and _LAST["model"] != model:
|
|
187
|
+
_unload(_LAST["model"], host)
|
|
188
|
+
_LAST["model"] = model
|
|
189
|
+
body = {"model": model, "messages": messages, "stream": True, "think": bool(think),
|
|
190
|
+
"options": {"temperature": 0.3, "num_ctx": num_ctx}}
|
|
191
|
+
if num_predict:
|
|
192
|
+
body["options"]["num_predict"] = num_predict
|
|
193
|
+
for attempt in (0, 1):
|
|
194
|
+
req = urllib.request.Request(_url(host or ollama_host()) + "/api/chat", json.dumps(body).encode(),
|
|
195
|
+
{"Content-Type": "application/json"})
|
|
196
|
+
try:
|
|
197
|
+
in_think = False
|
|
198
|
+
with urllib.request.urlopen(req, timeout=1800) as r:
|
|
199
|
+
for line in r:
|
|
200
|
+
if not line.strip():
|
|
201
|
+
continue
|
|
202
|
+
d = json.loads(line)
|
|
203
|
+
if d.get("error"):
|
|
204
|
+
raise RuntimeError(d["error"])
|
|
205
|
+
msg = d.get("message") or {}
|
|
206
|
+
if msg.get("thinking"):
|
|
207
|
+
if not in_think:
|
|
208
|
+
yield "<think>"
|
|
209
|
+
in_think = True
|
|
210
|
+
yield msg["thinking"]
|
|
211
|
+
piece = msg.get("content") or ""
|
|
212
|
+
if piece:
|
|
213
|
+
if in_think:
|
|
214
|
+
yield "</think>"
|
|
215
|
+
in_think = False
|
|
216
|
+
yield piece
|
|
217
|
+
if d.get("done"):
|
|
218
|
+
if info is not None:
|
|
219
|
+
info["done_reason"] = d.get("done_reason")
|
|
220
|
+
break
|
|
221
|
+
if in_think:
|
|
222
|
+
yield "</think>"
|
|
223
|
+
return
|
|
224
|
+
except urllib.error.HTTPError as e:
|
|
225
|
+
msg = e.read().decode(errors="replace")
|
|
226
|
+
if attempt == 0 and "think" in msg:
|
|
227
|
+
body.pop("think")
|
|
228
|
+
continue
|
|
229
|
+
raise RuntimeError(msg[:300]) from None
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
class ThinkSplit:
|
|
233
|
+
"""Splits a stream of text pieces into ("think", text) / ("text", text) by <think>…</think> — the tags may
|
|
234
|
+
come as pieces of their own (vyrii's stream_chat, ollama_chat above) or inside the model's text (a model
|
|
235
|
+
that writes them itself), even cut between two pieces."""
|
|
236
|
+
|
|
237
|
+
OPEN, CLOSE = "<think>", "</think>"
|
|
238
|
+
|
|
239
|
+
def __init__(self):
|
|
240
|
+
self.buf, self.inside = "", False
|
|
241
|
+
|
|
242
|
+
def feed(self, piece):
|
|
243
|
+
self.buf += piece
|
|
244
|
+
out = []
|
|
245
|
+
while True:
|
|
246
|
+
tag = self.CLOSE if self.inside else self.OPEN
|
|
247
|
+
i = self.buf.find(tag)
|
|
248
|
+
if i >= 0:
|
|
249
|
+
if i:
|
|
250
|
+
out.append(("think" if self.inside else "text", self.buf[:i]))
|
|
251
|
+
self.buf, self.inside = self.buf[i + len(tag):], not self.inside
|
|
252
|
+
continue
|
|
253
|
+
keep = 0 # a tag's beginning at the end waits for the rest
|
|
254
|
+
for k in range(min(len(tag) - 1, len(self.buf)), 0, -1):
|
|
255
|
+
if tag.startswith(self.buf[-k:]):
|
|
256
|
+
keep = k
|
|
257
|
+
break
|
|
258
|
+
if len(self.buf) > keep:
|
|
259
|
+
out.append(("think" if self.inside else "text", self.buf[:len(self.buf) - keep]))
|
|
260
|
+
self.buf = self.buf[len(self.buf) - keep:]
|
|
261
|
+
return out
|
|
262
|
+
|
|
263
|
+
def end(self):
|
|
264
|
+
rest, self.buf = self.buf, ""
|
|
265
|
+
return [("think" if self.inside else "text", rest)] if rest else []
|
khors/html.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""khors — the drawer's preview: the same blocks as the .odt / .odp, as HTML (everything escaped). Formulas and
|
|
2
|
+
diagrams are left for the page to draw (KaTeX, mermaid): `<span class="kh-math" data-tex=… data-display=…>` and
|
|
3
|
+
`<pre class="mermaid">`. Each top block carries data-line / data-end — its lines in the markdown (for the cursor
|
|
4
|
+
and the selection later).
|
|
5
|
+
"""
|
|
6
|
+
from html import escape
|
|
7
|
+
|
|
8
|
+
from .mdparse import HEAD_NUMBER, blocks, inline, outline, para_spans
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def spans(sp):
|
|
12
|
+
out = []
|
|
13
|
+
for s in sp:
|
|
14
|
+
k = s[0]
|
|
15
|
+
if k == "t":
|
|
16
|
+
out.append(escape(s[1]))
|
|
17
|
+
elif k == "b":
|
|
18
|
+
out.append(f"<strong>{spans(s[1])}</strong>")
|
|
19
|
+
elif k == "i":
|
|
20
|
+
out.append(f"<em>{spans(s[1])}</em>")
|
|
21
|
+
elif k == "s":
|
|
22
|
+
out.append(f"<del>{spans(s[1])}</del>")
|
|
23
|
+
elif k == "code":
|
|
24
|
+
out.append(f"<code>{escape(s[1])}</code>")
|
|
25
|
+
elif k == "math":
|
|
26
|
+
out.append(f'<span class="kh-math" data-display="0" data-tex="{escape(s[1])}">{escape(s[1])}</span>')
|
|
27
|
+
elif k == "link":
|
|
28
|
+
url = s[2] if s[2].split(":", 1)[0].lower() in ("http", "https", "mailto") or ":" not in s[2] else "#"
|
|
29
|
+
out.append(f'<a href="{escape(url)}" target="_blank" rel="noopener noreferrer">{spans(s[1])}</a>')
|
|
30
|
+
elif k == "br":
|
|
31
|
+
out.append("<br>")
|
|
32
|
+
return "".join(out)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def block(b, numbered, counters):
|
|
36
|
+
k = b["k"]
|
|
37
|
+
if k == "h":
|
|
38
|
+
text = b["text"]
|
|
39
|
+
num = ""
|
|
40
|
+
if numbered and b["level"] in counters["map"]:
|
|
41
|
+
lv = counters["map"][b["level"]]
|
|
42
|
+
c = counters["n"]
|
|
43
|
+
c[lv - 1] += 1
|
|
44
|
+
for j in range(lv, len(c)):
|
|
45
|
+
c[j] = 0
|
|
46
|
+
num = ".".join(str(x) for x in c[:lv]) + (". " if lv == 1 else " ")
|
|
47
|
+
text = HEAD_NUMBER.sub("", text)
|
|
48
|
+
lv = min(b["level"], 6)
|
|
49
|
+
return f'<h{lv}>{escape(num)}{spans(inline(text))}</h{lv}>'
|
|
50
|
+
if k == "p":
|
|
51
|
+
return f"<p>{spans(para_spans(b['lines']))}</p>"
|
|
52
|
+
if k == "quote":
|
|
53
|
+
return "<blockquote>" + "".join(block(c, numbered, counters) for c in b["children"]) + "</blockquote>"
|
|
54
|
+
if k == "list":
|
|
55
|
+
tag = "ol" if b["ordered"] else "ul"
|
|
56
|
+
start = f' start="{b["start"]}"' if b["ordered"] and b["start"] != 1 else ""
|
|
57
|
+
items = "".join(f"<li>{spans(inline(it['text']))}"
|
|
58
|
+
+ "".join(block(c, numbered, counters) for c in it["children"]) + "</li>" for it in b["items"])
|
|
59
|
+
return f"<{tag}{start}>{items}</{tag}>"
|
|
60
|
+
if k == "table":
|
|
61
|
+
head = "".join(f'<th style="text-align:{b["align"][c]}">{spans(inline(x))}</th>' for c, x in enumerate(b["head"]))
|
|
62
|
+
rows = "".join("<tr>" + "".join(f'<td style="text-align:{b["align"][c]}">{spans(inline(x))}</td>'
|
|
63
|
+
for c, x in enumerate(r)) + "</tr>" for r in b["rows"])
|
|
64
|
+
return f'<table class="kh-table"><thead><tr>{head}</tr></thead><tbody>{rows}</tbody></table>'
|
|
65
|
+
if k == "code":
|
|
66
|
+
return f"<pre><code>{escape(b['text'])}</code></pre>"
|
|
67
|
+
if k == "math":
|
|
68
|
+
return f'<div class="kh-math" data-display="1" data-tex="{escape(b["tex"])}">{escape(b["tex"])}</div>'
|
|
69
|
+
if k == "mermaid":
|
|
70
|
+
return f'<pre class="mermaid">{escape(b["src"])}</pre>'
|
|
71
|
+
if k == "hr":
|
|
72
|
+
return "<hr>"
|
|
73
|
+
return ""
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def render(md, numbered=False):
|
|
77
|
+
bl = blocks(md)
|
|
78
|
+
title_at, level_map = outline(bl)
|
|
79
|
+
counters = {"map": level_map, "n": [0] * 6}
|
|
80
|
+
out = []
|
|
81
|
+
for i, b in enumerate(bl):
|
|
82
|
+
inner = (f'<h1 class="kh-title">{spans(inline(b["text"]))}</h1>' if i == title_at
|
|
83
|
+
else block(b, numbered, counters))
|
|
84
|
+
out.append(f'<div class="kh-block" data-line="{b["line"]}" data-end="{b["end"]}">{inner}</div>')
|
|
85
|
+
return "".join(out)
|