fork/wezterm

git clone https://git.julia.blue/fork/wezterm

Wez Furlongdocs: add netbsd install instructions to tocb38726532

termiz-0.23.1
16.0 KiB513 linesraw
1#!/usr/bin/env python3
2import base64
3import glob
4import json
5import os
6import re
7import subprocess
8import sys
9
10
11class Page(object):
12    def __init__(self, title, filename, children=None):
13        self.title = title
14        self.filename = filename
15        self.children = children or []
16
17    def render(self, output, depth=0, mode="mdbook"):
18        indent = "  " * depth
19        bullet = "- " if depth > 0 else ""
20        if mode == "mdbook":
21            if self.filename:
22                output.write(f"{indent}{bullet}[{self.title}]({self.filename})\n")
23        elif mode == "mkdocs":
24            if depth > 0:
25                if len(self.children) == 0:
26                    output.write(f'{indent}{bullet}"{self.title}": {self.filename}\n')
27                else:
28                    output.write(f'{indent}{bullet}"{self.title}":\n')
29                    if self.filename:
30                        output.write(
31                            f'{indent}  {bullet}"{self.title}": {self.filename}\n'
32                        )
33        for kid in self.children:
34            kid.render(output, depth + 1, mode)
35
36
37# autogenerate an index page from the contents of a directory
38class Gen(object):
39    def __init__(self, title, dirname, index=None, extract_title=False):
40        self.title = title
41        self.dirname = dirname
42        self.index = index
43        self.extract_title = extract_title
44
45    def render(self, output, depth=0, mode="mdbook"):
46        names = sorted(glob.glob(f"{self.dirname}/*.md"))
47        children = []
48        for filename in names:
49            title = os.path.basename(filename).rsplit(".", 1)[0]
50            if title == "index":
51                continue
52
53            if self.extract_title:
54                with open(filename, "r") as f:
55                    title = f.readline().strip("#").strip()
56
57            children.append(Page(title, filename))
58
59        index_filename = f"{self.dirname}/index.md"
60        index_page = Page(self.title, index_filename, children=children)
61        index_page.render(output, depth, mode)
62        with open(f"{self.dirname}/index.md", "w") as idx:
63            if self.index:
64                idx.write(self.index)
65                idx.write("\n\n")
66            else:
67                try:
68                    with open(f"{self.dirname}/index.markdown", "r") as f:
69                        idx.write(f.read())
70                        idx.write("\n\n")
71                except FileNotFoundError:
72                    pass
73            for page in children:
74                idx.write(f"  - [{page.title}]({os.path.basename(page.filename)})\n")
75
76
77def load_scheme(scheme):
78    ident = re.sub(
79        "[^a-z0-9_]", "_", scheme["metadata"]["name"].lower().replace("+", "plus")
80    )
81
82    if "ansi" not in scheme["colors"]:
83        raise Exception(f"scheme {scheme} is missing ansi colors!!?")
84    colors = scheme["colors"]["ansi"] + scheme["colors"]["brights"]
85
86    data = {
87        "name": scheme["metadata"]["name"],
88        "prefix": scheme["metadata"]["prefix"],
89        "ident": ident,
90        "fg": scheme["colors"]["foreground"],
91        "bg": scheme["colors"]["background"],
92        "metadata": scheme["metadata"],
93    }
94
95    # <https://github.com/asciinema/asciinema-player/wiki/Custom-terminal-themes>
96    css = f"""
97.asciinema-theme-{ident} .asciinema-terminal {{
98    color: {data["fg"]};
99    background-color: {data["bg"]};
100    border-color: {data["bg"]};
101}}
102
103.asciinema-theme-{ident} .fg-bg {{
104    color: {data["bg"]};
105}}
106
107.asciinema-theme-{ident} .bg-fg {{
108    background-color: {data["fg"]};
109}}
110"""
111
112    if "cursor_border" in scheme["colors"]:
113        data["cursor"] = scheme["colors"]["cursor_border"]
114
115        css += f"""
116.asciinema-theme-{ident} .cursor-b {{
117    background-color: {data["cursor"]} !important;
118}}
119"""
120
121    if "selection_fg" in scheme["colors"] and "selection_bg" in scheme["colors"]:
122        selection_bg = scheme["colors"]["selection_bg"]
123        selection_fg = scheme["colors"]["selection_fg"]
124
125        css += f"""
126.asciinema-theme-{ident} .asciinema-terminal ::selection {{
127    color: {selection_fg};
128    background-color: {selection_bg};
129}}
130"""
131
132    for idx, color in enumerate(colors):
133        css += f"""
134.asciinema-theme-{ident} .fg-{idx} {{
135    color: {color};
136}}
137.asciinema-theme-{ident} .bg-{idx} {{
138    background-color: {color};
139}}
140"""
141
142    data["css"] = css
143    return data
144
145
146def screen_shot_table(scheme):
147    T = "gYw"
148    lines = [
149        scheme["name"],
150        "",
151        "         def     40m     41m     42m     43m     44m     45m     46m     47m",
152    ]
153    for fg_space in [
154        "    m",
155        "   1m",
156        "  30m",
157        "1;30m",
158        "  31m",
159        "1;31m",
160        "  32m",
161        "1;32m",
162        "  33m",
163        "1;33m",
164        "  34m",
165        "1;34m",
166        "  35m",
167        "1;35m",
168        "  36m",
169        "1;36m",
170        "  37m",
171        "1;37m",
172    ]:
173        fg = fg_space.strip()
174        line = f" {fg_space} \033[{fg}  {T}  "
175
176        for bg in ["40m", "41m", "42m", "43m", "44m", "45m", "46m", "47m"]:
177            line += f" \033[{fg}\033[{bg}  {T}  \033[0m"
178        lines.append(line)
179
180    lines.append("")
181    lines.append("")
182
183    screen = "\r\n".join(lines)
184
185    header = {
186        "version": 2,
187        "width": 80,
188        "height": 24,
189        "title": scheme["name"],
190    }
191    header = json.dumps(header, sort_keys=True)
192    data = json.dumps([0.0, "o", screen])
193
194    return base64.b64encode(f"{header}\n{data}\n".encode("UTF-8")).decode("UTF-8")
195
196
197class GenColorScheme(object):
198    def __init__(self, title, dirname, index=None):
199        self.title = title
200        self.dirname = dirname
201        self.index = index
202
203    def render(self, output, depth=0, mode="mdbook"):
204        with open("colorschemes/data.json") as f:
205            scheme_data = json.load(f)
206        by_prefix = {}
207        by_name = {}
208        for scheme in scheme_data:
209            scheme = load_scheme(scheme)
210            prefix = scheme["prefix"]
211            if prefix not in by_prefix:
212                by_prefix[prefix] = []
213            by_prefix[prefix].append(scheme)
214            by_name[scheme["name"]] = scheme
215
216        style_filename = f"{self.dirname}/scheme.css"
217        with open(style_filename, "w") as style_file:
218            for scheme in by_name.values():
219                style_file.write(scheme["css"])
220                style_file.write("\n")
221        js_filename = f"{self.dirname}/scheme.js"
222        with open(js_filename, "w") as js_file:
223            data_by_scheme = {}
224            for scheme in by_name.values():
225                ident = scheme["ident"]
226                data = screen_shot_table(scheme)
227                data_by_scheme[ident] = data
228
229            js_file.write(f"SCHEME_DATA = {json.dumps(data_by_scheme)};\n")
230            js_file.write(
231                f"""
232function load_scheme_player(ident) {{
233  var data = SCHEME_DATA[ident];
234  AsciinemaPlayer.create(
235    'data:text/plain;base64,' + data,
236    document.getElementById(ident + '-player'), {{
237    theme: ident,
238    autoPlay: true,
239  }});
240}}
241"""
242            )
243
244        children = []
245        for scheme_prefix in sorted(by_prefix.keys()):
246            scheme_filename = f"{self.dirname}/{scheme_prefix}/index.md"
247            os.makedirs(os.path.dirname(scheme_filename), exist_ok=True)
248            children.append(Page(scheme_prefix, scheme_filename))
249
250            with open(scheme_filename, "w") as idx:
251                idents_to_load = []
252
253                idx.write(
254                    f"""---
255title: Color Schemes with first letter "{scheme_prefix}"
256---
257
258"""
259                )
260
261                for scheme in by_prefix[scheme_prefix]:
262                    title = scheme["name"]
263                    idx.write(f"## {title}\n")
264
265                    data = screen_shot_table(scheme)
266                    ident = scheme["ident"]
267                    idents_to_load.append(ident)
268
269                    idx.write(
270                        f"""
271<div id="{ident}-player"></div>
272"""
273                    )
274
275                    author = scheme["metadata"].get("author", None)
276                    if author:
277                        idx.write(f"Author: `{author}`<br/>\n")
278                    origin_url = scheme["metadata"].get("origin_url", None)
279                    if origin_url:
280                        idx.write(f"Source: <{origin_url}><br/>\n")
281                    version = scheme["metadata"].get("wezterm_version", None)
282                    if version and version != "Always":
283                        idx.write(f"{{{{since('{version}')}}}}<br/>\n")
284
285                    aliases = scheme["metadata"]["aliases"]
286                    if len(aliases) > 0:
287                        alias_list = []
288                        for a in aliases:
289                            alias_list.append(f"`{a}`")
290                        aliases = ", ".join(alias_list)
291                        idx.write(f"This scheme is also known as {aliases}.<br/>\n")
292
293                    idx.write("\nTo use this scheme, add this to your config:\n")
294                    idx.write(
295                        f"""
296```lua
297config.color_scheme = '{title}'
298```
299
300"""
301                    )
302
303                idents_to_load = json.dumps(idents_to_load)
304                idx.write(
305                    f"""
306<script>
307document.addEventListener("DOMContentLoaded", function() {{
308  {idents_to_load}.forEach(ident => load_scheme_player(ident));
309}});
310</script>
311"""
312                )
313
314        index_filename = f"{self.dirname}/index.md"
315        index_page = Page(self.title, index_filename, children=children)
316        index_page.render(output, depth, mode)
317
318        with open(f"{self.dirname}/index.md", "w") as idx:
319            idx.write(f"{len(scheme_data)} Color schemes listed by first letter\n\n")
320            for page in children:
321                upper = page.title.upper()
322                idx.write(f"  - [{upper}]({page.title}/index.md)\n")
323
324
325TOC = [
326    Page(
327        "WezTerm",
328        "index.md",
329        children=[
330            Page("Features", "features.md"),
331            Page("Scrollback", "scrollback.md"),
332            Page("Quick Select Mode", "quickselect.md"),
333            Page("Copy Mode", "copymode.md"),
334            Page("Hyperlinks", "hyperlinks.md"),
335            Page("Shell Integration", "shell-integration.md"),
336            Page("iTerm Image Protocol", "imgcat.md"),
337            Page("SSH", "ssh.md"),
338            Page("Serial Ports & Arduino", "serial.md"),
339            Page("Multiplexing", "multiplexing.md"),
340        ],
341    ),
342    Page(
343        "Download",
344        "installation.md",
345        children=[
346            Page("Windows", "install/windows.md"),
347            Page("macOS", "install/macos.md"),
348            Page("Linux", "install/linux.md"),
349            Page("FreeBSD", "install/freebsd.md"),
350            Page("NetBSD", "install/netbsd.md"),
351            Page("Build from source", "install/source.md"),
352        ],
353    ),
354    Page(
355        "Configuration",
356        "config/files.md",
357        children=[
358            Page("Colors & Appearance", "config/appearance.md"),
359            Page("Launching Programs", "config/launch.md"),
360            Page("Fonts", "config/fonts.md"),
361            Page("Font Shaping", "config/font-shaping.md"),
362            Page("Keyboard Concepts", "config/keyboard-concepts.md"),
363            Page("Key Binding", "config/keys.md"),
364            Page("Key Tables", "config/key-tables.md"),
365            Page("Default Key Assignments", "config/default-keys.md"),
366            Page("Keyboard Encoding", "config/key-encoding.md"),
367            Page("Mouse Binding", "config/mouse.md"),
368            Page("Plugins", "config/plugins.md"),
369            GenColorScheme("Color Schemes", "colorschemes"),
370            Gen("Recipes", "recipes", extract_title=True),
371        ],
372    ),
373    Page(
374        "Full Config & Lua Reference",
375        "config/lua/general.md",
376        children=[
377            Gen(
378                "Config Options",
379                "config/lua/config",
380            ),
381            Gen(
382                "module: wezterm",
383                "config/lua/wezterm",
384            ),
385            Gen(
386                "module: wezterm.color",
387                "config/lua/wezterm.color",
388            ),
389            Gen(
390                "module: wezterm.gui",
391                "config/lua/wezterm.gui",
392            ),
393            Gen(
394                "module: wezterm.mux",
395                "config/lua/wezterm.mux",
396            ),
397            Gen(
398                "module: wezterm.plugin",
399                "config/lua/wezterm.plugin",
400            ),
401            Gen(
402                "module: wezterm.procinfo",
403                "config/lua/wezterm.procinfo",
404            ),
405            Gen(
406                "module: wezterm.serde",
407                "config/lua/wezterm.serde",
408            ),
409            Gen(
410                "module: wezterm.time",
411                "config/lua/wezterm.time",
412            ),
413            Gen(
414                "module: wezterm.url",
415                "config/lua/wezterm.url",
416            ),
417            Gen(
418                "enum: KeyAssignment",
419                "config/lua/keyassignment",
420            ),
421            Gen(
422                "enum: CopyModeAssignment",
423                "config/lua/keyassignment/CopyMode",
424            ),
425            Gen("object: Color", "config/lua/color"),
426            Page("object: ExecDomain", "config/lua/ExecDomain.md"),
427            Page("object: LocalProcessInfo", "config/lua/LocalProcessInfo.md"),
428            Gen("object: MuxDomain", "config/lua/MuxDomain"),
429            Gen("object: MuxWindow", "config/lua/mux-window"),
430            Gen("object: MuxTab", "config/lua/MuxTab"),
431            Page("object: PaneInformation", "config/lua/PaneInformation.md"),
432            Page("object: TabInformation", "config/lua/TabInformation.md"),
433            Page("object: SshDomain", "config/lua/SshDomain.md"),
434            Page("object: SpawnCommand", "config/lua/SpawnCommand.md"),
435            Gen("object: Time", "config/lua/wezterm.time/Time"),
436            Page("object: TlsDomainClient", "config/lua/TlsDomainClient.md"),
437            Page("object: TlsDomainServer", "config/lua/TlsDomainServer.md"),
438            Gen(
439                "object: Pane",
440                "config/lua/pane",
441            ),
442            Gen(
443                "object: Window",
444                "config/lua/window",
445            ),
446            Page("object: WslDomain", "config/lua/WslDomain.md"),
447            Gen(
448                "events: Gui",
449                "config/lua/gui-events",
450            ),
451            Gen(
452                "events: Multiplexer",
453                "config/lua/mux-events",
454            ),
455            Gen(
456                "events: Window",
457                "config/lua/window-events",
458            ),
459        ],
460    ),
461    Page(
462        "CLI Reference",
463        "cli/general.md",
464        children=[
465            Gen("wezterm cli", "cli/cli"),
466            Page("wezterm connect", "cli/connect.md"),
467            Page("wezterm imgcat", "cli/imgcat.md"),
468            Page("wezterm ls-fonts", "cli/ls-fonts.md"),
469            Page("wezterm record", "cli/record.md"),
470            Page("wezterm replay", "cli/replay.md"),
471            Page("wezterm serial", "cli/serial.md"),
472            Page("wezterm set-working-directory", "cli/set-working-directory.md"),
473            Page("wezterm show-keys", "cli/show-keys.md"),
474            Page("wezterm ssh", "cli/ssh.md"),
475            Page("wezterm start", "cli/start.md"),
476        ],
477    ),
478    Page(
479        "Reference",
480        None,
481        children=[
482            Page("Escape Sequences", "escape-sequences.md"),
483            Page("What is a Terminal?", "what-is-a-terminal.md"),
484        ],
485    ),
486    Page(
487        "Get Help",
488        None,
489        children=[
490            Page("Troubleshooting", "troubleshooting.md"),
491            Page("F.A.Q.", "faq.md"),
492            Page("Getting Help", "help.md"),
493            Page("Contributing", "contributing.md"),
494        ],
495    ),
496    Page("Change Log", "changelog.md"),
497    Page("Sponsor", "sponsor.md"),
498]
499
500os.chdir("docs")
501
502with open("../mkdocs.yml", "w") as f:
503    f.write("# this is auto-generated by docs/generate-toc.py, do not edit\n")
504    f.write("INHERIT: docs/mkdocs-base.yml\n")
505    f.write("nav:\n")
506    for page in TOC:
507        page.render(f, depth=1, mode="mkdocs")
508
509
510with open("SUMMARY.md", "w") as f:
511    f.write("[root](index.md)\n")
512    for page in TOC:
513        page.render(f, depth=1, mode="mdbook")