diff --git a/CHANGELOG.md b/CHANGELOG.md index 167bef0..56b1306 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,18 @@ The format is inspired by [Keep a Changelog](https://keepachangelog.com/en/1.1.0 ### Fixed +- Example pages now show their intro paragraphs. Every source file opens with two or three paragraphs of explanation that the loader parsed and the page template then dropped, so the definition and the "when to use this" of most pages never reached a reader. They render under the summary and are part of the search index. +- Runner output reads like Python, not like the harness: tracebacks show only the learner's frames with their source lines (`File "example.py", line 3`), `exit()` and `sys.exit()` end the program instead of returning "Internal Server Error", stderr is shown in program order, and `input()` explains that the sandbox has no terminal. Pages that teach something the sandbox lacks (`sandbox_limit` in frontmatter: the venv module, child processes, threads, sockets) say so when Run fails. +- The editor has undo history, auto-indent after a block opener, Tab indentation (Esc then Tab leaves the editor), bracket matching, and Ctrl/⌘+Enter to run. Ctrl+Z used to fall through to the browser and corrupt the document. +- Figures stay readable on phones. A figure now fills the banner up to its intrinsic width and, when wider than the screen, keeps 72% of that width and scrolls sideways inside its own box; labels that shrank to under 6px now render at 9px or more. +- Journey pages render inline code; section titles and outcomes used to show literal backticks. +- `HEAD` requests are answered for every rendered page and `/sitemap.xml` (they returned 405), and trailing-slash URLs such as `/examples/values/` redirect to the canonical path (they returned 404). +- Cache hits leave the Worker with the intended `max-age=300`; a response read back from the Workers cache was reaching browsers with a four-hour lifetime. +- The Turnstile clearance cookie is bound to the client address that passed the check, so a copied cookie is not accepted elsewhere. +- Search finds pages by everyday words ("dictionary", "mutable", "regex") and by names a page uses in its prose or code (`zip`, `join`, `docstring`). +- The `hello-world` quality waiver is permanent; it would have expired on 2026-12-01 and failed `make verify` on every pull request. +- Early pages no longer depend on `def`, `class` or `try` before those are taught; `operators` no longer defines a class to demonstrate `@`. + - Deployment smoke now proves the production Turnstile secret. Its bypass header skips Siteverify, so a wrong, rotated, or test secret used to pass smoke while every new session's first run failed. With `PBE_SMOKE_BYPASS_SECRET`, `scripts/smoke_deployment.py` calls the header-gated `POST /__smoke/turnstile`. The Worker sends its secret with Cloudflare's dummy token and reports `valid`, `invalid`, `testing_key`, `unverified`, `unexpected`, or `absent`. Smoke fails unless the secret is a working production secret with a site key, or Turnstile is off. - A Run whose Turnstile token the server rejects now ends with the server's message instead of re-challenging. The runner used to solve again every time the response carried the challenge marker, so a persistently failing Siteverify (wrong secret, hostname, or action) turned one click into an unbounded loop of solves, Worker POSTs, and Siteverify subrequests. Each Run now earns at most one challenge, and the failure message says to press Run again. @@ -18,12 +30,22 @@ The format is inspired by [Keep a Changelog](https://keepachangelog.com/en/1.1.0 ### Changed +- CodeMirror and Shiki are bundled from npm packages pinned in `package-lock.json` (`make browser-bundles`, sources in `web/`) instead of being imported from esm.sh at page load. An example page went from about 100 requests and 617 KB of third-party script to two first-party bundles, the CSP no longer allows esm.sh or `wasm-unsafe-eval`, and the code visitors run can only change with a commit. The privacy notice is updated. +- `generics-and-typevar` leads with PEP 695 type parameter syntax and shows `TypeVar` as the legacy spelling; `dataclasses`, `typed-dicts`, `warnings` and generics now use features introduced in Python 3.13 (`copy.replace()`, `ReadOnly`, `warnings.deprecated`, type parameter defaults). +- The scoring heuristic no longer credits a page for containing `print(` or particular name strings. +- The home page hero, About and privacy pages describe what the site does today. + - Figures now paint with `--fig-ink`, `--fig-ink-soft`, `--fig-accent` and `--fig-soft` tokens instead of literal colours, and `site.css` defines the tokens for both colour schemes. Dark mode recolours every figure with the page; the light "paper chip" behind figures is gone. Figure mono and sans faces follow the page's own font stacks, and mono runs are pinned to the grammar's character advance with `textLength` so divider positions hold on every platform. Paired figures in a banner share a baseline (a two-row subgrid). Five figures lost an accent that marked an arbitrary row (`naming-decisions`, `iteration-loop-selector`, `type-shape-catalog`, `reliability-signal-map`, `container-methods`); nine arrows that were mostly arrowhead were lengthened to the new 20-unit minimum. - Ten figures redrawn as mechanisms carrying the lesson's own values: closures is an environment diagram with the returned frame ghosted and one live `__closure__` reference; generators shows the cell's two `next()` calls on `countdown(3)` with the surviving local beside each; recursion shows the example's tree at the deepest frame of `total(tree)` with the values each frame returns; dicts shows the cell's keys hashed to slots with the insert of `"year"`; sentinel iteration shows `read_chunk` yielding `"py"` and `"thon"` and stopping on the empty string; string formatting's format spec is a railroad tracing the cell's `05.1f`, skipped stations ghosted under a bypass rail; bytes-and-bytearray draws the example's bytes as integer slots with the in-place write and moves to the cell that performs it; regular expressions shows the cell's two capture groups landing on `Ada: 10`; values shows `text` bound to a `str` object and the `type()` hop to where `upper()` lives; logging shows the cell's three records crossing the handler's INFO gate. The binding figure is a parametrised factory, so `variables` shows `message → "hi"` and `constants` shows `MAX_RETRIES → 3`. - The rubric states that table-shaped figures are redrawn rather than removed, that a figure whose caption names no single element carries no accent, and how cell-0 anchors are scored. The review, principles and queue are in `docs/diagram-upgrade-plan.md`. ### Added +- `files-and-pathlib` example: `Path` joining, whole-file and line-by-line text I/O, directory listing, and the missing-file boundary. +- `/llms.txt`, and every example's authored Markdown at `/examples/.md`. +- `make runtime-examples-test` (part of `make verify`): posts every example's complete program to the local dev Worker and compares the sandbox output with the expected output. `verify-examples` only ever ran the catalog under host CPython. +- The browser gate now checks editor keys, the smallest figure label on a 390px phone, and that an example page makes no third-party request before Run. + - `/about` page describing how the site is made — the verified-output pipeline, the runner sandbox, the figure grammar, and the quality gates — with a design-language section that renders the live CSS tokens (color swatches, spacing scale, type specimens, and a real walkthrough cell as a specimen). Linked from the nav on every page and listed in the sitemap. - Copy buttons on read-only source cells: injected client-side onto `.cell-source` wrappers (so no-JS pages render no dead buttons), clipboard API with a hidden-textarea fallback, and a quiet icon-in-pill treatment — the Lucide copy glyph drawn as a `currentColor` CSS mask (checkmark on success, x on failure), a visually hidden live region announcing the result, and a ~44px tap target around the small pill. These are the site's first and only UI icons; every other action stays text. - Keyboard navigation on example pages: `←`/`→` follow the existing `rel="prev"`/`rel="next"` links, ignoring keystrokes with modifiers or focus inside the editor, inputs, or any editable surface. Arrows only fire while the editor is unedited (so a slip never discards work), and the prev/next links carry title hints naming the shortcut. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b8163d6..1eceaf7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,8 +29,11 @@ Do not edit generated files by hand: src/example_sources_data.py src/asset_manifest.py public/*.css/js fingerprinted copies +public/editor.js and public/highlighter.js (bundled from web/*.js) ``` +The editor and syntax highlighter live in `web/`; their npm dependencies are pinned in `package-lock.json` and bundled into `public/` by `make browser-bundles`, which `make build` runs. + Regenerate them with: ```bash @@ -66,7 +69,7 @@ make check-generated ## Quality checks -These scripts enforce the catalog-level rules from `docs/example-quality-rubric.md`. Run them together with `make quality-checks`. CI does not schedule a waiver-expiry run; before a release or once a month, run `make check-waiver-expiry`, which fails while any waiver has 30 days or fewer left. +These scripts enforce the catalog-level rules from `docs/example-quality-rubric.md`. Run them together with `make quality-checks`. CI does not schedule a waiver-expiry run; before a release or once a month, run `make check-waiver-expiry`, which fails while any time-boxed waiver has 30 days or fewer left. A waiver whose reason can never stop being true sets `permanent = true` instead of `expires` (Hello World is the only one); the two fields are mutually exclusive. | Script | What it gates | | --- | --- | @@ -79,7 +82,7 @@ These scripts enforce the catalog-level rules from `docs/example-quality-rubric. | `scripts/check_prose_duplication.py` | No verbatim repeated paragraphs, no cell prose copied from the intro, no duplicate note bullets. | | `scripts/check_inline_links.py` | Inline `[text](target)` links in prose resolve to real `/examples` or `/journeys` pages. | | `scripts/score_example_criteria.py` | Heuristic criterion scores per example; fails when a curated score exceeds the heuristic by more than the delta bound, so the score registry cannot inflate without the page changing. | -| `scripts/check_quality_scores.py` | Curated scores meet the 9.0 target / 8.5 hard minimum, waivers carry future expiry dates (with a warning in their last 30 days) and are dropped when stale, and the journey-section average stays above its floor. | +| `scripts/check_quality_scores.py` | Curated scores meet the 9.0 target / 8.5 hard minimum, waivers carry either a future expiry date (with a warning in its last 30 days) or `permanent = true`, and are dropped when stale, and the journey-section average stays above its floor. | | `scripts/check_no_figure_rationales.py` | No-figure opt-outs carry a reason and an unexpired `review_after` date. | | `scripts/check_journey_outcomes.py` | Every journey section declares learner outcomes. | | `scripts/audit_example_graph.py --check` | The `see_also` graph has no broken targets, self-links, over-linked pages, or orphaned examples. | diff --git a/Makefile b/Makefile index ffd5a69..6409ebe 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,7 @@ PY := uv run --python 3.13 NODE_DEPS_STAMP := node_modules/.package-lock.json -.PHONY: check-node-version node-deps test embed-examples embed-editorial-registry build-search-index build check-generated fingerprint prototypes browser-layout-test search-ranking-test social-cards check-social-cards seo-cache-lint verify-examples check-registry-integrity check-confusable-pairs check-broad-surface-tours check-footgun-coverage check-notes-supported check-program-covers-cells check-prose-duplication check-inline-links score-example-criteria check-quality-scores check-waiver-expiry check-no-figure-rationales check-journey-outcomes audit-example-graph quality-checks rubric-audit format-examples verify-python-version verify smoke-deployment post-deploy-smoke dev deploy upgrade-runtime-deps lint +.PHONY: check-node-version node-deps test embed-examples embed-editorial-registry build-search-index build check-generated fingerprint prototypes browser-bundles browser-layout-test runtime-examples-test search-ranking-test social-cards check-social-cards seo-cache-lint verify-examples check-registry-integrity check-confusable-pairs check-broad-surface-tours check-footgun-coverage check-notes-supported check-program-covers-cells check-prose-duplication check-inline-links score-example-criteria check-quality-scores check-waiver-expiry check-no-figure-rationales check-journey-outcomes audit-example-graph quality-checks rubric-audit format-examples verify-python-version verify smoke-deployment post-deploy-smoke dev deploy upgrade-runtime-deps lint check-node-version: @major="$$(node -p 'process.versions.node.split(".")[0]')"; \ @@ -32,11 +32,16 @@ build-search-index: embed-examples build: embed-examples embed-editorial-registry build-search-index fingerprint prototypes check-generated: build check-social-cards - git diff --exit-code src/example_sources_data.py src/editorial_registry_data.py src/asset_manifest.py public/_headers public/prototyping public/search-index.json + git diff --exit-code src/example_sources_data.py src/editorial_registry_data.py src/asset_manifest.py public/_headers public/prototyping public/search-index.json public/editor.js public/highlighter.js # Tracked generated changes may be staged for commit; reject only untracked output here because git diff above already catches unstaged tracked drift. test -z "$$(git ls-files --others --exclude-standard -- public/prototyping public/*.css public/*.js public/*.json)" -fingerprint: embed-examples embed-editorial-registry build-search-index +# public/editor.js and public/highlighter.js are bundles of web/*.js plus the +# npm packages pinned in package-lock.json. Edit the sources in web/. +browser-bundles: node-deps + node scripts/build_browser_bundles.mjs + +fingerprint: embed-examples embed-editorial-registry build-search-index browser-bundles $(PY) scripts/fingerprint_assets.py prototypes: embed-examples @@ -46,6 +51,11 @@ prototypes: embed-examples browser-layout-test: scripts/check_browser_layout.mjs +# Run every example's complete program in the real sandbox (the local dev +# Worker) and compare with its expected output. +runtime-examples-test: + $(PY) scripts/check_runtime_examples.py + search-ranking-test: scripts/check_search_ranking.mjs @@ -92,9 +102,10 @@ score-example-criteria: check-quality-scores: $(PY) scripts/check_quality_scores.py -# Manual gate, not run in CI: fail while a quality waiver has 30 days or fewer -# left, so an expiry can be caught before it turns every pull request red. -# `make verify` (CI) already prints a warning inside the same 30-day window. +# Manual gate, not run in CI: fail while a time-boxed quality waiver has 30 +# days or fewer left, so an expiry can be caught before it turns every pull +# request red. `make verify` (CI) already prints a warning inside the same +# 30-day window. Waivers marked `permanent = true` have no date and are skipped. check-waiver-expiry: $(PY) scripts/check_quality_scores.py --fail-within-days 30 @@ -121,7 +132,7 @@ verify-python-version: build lint: uv run ruff check src tests scripts -verify: build test seo-cache-lint verify-examples quality-checks browser-layout-test search-ranking-test lint check-generated +verify: build test seo-cache-lint verify-examples quality-checks browser-layout-test runtime-examples-test search-ranking-test lint check-generated dev: node-deps uv run --group workers pywrangler dev --port 9696 diff --git a/README.md b/README.md index 5eaf19b..87937d4 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Production: (`workers.dev` is disabled so the - Learner-behavior reporting from Worker wide events (`docs/learner-analytics.md`) - A quality-gate suite for registries, rubric scores, coverage, and teaching structure that fails builds when content regresses - `/about` page describing the verification pipeline, runner sandbox, figure grammar, and live design tokens -- `/privacy` notice covering runner submissions, operational logs, Invisible Turnstile, cookies, and optional browser CDNs +- `/privacy` notice covering runner submissions, operational logs, Invisible Turnstile, cookies, and the self-hosted editor scripts - Copy buttons on read-only source cells - Keyboard prev/next navigation (`←`/`→`) on example pages - "Copy link" sharing of the runner's current code via `#code=` URLs @@ -125,6 +125,8 @@ git diff --check - Worker Cache API keys include the HTML version - prototype layout pages are not cached +`make runtime-examples-test` posts every example's complete program to the local Worker and compares what the sandbox prints with the expected output. + `make browser-layout-test` launches headless Chrome against the local Worker. It checks the rendered Shiki code-block layout so generated line markup does not create visual blank rows, drives the runner, sharing, copy, search and keyboard navigation through the page, and measures computed styles (pressed states, touch targets, contrast in both themes, marginalia figure colours against the grammar's `--fig-*` tokens, the reader's font size, reduced-transparency and more-contrast fallbacks) in place of unit tests that matched CSS text. ## Asset fingerprinting and cache busting @@ -138,6 +140,8 @@ public/editor.js public/runner.js ``` +`public/editor.js` and `public/highlighter.js` are bundles: their sources are `web/editor.js` and `web/highlighter.js`, built with the npm packages pinned in `package-lock.json`. + Before tests/deploy, regenerate embedded example data, fingerprinted asset copies, and Python manifests: ```bash @@ -185,7 +189,7 @@ make upgrade-runtime-deps make verify ``` -Dependabot proposes npm, GitHub Actions, and development-tool updates weekly. It skips runtime packages (their versions depend on which Pyodide wheels exist) and Ruff (upgrades are deliberate because they change lint rules). The browser libraries loaded from esm.sh are pinned in `public/editor.js` and `public/syntax-highlight.js` and are updated by hand. +Dependabot proposes npm, GitHub Actions, and development-tool updates weekly. It skips runtime packages (their versions depend on which Pyodide wheels exist) and Ruff (upgrades are deliberate because they change lint rules). The browser libraries (CodeMirror and Shiki) are npm dev dependencies pinned in `package-lock.json`; `make browser-bundles` bundles `web/editor.js` and `web/highlighter.js` into `public/`, so pages load no third-party CDN and Dependabot proposes their updates. ## Contributing @@ -229,8 +233,10 @@ footgun, notes, program/cell, prose-duplication, inline-link, scoring, figure, journey, and example-graph gates. `make check-waiver-expiry` is a manual check, not run in CI: it fails while -any quality waiver has 30 days or fewer left. `make quality-checks` (and so CI) -only prints a warning in that window, then fails once the waiver has expired. +any time-boxed quality waiver has 30 days or fewer left. `make quality-checks` +(and so CI) only prints a warning in that window, then fails once the waiver +has expired. A waiver whose reason is permanent sets `permanent = true` +instead of `expires` and is never date-checked; Hello World is the only one. `src/example_sources_data.py` is generated and committed so Cloudflare Workers can load examples in production. Do not edit it by hand. diff --git a/docs/elevation-strategy.md b/docs/elevation-strategy.md index a78b5bf..d1e547f 100644 --- a/docs/elevation-strategy.md +++ b/docs/elevation-strategy.md @@ -171,9 +171,6 @@ all aimed at the scorecard's engagement and return lines: assistants are now a first-class referrer of learners; being the cleanest citable source for "Python by example" queries is cheap and fully on-essence. -- **Feeds.** An Atom feed of new and substantially revised examples so - newsletters and aggregators can pick up changes without watching the - repo. - **Edit this page on GitHub.** A per-example source link converts readers into contributors (CONTRIBUTING and issue templates already exist) and is a further trust signal. @@ -210,7 +207,10 @@ all aimed at the scorecard's engagement and return lines: *(Both shipped 2026-07-10.)* 2. `/about` page + edit-on-GitHub links. *(`/about` shipped 2026-07-10; edit-on-GitHub links are still open.)* -3. `/llms.txt`, per-example Markdown endpoints, Atom feed. +3. `/llms.txt`, per-example Markdown endpoints. + *(Both shipped 2026-11-14. An Atom feed was dropped 2026-11-14: the + catalogue changes rarely, no source records per-example dates, and + reference pages are found by search, not subscribed to.)* 4. Search-console registration + the first weekly learner-report ritual. *(Google Search Console ownership verified 2026-07-10; sitemap submission waits on the next deploy.)* diff --git a/docs/example-quality-rubric.md b/docs/example-quality-rubric.md index aba63c1..1b753de 100644 --- a/docs/example-quality-rubric.md +++ b/docs/example-quality-rubric.md @@ -42,7 +42,7 @@ Quality bands: - **7.0-7.9**: serviceable tutorial material, not yet reference-grade. - **below 7.0**: rewrite before publishing. -Project gate (enforced by `scripts/check_quality_scores.py` against `docs/quality-registries.toml`): every shipped example targets **9.0**; anything below target needs a time-boxed waiver, and anything below the **8.5** hard minimum needs an improvement-backlog entry with a concrete next action. The catalog average should exceed sampled Go By Example and Rust By Example pages on craft and understandability. The score is a guide, not a substitute for reading the page. +Project gate (enforced by `scripts/check_quality_scores.py` against `docs/quality-registries.toml`): every shipped example targets **9.0**; anything below target needs a waiver (time-boxed with `expires`, or `permanent = true` when the reason cannot lapse, as for Hello World), and anything below the **8.5** hard minimum needs an improvement-backlog entry with a concrete next action. The catalog average should exceed sampled Go By Example and Rust By Example pages on craft and understandability. The score is a guide, not a substitute for reading the page. ## Weak-example smells diff --git a/docs/example-source-format-spec.md b/docs/example-source-format-spec.md index 0aab875..712b00f 100644 --- a/docs/example-source-format-spec.md +++ b/docs/example-source-format-spec.md @@ -213,6 +213,11 @@ Frontmatter fields beyond the navigation basics: - `expected_output` overrides the generated program output for environment-shaped pages whose real output the build environment cannot reproduce deterministically; the verifier still executes the program. +- `sandbox_limit` names what the in-browser sandbox lacks on a page that + teaches it anyway (for example `"child processes"` or `"sockets"`). When + Run fails on such a page the output starts by naming the limit, and + `make runtime-examples-test` expects that explanation instead of the + CPython output. - `standalone_cells = true` opts a page out of the program-covers-cells gate when it deliberately demonstrates code the editable program does not contain; the opt-out is reported on every run so it stays a visible diff --git a/docs/quality-registries.toml b/docs/quality-registries.toml index 1ba768b..2d3606b 100644 --- a/docs/quality-registries.toml +++ b/docs/quality-registries.toml @@ -191,10 +191,12 @@ example_hard_min = 8.5 journey_section_min = 8.5 journey_average_min = 8.8 +# A waiver is time-boxed with `expires = "YYYY-MM-DD"`. Use `permanent = true` +# (and no `expires`) only when the reason can never stop being true. [quality_waivers.hello-world] accepted_min = 7.0 reason = "Traditional first example is intentionally tiny: program -> output is the goal, not a full concept tour." -expires = "2026-12-01" +permanent = true [no_figure_rationales] # Slugs may be added here only when the page is constraint-shaped, @@ -387,6 +389,7 @@ journey = "shapes" section = "Cross text and data boundaries." support = [ "number-parsing", + "files-and-pathlib", "json", "regular-expressions", "datetime", @@ -906,6 +909,11 @@ kind = "example" value = "number-parsing" description = "turn text into numbers safely" +[[journeys.sections.items]] +kind = "example" +value = "files-and-pathlib" +description = "read and write text files through `Path` objects" + [[journeys.sections.items]] kind = "example" value = "json" @@ -1664,7 +1672,7 @@ caption = "Both objects hold the same two bytes as integers; b\"py\" cannot chan slug = "sentinel-iteration" anchor = "cell-0" figure = "sentinel-iteration" -caption = "iter(read_chunk, \"\") keeps calling read_chunk and yields \"py\" and \"thon\"; the empty string is the sentinel, so it stops the loop and is never yielded." +caption = "iter(queue.popleft, \"\") keeps calling queue.popleft and yields \"py\" and \"thon\"; the empty string is the sentinel, so it stops the loop and is never yielded." [[figure_attachments]] slug = "partial-functions" @@ -1738,6 +1746,12 @@ anchor = "cell-0" figure = "datetime-instant" caption = "An aware datetime carries a UTC offset; one instant in time reads differently on two clocks." +[[figure_attachments]] +slug = "files-and-pathlib" +anchor = "cell-0" +figure = "path-tree" +caption = "Each `Path` names one place in the directory tree; `/` steps down one level per name." + [[figure_attachments]] slug = "json" anchor = "cell-0" @@ -2401,6 +2415,11 @@ slug = "regular-expressions" score = 9.0 comment = "the cell's pattern with both capture groups dropped onto Ada: 10; one-move 0.75 and restraint 0.75 for two rows plus two drops; 1.5/1/0.75/1/1 · 1/1/0.75 · 1/0.5" +[[example_figure_scores]] +slug = "files-and-pathlib" +score = 9.0 +comment = "the page's own tree with the two paths the cells build; containment hairlines, dashed path-to-place links, no accent" + [[example_figure_scores]] slug = "json" score = 9.0 @@ -2584,7 +2603,7 @@ comment = "the example's two bytes as integer slots, packet[0] rewritten in plac [[example_figure_scores]] slug = "sentinel-iteration" score = 9.0 -comment = "the cell's read_chunk and chunks; the empty string ghosted as the sentinel; earns-place 0.75, the output already omits it; 1.5/0.75/1/1/1 · 1/1/1 · 1/0.5" +comment = "the cell's queue.popleft call and queued chunks; the empty string ghosted as the sentinel; earns-place 0.75, the output already omits it; 1.5/0.75/1/1/1 · 1/1/1 · 1/0.5" [[example_figure_scores]] slug = "partial-functions" @@ -3298,6 +3317,11 @@ slug = "custom-exceptions" score = 9.0 comment = "domain error naming, raise point, recovery boundary" +[[example_quality_scores]] +slug = "files-and-pathlib" +score = 9.0 +comment = "path vs file distinction, whole-file and line-by-line reading, directory listing, missing-file boundary; all cells run in the sandbox" + [[example_quality_scores]] slug = "json" score = 9.0 diff --git a/docs/quality-search.md b/docs/quality-search.md index 8870a42..dae688d 100644 --- a/docs/quality-search.md +++ b/docs/quality-search.md @@ -5,7 +5,7 @@ Python By Example now has two complementary scoring loops: 1. `scripts/check_quality_scores.py` is the editorial gate. It enforces the curated score registry, hard-minimum waivers, stale backlog cleanup, weak journey-section tracking, and the 10-point rubric weight model. 2. `scripts/score_example_criteria.py` is the search aid. It breaks each page into rubric criteria so rewrite work can target the weakest axis instead of treating the score as one opaque number. -The criterion report is deliberately heuristic. It should suggest candidates, not replace editorial review. +The criterion report is deliberately heuristic. It should suggest candidates, not replace editorial review. Accuracy and practical usefulness are not observable from page text, so those two criteria only penalise metasyntactic names (`foo`, `spam`) and are capped below full marks; they award nothing for surface tokens such as `print(` or domain-sounding identifiers. ## Hill-climbing move types diff --git a/package-lock.json b/package-lock.json index 6f40882..aaa3f69 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6,6 +6,15 @@ "": { "name": "pythonbyexample-tooling", "devDependencies": { + "@codemirror/autocomplete": "6.20.4", + "@codemirror/commands": "6.11.1", + "@codemirror/lang-python": "6.2.1", + "@codemirror/language": "6.12.4", + "@codemirror/state": "6.7.6", + "@codemirror/theme-one-dark": "6.1.3", + "@codemirror/view": "6.43.13", + "esbuild": "0.25.12", + "shiki": "4.4.3", "wrangler": "4.158.0" }, "engines": { @@ -123,6 +132,97 @@ "node": ">=16" } }, + "node_modules/@codemirror/autocomplete": { + "version": "6.20.4", + "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.4.tgz", + "integrity": "sha512-yF8RhOf2SXlg00+qtupzLhrglcas61boqaONiNcbPIebHCpJocpqTBA6dyrtUrQO47hqyTdeob/3XnYilT7TaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.17.0", + "@lezer/common": "^1.0.0" + } + }, + "node_modules/@codemirror/commands": { + "version": "6.11.1", + "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.11.1.tgz", + "integrity": "sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.7.0", + "@codemirror/view": "^6.27.0", + "@lezer/common": "^1.1.0" + } + }, + "node_modules/@codemirror/lang-python": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/@codemirror/lang-python/-/lang-python-6.2.1.tgz", + "integrity": "sha512-IRjC8RUBhn9mGR9ywecNhB51yePWCGgvHfY1lWN/Mrp3cKuHr0isDKia+9HnvhiWNnMpbGhWrkhuWOc09exRyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@codemirror/autocomplete": "^6.3.2", + "@codemirror/language": "^6.8.0", + "@codemirror/state": "^6.0.0", + "@lezer/common": "^1.2.1", + "@lezer/python": "^1.1.4" + } + }, + "node_modules/@codemirror/language": { + "version": "6.12.4", + "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.4.tgz", + "integrity": "sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.23.0", + "@lezer/common": "^1.5.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0", + "style-mod": "^4.0.0" + } + }, + "node_modules/@codemirror/state": { + "version": "6.7.6", + "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.6.tgz", + "integrity": "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@marijn/find-cluster-break": "^1.0.0" + } + }, + "node_modules/@codemirror/theme-one-dark": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/@codemirror/theme-one-dark/-/theme-one-dark-6.1.3.tgz", + "integrity": "sha512-NzBdIvEJmx6fjeremiGp3t/okrLPYT0d9orIc7AFun8oZcRk58aejkqhv6spnz4MLAevrKNPMQYXEWMg4s+sKA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0", + "@lezer/highlight": "^1.0.0" + } + }, + "node_modules/@codemirror/view": { + "version": "6.43.13", + "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.13.tgz", + "integrity": "sha512-sihaFrUzAsYBQsL9J2t69y8nfMQGwcYmggAZsk+kjPbjYZMyuf2hU8tUNTZ+P+isb6XRr8JE22TZlJxBoVdH1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.7.0", + "crelt": "^1.0.6", + "style-mod": "^4.1.0", + "w3c-keyname": "^2.2.4" + } + }, "node_modules/@cspotcode/source-map-support": { "version": "0.8.1", "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", @@ -148,9 +248,9 @@ } }, "node_modules/@esbuild/aix-ppc64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", - "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", "cpu": [ "ppc64" ], @@ -165,9 +265,9 @@ } }, "node_modules/@esbuild/android-arm": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", - "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", "cpu": [ "arm" ], @@ -182,9 +282,9 @@ } }, "node_modules/@esbuild/android-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", - "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", "cpu": [ "arm64" ], @@ -199,9 +299,9 @@ } }, "node_modules/@esbuild/android-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", - "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", "cpu": [ "x64" ], @@ -216,9 +316,9 @@ } }, "node_modules/@esbuild/darwin-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", - "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", "cpu": [ "arm64" ], @@ -233,9 +333,9 @@ } }, "node_modules/@esbuild/darwin-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", - "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", "cpu": [ "x64" ], @@ -250,9 +350,9 @@ } }, "node_modules/@esbuild/freebsd-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", - "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", "cpu": [ "arm64" ], @@ -267,9 +367,9 @@ } }, "node_modules/@esbuild/freebsd-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", - "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", "cpu": [ "x64" ], @@ -284,9 +384,9 @@ } }, "node_modules/@esbuild/linux-arm": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", - "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", "cpu": [ "arm" ], @@ -301,9 +401,9 @@ } }, "node_modules/@esbuild/linux-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", - "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", "cpu": [ "arm64" ], @@ -318,9 +418,9 @@ } }, "node_modules/@esbuild/linux-ia32": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", - "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", "cpu": [ "ia32" ], @@ -335,9 +435,9 @@ } }, "node_modules/@esbuild/linux-loong64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", - "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", "cpu": [ "loong64" ], @@ -352,9 +452,9 @@ } }, "node_modules/@esbuild/linux-mips64el": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", - "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", "cpu": [ "mips64el" ], @@ -369,9 +469,9 @@ } }, "node_modules/@esbuild/linux-ppc64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", - "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", "cpu": [ "ppc64" ], @@ -386,9 +486,9 @@ } }, "node_modules/@esbuild/linux-riscv64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", - "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", "cpu": [ "riscv64" ], @@ -403,9 +503,9 @@ } }, "node_modules/@esbuild/linux-s390x": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", - "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", "cpu": [ "s390x" ], @@ -420,9 +520,9 @@ } }, "node_modules/@esbuild/linux-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", - "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", "cpu": [ "x64" ], @@ -437,9 +537,9 @@ } }, "node_modules/@esbuild/netbsd-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", - "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", "cpu": [ "arm64" ], @@ -454,9 +554,9 @@ } }, "node_modules/@esbuild/netbsd-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", - "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", "cpu": [ "x64" ], @@ -471,9 +571,9 @@ } }, "node_modules/@esbuild/openbsd-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", - "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", "cpu": [ "arm64" ], @@ -488,9 +588,9 @@ } }, "node_modules/@esbuild/openbsd-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", - "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", "cpu": [ "x64" ], @@ -505,9 +605,9 @@ } }, "node_modules/@esbuild/openharmony-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", - "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", "cpu": [ "arm64" ], @@ -522,9 +622,9 @@ } }, "node_modules/@esbuild/sunos-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", - "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", "cpu": [ "x64" ], @@ -539,9 +639,9 @@ } }, "node_modules/@esbuild/win32-arm64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", - "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", "cpu": [ "arm64" ], @@ -556,9 +656,9 @@ } }, "node_modules/@esbuild/win32-ia32": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", - "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", "cpu": [ "ia32" ], @@ -573,9 +673,9 @@ } }, "node_modules/@esbuild/win32-x64": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", - "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", "cpu": [ "x64" ], @@ -1144,6 +1244,52 @@ "@jridgewell/sourcemap-codec": "^1.4.10" } }, + "node_modules/@lezer/common": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.5.tgz", + "integrity": "sha512-Pw7PVCndruF1pb3ebCxpSVpkMHSDjwRCLcTRw+RizUKco5QbWylwq2g4lnG/RYN7yTTQDXE9F77MwtkAyphrjg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@lezer/highlight": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.5.tgz", + "integrity": "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.3.0" + } + }, + "node_modules/@lezer/lr": { + "version": "1.4.12", + "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.12.tgz", + "integrity": "sha512-On9HU4oMMiHPMkQDgoTnGahjgG5n/MkN38CgG77sMraKLL+3JBbeQNi1FcCXV9QRqwF9/BUXP3caHyJC1fBOTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.0.0" + } + }, + "node_modules/@lezer/python": { + "version": "1.1.19", + "resolved": "https://registry.npmjs.org/@lezer/python/-/python-1.1.19.tgz", + "integrity": "sha512-MhQIURHRytsNzP/YXnqpYKW6la6voAH3kyplTOOiCdjyFY6cWWGFVmYVdHIPrElqSDf4iCDktQCockB9FxuhzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" + } + }, + "node_modules/@marijn/find-cluster-break": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz", + "integrity": "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@poppinss/colors": { "version": "4.1.6", "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz", @@ -1173,6 +1319,114 @@ "dev": true, "license": "MIT" }, + "node_modules/@shikijs/core": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-4.4.3.tgz", + "integrity": "sha512-QCR4q2ZO/ILJEuwiBMel4wdcTDb1JGwfjKTxPDF6x8ixOaluPrVqIn06C99AcRPhmYlBR56d/Fb+GN58GzExpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/primitive": "4.4.3", + "@shikijs/types": "4.4.3", + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.5", + "hast-util-to-html": "^9.0.5" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/engine-javascript": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-4.4.3.tgz", + "integrity": "sha512-FbOjFJp9VLdo1Wevs10BBtVxiTWwNLqZh5Gkhjgda/ioL15YOgeSl9n+6XMa3qRlPQzfhFNe641SrynFHYG0nQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.4.3", + "@shikijs/vscode-textmate": "^10.0.2", + "oniguruma-to-es": "^4.3.6" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/engine-oniguruma": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-4.4.3.tgz", + "integrity": "sha512-EcOQkxdxGQrc1Row/cC2c96/v1dbZqGnEVu1qTuT/MJmp6+cXCvQussowVmCv5Tqr3KuY3c7IbM6HTW3LJ1k9w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.4.3", + "@shikijs/vscode-textmate": "^10.0.2" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/langs": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-4.4.3.tgz", + "integrity": "sha512-ePic0yfAJGOF83D5wBHK/00EjK65oahBYxFk5epgq33WRv7X9UuxLEV8PtR0szC0z8dl7INIpIodB99JRFlR+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.4.3" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/primitive": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/@shikijs/primitive/-/primitive-4.4.3.tgz", + "integrity": "sha512-m0wBeLDQDeIxRdUmrCPdQqfuUamDwRL5isCfYbguKD6NiaKpVbsv+3J81DyIKgNW5h4WAIIr8T4EkgQrBBxvaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.4.3", + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.5" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/themes": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-4.4.3.tgz", + "integrity": "sha512-w8UHjeUnIR965KMWJHUPXOc2mNJUnK3vpVLYLvw5IYU2mnTTJ89E24OrJDBNiJDQ0qzb0tc4l7mrIXx5cFeIyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "4.4.3" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/types": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-4.4.3.tgz", + "integrity": "sha512-UEJxmRR++MAGR6hugn0vgVS2W/6lWAts84FFSrnlH9sP0LNol7E5+NQ792pH8liWUhyMyjhTgSUH3k7iD7tc5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.5" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/vscode-textmate": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.1.0.tgz", + "integrity": "sha512-cVBuhDQjBZaNMTwBquYfPydrUP+E3hE6oYGasx8h6ZrODIM7/r+gxLDXdd66oszbrggZHEntdE6j+5gYIVyMWQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@sindresorhus/is": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz", @@ -1193,6 +1447,40 @@ "dev": true, "license": "CC0-1.0" }, + "node_modules/@types/hast": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.5.tgz", + "integrity": "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/mdast": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", + "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@ungap/structured-clone": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.4.0.tgz", + "integrity": "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==", + "dev": true, + "license": "ISC" + }, "node_modules/blake3-wasm": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz", @@ -1200,6 +1488,50 @@ "dev": true, "license": "MIT" }, + "node_modules/ccount": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", + "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-html4": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", + "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-legacy": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", + "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/comma-separated-tokens": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", + "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/cookie": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", @@ -1214,6 +1546,23 @@ "url": "https://opencollective.com/express" } }, + "node_modules/crelt": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz", + "integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==", + "dev": true, + "license": "MIT" + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -1224,6 +1573,20 @@ "node": ">=8" } }, + "node_modules/devlop": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", + "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", + "dev": true, + "license": "MIT", + "dependencies": { + "dequal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/error-stack-parser-es": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz", @@ -1235,9 +1598,9 @@ } }, "node_modules/esbuild": { - "version": "0.28.2", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", - "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", "dev": true, "hasInstallScript": true, "license": "MIT", @@ -1248,32 +1611,32 @@ "node": ">=18" }, "optionalDependencies": { - "@esbuild/aix-ppc64": "0.28.2", - "@esbuild/android-arm": "0.28.2", - "@esbuild/android-arm64": "0.28.2", - "@esbuild/android-x64": "0.28.2", - "@esbuild/darwin-arm64": "0.28.2", - "@esbuild/darwin-x64": "0.28.2", - "@esbuild/freebsd-arm64": "0.28.2", - "@esbuild/freebsd-x64": "0.28.2", - "@esbuild/linux-arm": "0.28.2", - "@esbuild/linux-arm64": "0.28.2", - "@esbuild/linux-ia32": "0.28.2", - "@esbuild/linux-loong64": "0.28.2", - "@esbuild/linux-mips64el": "0.28.2", - "@esbuild/linux-ppc64": "0.28.2", - "@esbuild/linux-riscv64": "0.28.2", - "@esbuild/linux-s390x": "0.28.2", - "@esbuild/linux-x64": "0.28.2", - "@esbuild/netbsd-arm64": "0.28.2", - "@esbuild/netbsd-x64": "0.28.2", - "@esbuild/openbsd-arm64": "0.28.2", - "@esbuild/openbsd-x64": "0.28.2", - "@esbuild/openharmony-arm64": "0.28.2", - "@esbuild/sunos-x64": "0.28.2", - "@esbuild/win32-arm64": "0.28.2", - "@esbuild/win32-ia32": "0.28.2", - "@esbuild/win32-x64": "0.28.2" + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" } }, "node_modules/fsevents": { @@ -1291,6 +1654,55 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/hast-util-to-html": { + "version": "9.0.6", + "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.6.tgz", + "integrity": "sha512-1SZUxCN3TtJAE7e2BQN2MBHsoZ1gnmi9GoCP5Di59CSWptIezSAW09yDZyVbanb78V9eCwrKqdQsjtfVTxYHWA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "ccount": "^2.0.0", + "comma-separated-tokens": "^2.0.0", + "hast-util-whitespace": "^3.0.0", + "html-void-elements": "^3.0.0", + "mdast-util-to-hast": "^13.0.0", + "property-information": "^7.0.0", + "space-separated-tokens": "^2.0.0", + "stringify-entities": "^4.0.0", + "zwitch": "^2.0.4" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-whitespace": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", + "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/html-void-elements": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz", + "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/kleur": { "version": "4.1.5", "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", @@ -1301,6 +1713,122 @@ "node": ">=6" } }, + "node_modules/mdast-util-to-hast": { + "version": "13.2.2", + "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.2.tgz", + "integrity": "sha512-l2pnmOuqs+SGLVpTVXnRLQu5v1AzvDe181404fbXzzqObVxrAnnVxapAP27pUwzLBL/ABIkgUhGlPVU7QSvIFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/mdast": "^4.0.0", + "@ungap/structured-clone": "^1.0.0", + "devlop": "^1.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "trim-lines": "^3.0.0", + "unist-util-position": "^5.0.0", + "unist-util-visit": "^5.0.0", + "vfile": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-util-character": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", + "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-encode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", + "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-sanitize-uri": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", + "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-symbol": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", + "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-types": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.3.tgz", + "integrity": "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, "node_modules/miniflare": { "version": "5.20261104.0-beta", "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261104.0-beta.tgz", @@ -1319,6 +1847,25 @@ "node": ">=22.0.0" } }, + "node_modules/oniguruma-parser": { + "version": "0.12.2", + "resolved": "https://registry.npmjs.org/oniguruma-parser/-/oniguruma-parser-0.12.2.tgz", + "integrity": "sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw==", + "dev": true, + "license": "MIT" + }, + "node_modules/oniguruma-to-es": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-4.3.6.tgz", + "integrity": "sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==", + "dev": true, + "license": "MIT", + "dependencies": { + "oniguruma-parser": "^0.12.2", + "regex": "^6.1.0", + "regex-recursion": "^6.0.2" + } + }, "node_modules/path-to-regexp": { "version": "6.3.0", "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz", @@ -1333,6 +1880,44 @@ "dev": true, "license": "MIT" }, + "node_modules/property-information": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.2.0.tgz", + "integrity": "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/regex/-/regex-6.1.0.tgz", + "integrity": "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg==", + "dev": true, + "license": "MIT", + "dependencies": { + "regex-utilities": "^2.3.0" + } + }, + "node_modules/regex-recursion": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz", + "integrity": "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==", + "dev": true, + "license": "MIT", + "dependencies": { + "regex-utilities": "^2.3.0" + } + }, + "node_modules/regex-utilities": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz", + "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==", + "dev": true, + "license": "MIT" + }, "node_modules/semver": { "version": "7.8.6", "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", @@ -1396,6 +1981,59 @@ } } }, + "node_modules/shiki": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/shiki/-/shiki-4.4.3.tgz", + "integrity": "sha512-Mb/GvXPHBAXdgGIcnfU5L3ldpn1XcxrGkPHwqgRx17/I2XRfqlFKk2vGkHWINn1kdXvzJZeuO3is6I9KLPFm0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/core": "4.4.3", + "@shikijs/engine-javascript": "4.4.3", + "@shikijs/engine-oniguruma": "4.4.3", + "@shikijs/langs": "4.4.3", + "@shikijs/themes": "4.4.3", + "@shikijs/types": "4.4.3", + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.5" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/space-separated-tokens": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", + "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/stringify-entities": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", + "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==", + "dev": true, + "license": "MIT", + "dependencies": { + "character-entities-html4": "^2.0.0", + "character-entities-legacy": "^3.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/style-mod": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.4.tgz", + "integrity": "sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==", + "dev": true, + "license": "MIT" + }, "node_modules/supports-color": { "version": "10.2.2", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz", @@ -1409,6 +2047,17 @@ "url": "https://github.com/chalk/supports-color?sponsor=1" } }, + "node_modules/trim-lines": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", + "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/tslib": { "version": "2.9.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", @@ -1437,6 +2086,116 @@ "pathe": "^2.0.3" } }, + "node_modules/unist-util-is": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz", + "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-position": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz", + "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-stringify-position": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", + "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.2.0.tgz", + "integrity": "sha512-fpsYs/VVoZxfGY9/j3FQpZmN8wdLJaV1Pt38AaJNZu9uKIHcFU3halCdBveEq1HGKO1OEfJY65w1zvoFV1b3qQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0", + "unist-util-visit-parents": "^6.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/unist-util-visit-parents": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.1.0.tgz", + "integrity": "sha512-vKXxz6O38sKDj1mtx/k2cWvkkFBuYGx6uGrlzBkVeWCRF/F8sdI0j3Wbkz/5rVNRRuVc8UrgRdbCxNhmYXgP3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-is": "^6.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", + "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "vfile-message": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/vfile-message": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.4.tgz", + "integrity": "sha512-66ycRswIkNmHH9PHku7ADtv5RVwgIrOcuv3J8Svz6h4qgGRrKVa+9/neuKyJZUXyOpYwLTvS+whZ4R2urHHgQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/unist": "^3.0.0", + "unist-util-stringify-position": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/w3c-keyname": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz", + "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==", + "dev": true, + "license": "MIT" + }, "node_modules/workerd": { "version": "1.20261104.1", "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20261104.1.tgz", @@ -1495,51 +2254,546 @@ } } }, - "node_modules/ws": { - "version": "8.21.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", - "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "node_modules/wrangler/node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], "dev": true, "license": "MIT", + "optional": true, + "os": [ + "aix" + ], "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } + "node": ">=18" } }, - "node_modules/youch": { - "version": "4.1.0-beta.10", - "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz", - "integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==", + "node_modules/wrangler/node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], "dev": true, "license": "MIT", - "dependencies": { - "@poppinss/colors": "^4.1.5", - "@poppinss/dumper": "^0.6.4", - "@speed-highlight/core": "^1.2.7", - "cookie": "^1.0.2", - "youch-core": "^0.3.3" + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" } }, - "node_modules/youch-core": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz", - "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==", + "node_modules/wrangler/node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], "dev": true, "license": "MIT", - "dependencies": { - "@poppinss/exception": "^1.2.2", - "error-stack-parser-es": "^1.0.5" + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/wrangler/node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/youch": { + "version": "4.1.0-beta.10", + "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz", + "integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/colors": "^4.1.5", + "@poppinss/dumper": "^0.6.4", + "@speed-highlight/core": "^1.2.7", + "cookie": "^1.0.2", + "youch-core": "^0.3.3" + } + }, + "node_modules/youch-core": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz", + "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@poppinss/exception": "^1.2.2", + "error-stack-parser-es": "^1.0.5" + } + }, + "node_modules/zwitch": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", + "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" } } } diff --git a/package.json b/package.json index 0a2ee18..0b65178 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,15 @@ "node": "22.x" }, "devDependencies": { + "@codemirror/autocomplete": "6.20.4", + "@codemirror/commands": "6.11.1", + "@codemirror/lang-python": "6.2.1", + "@codemirror/language": "6.12.4", + "@codemirror/state": "6.7.6", + "@codemirror/theme-one-dark": "6.1.3", + "@codemirror/view": "6.43.13", + "esbuild": "0.25.12", + "shiki": "4.4.3", "wrangler": "4.158.0" } } diff --git a/public/_headers b/public/_headers index 5ef8803..2514e87 100644 --- a/public/_headers +++ b/public/_headers @@ -3,7 +3,7 @@ Referrer-Policy: strict-origin-when-cross-origin X-Frame-Options: DENY Strict-Transport-Security: max-age=31536000; includeSubDomains; preload - Content-Security-Policy: default-src 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; img-src 'self' data:; font-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' https://esm.sh https://challenges.cloudflare.com 'wasm-unsafe-eval'; script-src-attr 'none'; connect-src 'self' https://esm.sh https://challenges.cloudflare.com; frame-src https://challenges.cloudflare.com; worker-src 'self' + Content-Security-Policy: default-src 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; img-src 'self' data:; font-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' https://challenges.cloudflare.com; script-src-attr 'none'; connect-src 'self' https://challenges.cloudflare.com; frame-src https://challenges.cloudflare.com; worker-src 'self' /site.*.css Cache-Control: public, max-age=31536000, immutable @@ -11,6 +11,9 @@ /syntax-highlight.*.js Cache-Control: public, max-age=31536000, immutable +/highlighter.*.js + Cache-Control: public, max-age=31536000, immutable + /editor.*.js Cache-Control: public, max-age=31536000, immutable diff --git a/public/editor.d656e57507ca.js b/public/editor.d656e57507ca.js new file mode 100644 index 0000000..41f95e1 --- /dev/null +++ b/public/editor.d656e57507ca.js @@ -0,0 +1,12 @@ +var gs=[],Uo=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Uo[i])e=i+1;else return!0;if(e==t)return!1}}function Fo(n){return n>=127462&&n<=127487}var _o=8205;function jo(n,e,t=!0,i=!0){return(t?Go:Kf)(n,e,i)}function Go(n,e,t){if(e==n.length)return e;e&&Zo(n.charCodeAt(e))&&Yo(n.charCodeAt(e-1))&&e--;let i=ms(n,e);for(e+=Ho(i);e=0&&Fo(ms(n,o));)r++,o-=2;if(r%2==0)break;e+=2}else break}return e}function Kf(n,e,t){for(;e>1;){let i=Go(n,e-2,t);if(i=56320&&n<57344}function Yo(n){return n>=55296&&n<56320}function Ho(n){return n<65536?1:2}var M=class n{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=Ut(this,e,t);let s=[];return this.decompose(0,e,s,2),i.length&&i.decompose(0,i.length,s,3),this.decompose(t,this.length,s,1),Ft.from(s,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=Ut(this,e,t);let i=[];return this.decompose(e,t,i,0),Ft.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),s=new wt(this),r=new wt(e);for(let o=t,l=t;;){if(s.next(o),r.next(o),o=0,s.lineBreak!=r.lineBreak||s.done!=r.done||s.value!=r.value)return!1;if(l+=s.value.length,s.done||l>=i)return!0}}iter(e=1){return new wt(this,e)}iterRange(e,t=this.length){return new on(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let s=this.line(e).from;i=this.iterRange(s,Math.max(s,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new ln(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?n.empty:e.length<=32?new de(e):Ft.from(de.split(e,[]))}},de=class n extends M{constructor(e,t=Jf(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.text[r],l=s+o.length;if((t?i:l)>=e)return new ys(s,l,i,o);s=l+1,i++}}decompose(e,t,i,s){let r=e<=0&&t>=this.length?this:new n(Ko(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(s&1){let o=i.pop(),l=rn(r.text,o.text.slice(),0,r.length);if(l.length<=32)i.push(new n(l,o.length+r.length));else{let a=l.length>>1;i.push(new n(l.slice(0,a)),new n(l.slice(a)))}}else i.push(r)}replace(e,t,i){if(!(i instanceof n))return super.replace(e,t,i);[e,t]=Ut(this,e,t);let s=rn(this.text,rn(i.text,Ko(this.text,0,e)),t),r=this.length+i.length-(t-e);return s.length<=32?new n(s,r):Ft.from(n.split(s,[]),r)}sliceString(e,t=this.length,i=` +`){[e,t]=Ut(this,e,t);let s="";for(let r=0,o=0;r<=t&&oe&&o&&(s+=i),er&&(s+=l.slice(Math.max(0,e-r),t-r)),r=a+1}return s}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],s=-1;for(let r of e)i.push(r),s+=r.length+1,i.length==32&&(t.push(new n(i,s)),i=[],s=-1);return s>-1&&t.push(new n(i,s)),t}},Ft=class n extends M{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.children[r],l=s+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,s);s=l+1,i=a+1}}decompose(e,t,i,s){for(let r=0,o=0;o<=t&&r=o){let h=s&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=Ut(this,e,t),i.lines=r&&t<=l){let a=o.replace(e-r,t-r,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let f=this.children.slice();return f[s]=a,new n(f,this.length-(t-e)+i.length)}return super.replace(r,l,a)}r=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` +`){[e,t]=Ut(this,e,t);let s="";for(let r=0,o=0;re&&r&&(s+=i),eo&&(s+=l.sliceString(e-o,t-o,i)),o=a+1}return s}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof n))return 0;let i=0,[s,r,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;s+=t,r+=t){if(s==o||r==l)return i;let a=this.children[s],h=e.children[r];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,s)=>i+s.length+1,-1)){let i=0;for(let d of e)i+=d.lines;if(i<32){let d=[];for(let p of e)p.flatten(d);return new de(d,t)}let s=Math.max(32,i>>5),r=s<<1,o=s>>1,l=[],a=0,h=-1,f=[];function c(d){let p;if(d.lines>r&&d instanceof n)for(let m of d.children)c(m);else d.lines>o&&(a>o||!a)?(u(),l.push(d)):d instanceof de&&a&&(p=f[f.length-1])instanceof de&&d.lines+p.lines<=32?(a+=d.lines,h+=d.length+1,f[f.length-1]=new de(p.text.concat(d.text),p.length+1+d.length)):(a+d.lines>s&&u(),a+=d.lines,h+=d.length+1,f.push(d))}function u(){a!=0&&(l.push(f.length==1?f[0]:n.from(f,h)),h=-1,a=f.length=0)}for(let d of e)c(d);return u(),l.length==1?l[0]:new n(l,t)}};M.empty=new de([""],0);function Jf(n){let e=-1;for(let t of n)e+=t.length+1;return e}function rn(n,e,t=0,i=1e9){for(let s=0,r=0,o=!0;r=t&&(a>i&&(l=l.slice(0,i-s)),s0?1:(e instanceof de?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,s=this.nodes[i],r=this.offsets[i],o=r>>1,l=s instanceof de?s.text.length:s.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((r&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` +`,this;e--}else if(s instanceof de){let a=s.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=s.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof de?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},on=class{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new wt(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:s}=this.cursor.next(e);return this.pos+=(s.length+e)*t,this.value=s.length<=i?s:t<0?s.slice(s.length-i):s.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}},ln=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:s}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=s,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<"u"&&(M.prototype[Symbol.iterator]=function(){return this.iter()},wt.prototype[Symbol.iterator]=on.prototype[Symbol.iterator]=ln.prototype[Symbol.iterator]=function(){return this});var ys=class{constructor(e,t,i,s){this.from=e,this.to=t,this.number=i,this.text=s}get length(){return this.to-this.from}};function Ut(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function K(n,e,t=!0,i=!0){return jo(n,e,t,i)}function ec(n){return n>=56320&&n<57344}function tc(n){return n>=55296&&n<56320}function lt(n,e){let t=n.charCodeAt(e);if(!tc(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return ec(i)?(t-55296<<10)+(i-56320)+65536:t}function nl(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Gt(n){return n<65536?1:2}var bs=/\r\n?|\n/,Y=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(Y||(Y={})),Ue=class n{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return r+(e-s);r+=l}else{if(i!=Y.Simple&&h>=e&&(i==Y.TrackDel&&se||i==Y.TrackBefore&&se))return null;if(h>e||h==e&&t<0&&!l)return e==s||t<0?r:r+a;r+=a}s=h}if(e>s)throw new RangeError(`Position ${e} is out of range for changeset of length ${s}`);return r}touchesRange(e,t=e){for(let i=0,s=0;i=0&&s<=t&&l>=e)return st?"cover":!0;s=l}return!1}toString(){let e="";for(let t=0;t=0?":"+s:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new n(e)}static create(e){return new n(e)}},oe=class n extends Ue{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ss(this,(t,i,s,r,o)=>e=e.replace(s,s+(i-t),o),!1),e}mapDesc(e,t=!1){return xs(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let s=0,r=0;s=0){t[s]=l,t[s+1]=o;let a=s>>1;for(;i.length0&&rt(i,t,r.text),r.forward(f),l+=f}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let s=[],r=[],o=0,l=null;function a(f=!1){if(!f&&!s.length)return;ou||c<0||u>t)throw new RangeError(`Invalid change range ${c} to ${u} (in doc of length ${t})`);let p=d?typeof d=="string"?M.of(d.split(i||bs)):d:M.empty,m=p.length;if(c==u&&m==0)return;co&&te(s,c-o,-1),te(s,u-c,m),rt(r,s,p),o=u}}return h(e),a(!l),l}static empty(e){return new n(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let s=0;sl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(r.length==1)t.push(r[0],0);else{for(;i.length=0&&t<=0&&t==n[s+1]?n[s]+=e:s>=0&&e==0&&n[s]==0?n[s+1]+=t:i?(n[s]+=e,n[s+1]+=t):n.push(e,t)}function rt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(s,h,r,f,c),s=h,r=f}}}function xs(n,e,t,i=!1){let s=[],r=i?[]:null,o=new vt(n),l=new vt(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);te(s,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,f=o.len;for(;f;)if(l.ins==-1){let c=Math.min(f,l.len);h+=c,f-=c,l.forward(c)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),r.forward2(a),o.forward(a)}}}}var vt=class{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?M.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?M.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}},St=class n{constructor(e,t,i,s){this.from=e,this.to=t,this.flags=i,this.goalColumn=s}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,s;return this.empty?i=s=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),s=e.mapPos(this.to,-1)),i==this.from&&s==this.to?this:new n(i,s,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return b.range(e,t,void 0,void 0,i);let s=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return b.range(this.anchor,s,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return b.range(e.anchor,e.head)}static create(e,t,i,s){return new n(e,t,i,s)}},b=class n{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:n.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new n(e.ranges.map(t=>St.fromJSON(t)),e.main)}static single(e,t=e){return new n([n.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,s=0;ss.from-r.from),t=e.indexOf(i);for(let s=1;sr.head?n.range(a,l):n.range(l,a))}}return new n(e,t)}};function rl(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}var Ms=0,v=class n{constructor(e,t,i,s,r){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=s,this.id=Ms++,this.default=e([]),this.extensions=typeof r=="function"?r(this):r}get reader(){return this}static define(e={}){return new n(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Es),!!e.static,e.enables)}of(e){return new _t([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new _t(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new _t(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}};function Es(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}var _t=class{constructor(e,t,i,s){this.dependencies=e,this.facet=t,this.type=i,this.value=s,this.id=Ms++}dynamicSlot(e){var t;let i=this.value,s=this.facet.compareInput,r=this.id,o=e[r]>>1,l=this.type==2,a=!1,h=!1,f=[];for(let c of this.dependencies)c=="doc"?a=!0:c=="selection"?h=!0:(((t=e[c.id])!==null&&t!==void 0?t:1)&1)==0&&f.push(e[c.id]);return{create(c){return c.values[o]=i(c),1},update(c,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||ks(c,f)){let d=i(c);if(l?!Jo(d,c.values[o],s):!s(d,c.values[o]))return c.values[o]=d,1}return 0},reconfigure:(c,u)=>{let d,p=u.config.address[r];if(p!=null){let m=fn(u,p);if(this.dependencies.every(O=>O instanceof v?u.facet(O)===c.facet(O):O instanceof he?u.field(O,!1)==c.field(O,!1):!0)||(l?Jo(d=i(c),m,s):s(d=i(c),m)))return c.values[o]=m,0}else d=i(c);return c.values[o]=d,1}}}get extension(){return this}};function Jo(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),s=t.map(a=>a.type),r=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let f=0;fi===s),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(tn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,s)=>{let r=i.values[t],o=this.updateF(r,s);return this.compareF(r,o)?0:(i.values[t]=o,1)},reconfigure:(i,s)=>{let r=i.facet(tn),o=s.facet(tn),l;return(l=r.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):s.config.address[this.id]!=null?(i.values[t]=s.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,tn.of({field:this,create:e})]}get extension(){return this}},xt={lowest:4,low:3,default:2,high:1,highest:0};function bi(n){return e=>new an(e,n)}var at={highest:bi(xt.highest),high:bi(xt.high),default:bi(xt.default),low:bi(xt.low),lowest:bi(xt.lowest)},an=class{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}},jt=class n{of(e){return new xi(this,e)}reconfigure(e){return n.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}},xi=class{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}},hn=class n{constructor(e,t,i,s,r,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=s,this.staticValues=r,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let s=[],r=Object.create(null),o=new Map;for(let u of nc(e,t,o))u instanceof he?s.push(u):(r[u.facet.id]||(r[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of s)l[u.id]=h.length<<1,h.push(d=>u.slot(d));let f=i?.config.facets;for(let u in r){let d=r[u],p=d[0].facet,m=f&&f[u]||[];if(d.every(O=>O.type==0))if(l[p.id]=a.length<<1|1,Es(m,d))a.push(i.facet(p));else{let O=p.combine(d.map(y=>y.value));a.push(i&&p.compare(O,i.facet(p))?i.facet(p):O)}else{for(let O of d)O.type==0?(l[O.id]=a.length<<1|1,a.push(O.value)):(l[O.id]=h.length<<1,h.push(y=>O.dynamicSlot(y)));l[p.id]=h.length<<1,h.push(O=>ic(O,p,d))}}let c=h.map(u=>u(l));return new n(e,o,c,l,a,r)}};function nc(n,e,t){let i=[[],[],[],[],[]],s=new Map;function r(o,l){let a=s.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof xi&&t.delete(o.compartment)}if(s.set(o,l),Array.isArray(o))for(let h of o)r(h,l);else if(o instanceof xi){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),r(h,l)}else if(o instanceof an)r(o.inner,o.prec);else if(o instanceof he)i[l].push(o),o.provides&&r(o.provides,l);else if(o instanceof _t)i[l].push(o),o.facet.extensions&&r(o.facet.extensions,xt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);r(h,l)}}return r(n,xt.default),i.reduce((o,l)=>o.concat(l))}function Si(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let s=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|s}function fn(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}var ol=v.define(),ws=v.define({combine:n=>n.some(e=>e),static:!0}),ll=v.define({combine:n=>n.length?n[0]:void 0,static:!0}),al=v.define(),hl=v.define(),fl=v.define(),cl=v.define({combine:n=>n.length?n[0]:!1}),fe=class{constructor(e,t){this.type=e,this.value=t}static define(){return new vs}},vs=class{of(e){return new fe(this,e)}},Ts=class{constructor(e){this.map=e}of(e){return new W(this,e)}},W=class n{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new n(this.type,t)}is(e){return this.type==e}static define(e={}){return new Ts(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let s of e){let r=s.map(t);r&&i.push(r)}return i}};W.reconfigure=W.define();W.appendConfig=W.define();var G=class n{constructor(e,t,i,s,r,o){this.startState=e,this.changes=t,this.selection=i,this.effects=s,this.annotations=r,this.scrollIntoView=o,this._doc=null,this._state=null,i&&rl(i,t.newLength),r.some(l=>l.type==n.time)||(this.annotations=r.concat(n.time.of(Date.now())))}static create(e,t,i,s,r,o){return new n(e,t,i,s,r,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(n.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}};G.time=fe.define();G.userEvent=fe.define();G.addToHistory=fe.define();G.remote=fe.define();function sc(n,e){let t=[];for(let i=0,s=0;;){let r,o;if(i=n[i]))r=n[i++],o=n[i++];else if(s=0;s--){let r=i[s](n);r instanceof G?n=r:Array.isArray(r)&&r.length==1&&r[0]instanceof G?n=r[0]:n=dl(e,Ht(r),!1)}return n}function oc(n){let e=n.startState,t=e.facet(fl),i=n;for(let s=t.length-1;s>=0;s--){let r=t[s](n);r&&Object.keys(r).length&&(i=ul(i,Cs(e,r,n.changes.newLength),!0))}return i==n?n:G.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}var lc=[];function Ht(n){return n==null?lc:Array.isArray(n)?n:[n]}var re=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(re||(re={})),ac=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Qs;try{Qs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function hc(n){if(Qs)return Qs.test(n);for(let e=0;e"\x80"&&(t.toUpperCase()!=t.toLowerCase()||ac.test(t)))return!0}return!1}function fc(n){return e=>{if(!/\S/.test(e))return re.Space;if(hc(e))return re.Word;for(let t=0;t-1)return re.Word;return re.Other}}var z=class n{constructor(e,t,i,s,r,o){this.config=e,this.doc=t,this.selection=i,this.values=s,this.status=e.statusTemplate.slice(),this.computeSlot=r,o&&(o._state=this);for(let l=0;ls.set(h,a)),t=null),s.set(l.value.compartment,l.value.extension)):l.is(W.reconfigure)?(t=null,i=l.value):l.is(W.appendConfig)&&(t=null,i=Ht(i).concat(l.value));let r;t?r=e.startState.values.slice():(t=hn.resolve(i,s,this),r=new n(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(ws)?e.newSelection:e.newSelection.asSingle();new n(t,e.newDoc,o,r,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:b.cursor(t.from+e.length,-1)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),s=this.changes(i.changes),r=[i.range],o=Ht(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return n.create({doc:e.doc,selection:b.fromJSON(e.selection),extensions:t.extensions?s.concat([t.extensions]):s})}static create(e={}){let t=hn.resolve(e.extensions||[],new Map),i=e.doc instanceof M?e.doc:M.of((e.doc||"").split(t.staticFacet(n.lineSeparator)||bs)),s=e.selection?e.selection instanceof b?e.selection:b.single(e.selection.anchor,e.selection.head):b.single(0);return rl(s,i.length),t.staticFacet(ws)||(s=s.asSingle()),new n(t,i,s,t.dynamicSlots.map(()=>null),(r,o)=>o.create(r),null)}get tabSize(){return this.facet(n.tabSize)}get lineBreak(){return this.facet(n.lineSeparator)||` +`}get readOnly(){return this.facet(cl)}phrase(e,...t){for(let i of this.facet(n.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,s)=>{if(s=="$")return"$";let r=+(s||1);return!r||r>t.length?i:t[r-1]})),e}languageDataAt(e,t,i=-1){let s=[];for(let r of this.facet(ol))for(let o of r(this,t,i))Object.prototype.hasOwnProperty.call(o,e)&&s.push(o[e]);return s}charCategorizer(e){let t=this.languageDataAt("wordChars",e);return fc(t.length?t[0]:"")}wordAt(e){let{text:t,from:i,length:s}=this.doc.lineAt(e),r=this.charCategorizer(e),o=e-i,l=e-i;for(;o>0;){let a=K(t,o,!1);if(r(t.slice(a,o))!=re.Word)break;o=a}for(;ln.length?n[0]:4});z.lineSeparator=ll;z.readOnly=cl;z.phrases=v.define({compare(n,e){let t=Object.keys(n),i=Object.keys(e);return t.length==i.length&&t.every(s=>n[s]==e[s])}});z.languageData=ol;z.changeFilter=al;z.transactionFilter=hl;z.transactionExtender=fl;jt.reconfigure=W.define();function Tt(n,e,t={}){let i={};for(let s of n)for(let r of Object.keys(s)){let o=s[r],l=i[r];if(l===void 0)i[r]=o;else if(!(l===o||o===void 0))if(Object.hasOwnProperty.call(t,r))i[r]=t[r](l,o);else throw new Error("Config merge conflict for field "+r)}for(let s in e)i[s]===void 0&&(i[s]=e[s]);return i}var Oe=class{eq(e){return this==e}range(e,t=e){return ki.create(e,t,this)}};Oe.prototype.startSide=Oe.prototype.endSide=0;Oe.prototype.point=!1;Oe.prototype.mapMode=Y.TrackDel;function Ds(n,e){return n==e||n.constructor==e.constructor&&n.eq(e)}var ki=class n{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new n(e,t,i)}};function Ps(n,e){return n.from-e.from||n.value.startSide-e.value.startSide}var As=class n{constructor(e,t,i,s){this.from=e,this.to=t,this.value=i,this.maxPoint=s}get length(){return Xt(this.to)}findIndex(e,t,i,s=0){let r=i?this.to:this.from;for(let o=s,l=r.length;;){if(o==l)return o;let a=o+l>>1,h=r[a]-e||(i?this.value[a].endSide:this.value[a].startSide)-t;if(a==o)return h>=0?o:l;h>=0?l=a:o=a+1}}between(e,t,i,s){for(let r=this.findIndex(t,-1e9,!0),o=this.findIndex(i,1e9,!1,r);rO||m==O&&u.startSide>0&&u.endSide<=0)continue;if(!((O-m||u.endSide-u.startSide)<0))if(h<0&&(h=m),u.point&&(f=Math.max(f,O-m)),(m-i||u.startSide-s)>=0)o.push(u),l.push(m-h),a.push(O-h),i=O,s=u.endSide;else{if(m==O)for(let y=o.length;y>0;y--){if((m-(a[y-1]+h)||u.startSide-o[y-1].endSide)>=0){o.splice(y,0,u),l.splice(y,0,m-h),a.splice(y,0,O-h);continue e}if((m-(l[y-1]+h)||u.endSide-o[y-1].startSide)>0)break}r(m,O,u)}}return{mapped:o.length?new n(l,a,o,f):null,pos:h}}},B=class n{constructor(e,t,i,s){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=s}static create(e,t,i,s){return new n(e,t,i,s)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:i=!1,filterFrom:s=0,filterTo:r=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(i&&(t=t.slice().sort(Ps)),this.isEmpty)return t.length?n.of(t):this;let l=new cn(this,null,-1).goto(0),a=0,h=[],f=new ot;for(;l.value||a=0){let c=t[a++];f.addInner(c.from,c.to,c.value,!1)||h.push(c)}else l.rangeIndex==1&&l.chunkIndexthis.chunkEnd(l.chunkIndex)||rl.to||r{r||(r=new ot),r.addRange(a,h,f,!1)};for(let a=0;a=r&&e<=r+o.length&&o.between(r,e-r,t-r,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return wi.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return wi.from(e).goto(t)}static compare(e,t,i,s,r=-1){let o=e.filter(c=>c.maxPoint>0||!c.isEmpty&&c.maxPoint>=r),l=t.filter(c=>c.maxPoint>0||!c.isEmpty&&c.maxPoint>=r),a=el(o,l,i),h=new kt(o,a,r),f=new kt(l,a,r);i.iterGaps((c,u,d)=>tl(h,c,f,u,d,s)),i.empty&&i.length==0&&tl(h,0,f,0,0,s)}static eq(e,t,i=0,s){s==null&&(s=999999999);let r=e.filter(f=>!f.isEmpty&&t.indexOf(f)<0),o=t.filter(f=>!f.isEmpty&&e.indexOf(f)<0);if(r.length!=o.length)return!1;if(!r.length)return!0;let l=el(r,o),a=new kt(r,l,0).goto(i),h=new kt(o,l,0).goto(i);for(;;){if(a.to!=h.to||!Rs(a.active,h.active)||a.point&&(!h.point||!Ds(a.point,h.point)))return!1;if(a.to>s)return!0;a.next(),h.next()}}static spans(e,t,i,s,r=-1){let o=new kt(e,null,r).goto(t),l=t,a=o.openStart;for(;;){let h=Math.min(o.to,i);if(o.point){let f=o.activeForPoint(o.to),c=o.pointFroml&&(s.span(l,h,o.active,a),a=o.openEnd(h));if(o.to>i)return a+(o.point&&o.to>i?1:0);l=o.to,o.next()}}static of(e,t=!1){let i=new ot;for(let s of e instanceof ki?[e]:t?cc(e):e)i.add(s.from,s.to,s.value);return i.finish()}static join(e){if(!e.length)return n.empty;let t=Xt(e);for(let i=e.length-2;i>=0;i--)for(let s=e[i];s!=n.empty;s=s.nextLayer)t=new n(s.chunkPos,s.chunk,t,Math.max(s.maxPoint,t.maxPoint));return t}};B.empty=new B([],[],null,-1);function Xt(n){return n[n.length-1]}function cc(n){if(n.length>1)for(let e=n[0],t=1;t0)return n.slice().sort(Ps);e=i}return n}B.empty.nextLayer=B.empty;var ot=class n{finishChunk(e){this.chunks.push(new As(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(e,t,i){this.addRange(e,t,i,!0)}addRange(e,t,i,s){this.addInner(e,t,i,s)||(this.nextLayer||(this.nextLayer=new n)).addRange(e,t,i,s)}addInner(e,t,i,s){let r=e-this.lastTo||i.startSide-this.last.endSide;if(s&&r<=0&&(e-this.lastFrom||i.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return r<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=i,this.lastFrom=e,this.lastTo=t,this.value.push(i),i.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let i=t.value.length-1;return this.last=t.value[i],this.lastFrom=t.from[i]+e,this.lastTo=t.to[i]+e,!0}finish(){return this.finishInner(B.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=B.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}};function el(n,e,t){let i=new Map;for(let r of n)for(let o=0;o=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex=i&&s.push(new cn(o,t,i,r));return s.length==1?s[0]:new n(s)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let i of this.heap)i.goto(e,t);for(let i=this.heap.length>>1;i>=0;i--)Os(this.heap,i);return this.next(),this}forward(e,t){for(let i of this.heap)i.forward(e,t);for(let i=this.heap.length>>1;i>=0;i--)Os(this.heap,i);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),Os(this.heap,0)}}};function Os(n,e){for(let t=n[e];;){let i=(e<<1)+1;if(i>=n.length)break;let s=n[i];if(i+1=0&&(s=n[i+1],i++),t.compare(s)<0)break;n[i]=t,n[e]=s,e=i}}var kt=class{constructor(e,t,i){this.minPoint=i,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=wi.from(e,t,i)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){nn(this.active,e),nn(this.activeTo,e),nn(this.activeRank,e),this.minActive=il(this.active,this.activeTo)}addActive(e){let t=0,{value:i,to:s,rank:r}=this.cursor;for(;t0;)t++;sn(this.active,t,i),sn(this.activeTo,t,s),sn(this.activeRank,t,r),e&&sn(e,t,this.cursor.from),this.minActive=il(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let i=this.openStart<0?[]:null;for(;;){let s=this.minActive;if(s>-1&&(this.activeTo[s]-this.cursor.from||this.active[s].endSide-this.cursor.startSide)<0){if(this.activeTo[s]>e){this.to=this.activeTo[s],this.endSide=this.active[s].endSide;break}this.removeActive(s),i&&nn(i,s)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let r=this.cursor.value;if(!r.point)this.addActive(i),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from=0&&i[s]=0&&!(this.activeRank[i]e||this.activeTo[i]==e&&this.active[i].endSide>=this.point.endSide)&&t.push(this.active[i]);return t.reverse()}openEnd(e){let t=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>e;i--)t++;return t}};function tl(n,e,t,i,s,r){n.goto(e),t.goto(i);let o=i+s,l=i,a=i-e,h=!!r.boundChange;for(let f=!1;;){let c=n.to+a-t.to,u=c||n.endSide-t.endSide,d=u<0?n.to+a:t.to,p=Math.min(d,o);if(n.point||t.point?(n.point&&t.point&&Ds(n.point,t.point)&&Rs(n.activeForPoint(n.to),t.activeForPoint(t.to))||r.comparePoint(l,p,n.point,t.point),f=!1):(f&&(r.boundChange(l),f=!1),p>l&&!Rs(n.active,t.active)&&r.compareRange(l,p,n.active,t.active),h&&po)break;l=d,u<=0&&n.next(),u>=0&&t.next()}}function Rs(n,e){if(n.length!=e.length)return!1;for(let t=0;t=e;i--)n[i+1]=n[i];n[e]=t}function il(n,e){let t=-1,i=1e9;for(let s=0;s=e)return s;if(s==n.length)break;r+=n.charCodeAt(s)==9?t-r%t:1,s=K(n,s)}return i===!0?-1:n.length}var ml=typeof Symbol>"u"?"__\u037C":Symbol.for("\u037C"),Bs=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),gl=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{},ye=class{constructor(e,t){this.rules=[];let{finish:i}=t||{};function s(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function r(o,l,a,h){let f=[],c=/^@(\w+)\b/.exec(o[0]),u=c&&c[1]=="keyframes";if(c&&l==null)return a.push(o[0]+";");for(let d in l){let p=l[d];if(/&/.test(d))r(d.split(/,\s*/).map(m=>o.map(O=>m.replace(/&/,O))).reduce((m,O)=>m.concat(O)),p,a);else if(p&&typeof p=="object"){if(!c)throw new RangeError("The value of a property ("+d+") should be a primitive value.");r(s(d),p,f,u)}else p!=null&&f.push(d.replace(/_.*/,"").replace(/[A-Z]/g,m=>"-"+m.toLowerCase())+": "+p+";")}(f.length||u)&&a.push((i&&!c&&!h?o.map(i):o).join(", ")+" {"+f.join(" ")+"}")}for(let o in e)r(s(o),e[o],this.rules)}getRules(){return this.rules.join(` +`)}static newName(){let e=gl[ml]||1;return gl[ml]=e+1,"\u037C"+e.toString(36)}static mount(e,t,i){let s=e[Bs],r=i&&i.nonce;s?r&&s.setNonce(r):s=new qs(e,r),s.mount(Array.isArray(t)?t:[t],e)}},Ol=new Map,qs=class{constructor(e,t){let i=e.ownerDocument||e,s=i.defaultView;if(!e.head&&e.adoptedStyleSheets&&s.CSSStyleSheet){let r=Ol.get(i);if(r)return e[Bs]=r;this.sheet=new s.CSSStyleSheet,Ol.set(i,this)}else this.styleTag=i.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[Bs]=this}mount(e,t){let i=this.sheet,s=0,r=0,o=!1;for(let l=0;l-1&&(this.modules.splice(h,1),o=!0,r--,h=-1),h==-1){if(this.modules.splice(r++,0,a),o=!0,i)for(let f=0;f",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},uc=typeof navigator<"u"&&/Mac/.test(navigator.platform),dc=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(Z=0;Z<10;Z++)je[48+Z]=je[96+Z]=String(Z);var Z;for(Z=1;Z<=24;Z++)je[Z+111]="F"+Z;var Z;for(Z=65;Z<=90;Z++)je[Z]=String.fromCharCode(Z+32),Zt[Z]=String.fromCharCode(Z);var Z;for(un in je)Zt.hasOwnProperty(un)||(Zt[un]=je[un]);var un;function yl(n){var e=uc&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||dc&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?Zt:je)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}var le=typeof navigator<"u"?navigator:{userAgent:"",vendor:"",platform:""},Xs=typeof document<"u"?document:{documentElement:{style:{}}},Fs=/Edge\/(\d+)/.exec(le.userAgent),jl=/MSIE \d/.test(le.userAgent),_s=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(le.userAgent),Ln=!!(jl||_s||Fs),bl=!Ln&&/gecko\/(\d+)/i.test(le.userAgent),Ws=!Ln&&/Chrome\/(\d+)/.exec(le.userAgent),Sl="webkitFontSmoothing"in Xs.documentElement.style,Hs=!Ln&&/Apple Computer/.test(le.vendor),xl=Hs&&(/Mobile\/\w+/.test(le.userAgent)||le.maxTouchPoints>2),x={mac:xl||/Mac/.test(le.platform),windows:/Win/.test(le.platform),linux:/Linux|X11/.test(le.platform),ie:Ln,ie_version:jl?Xs.documentMode||6:_s?+_s[1]:Fs?+Fs[1]:0,gecko:bl,gecko_version:bl?+(/Firefox\/(\d+)/.exec(le.userAgent)||[0,0])[1]:0,chrome:!!Ws,chrome_version:Ws?+Ws[1]:0,ios:xl,android:/Android\b/.test(le.userAgent),webkit:Sl,webkit_version:Sl?+(/\bAppleWebKit\/(\d+)/.exec(le.userAgent)||[0,0])[1]:0,safari:Hs,safari_version:Hs?+(/\bVersion\/(\d+(\.\d+)?)/.exec(le.userAgent)||[0,0])[1]:0,tabSize:Xs.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};function Rr(n,e){for(let t in n)t=="class"&&e.class?e.class+=" "+n.class:t=="style"&&e.style?e.style+=";"+n.style:e[t]=n[t];return e}var wn=Object.create(null);function Mr(n,e,t){if(n==e)return!0;n||(n=wn),e||(e=wn);let i=Object.keys(n),s=Object.keys(e);if(i.length-(t&&i.indexOf(t)>-1?1:0)!=s.length-(t&&s.indexOf(t)>-1?1:0))return!1;for(let r of i)if(r!=t&&(s.indexOf(r)==-1||n[r]!==e[r]))return!1;return!0}function pc(n,e){for(let t=n.attributes.length-1;t>=0;t--){let i=n.attributes[t].name;e[i]==null&&n.removeAttribute(i)}for(let t in e){let i=e[t];t=="style"?n.style.cssText=i:n.getAttribute(t)!=i&&n.setAttribute(t,i)}}function kl(n,e,t){let i=!1;if(e)for(let s in e)t&&s in t||(i=!0,s=="style"?n.style.cssText="":n.removeAttribute(s));if(t)for(let s in t)e&&e[s]==t[s]||(i=!0,s=="style"?n.style.cssText=t[s]:n.setAttribute(s,t[s]));return i}function mc(n){let e=Object.create(null);for(let t=0;t0?3e8:-4e8:t>0?1e8:-1e8,new At(e,t,t,i,e.widget||null,!1)}static replace(e){let t=!!e.block,i,s;if(e.isBlockGap)i=-5e8,s=4e8;else{let{start:r,end:o}=Gl(e,t);i=(r?t?-3e8:-1:5e8)-1,s=(o?t?2e8:1:-6e8)+1}return new At(e,i,s,t,e.widget||null,!0)}static line(e){return new qi(e)}static set(e,t=!1){return B.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}};q.none=B.empty;var Bi=class n extends q{constructor(e){let{start:t,end:i}=Gl(e);super(t?-1:5e8,i?1:-6e8,null,e),this.tagName=e.tagName||"span",this.attrs=e.class&&e.attributes?Rr(e.attributes,{class:e.class}):e.class?{class:e.class}:e.attributes||wn}eq(e){return this==e||e instanceof n&&this.tagName==e.tagName&&Mr(this.attrs,e.attrs)}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}};Bi.prototype.point=!1;var qi=class n extends q{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof n&&this.spec.class==e.spec.class&&Mr(this.spec.attributes,e.spec.attributes)}range(e,t=e){if(t!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,t)}};qi.prototype.mapMode=Y.TrackBefore;qi.prototype.point=!0;var At=class n extends q{constructor(e,t,i,s,r,o){super(t,i,r,e),this.block=s,this.isReplace=o,this.mapMode=s?t<=0?Y.TrackBefore:Y.TrackAfter:Y.TrackDel}get type(){return this.startSide!=this.endSide?ue.WidgetRange:this.startSide<=0?ue.WidgetBefore:ue.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof n&&gc(this.widget,e.widget)&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide}range(e,t=e){if(this.isReplace&&(e>t||e==t&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&t!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,t)}};At.prototype.point=!0;function Gl(n,e=!1){let{inclusiveStart:t,inclusiveEnd:i}=n;return t==null&&(t=n.inclusive),i==null&&(i=n.inclusive),{start:t??e,end:i??e}}function gc(n,e){return n==e||!!(n&&e&&n.compare(e))}function ti(n,e,t,i=0){let s=t.length-1;s>=0&&t[s]+i>=n?t[s]=Math.max(t[s],e):t.push(n,e)}var vn=class n extends Oe{constructor(e,t,i){super(),this.tagName=e,this.attributes=t,this.rank=i}eq(e){return e==this||e instanceof n&&this.tagName==e.tagName&&Mr(this.attributes,e.attributes)}static create(e){return new n(e.tagName,e.attributes||wn,e.rank==null?50:Math.max(0,Math.min(e.rank,100)))}static set(e,t=!1){return B.of(e,t)}};vn.prototype.startSide=vn.prototype.endSide=-1;function Wi(n){let e;return n.nodeType==11?e=n.getSelection?n:n.ownerDocument:e=n,e.getSelection()}function Us(n,e){return e?n==e||n.contains(e.nodeType!=1?e.parentNode:e):!1}function Ci(n,e){if(!e.anchorNode)return!1;try{return Us(n,e.anchorNode)}catch{return!1}}function Sn(n){return n.nodeType==3?$i(n,0,n.nodeValue.length).getClientRects():n.nodeType==1?n.getClientRects():[]}function Qi(n,e,t,i){return t?wl(n,e,t,i,-1)||wl(n,e,t,i,1):!1}function ct(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e}function Tn(n){return n.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(n.nodeName)}function wl(n,e,t,i,s){for(;;){if(n==t&&e==i)return!0;if(e==(s<0?0:Ke(n))){if(n.nodeName=="DIV")return!1;let r=n.parentNode;if(!r||r.nodeType!=1)return!1;e=ct(n)+(s<0?0:1),n=r}else if(n.nodeType==1){if(n=n.childNodes[e+(s<0?-1:0)],n.nodeType==1&&n.contentEditable=="false")return!1;e=s<0?Ke(n):0}else return!1}}function Ke(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Cn(n,e){let{left:t,right:i}=n;if(t==i)return n;let s=e?t:i;return{left:s,right:s,top:n.top,bottom:n.bottom}}function Oc(n){let e=n.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.innerWidth,top:0,bottom:n.innerHeight}}function Zl(n,e){let t=e.width/n.offsetWidth,i=e.height/n.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-n.offsetWidth)<1)&&(t=1),(i>.995&&i<1.005||!isFinite(i)||Math.abs(e.height-n.offsetHeight)<1)&&(i=1),{scaleX:t,scaleY:i}}function yc(n,e,t,i,s,r,o,l){let a=n.ownerDocument,h=a.defaultView||window;for(let f=n,c=!1;f&&!c;)if(f.nodeType==1){let u,d=f==a.body,p=1,m=1;if(d)u=Oc(h);else{if(/^(fixed|sticky)$/.test(getComputedStyle(f).position)&&(c=!0),f.scrollHeight<=f.clientHeight&&f.scrollWidth<=f.clientWidth){f=f.assignedSlot||f.parentNode;continue}let w=f.getBoundingClientRect();({scaleX:p,scaleY:m}=Zl(f,w)),u={left:w.left,right:w.left+f.clientWidth*p,top:w.top,bottom:w.top+f.clientHeight*m}}let O=0,y=0;if(s=="nearest")e.top0&&e.bottom>u.bottom+y&&(y=e.bottom-u.bottom+o)):e.bottom>u.bottom-o&&(y=e.bottom-u.bottom+o,t<0&&e.top-y0&&e.right>u.right+O&&(O=e.right-u.right+r)):e.right>u.right-r&&(O=e.right-u.right+r,t<0&&e.leftu.bottom||e.leftu.right)&&(e={left:Math.max(e.left,u.left),right:Math.min(e.right,u.right),top:Math.max(e.top,u.top),bottom:Math.min(e.bottom,u.bottom)}),f=f.assignedSlot||f.parentNode}else if(f.nodeType==11)f=f.host;else break}function Yl(n,e=!0){let t=n.ownerDocument,i=null,s=null;for(let r=n.parentNode;r&&!(r==t.body||(!e||i)&&s);)if(r.nodeType==1)!s&&r.scrollHeight>r.clientHeight&&(s=r),e&&!i&&r.scrollWidth>r.clientWidth&&(i=r),r=r.assignedSlot||r.parentNode;else if(r.nodeType==11)r=r.host;else break;return{x:i,y:s}}var js=class{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:t,focusNode:i}=e;this.set(t,Math.min(e.anchorOffset,t?Ke(t):0),i,Math.min(e.focusOffset,i?Ke(i):0))}set(e,t,i,s){this.anchorNode=e,this.anchorOffset=t,this.focusNode=i,this.focusOffset=s}};function Kl(n){let e=[];for(let t=n;t;t=t.nodeType==11?t.host:t.parentNode)t.nodeType==1&&e.push({node:t,left:t.scrollLeft,top:t.scrollTop});return e}function Jl(n,e=!0){for(let{node:t,left:i,top:s}of n)e&&t.scrollTop!=s&&(t.scrollTop=s),t.scrollLeft!=i&&(t.scrollLeft=i)}var Qt=null;x.safari&&x.safari_version>=26&&(Qt=!1);function ea(n){if(n.setActive)return n.setActive();if(Qt)return n.focus(Qt);let e=Kl(n);n.focus(Qt==null?{get preventScroll(){return Qt={preventScroll:!0},!0}}:void 0),Qt||(Qt=!1,Jl(e))}var vl;function $i(n,e,t=e){let i=vl||(vl=document.createRange());return i.setEnd(n,t),i.setStart(n,e),i}function ii(n,e,t,i){let s={key:e,code:e,keyCode:t,which:t,cancelable:!0};i&&({altKey:s.altKey,ctrlKey:s.ctrlKey,shiftKey:s.shiftKey,metaKey:s.metaKey}=i);let r=new KeyboardEvent("keydown",s);r.synthetic=!0,n.dispatchEvent(r);let o=new KeyboardEvent("keyup",s);return o.synthetic=!0,n.dispatchEvent(o),r.defaultPrevented||o.defaultPrevented}function bc(n){for(;n;){if(n&&(n.nodeType==9||n.nodeType==11&&n.host))return n;n=n.assignedSlot||n.parentNode}return null}function Sc(n,e){let t=e.focusNode,i=e.focusOffset;if(!t||e.anchorNode!=t||e.anchorOffset!=i)return!1;for(i=Math.min(i,Ke(t));;)if(i){if(t.nodeType!=1)return!1;let s=t.childNodes[i-1];s.contentEditable=="false"?i--:(t=s,i=Ke(t))}else{if(t==n)return!0;i=ct(t),t=t.parentNode}}function ta(n){return n instanceof Window?n.pageYOffset>Math.max(0,n.document.documentElement.scrollHeight-n.innerHeight-4):n.scrollTop>Math.max(1,n.scrollHeight-n.clientHeight-4)}function ia(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i>0)return{node:t,offset:i};if(t.nodeType==1&&i>0){if(t.contentEditable=="false")return null;t=t.childNodes[i-1],i=Ke(t)}else if(t.parentNode&&!Tn(t))i=ct(t),t=t.parentNode;else return null}}function na(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i=t){if(l.level==i)return o;(r<0||(s!=0?s<0?l.fromt:e[r].level>l.level))&&(r=o)}}if(r<0)throw new RangeError("Index out of range");return r}};function oa(n,e){if(n.length!=e.length)return!1;for(let t=0;t=0;m-=3)if(We[m+1]==-d){let O=We[m+2],y=O&2?s:O&4?O&1?r:s:0;y&&(L[c]=L[We[m]]=y),l=m;break}}else{if(We.length==189)break;We[l++]=c,We[l++]=u,We[l++]=a}else if((p=L[c])==2||p==1){let m=p==s;a=m?0:1;for(let O=l-3;O>=0;O-=3){let y=We[O+2];if(y&2)break;if(m)We[O+2]|=2;else{if(y&4)break;We[O+2]|=4}}}}}function Cc(n,e,t,i){for(let s=0,r=i;s<=t.length;s++){let o=s?t[s-1].to:n,l=sa;)p==O&&(p=t[--m].from,O=m?t[m-1].to:n),L[--p]=d;a=f}else r=h,a++}}}function Zs(n,e,t,i,s,r,o){let l=i%2?2:1;if(i%2==s%2)for(let a=e,h=0;aa&&o.push(new xe(a,m.from,d));let O=m.direction==Rt!=!(d%2);Ys(n,O?i+1:i,s,m.inner,m.from,m.to,o),a=m.to}p=m.to}else{if(p==t||(f?L[p]!=l:L[p]==l))break;p++}u?Zs(n,a,p,i+1,s,u,o):ae;){let f=!0,c=!1;if(!h||a>r[h-1].to){let m=L[a-1];m!=l&&(f=!1,c=m==16)}let u=!f&&l==1?[]:null,d=f?i:i+1,p=a;e:for(;;)if(h&&p==r[h-1].to){if(c)break e;let m=r[--h];if(!f)for(let O=m.from,y=h;;){if(O==e)break e;if(y&&r[y-1].to==O)O=r[--y].from;else{if(L[O-1]==l)break e;break}}if(u)u.push(m);else{m.toL.length;)L[L.length]=256;let i=[],s=e==Rt?0:1;return Ys(n,s,s,t,0,n.length,i),i}function la(n){return[new xe(0,n,0)]}var aa="";function Pc(n,e,t,i,s){var r;if(!n.length)return null;let o=i.head-n.from,l;if(i.head==n.from&&i.assoc<0){if(!s)return null;o=e[l=0].side(!1,t)}else if(i.head==n.to&&i.assoc>0){if(s)return null;o=e[l=e.length-1].side(!0,t)}else l=xe.find(e,o,(r=i.bidiLevel)!==null&&r!==void 0?r:-1,i.assoc);let a=e[l],h=a.side(s,t);if(o==h){let u=l+=s?1:-1;if(u<0||u>=e.length)return null;a=e[l=u],o=a.side(!s,t),h=a.side(s,t)}let f=K(n.text,o,a.forward(s,t));(fa.to)&&(f=h),aa=n.text.slice(Math.min(o,f),Math.max(o,f));let c=l==(s?e.length-1:0)?null:e[l+(s?1:-1)];if(f==h){if(!c)return s?b.cursor(n.to,1):b.cursor(n.from,-1);if(c.level+(s?0:1)n.some(e=>e)}),Rc=v.define({combine:n=>n.some(e=>e)}),ga=v.define(),Pi=class n{constructor(e,t,i,s,r,o=!1){this.range=e,this.y=t,this.x=i,this.yMargin=s,this.xMargin=r,this.isSnapshot=o}map(e){return e.empty?this:new n(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(e){return this.range.to<=e.doc.length?this:new n(b.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}},dn=W.define({map:(n,e)=>n.map(e)}),Oa=W.define();function ke(n,e,t){let i=n.facet(ua);i.length?i[0](e):window.onerror&&window.onerror(String(e),t,void 0,void 0,e)||(t?console.error(t+":",e):console.error(e))}var Ge=v.define({combine:n=>n.length?n[0]:!0}),Mc=0,Kt=v.define({combine(n){return n.filter((e,t)=>{for(let i=0;i{let a=[];return o&&a.push(zn.of(h=>{let f=h.plugin(l);return f?o(f):q.none})),r&&a.push(r(l)),a})}static fromClass(e,t){return n.define((i,s)=>new e(i,s),t)}},Ai=class{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}get plugin(){return this.spec&&this.spec.plugin}update(e){if(this.value){if(this.mustUpdate){let t=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(t)}catch(i){if(ke(t.state,i,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.plugin.create(e,this.spec.arg)}catch(t){ke(e.state,t,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var t;if(!((t=this.value)===null||t===void 0)&&t.destroy)try{this.value.destroy()}catch(i){ke(e.state,i,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}},ya=v.define(),qr=v.define(),zn=v.define(),ba=v.define(),Wr=v.define(),Li=v.define(),Sa=v.define();function Tl(n,e){let t=n.state.facet(Sa);if(!t.length)return t;let i=t.map(r=>r instanceof Function?r(n):r),s=[];return B.spans(i,e.from,e.to,{point(){},span(r,o,l,a){let h=r-e.from,f=o-e.from,c=s;for(let u=l.length-1;u>=0;u--,a--){let d=l[u].spec.bidiIsolate,p;if(d==null&&(d=Ac(e.text,h,f)),a>0&&c.length&&(p=c[c.length-1]).to==h&&p.direction==d)p.to=f,c=p.inner;else{let m={from:h,to:f,direction:d,inner:[]};c.push(m),c=m.inner}}}}),s}var xa=v.define();function ka(n){let e=0,t=0,i=0,s=0;for(let r of n.state.facet(xa)){let o=r(n);o&&(o.left!=null&&(e=Math.max(e,o.left)),o.right!=null&&(t=Math.max(t,o.right)),o.top!=null&&(i=Math.max(i,o.top)),o.bottom!=null&&(s=Math.max(s,o.bottom)))}return{left:e,right:t,top:i,bottom:s}}var vi=v.define(),Pe=class n{constructor(e,t,i,s){this.fromA=e,this.toA=t,this.fromB=i,this.toB=s}join(e){return new n(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let t=e.length,i=this;for(;t>0;t--){let s=e[t-1];if(!(s.fromA>i.toA)){if(s.toAs.push(new Pe(r,o,l,a))),this.changedRanges=s}static create(e,t,i){return new n(e,t,i)}get viewportChanged(){return(this.flags&4)>0}get viewportMoved(){return(this.flags&8)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&18)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}},Ec=[],_=class{constructor(e,t,i=0){this.dom=e,this.length=t,this.flags=i,this.parent=null,e.cmTile=this}get breakAfter(){return this.flags&1}get children(){return Ec}isWidget(){return!1}get isHidden(){return!1}isComposite(){return!1}isLine(){return!1}isText(){return!1}isBlock(){return!1}get domAttrs(){return null}sync(e){if(this.flags|=2,this.flags&4){this.flags&=-5;let t=this.domAttrs;t&&pc(this.dom,t)}}toString(){return this.constructor.name+(this.children.length?`(${this.children})`:"")+(this.breakAfter?"#":"")}destroy(){this.parent=null}setDOM(e){this.dom=e,e.cmTile=this}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e,t=this.posAtStart){let i=t;for(let s of this.children){if(s==e)return i;i+=s.length+s.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}covers(e){return!0}coordsIn(e,t,i){return null}domPosFor(e,t){let i=ct(this.dom),s=this.length?e>0:t>0;return new $e(this.parent.dom,i+(s?1:0),e==0||e==this.length)}markDirty(e){this.flags&=-3,e&&(this.flags|=4),this.parent&&this.parent.flags&2&&this.parent.markDirty(!1)}get overrideDOMText(){return null}get root(){for(let e=this;e;e=e.parent)if(e instanceof si)return e;return null}static get(e){return e.cmTile}},ni=class extends _{constructor(e){super(e,0),this._children=[]}isComposite(){return!0}get children(){return this._children}get lastChild(){return this.children.length?this.children[this.children.length-1]:null}append(e){this.children.push(e),e.parent=this}sync(e){if(this.flags&2)return;super.sync(e);let t=this.dom,i=null,s,r=e?.node==t?e:null,o=0;for(let l of this.children){if(l.sync(e),o+=l.length+l.breakAfter,s=i?i.nextSibling:t.firstChild,r&&s!=l.dom&&(r.written=!0),l.dom.parentNode==t)for(;s&&s!=l.dom;)s=Cl(s);else t.insertBefore(l.dom,s);i=l.dom}for(s=i?i.nextSibling:t.firstChild,r&&s&&(r.written=!0);s;)s=Cl(s);this.length=o}};function Cl(n){let e=n.nextSibling;return n.parentNode.removeChild(n),e}var si=class extends ni{constructor(e,t){super(t),this.view=e}owns(e){for(;e;e=e.parent)if(e==this)return!0;return!1}isBlock(){return!0}nearest(e){for(;;){if(!e)return null;let t=_.get(e);if(t&&this.owns(t))return t;e=e.parentNode}}blockTiles(e){for(let t=[],i=this,s=0,r=0;;)if(s==i.children.length){if(!t.length)return;i=i.parent,i.breakAfter&&r++,s=t.pop()}else{let o=i.children[s++];if(o instanceof Ze)t.push(s),i=o,s=0;else{let l=r+o.length,a=e(o,r);if(a!==void 0)return a;r=l+o.breakAfter}}}resolveBlock(e,t){let i,s=-1,r,o=-1;if(this.blockTiles((l,a)=>{let h=a+l.length;if(e>=a&&e<=h){if(l.isWidget()&&t>=-1&&t<=1){if(l.flags&32)return!0;l.flags&16&&(i=void 0)}(ae||e==a&&(t>1?l.length:l.covers(-1)))&&(!r||!l.isWidget()&&r.isWidget())&&(r=l,o=e-a)}}),!i&&!r)throw new Error("No tile at position "+e);return i&&t<0||!r?{tile:i,offset:s}:{tile:r,offset:o}}},Ze=class n extends ni{constructor(e,t){super(e),this.wrapper=t}isBlock(){return!0}covers(e){return this.children.length?e<0?this.children[0].covers(-1):this.lastChild.covers(1):!1}get domAttrs(){return this.wrapper.attributes}static of(e,t){let i=new n(t||document.createElement(e.tagName),e);return t||(i.flags|=4),i}},ri=class n extends ni{constructor(e,t){super(e),this.attrs=t}isLine(){return!0}static start(e,t,i){let s=new n(t||document.createElement("div"),e);return(!t||!i)&&(s.flags|=4),s}get domAttrs(){return this.attrs}resolveInline(e,t,i){let s=null,r=-1,o=null,l=-1;function a(f,c){for(let u=0,d=0;u=c&&(p.isComposite()?a(p,c-d):(!o||o.isHidden&&(t>0&&!(o.flags&32)||i&&Bc(o,p)))&&(m>c||p.flags&32&&t<=1)?(o=p,l=c-d):(d=-1)&&(s=p,r=c-d)),d=m}}a(this,e);let h=(t<0?s:o)||s||o;return h?{tile:h,offset:h==s?r:l}:null}coordsIn(e,t,i){let s=this.resolveInline(e,t,!0);return s?s.tile.coordsIn(Math.max(0,s.offset),t,i):Dc(this)}domIn(e,t){let i=this.resolveInline(e,t);if(i){let{tile:s,offset:r}=i;if(this.dom.contains(s.dom))return s.isText()?new $e(s.dom,Math.min(s.dom.nodeValue.length,r)):s.domPosFor(r,s.flags&16?1:s.flags&32?-1:t);let o=i.tile.parent,l=!1;for(let a of o.children){if(l)return new $e(a.dom,0);a==i.tile&&(l=!0)}}return new $e(this.dom,0)}};function Dc(n){let e=n.dom.lastChild;if(!e)return n.dom.getBoundingClientRect();let t=Sn(e);return t[t.length-1]||null}function Bc(n,e){let t=n.coordsIn(0,1),i=e.coordsIn(0,1);return t&&i&&i.tops&&(e=s);let r=e,o=e,l=0;e==0&&t<0||e==s&&t>=0?x.chrome||x.gecko||(e?(r--,l=1):o=0)?0:a.length-1];return x.safari&&!l&&h.width==0&&(h=Array.prototype.find.call(a,f=>f.width)||h),i==null?h:Cn(h,(l?l>0:t<0)==i)}static of(e,t){let i=new n(t||document.createTextNode(e),e);return t||(i.flags|=2),i}},Mt=class n extends _{constructor(e,t,i,s){super(e,t,s),this.widget=i}isWidget(){return!0}get isHidden(){return this.widget.isHidden}covers(e){return this.flags&48?!1:(this.flags&(e<0?64:128))>0}coordsIn(e,t){return this.coordsInWidget(e,t,!1)}coordsInWidget(e,t,i){let s=this.widget.coordsAt(this.dom,e,t);if(s)return s;if(i)return Cn(this.dom.getBoundingClientRect(),this.length?e==0:t<=0);{let r=this.dom.getClientRects(),o=null;if(!r.length)return null;let l=this.flags&16?!0:this.flags&32?!1:e>0;for(let a=l?r.length-1:0;o=r[a],!(e>0?a==0:a==r.length-1||o.top0==i)}},Js=class{constructor(e){this.index=0,this.beforeBreak=!1,this.parents=[],this.tile=e}advance(e,t,i){let{tile:s,index:r,beforeBreak:o,parents:l}=this;for(;e||t>0;)if(s.isComposite())if(o){if(!e)break;i&&i.break(),e--,o=!1}else if(r==s.children.length){if(!e&&!l.length)break;i&&i.leave(s),o=!!s.breakAfter,{tile:s,index:r}=l.pop(),r++}else{let a=s.children[r],h=a.breakAfter;(t>0?a.length<=e:a.length=0;l--){let a=t.marks[l],h=s.lastChild;if(h instanceof ce&&h.mark.eq(a.mark))h.dom!=a.dom&&h.setDOM($s(a.dom)),s=h;else{let{dom:f}=a;this.cache.reused.get(a)&&_.get(a.dom)&&(f=$s(a.dom));let c=ce.of(a.mark,f);s.append(c),s=c}this.cache.reused.set(a,2)}let r=_.get(e.text);r&&this.cache.reused.set(r,2);let o=new Pt(e.text,e.text.nodeValue);o.flags|=8,this.pos=e.range.toB,s.append(o)}addInlineWidget(e,t,i){let s=this.afterWidget&&e.flags&48&&(this.afterWidget.flags&48)==(e.flags&48);s||this.flushBuffer();let r=this.ensureMarks(t,i);!s&&!(e.flags&16)&&r.append(this.getBuffer(1)),r.append(e),this.pos+=e.length,this.afterWidget=e}addMark(e,t,i){this.flushBuffer(),this.ensureMarks(t,i).append(e),this.pos+=e.length,this.afterWidget=null}addBlockWidget(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}continueWidget(e){let t=this.afterWidget||this.lastBlock;t.length+=e,this.pos+=e}addLineStart(e,t){var i;e||(e=wa);let s=ri.start(e,t||((i=this.cache.find(ri))===null||i===void 0?void 0:i.dom),!!t);this.getBlockPos().append(this.lastBlock=this.curLine=s)}addLine(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}addBreak(){this.lastBlock.flags|=1,this.endLine(),this.pos++}addLineStartIfNotCovered(e){this.blockPosCovered()||this.addLineStart(e)}ensureLine(e){this.curLine||this.addLineStart(e)}ensureMarks(e,t){var i;let s=this.curLine;for(let r=e.length-1;r>=0;r--){let o=e[r],l;if(t>0&&(l=s.lastChild)&&l instanceof ce&&l.mark.eq(o))s=l,t--;else{let a=ce.of(o,(i=this.cache.find(ce,h=>h.mark.eq(o)))===null||i===void 0?void 0:i.dom);s.append(a),s=a,t=0}}return s}endLine(){if(this.curLine){this.flushBuffer();let e=this.curLine.lastChild;(!e||!Ql(this.curLine,!1)||e.dom.nodeName!="BR"&&e.isWidget()&&!(x.ios&&Ql(this.curLine,!0)))&&this.curLine.append(this.cache.findWidget(Ls,0,32)||new Mt(Ls.toDOM(),0,Ls,32)),this.curLine=this.afterWidget=null}}updateBlockWrappers(){this.wrapperPos>this.pos+1e4&&(this.blockWrappers.goto(this.pos),this.wrappers.length=0);for(let e=this.wrappers.length-1;e>=0;e--)this.wrappers[e].to=this.pos){let t=e.rank*102+e.value.rank,i=new er(e.from,e.to,e.value,t),s=this.wrappers.length;for(;s>0&&(this.wrappers[s-1].rank-i.rank||this.wrappers[s-1].to-i.to)<0;)s--;this.wrappers.splice(s,0,i)}this.wrapperPos=this.pos}getBlockPos(){var e;this.updateBlockWrappers();let t=this.root;for(let i of this.wrappers){let s=t.lastChild;if(i.fromo.wrapper.eq(i.wrapper)))===null||e===void 0?void 0:e.dom);t.append(r),t=r}}return t}blockPosCovered(){let e=this.lastBlock;return e!=null&&!e.breakAfter&&(!e.isWidget()||(e.flags&160)>0)}getBuffer(e){let t=2|(e<0?16:32),i=this.cache.find(oi,void 0,1);return i&&(i.flags=t),i||new oi(t)}flushBuffer(){this.afterWidget&&!(this.afterWidget.flags&32)&&(this.afterWidget.parent.append(this.getBuffer(-1)),this.afterWidget=null)}},ir=class{constructor(e){this.skipCount=0,this.text="",this.textOff=0,this.cursor=e.iter()}skip(e){this.textOff+e<=this.text.length?this.textOff+=e:(this.skipCount+=e-(this.text.length-this.textOff),this.text="",this.textOff=0)}next(e){if(this.textOff==this.text.length){let{value:s,lineBreak:r,done:o}=this.cursor.next(this.skipCount);if(this.skipCount=0,o)throw new Error("Ran out of text content when drawing inline views");this.text=s;let l=this.textOff=Math.min(e,s.length);return r?null:s.slice(0,l)}let t=Math.min(this.text.length,this.textOff+e),i=this.text.slice(this.textOff,t);return this.textOff=t,i}},Pn=[Mt,ri,Pt,ce,oi,Ze,si];for(let n=0;n[]),this.index=Pn.map(()=>0),this.reused=new Map}add(e){let t=e.constructor.bucket,i=this.buckets[t];i.length<6?i.push(e):i[this.index[t]=(this.index[t]+1)%6]=e}find(e,t,i=2){let s=e.bucket,r=this.buckets[s],o=this.index[s];for(let l=0;l{if(this.cache.add(o),o.isComposite())return!1},enter:o=>this.cache.add(o),leave:()=>{},break:()=>{}}}run(e,t){let i=t&&this.getCompositionContext(t.text);for(let s=0,r=0,o=0;;){let l=os){let h=a-s;this.preserve(h,!o,!l),s=a,r+=h}if(!l)break;t&&l.fromA<=t.range.fromA&&l.toA>=t.range.toA?(this.forward(l.fromA,t.range.fromA,t.range.fromA{if(o.isWidget())if(this.openWidget)this.builder.continueWidget(a-l);else{let h=a>0||l{o.isLine()?this.builder.addLineStart(o.attrs,this.cache.maybeReuse(o)):(this.cache.add(o),o instanceof ce&&s.unshift(o.mark)),this.openWidget=!1},leave:o=>{o.isLine()?s.length&&(s.length=r=0):o instanceof ce&&(s.shift(),r=Math.min(r,s.length))},break:()=>{this.builder.addBreak(),this.openWidget=!1}}),this.text.skip(e)}emit(e,t){let i=null,s=this.builder,r=-1,o=B.spans(this.decorations,e,t,{point:(l,a,h,f,c,u)=>{if(h instanceof At){if(this.disallowBlockEffectsFor[u]){if(h.block)throw new RangeError("Block decorations may not be specified via plugins");if(a>this.view.state.doc.lineAt(l).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}if(r=f.length,c>f.length)s.continueWidget(a-l);else{let d=h.widget||(h.block?ut.block:ut.inline),p=qc(h),m=this.cache.findWidget(d,a-l,p)||Mt.of(d,this.view,a-l,p);h.block?(h.startSide>0&&s.addLineStartIfNotCovered(i),s.addBlockWidget(m)):(s.ensureLine(i),s.addInlineWidget(m,f,c))}i=null}else i=Wc(i,h);a>l&&this.text.skip(a-l)},span:(l,a,h,f)=>{for(let c=l;c-1&&(this.openWidget=o>r),this.openWidget||s.addLineStartIfNotCovered(i),this.openMarks=o}forward(e,t,i=1){t-e<=10?this.old.advance(t-e,i,this.reuseWalker):(this.old.advance(5,-1,this.reuseWalker),this.old.advance(t-e-10,-1),this.old.advance(5,i,this.reuseWalker))}getCompositionContext(e){let t=[],i=null;for(let s=e.parentNode;;s=s.parentNode){let r=_.get(s);if(s==this.view.contentDOM)break;r instanceof ce?t.push(r):r?.isLine()?i=r:r instanceof Ze||(s.nodeName=="DIV"&&!i?i=new ri(s,wa):i||t.push(ce.of(new Bi({tagName:s.nodeName.toLowerCase(),attributes:mc(s)}),s)))}return i?{line:i,marks:t}:null}};function Ql(n,e){let t=i=>{for(let s of i.children)if((e?s.isText():s.length)||t(s))return!0;return!1};return t(n)}function qc(n){let e=n.isReplace?(n.startSide<0?64:0)|(n.endSide>0?128:0):n.startSide>0?32:16;return n.block&&(e|=256),e}var wa={class:"cm-line"};function Wc(n,e){let t=e.spec.attributes,i=e.spec.class;return!t&&!i||(n||(n={class:"cm-line"}),t&&Rr(t,n),i&&(n.class+=" "+i)),n}function $c(n){let e=[];for(let t=n.parents.length;t>1;t--){let i=t==n.parents.length?n.tile:n.parents[t].tile;i instanceof ce&&e.push(i.mark)}return e}function $s(n){let e=_.get(n);return e&&e.setDOM(n.cloneNode()),n}var ut=class extends Ye{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}};ut.inline=new ut("span");ut.block=new ut("div");var Ls=new class extends Ye{toDOM(){return document.createElement("br")}get isHidden(){return!0}get editable(){return!0}},An=class{constructor(e){this.view=e,this.decorations=[],this.blockWrappers=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.editContextFormatting=q.none,this.lastCompositionAfterCursor=!1,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.updateDeco(),this.tile=new si(e,e.contentDOM),this.updateInner([new Pe(0,0,0,e.state.doc.length)],null)}update(e){var t;let i=e.changedRanges;this.minWidth>0&&i.length&&(i.every(({fromA:f,toA:c})=>cthis.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.updateEditContextFormatting(e);let s=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&(!((t=this.domChanged)===null||t===void 0)&&t.newSel?s=this.domChanged.newSel.head:!_c(e.changes,this.hasComposition)&&!e.selectionSet&&(s=e.state.selection.main.head));let r=s>-1?zc(this.view,e.changes,s):null;if(this.domChanged=null,this.hasComposition){let{from:f,to:c}=this.hasComposition;i=new Pe(f,c,e.changes.mapPos(f,-1),e.changes.mapPos(c,1)).addToSet(i.slice())}this.hasComposition=r?{from:r.range.fromB,to:r.range.toB}:null,(x.ie||x.chrome)&&!r&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=this.decorations,l=this.blockWrappers;this.updateDeco();let a=Vc(o,this.decorations,e.changes);a.length&&(i=Pe.extendWithRanges(i,a));let h=Xc(l,this.blockWrappers,e.changes);return h.length&&(i=Pe.extendWithRanges(i,h)),r&&!i.some(f=>f.fromA<=r.range.fromA&&f.toA>=r.range.toA)&&(i=r.range.addToSet(i.slice())),this.tile.flags&2&&i.length==0?!1:(this.updateInner(i,r),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t){this.view.viewState.mustMeasureContent=!0;let{observer:i}=this.view;i.ignore(()=>{if(t||e.length){let o=this.tile,l=new sr(this.view,o,this.blockWrappers,this.decorations,this.dynamicDecorationMap);t&&_.get(t.text)&&l.cache.reused.set(_.get(t.text),2),this.tile=l.run(e,t),rr(o,l.cache.reused)}this.tile.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.tile.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let r=x.chrome||x.ios?{node:i.selectionRange.focusNode,written:!1}:void 0;this.tile.sync(r),r&&(r.written||i.selectionRange.focusNode!=r.node||!this.tile.dom.contains(r.node))&&(this.forceSelection=!0),this.tile.dom.style.height=""});let s=[];if(this.view.viewport.from||this.view.viewport.to-1)&&Ci(i,this.view.observer.selectionRange)&&!(s&&i.contains(s));if(!(r||t||o))return;let l=this.forceSelection;this.forceSelection=!1;let a=this.view.state.selection.main,h,f;if(a.empty?f=h=this.inlineDOMNearPos(a.anchor,a.assoc||1):(f=this.inlineDOMNearPos(a.head,a.head==a.from?1:-1),h=this.inlineDOMNearPos(a.anchor,a.anchor==a.from?1:-1)),x.gecko&&a.empty&&!this.hasComposition&&Lc(h)){let u=document.createTextNode("");this.view.observer.ignore(()=>h.node.insertBefore(u,h.node.childNodes[h.offset]||null)),h=f=new $e(u,0),l=!0}let c=this.view.observer.selectionRange;(l||!c.focusNode||(!Qi(h.node,h.offset,c.anchorNode,c.anchorOffset)||!Qi(f.node,f.offset,c.focusNode,c.focusOffset))&&!this.suppressWidgetCursorChange(c,a))&&(this.view.observer.ignore(()=>{x.android&&x.chrome&&i.contains(c.focusNode)&&Fc(c.focusNode,i)&&(i.blur(),i.focus({preventScroll:!0}));let u=Wi(this.view.root);if(u)if(a.empty){if(x.gecko){let d=Ic(h.node,h.offset);if(d&&d!=3){let p=(d==1?ia:na)(h.node,h.offset);p&&(h=new $e(p.node,p.offset))}}u.collapse(h.node,h.offset),a.bidiLevel!=null&&u.caretBidiLevel!==void 0&&(u.caretBidiLevel=a.bidiLevel)}else if(u.extend){u.collapse(h.node,h.offset);try{u.extend(f.node,f.offset)}catch{}}else{let d=document.createRange();a.anchor>a.head&&([h,f]=[f,h]),d.setEnd(f.node,f.offset),d.setStart(h.node,h.offset),u.removeAllRanges(),u.addRange(d)}o&&this.view.root.activeElement==i&&(i.blur(),s&&s.focus())}),this.view.observer.setSelectionRange(h,f)),this.impreciseAnchor=h.precise?null:new $e(c.anchorNode,c.anchorOffset),this.impreciseHead=f.precise?null:new $e(c.focusNode,c.focusOffset)}suppressWidgetCursorChange(e,t){return this.hasComposition&&t.empty&&Qi(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)&&this.posFromDOM(e.focusNode,e.focusOffset)==t.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,t=e.state.selection.main,i=Wi(e.root),{anchorNode:s,anchorOffset:r}=e.observer.selectionRange;if(!i||!t.empty||!t.assoc||!i.modify)return;let o=this.lineAt(t.head,t.assoc);if(!o)return;let l=o.posAtStart;if(t.head==l||t.head==l+o.length)return;let a=this.coordsAt(t.head,-1),h=this.coordsAt(t.head,1);if(!a||!h||a.bottom>h.top)return;let f=this.domAtPos(t.head+t.assoc,t.assoc);i.collapse(f.node,f.offset),i.modify("move",t.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let c=e.observer.selectionRange;e.docView.posFromDOM(c.anchorNode,c.anchorOffset)!=t.from&&i.collapse(s,r)}posFromDOM(e,t){let i=this.tile.nearest(e);if(!i)return this.tile.dom.compareDocumentPosition(e)&2?0:this.view.state.doc.length;let s=i.posAtStart;if(i.isComposite()){let r;if(e==i.dom)r=i.dom.childNodes[t];else{let o=Ke(e)==0?0:t==0?-1:1;for(;;){let l=e.parentNode;if(l==i.dom)break;o==0&&l.firstChild!=l.lastChild&&(e==l.firstChild?o=-1:o=1),e=l}o<0?r=e:r=e.nextSibling}if(r==i.dom.firstChild)return s;for(;r&&!_.get(r);)r=r.nextSibling;if(!r)return s+i.length;for(let o=0,l=s;;o++){let a=i.children[o];if(a.dom==r)return l;l+=a.length+a.breakAfter}}else return i.isText()?e==i.dom?s+t:s+(t?i.length:0):s}domAtPos(e,t){let{tile:i,offset:s}=this.tile.resolveBlock(e,t);return i.isWidget()?i.domPosFor(s,t):i.domIn(s,t)}inlineDOMNearPos(e,t){let i,s=-1,r=!1,o,l=-1,a=!1;return this.tile.blockTiles((h,f)=>{if(h.isWidget()){if(h.flags&32&&f>=e)return!0;h.flags&16&&(r=!0)}else{let c=f+h.length;if(f<=e&&(i=h,s=e-f,r=c=e&&!o&&(o=h,l=e-f,a=f>e),f>e&&o)return!0}}),!i&&!o?this.domAtPos(e,t):(r&&o?i=null:a&&i&&(o=null),i&&t<0||!o?i.domIn(s,t):o.domIn(l,t))}coordsAt(e,t,i){let{tile:s,offset:r}=this.tile.resolveBlock(e,t);return s.isWidget()?s.widget instanceof Ri?null:s.coordsInWidget(r,t,!0):s.coordsIn(r,t,i)}lineAt(e,t){let{tile:i}=this.tile.resolveBlock(e,t);return i.isLine()?i:null}coordsForChar(e){let{tile:t,offset:i}=this.tile.resolveBlock(e,1);if(!t.isLine())return null;function s(r,o){if(r.isComposite())for(let l of r.children){if(l.length>=o){let a=s(l,o);if(a)return a}if(o-=l.length,o<0)break}else if(r.isText()&&oMath.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,l=-1,a=this.view.textDirection==F.LTR,h=0,f=(c,u,d)=>{for(let p=0;ps);p++){let m=c.children[p],O=u+m.length,y=m.dom.getBoundingClientRect(),{height:w}=y;if(d&&!p&&(h+=y.top-d.top),m instanceof Ze)O>i&&f(m,u,y);else if(u>=i&&(h>0&&t.push(-h),t.push(w+h),h=0,o)){let k=m.dom.lastChild,D=k?Sn(k):[];if(D.length){let Q=D[D.length-1],P=a?Q.right-y.left:y.right-Q.left;P>l&&(l=P,this.minWidth=r,this.minWidthFrom=u,this.minWidthTo=O)}}d&&p==c.children.length-1&&(h+=d.bottom-y.bottom),u=O+m.breakAfter}};return f(this.tile,0,null),t}textDirectionAt(e){let{tile:t}=this.tile.resolveBlock(e,1);return getComputedStyle(t.dom).direction=="rtl"?F.RTL:F.LTR}measureTextSize(){let e=this.tile.blockTiles(o=>{if(o.isLine()&&o.children.length&&o.length<=20){let l=0,a;for(let h of o.children){if(!h.isText()||/[^ -~]/.test(h.text))return;let f=Sn(h.dom);if(f.length!=1)return;l+=f[0].width,a=f[0].height}if(l)return{lineHeight:o.dom.getBoundingClientRect().height,charWidth:l/o.length,textHeight:a}}});if(e)return e;let t=document.createElement("div"),i,s,r;return t.className="cm-line",t.style.width="99999px",t.style.position="absolute",t.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.tile.dom.appendChild(t);let o=Sn(t.firstChild)[0];i=t.getBoundingClientRect().height,s=o&&o.width?o.width/27:7,r=o&&o.height?o.height:i,t.remove()}),{lineHeight:i,charWidth:s,textHeight:r}}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let i=0,s=0;;s++){let r=s==t.viewports.length?null:t.viewports[s],o=r?r.from-1:this.view.state.doc.length;if(o>i){let l=(t.lineBlockAt(o).bottom-t.lineBlockAt(i).top)/this.view.scaleY;e.push(q.replace({widget:new Ri(l),block:!0,inclusive:!0,isBlockGap:!0}).range(i,o))}if(!r)break;i=r.to+1}return q.set(e)}updateDeco(){let e=1,t=this.view.state.facet(zn).map(r=>(this.dynamicDecorationMap[e++]=typeof r=="function")?r(this.view):r),i=!1,s=this.view.state.facet(Wr).map((r,o)=>{let l=typeof r=="function";return l&&(i=!0),l?r(this.view):r});for(s.length&&(this.dynamicDecorationMap[e++]=i,t.push(B.join(s))),this.decorations=[this.editContextFormatting,...t,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];etypeof r=="function"?r(this.view):r)}scrollIntoView(e){if(e.isSnapshot){let h=this.view.viewState.lineBlockAt(e.range.head);this.view.scrollDOM.scrollTop=h.top-e.yMargin,this.view.scrollDOM.scrollLeft=e.xMargin;return}for(let h of this.view.state.facet(ga))try{if(h(this.view,e.range,e))return!0}catch(f){ke(this.view.state,f,"scroll handler")}let{range:t}=e,i=this.coordsAt(t.head,t.assoc||(t.head>t.anchor?-1:1)),s;if(!i)return;!t.empty&&(s=this.coordsAt(t.anchor,t.anchor>t.head?-1:1))&&(i={left:Math.min(i.left,s.left),top:Math.min(i.top,s.top),right:Math.max(i.right,s.right),bottom:Math.max(i.bottom,s.bottom)});let r=ka(this.view),o={left:i.left-r.left,top:i.top-r.top,right:i.right+r.right,bottom:i.bottom+r.bottom},{offsetWidth:l,offsetHeight:a}=this.view.scrollDOM;if(yc(this.view.scrollDOM,o,t.head1&&(i.top>window.visualViewport.offsetTop+window.visualViewport.height||i.bottomi.isWidget()||i.children.some(t);return t(this.tile.resolveBlock(e,1).tile)}destroy(){rr(this.tile)}};function rr(n,e){let t=e?.get(n);if(t!=1){t==null&&n.destroy();for(let i of n.children)rr(i,e)}}function Lc(n){return n.node.nodeType==1&&n.node.firstChild&&(n.offset==0||n.node.childNodes[n.offset-1].contentEditable=="false")&&(n.offset==n.node.childNodes.length||n.node.childNodes[n.offset].contentEditable=="false")}function va(n,e){let t=n.observer.selectionRange;if(!t.focusNode)return null;let i=ia(t.focusNode,t.focusOffset),s=na(t.focusNode,t.focusOffset),r=i||s;if(s&&i&&s.node!=i.node){let l=_.get(s.node);if(!l||l.isText()&&l.text!=s.node.nodeValue)r=s;else if(n.docView.lastCompositionAfterCursor){let a=_.get(i.node);!a||a.isText()&&a.text!=i.node.nodeValue||(r=s)}}if(n.docView.lastCompositionAfterCursor=r!=i,!r)return null;let o=e-r.offset;return{from:o,to:o+r.node.nodeValue.length,node:r.node}}function zc(n,e,t){let i=va(n,t);if(!i)return null;let{node:s,from:r,to:o}=i,l=s.nodeValue;if(/[\n\r]/.test(l)||n.state.doc.sliceString(i.from,i.to)!=l)return null;let a=e.invertedDesc;return{range:new Pe(a.mapPos(r),a.mapPos(o),r,o),text:s}}function Ic(n,e){return n.nodeType!=1?0:(e&&n.childNodes[e-1].contentEditable=="false"?1:0)|(e{ie.from&&(t=!0)}),t}var Ri=class extends Ye{constructor(e){super(),this.height=e}toDOM(){let e=document.createElement("div");return e.className="cm-gap",this.updateDOM(e),e}eq(e){return e.height==this.height}updateDOM(e){return e.style.height=this.height+"px",!0}get editable(){return!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}};function Hc(n,e,t=1){let i=n.charCategorizer(e),s=n.doc.lineAt(e),r=e-s.from;if(s.length==0)return b.cursor(e);r==0?t=1:r==s.length&&(t=-1);let o=r,l=r;t<0?o=K(s.text,r,!1):l=K(s.text,r);let a=i(s.text.slice(o,l));for(;o>0;){let h=K(s.text,o,!1);if(i(s.text.slice(h,o))!=a)break;o=h}for(;ln.defaultLineHeight*1.5){let l=n.viewState.heightOracle.textHeight,a=Math.floor((s-t.top-(n.defaultLineHeight-l)*.5)/l);r+=a*n.viewState.heightOracle.lineLength}let o=n.state.sliceDoc(t.from,t.to);return t.from+pl(o,r,n.state.tabSize)}function jc(n,e,t){let i=n.lineBlockAt(e);if(Array.isArray(i.type)){let s;for(let r of i.type){if(r.from>e)break;if(!(r.toe)return r;(!s||r.type==ue.Text&&(s.type!=r.type||(t<0?r.frome)))&&(s=r)}}return s||i}return i}function Gc(n,e,t,i){let s=jc(n,e.head,e.assoc||-1),r=!i||s.type!=ue.Text||!(n.lineWrapping||s.widgetLineBreaks)?null:n.coordsAtPos(e.assoc<0&&e.head>s.from?e.head-1:e.head);if(r){let o=n.dom.getBoundingClientRect(),l=n.textDirectionAt(s.from),a=n.posAtCoords({x:t==(l==F.LTR)?o.right-1:o.left+1,y:(r.top+r.bottom)/2});if(a!=null)return b.cursor(a,t?-1:1)}return b.cursor(t?s.to:s.from,t?-1:1)}function Pl(n,e,t,i){let s=n.state.doc.lineAt(e.head),r=n.bidiSpans(s),o=n.textDirectionAt(s.from);for(let l=e,a=null;;){let h=Pc(s,r,o,l,t),f=aa;if(!h){if(s.number==(t?n.state.doc.lines:1))return l;f=` +`,s=n.state.doc.line(s.number+(t?1:-1)),r=n.bidiSpans(s),h=t?b.cursor(s.from,-1):b.cursor(s.to,1)}if(a){if(!a(f))return l}else{if(!i)return h;a=i(f)}l=h}}function Zc(n,e,t){let i=n.state.charCategorizer(e),s=i(t);return r=>{let o=i(r);return s==re.Space&&(s=o),s==o}}function Yc(n,e,t,i){let s=e.head,r=t?1:-1;if(s==(t?n.state.doc.length:0))return b.cursor(s,e.assoc);let o=e.goalColumn,l,a=n.contentDOM.getBoundingClientRect(),h=n.coordsAtPos(s,e.assoc||((e.empty?t:e.head==e.from)?1:-1)),f=n.documentTop;if(h)o==null&&(o=h.left-a.left),l=r<0?h.top:h.bottom;else{let p=n.viewState.lineBlockAt(s);o==null&&(o=Math.min(a.right-a.left,n.defaultCharacterWidth*(s-p.from))),l=(r<0?p.top:p.bottom)+f}let c=a.left+o,u=n.viewState.heightOracle.textHeight>>1,d=i??u;for(let p=0;;p+=u){let m=l+(d+p)*r,O=lr(n,{x:c,y:m},!1,r);if(t?m>a.bottom:ml:w{if(e>r&&es(n)),t.from,e.head>t.from?-1:1);return i==t.from?t:b.cursor(i,in.viewState.docHeight)return new Se(n.state.doc.length,-1);if(h=n.elementAtHeight(a),i==null)break;if(h.type==ue.Text){if(i<0?h.ton.viewport.to)break;let u=n.docView.coordsAt(i<0?h.from:h.to,i>0?-1:1);if(u&&(i<0?u.top<=a+r:u.bottom>=a+r))break}let c=n.viewState.heightOracle.textHeight/2;a=i>0?h.bottom+c:h.top-c}if(n.viewport.from>=h.to||n.viewport.to<=h.from){if(t)return null;if(h.type==ue.Text){let c=Uc(n,s,h,o,l);return new Se(c,c==h.from?1:-1)}}if(h.type!=ue.Text)return a<(h.top+h.bottom)/2?new Se(h.from,1):new Se(h.to,-1);let f=n.docView.lineAt(h.from,2);return(!f||f.length!=h.length)&&(f=n.docView.lineAt(h.from,-2)),new ar(n,o,l,n.textDirectionAt(h.from)).scanTile(f,h.from)}var ar=class{constructor(e,t,i,s){this.view=e,this.x=t,this.y=i,this.baseDir=s,this.line=null,this.spans=null}bidiSpansAt(e){return(!this.line||this.line.from>e||this.line.to1||i.length&&(i[0].level!=this.baseDir||i[0].to+s.from>1;t:if(o.has(m)){for(let w=1;w=r&&(k-=p),!o.has(k)){m=k;break t}}break e}o.add(m);let O=t(m),y=0;if(O)for(let w=0;w1))if(k.bottomthis.y)(!h||h.top>k.top)&&(h=k),y=-1;else{let D=k.left>this.x?this.x-k.left:k.right(p+p+m)/3)return this.y=a.bottom-1,this.scan(e,t,!0);if(h&&h.top<(p+m+m)/3)return this.y=h.top+1,this.scan(e,t,!0)}let d=(l?this.dirAt(e[f],1):this.baseDir)==F.LTR;return{i:f,after:this.x>(u.left+u.right)/2==d}}scanText(e,t){let i=[];for(let r=0;r{let o=i[r]-t,l=i[r+1]-t;return $i(e.dom,o,l).getClientRects()});return s.after?new Se(i[s.i+1],-1):new Se(i[s.i],1)}scanTile(e,t){if(!e.length)return new Se(t,1);if(e.children.length==1){let l=e.children[0];if(l.isText())return this.scanText(l,t);if(l.isComposite())return this.scanTile(l,t)}let i=[t];for(let l=0,a=t;l{let a=e.children[l];return a.flags&48?null:(a.dom.nodeType==1?a.dom:$i(a.dom,0,a.length)).getClientRects()}),r=e.children[s.i],o=i[s.i];return r.isText()?this.scanText(r,o):r.isComposite()?this.scanTile(r,o):s.after?new Se(i[s.i+1],-1):new Se(o,1)}},Yt="\uFFFF",hr=class{constructor(e,t){this.points=e,this.view=t,this.text="",this.lineSeparator=t.state.facet(z.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=Yt}readRange(e,t){if(!e)return this;let i=e.parentNode;for(let s=e;;){this.findPointBefore(i,s);let r=this.text.length;this.readNode(s);let o=_.get(s),l=s.nextSibling;if(l==t){o?.breakAfter&&!l&&i!=this.view.contentDOM&&this.lineBreak();break}let a=_.get(l);(o&&a?o.breakAfter:(o?o.breakAfter:Tn(s))||Tn(l)&&(s.nodeName!="BR"||o?.isWidget())&&this.text.length>r)&&!Jc(l,t)&&this.lineBreak(),s=l}return this.findPointBefore(i,t),this}readTextNode(e){let t=e.nodeValue;for(let i of this.points)i.node==e&&(i.pos=this.text.length+Math.min(i.offset,t.length));for(let i=0,s=this.lineSeparator?null:/\r\n?|\n/g;;){let r=-1,o=1,l;if(this.lineSeparator?(r=t.indexOf(this.lineSeparator,i),o=this.lineSeparator.length):(l=s.exec(t))&&(r=l.index,o=l[0].length),this.append(t.slice(i,r<0?t.length:r)),r<0)break;if(this.lineBreak(),o>1)for(let a of this.points)a.node==e&&a.pos>this.text.length&&(a.pos-=o-1);i=r+o}}readNode(e){let t=_.get(e),i=t&&t.overrideDOMText;if(i!=null){this.findPointInside(e,i.length);for(let s=i.iter();!s.next().done;)s.lineBreak?this.lineBreak():this.append(s.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let i of this.points)i.node==e&&e.childNodes[i.offset]==t&&(i.pos=this.text.length)}findPointInside(e,t){for(let i of this.points)(e.nodeType==3?i.node==e:e.contains(i.node))&&(i.pos=this.text.length+(Kc(e,i.node,i.offset)?t:0))}};function Kc(n,e,t){for(;;){if(!e||t-1;let{impreciseHead:r,impreciseAnchor:o}=e.docView,l=e.state.selection;if(e.state.readOnly&&t>-1)this.newSel=null;else if(t>-1&&(this.bounds=Ca(e.docView.tile,t,i,0))){let a=r||o?[]:tu(e),h=new hr(a,e);h.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=h.text,this.newSel=iu(a,this.bounds.from)}else{let a=e.observer.selectionRange,h=r&&r.node==a.focusNode&&r.offset==a.focusOffset||!Us(e.contentDOM,a.focusNode)?l.main.head:e.docView.posFromDOM(a.focusNode,a.focusOffset),f=o&&o.node==a.anchorNode&&o.offset==a.anchorOffset||!Us(e.contentDOM,a.anchorNode)?l.main.anchor:e.docView.posFromDOM(a.anchorNode,a.anchorOffset),c=e.viewport;if((x.ios||x.chrome)&&h!=f&&Math.min(h,f)<=l.main.from&&Math.max(h,f)>=l.main.to&&(c.from>0||c.to-1&&l.ranges.length>1)this.newSel=l.replaceRange(b.range(f,h));else if(e.lineWrapping&&f==h&&!(l.main.empty&&l.main.head==h)&&e.inputState.lastTouchTime>Date.now()-100){let u=e.coordsAtPos(h,-1),d=0;u&&(d=e.inputState.lastTouchY<=u.bottom?-1:1),this.newSel=b.create([b.cursor(h,d)])}else this.newSel=b.single(f,h)}}};function Ca(n,e,t,i){if(n.isComposite()){let s=-1,r=-1,o=-1,l=-1;for(let a=0,h=i,f=i;at)return Ca(c,e,t,h);if(u>=e&&s==-1&&(s=a,r=h),h>t&&c.dom.parentNode==n.dom){o=a,l=f;break}f=u,h=u+c.breakAfter}return{from:r,to:l<0?i+n.length:l,startDOM:(s?n.children[s-1].dom.nextSibling:null)||n.dom.firstChild,endDOM:o=0?n.children[o].dom:null}}else return n.isText()?{from:i,to:i+n.length,startDOM:n.dom,endDOM:n.dom.nextSibling}:null}function Qa(n,e){let t,{newSel:i}=e,{state:s}=n,r=s.selection.main,o=n.inputState.lastKeyTime>Date.now()-100?n.inputState.lastKeyCode:-1;if(e.bounds){let{from:l,to:a}=e.bounds,h=r.from,f=null;(o===8||x.android&&e.text.length=l&&r.to<=a&&(e.typeOver||c!=e.text)&&c.slice(0,r.from-l)==e.text.slice(0,r.from-l)&&c.slice(r.to-l)==e.text.slice(u=e.text.length-(c.length-(r.to-l)))?t={from:r.from,to:r.to,insert:M.of(e.text.slice(r.from-l,u).split(Yt))}:(d=Pa(c,e.text,h-l,f))&&(x.chrome&&o==13&&d.toB==d.from+2&&e.text.slice(d.from,d.toB)==Yt+Yt&&d.toB--,t={from:l+d.from,to:l+d.toA,insert:M.of(e.text.slice(d.from,d.toB).split(Yt))})}else i&&(!n.hasFocus&&s.facet(Ge)||Mn(i,r))&&(i=null);if(!t&&!i)return!1;if((x.mac||x.android)&&t&&t.from==t.to&&t.from==r.head-1&&/^\. ?$/.test(t.insert.toString())&&n.contentDOM.getAttribute("autocorrect")=="off"?(i&&t.insert.length==2&&(i=b.single(i.main.anchor-1,i.main.head-1)),t={from:t.from,to:t.to,insert:M.of([t.insert.toString().replace("."," ")])}):s.doc.lineAt(r.from).toDate.now()-50?t={from:r.from,to:r.to,insert:s.toText(n.inputState.insertingText)}:x.chrome&&t&&t.from==t.to&&t.from==r.head&&t.insert.toString()==` + `&&n.lineWrapping&&(i&&(i=b.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:M.of([" "])}),t)return $r(n,t,i,o);if(i&&!Mn(i,r)){let l=!1,a="select";return n.inputState.lastSelectionTime>Date.now()-50&&(n.inputState.lastSelectionOrigin=="select"&&(l=!0),a=n.inputState.lastSelectionOrigin,a=="select.pointer"&&(i=Ta(s.facet(Li).map(h=>h(n)),i))),n.dispatch({selection:i,scrollIntoView:l,userEvent:a}),!0}else return!1}function $r(n,e,t,i=-1){if(x.ios&&n.inputState.flushIOSKey(e))return!0;let s=n.state.selection.main;if(x.android&&(e.to==s.to&&(e.from==s.from||e.from==s.from-1&&n.state.sliceDoc(e.from,s.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&ii(n.contentDOM,"Enter",13)||(e.from==s.from-1&&e.to==s.to&&e.insert.length==0||i==8&&e.insert.lengths.head)&&ii(n.contentDOM,"Backspace",8)||e.from==s.from&&e.to==s.to+1&&e.insert.length==0&&ii(n.contentDOM,"Delete",46)))return!0;let r=e.insert.toString();n.inputState.composing>=0&&n.inputState.composing++;let o,l=()=>o||(o=eu(n,e,t));return n.state.facet(da).some(a=>a(n,e.from,e.to,r,l))||n.dispatch(l()),!0}function eu(n,e,t){let i,s=n.state,r=s.selection.main,o=-1;if(e.from==e.to&&e.fromr.to){let a=e.fromc(n)),h,a);e.from==f&&(o=f)}if(o>-1)i={changes:e,selection:b.cursor(e.from+e.insert.length,-1)};else if(e.from>=r.from&&e.to<=r.to&&e.to-e.from>=(r.to-r.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&n.inputState.composing<0){let a=r.frome.to?s.sliceDoc(e.to,r.to):"";i=s.replaceSelection(n.state.toText(a+e.insert.sliceString(0,void 0,n.state.lineBreak)+h))}else{let a=s.changes(e),h=t&&t.main.to<=a.newLength?t.main:void 0;if(s.selection.ranges.length>1&&(n.inputState.composing>=0||n.inputState.compositionPendingChange)&&e.to<=r.to+10&&e.to>=r.to-10){let f=n.state.sliceDoc(e.from,e.to),c,u=t&&va(n,t.main.head);if(u){let p=e.insert.length-(e.to-e.from);c={from:u.from,to:u.to-p}}else c=n.state.doc.lineAt(r.head);let d=r.to-e.to;i=s.changeByRange(p=>{if(p.from==r.from&&p.to==r.to)return{changes:a,range:h||p.map(a)};let m=p.to-d,O=m-f.length;if(n.state.sliceDoc(O,m)!=f||m>=c.from&&O<=c.to)return{range:p};let y=s.changes({from:O,to:m,insert:e.insert}),w=p.to-r.to;return{changes:y,range:h?b.range(Math.max(0,h.anchor+w),Math.max(0,h.head+w)):p.map(y)}})}else i={changes:a,selection:h&&s.selection.replaceRange(h)}}let l="input.type";return(n.composing||n.inputState.compositionPendingChange&&n.inputState.compositionEndedAt>Date.now()-50)&&(n.inputState.compositionPendingChange=!1,l+=".compose",n.inputState.compositionFirstChange&&(l+=".start",n.inputState.compositionFirstChange=!1)),s.update(i,{userEvent:l,scrollIntoView:!0})}function Pa(n,e,t,i){let s=Math.min(n.length,e.length),r=0;for(;r0&&l>0&&n.charCodeAt(o-1)==e.charCodeAt(l-1);)o--,l--;if(i=="end"){let a=Math.max(0,r-Math.min(o,l));t-=o+a-r}if(o=o?r-t:0;r-=a,l=r+(l-o),o=r}else if(l=l?r-t:0;r-=a,o=r+(o-l),l=r}return{from:r,toA:o,toB:l}}function tu(n){let e=[];if(n.root.activeElement!=n.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}=n.observer.selectionRange;return t&&(e.push(new Rn(t,i)),(s!=t||r!=i)&&e.push(new Rn(s,r))),e}function iu(n,e){if(n.length==0)return null;let t=n[0].pos,i=n.length==2?n[1].pos:t;return t<0||i<0?null:t==i?b.create([b.cursor(i+e,-1)]):b.single(t+e,i+e)}function Mn(n,e){return e.head==n.main.head&&e.anchor==n.main.anchor}var cr=class{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.touchActive=!1,this.lastTouchTime=0,this.lastTouchX=0,this.lastTouchY=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.lastWheelEvent=0,this.pendingIOSKey=void 0,this.lastIOSMomentumScroll=0,this.tabFocusMode=-1,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.insertingText="",this.insertingTextAt=0,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,x.safari&&e.contentDOM.addEventListener("input",()=>null),x.gecko&&Ou(e.contentDOM.ownerDocument)}handleEvent(e){!fu(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||(this.view.updateState!=0?Promise.resolve().then(()=>this.runHandlers(e.type,e)):this.runHandlers(e.type,e))}runHandlers(e,t){let i=this.handlers[e];if(i){for(let s of i.observers)s(this.view,t);for(let s of i.handlers){if(t.defaultPrevented)break;if(s(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=su(e),i=this.handlers,s=this.view.contentDOM;for(let r in t)if(r!="scroll"){let o=!t[r].handlers.length,l=i[r];l&&o!=!l.handlers.length&&(s.removeEventListener(r,this.handleEvent),l=null),l||s.addEventListener(r,this.handleEvent,{passive:o})}for(let r in i)r!="scroll"&&!t[r]&&s.removeEventListener(r,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&this.tabFocusMode>-1&&(!this.tabFocusMode||Date.now()<=this.tabFocusMode))return!0;if(this.tabFocusMode>0&&e.keyCode!=27&&Ra.indexOf(e.keyCode)<0&&(this.tabFocusMode=-1),x.android&&x.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;if(x.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&(Aa.some(t=>t.keyCode==e.keyCode)&&!e.ctrlKey||ru.indexOf(e.key)>-1&&e.ctrlKey)){let t={ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey,shiftKey:e.shiftKey};t.shiftKey&&x.ios&&!/^(off|none)$/.test(this.view.contentDOM.autocapitalize)&&nu(this.view.win)&&(t.shiftKey=!1);let i=this.pendingIOSKey={key:e.key,keyCode:e.keyCode,mods:t};return setTimeout(()=>{this.pendingIOSKey==i&&this.flushIOSKey()},50),!0}return e.keyCode!=229&&this.view.observer.forceFlush(),!1}flushIOSKey(e){let t=this.pendingIOSKey;return!t||this.view.observer.pendingRecords().length||t.key=="Enter"&&e&&e.from0?!0:x.safari&&!x.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.view.observer.update(e),this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}};function nu(n){return n.visualViewport?n.visualViewport.height*n.visualViewport.scale/n.document.documentElement.clientHeight<.85:!1}function Al(n,e){return(t,i)=>{try{return e.call(n,i,t)}catch(s){ke(t.state,s)}}}function su(n){let e=Object.create(null);function t(i){return e[i]||(e[i]={observers:[],handlers:[]})}for(let i of n){let s=i.spec,r=s&&s.plugin.domEventHandlers,o=s&&s.plugin.domEventObservers;if(r)for(let l in r){let a=r[l];a&&t(l).handlers.push(Al(i.value,a))}if(o)for(let l in o){let a=o[l];a&&t(l).observers.push(Al(i.value,a))}}for(let i in Ae)t(i).handlers.push(Ae[i]);for(let i in ae)t(i).observers.push(ae[i]);return e}var Aa=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],ru="dthko",Ra=[16,17,18,20,91,92,224,225],pn=6;function mn(n){return Math.max(0,n)*.7+8}function ou(n,e){return Math.max(Math.abs(n.clientX-e.clientX),Math.abs(n.clientY-e.clientY))}var ur=class{constructor(e,t,i,s){this.view=e,this.startEvent=t,this.style=i,this.mustSelect=s,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParents=Yl(e.contentDOM),this.atoms=e.state.facet(Li).map(o=>o(e));let r=e.contentDOM.ownerDocument;r.addEventListener("mousemove",this.move=this.move.bind(this)),r.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(z.allowMultipleSelections)&&lu(e,t),this.dragging=hu(e,t)&&Da(t)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&ou(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let t=0,i=0,s=0,r=0,o=this.view.win.innerWidth,l=this.view.win.innerHeight;this.scrollParents.x&&({left:s,right:o}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:r,bottom:l}=this.scrollParents.y.getBoundingClientRect());let a=ka(this.view);e.clientX-a.left<=s+pn?t=-mn(s-e.clientX):e.clientX+a.right>=o-pn&&(t=mn(e.clientX-o)),e.clientY-a.top<=r+pn?i=-mn(r-e.clientY):e.clientY+a.bottom>=l-pn&&(i=mn(e.clientY-l)),this.setScrollSpeed(t,i)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,t){this.scrollSpeed={x:e,y:t},e||t?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){let{x:e,y:t}=this.scrollSpeed;e&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=e,e=0),t&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=t,t=0),(e||t)&&this.view.win.scrollBy(e,t),this.dragging===!1&&this.select(this.lastEvent)}select(e){let{view:t}=this,i=Ta(this.atoms,this.style.get(e,this.extend,this.multiple));(this.mustSelect||!i.eq(t.state.selection,this.dragging===!1))&&this.view.dispatch({selection:i,userEvent:"select.pointer"}),this.mustSelect=!1}update(e){e.transactions.some(t=>t.isUserEvent("input.type"))?this.destroy():this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}};function lu(n,e){let t=n.state.facet(ha);return t.length?t[0](e):x.mac?e.metaKey:e.ctrlKey}function au(n,e){let t=n.state.facet(fa);return t.length?t[0](e):x.mac?!e.altKey:!e.ctrlKey}function hu(n,e){let{main:t}=n.state.selection;if(t.empty)return!1;let i=Wi(n.root);if(!i||i.rangeCount==0)return!0;let s=i.getRangeAt(0).getClientRects();for(let r=0;r=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function fu(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,i;t!=n.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(i=_.get(t))&&i.isWidget()&&!i.isHidden&&i.widget.ignoreEvent(e))return!1;return!0}var Ae=Object.create(null),ae=Object.create(null),Ma=x.ie&&x.ie_version<15||x.ios&&x.webkit_version<604;function cu(n){let e=n.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{n.focus(),t.remove(),Ea(n,t.value)},50)}function In(n,e,t){for(let i of n.facet(e))t=i(t,n);return t}function Ea(n,e){e=In(n.state,Dr,e);let{state:t}=n,i,s=1,r=t.toText(e),o=r.lines==t.selection.ranges.length;if(dr!=null&&t.selection.ranges.every(a=>a.empty)&&dr==r.toString()){let a=-1;i=t.changeByRange(h=>{let f=t.doc.lineAt(h.from);if(f.from==a)return{range:h};a=f.from;let c=t.toText((o?r.line(s++).text:e)+t.lineBreak);return{changes:{from:f.from,insert:c},range:b.cursor(h.from+c.length,-1)}})}else o?i=t.changeByRange(a=>{let h=r.line(s++);return{changes:{from:a.from,to:a.to,insert:h.text},range:b.cursor(a.from+h.length,-1)}}):i=t.replaceSelection(r);n.dispatch(i,{userEvent:"input.paste",scrollIntoView:!0})}ae.scroll=n=>{let e=n.inputState;e.lastScrollTop=n.scrollDOM.scrollTop,e.lastScrollLeft=n.scrollDOM.scrollLeft,x.ios&&!e.touchActive&&(e.lastIOSMomentumScroll=Date.now())};ae.wheel=ae.mousewheel=n=>{n.inputState.lastWheelEvent=Date.now()};Ae.keydown=(n,e)=>(n.inputState.setSelectionOrigin("select"),e.keyCode==27&&n.inputState.tabFocusMode!=0&&(n.inputState.tabFocusMode=Date.now()+2e3),!1);ae.touchstart=(n,e)=>{let t=n.inputState,i=e.targetTouches[0];t.touchActive=!0,t.lastTouchTime=Date.now(),i&&(t.lastTouchX=i.clientX,t.lastTouchY=i.clientY),t.setSelectionOrigin("select.pointer")};ae.touchmove=n=>{n.inputState.setSelectionOrigin("select.pointer")};ae.touchend=(n,e)=>{n.inputState.touchActive=!1};Ae.mousedown=(n,e)=>{if(n.observer.flush(),n.inputState.lastTouchTime>Date.now()-2e3)return!1;let t=null;for(let i of n.state.facet(ca))if(t=i(n,e),t)break;if(!t&&e.button==0&&(t=du(n,e)),t){let i=!n.hasFocus;n.inputState.startMouseSelection(new ur(n,e,t,i)),i&&n.observer.ignore(()=>{ea(n.contentDOM);let r=n.root.activeElement;r&&!r.contains(n.contentDOM)&&r.blur()});let s=n.inputState.mouseSelection;if(s)return s.start(e),s.dragging===!1}else n.inputState.setSelectionOrigin("select.pointer");return!1};function Rl(n,e,t,i){if(i==1)return b.cursor(e,t);if(i==2)return Hc(n.state,e,t);{let s=n.docView.lineAt(e,t),r=n.state.doc.lineAt(s?s.posAtEnd:e),o=s?s.posAtStart:r.from,l=s?s.posAtEnd:r.to;return lDate.now()-400&&Math.abs(e.clientX-n.clientX)<2&&Math.abs(e.clientY-n.clientY)<2?(El+1)%3:1}function du(n,e){let t=n.posAndSideAtCoords({x:e.clientX,y:e.clientY},!1),i=Da(e),s=n.state.selection;return{update(r){r.docChanged&&(t.pos=r.changes.mapPos(t.pos),s=s.map(r.changes))},get(r,o,l){let a=n.posAndSideAtCoords({x:r.clientX,y:r.clientY},!1),h,f=Rl(n,a.pos,a.assoc,i);if(t.pos!=a.pos&&!o){let c=Rl(n,t.pos,t.assoc,i),u=Math.min(c.from,f.from),d=Math.max(c.to,f.to);f=u1&&(h=pu(s,a.pos))?h:l?s.addRange(f):b.create([f])}}}function pu(n,e){for(let t=0;t=e)return b.create(n.ranges.slice(0,t).concat(n.ranges.slice(t+1)),n.mainIndex==t?0:n.mainIndex-(n.mainIndex>t?1:0))}return null}Ae.dragstart=(n,e)=>{let{selection:{main:t}}=n.state;if(e.target.draggable){let s=n.docView.tile.nearest(e.target);if(s&&s.isWidget()){let r=s.posAtStart,o=r+s.length;(r>=t.to||o<=t.from)&&(t=b.undirectionalRange(r,o))}}let{inputState:i}=n;return i.mouseSelection&&(i.mouseSelection.dragging=!0),i.draggedContent=t,e.dataTransfer&&(e.dataTransfer.setData("Text",In(n.state,Br,n.state.sliceDoc(t.from,t.to))),e.dataTransfer.effectAllowed="copyMove"),!1};Ae.dragend=n=>(n.inputState.draggedContent=null,!1);function Bl(n,e,t,i){if(t=In(n.state,Dr,t),!t)return;let s=n.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:r}=n.inputState,o=i&&r&&au(n,e)?{from:r.from,to:r.to}:null,l={from:s,insert:t},a=n.state.changes(o?[o,l]:l);n.focus(),n.dispatch({changes:a,selection:{anchor:a.mapPos(s,-1),head:a.mapPos(s,1)},userEvent:o?"move.drop":"input.drop"}),n.inputState.draggedContent=null}Ae.drop=(n,e)=>{if(!e.dataTransfer)return!1;if(n.state.readOnly)return!0;let t=e.dataTransfer.files;if(t&&t.length){let i=Array(t.length),s=0,r=()=>{++s==t.length&&Bl(n,e,i.filter(o=>o!=null).join(n.state.lineBreak),!1)};for(let o=0;o{/[\x00-\x08\x0e-\x1f]{2}/.test(l.result)||(i[o]=l.result),r()},l.readAsText(t[o])}return!0}else{let i=e.dataTransfer.getData("Text");if(i)return Bl(n,e,i,!0),!0}return!1};Ae.paste=(n,e)=>{if(n.state.readOnly)return!0;n.observer.flush();let t=Ma?null:e.clipboardData;return t?(Ea(n,t.getData("text/plain")||t.getData("text/uri-list")),!0):(cu(n),!1)};function mu(n,e){let t=n.dom.parentNode;if(!t)return;let i=t.appendChild(document.createElement("textarea"));i.style.cssText="position: fixed; left: -10000px; top: 10px",i.value=e,i.focus(),i.selectionEnd=e.length,i.selectionStart=0,setTimeout(()=>{i.remove(),n.focus()},50)}function gu(n){let e=[],t=[],i=!1;for(let s of n.selection.ranges)s.empty||(e.push(n.sliceDoc(s.from,s.to)),t.push(s));if(!e.length){let s=-1;for(let{from:r}of n.selection.ranges){let o=n.doc.lineAt(r);o.number>s&&(e.push(o.text),t.push({from:o.from,to:Math.min(n.doc.length,o.to+1)})),s=o.number}i=!0}return{text:In(n,Br,e.join(n.lineBreak)),ranges:t,linewise:i}}var dr=null;Ae.copy=Ae.cut=(n,e)=>{if(!Ci(n.contentDOM,n.observer.selectionRange))return!1;let{text:t,ranges:i,linewise:s}=gu(n.state);if(!t&&!s)return!1;dr=s?t:null,e.type=="cut"&&!n.state.readOnly&&n.dispatch({changes:i,scrollIntoView:!0,userEvent:"delete.cut"});let r=Ma?null:e.clipboardData;return r?(r.clearData(),r.setData("text/plain",t),!0):(mu(n,t),!1)};var Ba=fe.define();function qa(n,e){let t=[];for(let i of n.facet(pa)){let s=i(n,e);s&&t.push(s)}return t.length?n.update({effects:t,annotations:Ba.of(!0)}):null}function Wa(n){setTimeout(()=>{let e=n.hasFocus;if(e!=n.inputState.notifiedFocused){let t=qa(n.state,e);t?n.dispatch(t):n.update([])}},10)}ae.focus=n=>{n.inputState.lastFocusTime=Date.now(),!n.scrollDOM.scrollTop&&(n.inputState.lastScrollTop||n.inputState.lastScrollLeft)&&(n.scrollDOM.scrollTop=n.inputState.lastScrollTop,n.scrollDOM.scrollLeft=n.inputState.lastScrollLeft),Wa(n)};ae.blur=n=>{n.observer.clearSelectionRange(),Wa(n)};ae.compositionstart=ae.compositionupdate=n=>{if(!n.observer.editContext&&(n.inputState.compositionFirstChange==null&&(n.inputState.compositionFirstChange=!0),n.inputState.composing<0)){let{main:e}=n.state.selection;!e.empty&&n.lineBlockAt(e.from).from!=n.lineBlockAt(e.to).from&&n.dispatch({changes:n.state.selection.ranges.filter(t=>!t.empty).map(t=>({from:t.from,to:t.to})),userEvent:"input"}),n.inputState.composing=0}};ae.compositionend=n=>{n.observer.editContext||(n.inputState.composing=-1,n.inputState.compositionEndedAt=Date.now(),n.inputState.compositionPendingKey=!0,n.inputState.compositionPendingChange=n.observer.pendingRecords().length>0,n.inputState.compositionFirstChange=null,x.chrome&&x.android?n.observer.flushSoon():n.inputState.compositionPendingChange?Promise.resolve().then(()=>n.observer.flush()):setTimeout(()=>{n.inputState.composing<0&&n.docView.hasComposition&&n.update([])},50))};ae.contextmenu=n=>{n.inputState.lastContextMenu=Date.now()};Ae.beforeinput=(n,e)=>{var t,i;if((e.inputType=="insertText"||e.inputType=="insertCompositionText")&&(n.inputState.insertingText=e.data,n.inputState.insertingTextAt=Date.now()),e.inputType=="insertReplacementText"&&n.observer.editContext){let r=(t=e.dataTransfer)===null||t===void 0?void 0:t.getData("text/plain"),o=e.getTargetRanges();if(r&&o.length){let l=o[0],a=n.posAtDOM(l.startContainer,l.startOffset),h=n.posAtDOM(l.endContainer,l.endOffset);return $r(n,{from:a,to:h,insert:n.state.toText(r)},null),!0}}let s;if(x.chrome&&x.android&&(s=Aa.find(r=>r.inputType==e.inputType))&&(n.observer.delayAndroidKey(s.key,s.keyCode),s.key=="Backspace"||s.key=="Delete")){let r=((i=window.visualViewport)===null||i===void 0?void 0:i.height)||0;setTimeout(()=>{var o;(((o=window.visualViewport)===null||o===void 0?void 0:o.height)||0)>r+10&&n.hasFocus&&(n.contentDOM.blur(),n.focus())},100)}return x.ios&&e.inputType=="deleteContentForward"&&n.observer.flushSoon(),x.safari&&e.inputType=="insertText"&&n.inputState.composing>=0&&setTimeout(()=>ae.compositionend(n,e),20),!1};var ql=new Set;function Ou(n){ql.has(n)||(ql.add(n),n.addEventListener("copy",()=>{}),n.addEventListener("cut",()=>{}))}var Wl=["pre-wrap","normal","pre-line","break-spaces"],li=!1;function $l(){li=!1}var pr=class{constructor(e){this.lineWrapping=e,this.doc=M.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30}heightForGap(e,t){let i=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(i+=Math.max(0,Math.ceil((t-e-i*this.lineLength*.5)/this.lineLength))),this.lineHeight*i}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/Math.max(1,this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return Wl.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let i=0;i-1,a=Math.abs(t-this.lineHeight)>.3||this.lineWrapping!=l;if(this.lineWrapping=l,this.lineHeight=t,this.charWidth=i,this.textHeight=s,this.lineLength=r,a){this.heightSamples={};for(let h=0;h0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e){this.height!=e&&(Math.abs(this.height-e)>xn&&(li=!0),this.height=e)}replace(e,t,i){return n.of(i)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,i,s){let r=this,o=i.doc;for(let l=s.length-1;l>=0;l--){let{fromA:a,toA:h,fromB:f,toB:c}=s[l],u=r.lineAt(a,I.ByPosNoHeight,i.setDoc(t),0,0),d=u.to>=h?u:r.lineAt(h,I.ByPosNoHeight,i,0,0);for(c+=d.to-h,h=d.to;l>0&&u.from<=s[l-1].toA;)a=s[l-1].fromA,f=s[l-1].fromB,l--,ar*2){let l=e[t-1];l.break?e.splice(--t,1,l.left,null,l.right):e.splice(--t,1,l.left,l.right),i+=1+l.break,s-=l.size}else if(r>s*2){let l=e[i];l.break?e.splice(i,1,l.left,null,l.right):e.splice(i,1,l.left,l.right),i+=2+l.break,r-=l.size}else break;else if(s=r&&o(this.lineAt(0,I.ByPos,i,s,r))}setMeasuredHeight(e){let t=e.heights[e.index++];t<0?(this.spaceAbove=-t,t=e.heights[e.index++]):this.spaceAbove=0,this.setHeight(t)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more&&this.setMeasuredHeight(s),this.outdated=!1,this}toString(){return`block(${this.length})`}},be=class n extends Dn{constructor(e,t,i){super(e,t,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0,this.spaceAbove=i}mainBlock(e,t){return new Qe(t,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.breaks)}replace(e,t,i){let s=i[0];return i.length==1&&(s instanceof n||s instanceof ft&&s.flags&4)&&Math.abs(this.length-s.length)<10?(s instanceof ft?s=new n(s.length,this.height,this.spaceAbove):s.height=this.height,this.outdated||(s.outdated=!1),s):pe.of(i)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more?this.setMeasuredHeight(s):(i||this.outdated)&&(this.spaceAbove=0,this.setHeight(Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))+this.breaks*e.lineHeight)),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}},ft=class n extends pe{constructor(e){super(e,0)}heightMetrics(e,t){let i=e.doc.lineAt(t).number,s=e.doc.lineAt(t+this.length).number,r=s-i+1,o,l=0;if(e.lineWrapping){let a=Math.min(this.height,e.lineHeight*r);o=a/r,this.length>r+1&&(l=(this.height-a)/(this.length-r-1))}else o=this.height/r;return{firstLine:i,lastLine:s,perLine:o,perChar:l}}blockAt(e,t,i,s){let{firstLine:r,lastLine:o,perLine:l,perChar:a}=this.heightMetrics(t,s);if(t.lineWrapping){let h=s+(e0){let r=i[i.length-1];r instanceof n?i[i.length-1]=new n(r.length+s):i.push(null,new n(s-1))}if(e>0){let r=i[0];r instanceof n?i[0]=new n(e+r.length):i.unshift(new n(e-1),null)}return pe.of(i)}decomposeLeft(e,t){t.push(new n(e-1),null)}decomposeRight(e,t){t.push(null,new n(this.length-e-1))}updateHeight(e,t=0,i=!1,s){let r=t+this.length;if(s&&s.from<=t+this.length&&s.more){let o=[],l=Math.max(t,s.from),a=-1;for(s.from>t&&o.push(new n(s.from-t-1).updateHeight(e,t));l<=r&&s.more;){let f=e.doc.lineAt(l).length;o.length&&o.push(null);let c=s.heights[s.index++],u=0;c<0&&(u=-c,c=s.heights[s.index++]),a==-1?a=c:Math.abs(c-a)>=xn&&(a=-2);let d=new be(f,c,u);d.outdated=!1,o.push(d),l+=f+1}l<=r&&o.push(null,new n(r-l).updateHeight(e,l));let h=pe.of(o);return(a<0||Math.abs(h.height-this.height)>=xn||Math.abs(a-this.heightMetrics(e,t).perLine)>=xn)&&(li=!0),En(this,h)}else(i||this.outdated)&&(this.setHeight(e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}},gr=class extends pe{constructor(e,t,i){super(e.length+(t?1:0)+i.length,e.height+i.height,(t?1:0)|(e.outdated||i.outdated?2:0)),this.left=e,this.right=i,this.size=e.size+i.size}get break(){return this.flags&1}blockAt(e,t,i,s){let r=i+this.left.height;return el))return h;let f=t==I.ByPosNoHeight?I.ByPosNoHeight:I.ByPos;return a?h.join(this.right.lineAt(l,f,i,o,l)):this.left.lineAt(l,f,i,s,r).join(h)}forEachLine(e,t,i,s,r,o){let l=s+this.left.height,a=r+this.left.length+this.break;if(this.break)e=a&&this.right.forEachLine(e,t,i,l,a,o);else{let h=this.lineAt(a,I.ByPos,i,s,r);e=e&&h.from<=t&&o(h),t>h.to&&this.right.forEachLine(Math.max(e,h.to+1),t,i,l,a,o)}}replace(e,t,i){let s=this.left.length+this.break;if(tthis.left.length)return this.balanced(this.left,this.right.replace(e-s,t-s,i));let r=[];e>0&&this.decomposeLeft(e,r);let o=r.length;for(let l of i)r.push(l);if(e>0&&Ll(r,o-1),t=i&&t.push(null)),e>i&&this.right.decomposeLeft(e-i,t)}decomposeRight(e,t){let i=this.left.length,s=i+this.break;if(e>=s)return this.right.decomposeRight(e-s,t);e2*t.size||t.size>2*e.size?pe.of(this.break?[e,null,t]:[e,t]):(this.left=En(this.left,e),this.right=En(this.right,t),this.setHeight(e.height+t.height),this.outdated=e.outdated||t.outdated,this.size=e.size+t.size,this.length=e.length+this.break+t.length,this)}updateHeight(e,t=0,i=!1,s){let{left:r,right:o}=this,l=t+r.length+this.break,a=null;return s&&s.from<=t+r.length&&s.more?a=r=r.updateHeight(e,t,i,s):r.updateHeight(e,t,i),s&&s.from<=l+o.length&&s.more?a=o=o.updateHeight(e,l,i,s):o.updateHeight(e,l,i),a?this.balanced(r,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}};function Ll(n,e){let t,i;n[e]==null&&(t=n[e-1])instanceof ft&&(i=n[e+1])instanceof ft&&n.splice(e-1,3,new ft(t.length+1+i.length))}var bu=5,Or=class n{constructor(e,t){this.pos=e,this.oracle=t,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let i=Math.min(t,this.lineEnd),s=this.nodes[this.nodes.length-1];s instanceof be?s.length+=i-this.pos:(i>this.pos||!this.isCovered)&&this.nodes.push(new be(i-this.pos,-1,0)),this.writtenTo=i,t>i&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,i){if(e=bu)&&this.addLineDeco(s,r,o)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenToe&&this.nodes.push(new be(this.pos-e,-1,0)),this.writtenTo=this.pos}blankContent(e,t){let i=new ft(t-e);return this.oracle.doc.lineAt(e).to==t&&(i.flags|=4),i}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof be)return e;let t=new be(0,-1,0);return this.nodes.push(t),t}addBlock(e){this.enterLine();let t=e.deco;t&&t.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,t&&t.endSide>0&&(this.covering=e)}addLineDeco(e,t,i){let s=this.ensureLine();s.length+=i,s.collapsed+=i,s.widgetHeight=Math.max(s.widgetHeight,e),s.breaks+=t,this.writtenTo=this.pos=this.pos+i}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof be)&&!this.isCovered?this.nodes.push(new be(0,-1,0)):(this.writtenTof.clientHeight||f.scrollWidth>f.clientWidth)&&c.overflow!="visible"){let u=f.getBoundingClientRect();r=Math.max(r,u.left),o=Math.min(o,u.right),l=Math.max(l,u.top),a=Math.min(h==n.parentNode?s.innerHeight:a,u.bottom)}h=c.position=="absolute"||c.position=="fixed"?f.offsetParent:f.parentNode}else if(h.nodeType==11)h=h.host;else break;return{left:r-t.left,right:Math.max(r,o)-t.left,top:l-(t.top+e),bottom:Math.max(l,a)-(t.top+e)}}function ku(n){let e=n.getBoundingClientRect(),t=n.ownerDocument.defaultView||window;return e.left0&&e.top0}function wu(n,e){let t=n.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}var Ei=class{constructor(e,t,i,s){this.from=e,this.to=t,this.size=i,this.displaySize=s}static same(e,t){if(e.length!=t.length)return!1;for(let i=0;itypeof s!="function"&&s.class=="cm-lineWrapping");this.heightOracle=new pr(i),this.stateDeco=Il(t),this.heightMap=pe.empty().applyChanges(this.stateDeco,M.empty,this.heightOracle.setDoc(t.doc),[new Pe(0,0,0,t.doc.length)]);for(let s=0;s<2&&(this.viewport=this.getViewport(0,null),!!this.updateForViewport());s++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=q.set(this.lineGaps.map(s=>s.draw(this,!1))),this.scrollParent=e.scrollDOM,this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let i=0;i<=1;i++){let s=i?t.head:t.anchor;if(!e.some(({from:r,to:o})=>s>=r&&s<=o)){let{from:r,to:o}=this.lineBlockAt(s);e.push(new Jt(r,o))}}return this.viewports=e.sort((i,s)=>i.from-s.from),this.updateScaler()}updateScaler(){let e=this.scaler;return this.scaler=this.heightMap.height<=7e6?zl:new Sr(this.heightOracle,this.heightMap,this.viewports),e.eq(this.scaler)?0:2}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(Ti(e,this.scaler))})}update(e,t=null){this.state=e.state;let i=this.stateDeco;this.stateDeco=Il(this.state);let s=e.changedRanges,r=Pe.extendWithRanges(s,Su(i,this.stateDeco,e?e.changes:oe.empty(this.state.doc.length))),o=this.heightMap.height,l=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollOffset);$l(),this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),r),(this.heightMap.height!=o||li)&&(e.flags|=2),l?(this.scrollAnchorPos=e.changes.mapPos(l.from,-1),this.scrollAnchorHeight=l.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=o);let a=r.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.heada.to)||!this.viewportIsAppropriate(a))&&(a=this.getViewport(0,t));let h=a.from!=this.viewport.from||a.to!=this.viewport.to;this.viewport=a,e.flags|=this.updateForViewport(),(h||!e.changes.empty||e.flags&2)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(e.changes),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&(e.selectionSet||e.focusChanged)&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(Rc)&&(this.mustEnforceCursorAssoc=!0)}measure(){let{view:e}=this,t=e.contentDOM,i=window.getComputedStyle(t),s=this.heightOracle,r=i.whiteSpace;this.defaultTextDirection=i.direction=="rtl"?F.RTL:F.LTR;let o=this.heightOracle.mustRefreshForWrapping(r)||this.mustMeasureContent==="refresh",l=t.getBoundingClientRect(),a=o||this.mustMeasureContent||this.contentDOMHeight!=l.height;this.contentDOMHeight=l.height,this.mustMeasureContent=!1;let h=0,f=0;if(l.width&&l.height){let{scaleX:Q,scaleY:P}=Zl(t,l);(Q>.005&&Math.abs(this.scaleX-Q)>.005||P>.005&&Math.abs(this.scaleY-P)>.005)&&(this.scaleX=Q,this.scaleY=P,h|=16,o=a=!0)}let c=(parseInt(i.paddingTop)||0)*this.scaleY,u=(parseInt(i.paddingBottom)||0)*this.scaleY;(this.paddingTop!=c||this.paddingBottom!=u)&&(this.paddingTop=c,this.paddingBottom=u,h|=18),this.editorWidth!=e.scrollDOM.clientWidth&&(s.lineWrapping&&(a=!0),this.editorWidth=e.scrollDOM.clientWidth,h|=16);let d=Yl(this.view.contentDOM,!1).y;d!=this.scrollParent&&(this.scrollParent=d,this.scrollAnchorHeight=-1,this.scrollOffset=0);let p=this.getScrollOffset();this.scrollOffset!=p&&(this.scrollAnchorHeight=-1,this.scrollOffset=p),this.scrolledToBottom=ta(this.scrollParent||e.win);let m=(this.printing?wu:xu)(t,this.paddingTop),O=m.top-this.pixelViewport.top,y=m.bottom-this.pixelViewport.bottom;this.pixelViewport=m;let w=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(w!=this.inView&&(this.inView=w,w&&(a=!0)),!this.inView&&!this.scrollTarget&&!ku(e.dom))return 0;let k=l.width;if((this.contentDOMWidth!=k||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=l.width,this.editorHeight=e.scrollDOM.clientHeight,h|=16),a){let Q=e.docView.measureVisibleLineHeights(this.viewport);if(s.mustRefreshForHeights(Q)&&(o=!0),o||s.lineWrapping&&Math.abs(k-this.contentDOMWidth)>s.charWidth){let{lineHeight:P,charWidth:T,textHeight:V}=e.docView.measureTextSize();o=P>0&&s.refresh(r,P,T,V,Math.max(5,k/T),Q),o&&(e.docView.minWidth=0,h|=16)}O>0&&y>0?f=Math.max(O,y):O<0&&y<0&&(f=Math.min(O,y)),$l();for(let P of this.viewports){let T=P.from==this.viewport.from?Q:e.docView.measureVisibleLineHeights(P);this.heightMap=(o?pe.empty().applyChanges(this.stateDeco,M.empty,this.heightOracle,[new Pe(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(s,0,o,new mr(P.from,T))}li&&(h|=2)}let D=!this.viewportIsAppropriate(this.viewport,f)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return D&&(h&2&&(h|=this.updateScaler()),this.viewport=this.getViewport(f,this.scrollTarget),h|=this.updateForViewport()),(h&2||D)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,e)),h|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),h}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let i=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),s=this.heightMap,r=this.heightOracle,{visibleTop:o,visibleBottom:l}=this,a=new Jt(s.lineAt(o-i*1e3,I.ByHeight,r,0,0).from,s.lineAt(l+(1-i)*1e3,I.ByHeight,r,0,0).to);if(t){let{head:h}=t.range;if(ha.to){let f=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),c=s.lineAt(h,I.ByPos,r,0,0),u;t.y=="center"?u=(c.top+c.bottom)/2-f/2:t.y=="start"||t.y=="nearest"&&h=l+Math.max(10,Math.min(i,250)))&&s>o-2*1e3&&r>1,o=s<<1;if(this.defaultTextDirection!=F.LTR&&!i)return[];let l=[],a=(f,c,u,d)=>{if(c-ff&&yy.from>=u.from&&y.to<=u.to&&Math.abs(y.from-f)y.fromw));if(!O){if(ck.from<=c&&k.to>=c)){let k=t.moveToLineBoundary(b.cursor(c),!1,!0).head;k>f&&(c=k)}let y=this.gapSize(u,f,c,d),w=i||y<2e6?y:2e6;O=new Ei(f,c,y,w)}l.push(O)},h=f=>{if(f.length2e6)for(let P of e)P.from>=f.from&&P.fromf.from&&a(f.from,d,f,c),pt.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(e){let t=this.stateDeco;this.lineGaps.length&&(t=t.concat(this.lineGapDeco));let i=[];B.spans(t,this.viewport.from,this.viewport.to,{span(r,o){i.push({from:r,to:o})},point(){}},20);let s=0;if(i.length!=this.visibleRanges.length)s=12;else for(let r=0;r=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||Ti(this.heightMap.lineAt(e,I.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return e>=this.viewportLines[0].top&&e<=this.viewportLines[this.viewportLines.length-1].bottom&&this.viewportLines.find(t=>t.top<=e&&t.bottom>=e)||Ti(this.heightMap.lineAt(this.scaler.fromDOM(e),I.ByHeight,this.heightOracle,0,0),this.scaler)}getScrollOffset(){return this.scrollParent==this.view.scrollDOM?this.scrollParent.scrollTop*this.scaleY:(this.scrollParent?this.scrollParent.getBoundingClientRect().top:0)-this.view.contentDOM.getBoundingClientRect().top}scrollAnchorAt(e){let t=this.lineBlockAtHeight(e+8);return t.from>=this.viewport.from||this.viewportLines[0].top-e>200?t:this.viewportLines[0]}elementAtHeight(e){return Ti(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}},Jt=class{constructor(e,t){this.from=e,this.to=t}};function vu(n,e,t){let i=[],s=n,r=0;return B.spans(t,n,e,{span(){},point(o,l){o>s&&(i.push({from:s,to:o}),r+=o-s),s=l}},20),s=1)return e[e.length-1].to;let i=Math.floor(n*t);for(let s=0;;s++){let{from:r,to:o}=e[s],l=o-r;if(i<=l)return r+i;i-=l}}function On(n,e){let t=0;for(let{from:i,to:s}of n.ranges){if(e<=s){t+=e-i;break}t+=s-i}return t/n.total}function Tu(n,e){for(let t of n)if(e(t))return t}var zl={toDOM(n){return n},fromDOM(n){return n},scale:1,eq(n){return n==this}};function Il(n){let e=n.facet(zn).filter(i=>typeof i!="function"),t=n.facet(Wr).filter(i=>typeof i!="function");return t.length&&e.push(B.join(t)),e}var Sr=class n{constructor(e,t,i){let s=0,r=0,o=0;this.viewports=i.map(({from:l,to:a})=>{let h=t.lineAt(l,I.ByPos,e,0,0).top,f=t.lineAt(a,I.ByPos,e,0,0).bottom;return s+=f-h,{from:l,to:a,top:h,bottom:f,domTop:0,domBottom:0}}),this.scale=(7e6-s)/(t.height-s);for(let l of this.viewports)l.domTop=o+(l.top-r)*this.scale,o=l.domBottom=l.domTop+(l.bottom-l.top),r=l.bottom}toDOM(e){for(let t=0,i=0,s=0;;t++){let r=tt.from==e.viewports[i].from&&t.to==e.viewports[i].to):!1}};function Ti(n,e){if(e.scale==1)return n;let t=e.toDOM(n.top),i=e.toDOM(n.bottom);return new Qe(n.from,n.length,t,i-t,Array.isArray(n._content)?n._content.map(s=>Ti(s,e)):n._content)}var yn=v.define({combine:n=>n.join(" ")}),xr=v.define({combine:n=>n.indexOf(!0)>-1}),kr=ye.newName(),$a=ye.newName(),La=ye.newName(),za={"&light":"."+$a,"&dark":"."+La};function wr(n,e,t){return new ye(e,{finish(i){return/&/.test(i)?i.replace(/&\w*/,s=>{if(s=="&")return n;if(!t||!t[s])throw new RangeError(`Unsupported selector: ${s}`);return t[s]}):n+" "+i}})}var Cu=wr("."+kr,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0,overflowAnchor:"none"},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{userSelect:"none",position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#ddd"},".cm-selectionHandle":{backgroundColor:"currentColor",width:"1.5px"},".cm-selectionHandle-start::before, .cm-selectionHandle-end::before":{content:'""',backgroundColor:"inherit",borderRadius:"50%",width:"8px",height:"8px",position:"absolute",left:"-3.25px"},".cm-selectionHandle-start::before":{top:"-8px"},".cm-selectionHandle-end::before":{bottom:"-8px"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",zIndex:200},".cm-gutters-before":{insetInlineStart:0},".cm-gutters-after":{insetInlineEnd:0},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",border:"0px solid #ddd","&.cm-gutters-before":{borderRightWidth:"1px"},"&.cm-gutters-after":{borderLeftWidth:"1px"}},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0,zIndex:300},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},".cm-panels-top":{top:"0"},".cm-panels-bottom":{bottom:"0"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-dialog":{padding:"2px 19px 4px 6px",position:"relative","& label":{fontSize:"80%"}},".cm-dialog-close":{position:"absolute",top:"3px",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",fontSize:"14px",padding:"0"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top",userSelect:"none"},".cm-highlightSpace":{background:"radial-gradient(circle at 50% 55%, #aaa 20%, transparent 0) no-repeat",backgroundSize:".4em",backgroundPosition:"calc(min(50%, 0px)) center"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},za),Qu={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Is=x.ie&&x.ie_version<=11,vr=class{constructor(e){this.view=e,this.active=!1,this.editContext=null,this.selectionRange=new js,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let i of t)this.queue.push(i);(x.ie&&x.ie_version<=11||x.ios&&e.composing)&&t.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),window.EditContext&&x.android&&e.constructor.EDIT_CONTEXT!==!1&&!(x.chrome&&x.chrome_version<126)&&(this.editContext=new Tr(e),e.state.facet(Ge)&&(e.contentDOM.editContext=this.editContext.editContext)),Is&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate){this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(t=>{t.length>0&&t[t.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.editContext&&this.view.requestMeasure(this.editContext.measureReq),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(e){(e.type=="change"||!e.type)&&!e.matches||(this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500))}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((t,i)=>t!=e[i]))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:i}=this,s=this.selectionRange;if(i.state.facet(Ge)?i.root.activeElement!=this.dom:!Ci(this.dom,s))return;let r=s.anchorNode&&i.docView.tile.nearest(s.anchorNode);if(r&&r.isWidget()&&r.widget.ignoreEvent(e)){t||(this.selectionChanged=!1);return}(x.ie&&x.ie_version<=11||x.android&&x.chrome)&&!i.state.selection.main.empty&&s.focusNode&&Qi(s.focusNode,s.focusOffset,s.anchorNode,s.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=Wi(e.root);if(!t)return!1;let i=x.safari&&e.root.nodeType==11&&e.root.activeElement==this.dom&&Pu(this.view,t)||t;if(!i||this.selectionRange.eq(i))return!1;let s=Ci(this.dom,i);return s&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime{let r=this.delayedAndroidKey;r&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=r.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&r.force&&ii(this.dom,r.key,r.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(s)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let t=-1,i=-1,s=!1;for(let r of e){let o=this.readMutation(r);o&&(o.typeOver&&(s=!0),t==-1?{from:t,to:i}=o:(t=Math.min(o.from,t),i=Math.max(o.to,i)))}return{from:t,to:i,typeOver:s}}readChange(){let{from:e,to:t,typeOver:i}=this.processRecords(),s=this.selectionChanged&&Ci(this.dom,this.selectionRange);if(e<0&&!s)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let r=new fr(this.view,e,t,i);return this.view.docView.domChanged={newSel:r.newSel?r.newSel.main:null},r}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return this.view.requestMeasure(),!1;let i=this.view.state,s=Qa(this.view,t);return this.view.state==i&&(t.domChanged||t.newSel&&!Mn(this.view.state.selection,t.newSel.main))&&this.view.update([]),s}readMutation(e){let t=this.view.docView.tile.nearest(e.target);if(!t||t.isWidget())return null;if(t.markDirty(e.type=="attributes"),e.type=="childList"){let i=Nl(t,e.previousSibling||e.target.previousSibling,-1),s=Nl(t,e.nextSibling||e.target.nextSibling,1);return{from:i?t.posAfter(i):t.posAtStart,to:s?t.posBefore(s):t.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),this.printQuery?this.printQuery.addEventListener?this.printQuery.addEventListener("change",this.onPrint):this.printQuery.addListener(this.onPrint):e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),this.printQuery?this.printQuery.removeEventListener?this.printQuery.removeEventListener("change",this.onPrint):this.printQuery.removeListener(this.onPrint):e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}update(e){this.editContext&&(this.editContext.update(e),e.startState.facet(Ge)!=e.state.facet(Ge)&&(e.view.contentDOM.editContext=e.state.facet(Ge)?this.editContext.editContext:null))}destroy(){var e,t,i;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(t=this.gapIntersection)===null||t===void 0||t.disconnect(),(i=this.resizeScroll)===null||i===void 0||i.disconnect();for(let s of this.scrollTargets)s.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}};function Nl(n,e,t){for(;e;){let i=_.get(e);if(i&&i.parent==n)return i;let s=e.parentNode;e=s!=n.dom?s:t>0?e.nextSibling:e.previousSibling}return null}function Vl(n,e){let t=e.startContainer,i=e.startOffset,s=e.endContainer,r=e.endOffset,o=n.docView.domAtPos(n.state.selection.main.anchor,1);return Qi(o.node,o.offset,s,r)&&([t,i,s,r]=[s,r,t,i]),{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}}function Pu(n,e){if(e.getComposedRanges){let s=e.getComposedRanges(n.root)[0];if(s)return Vl(n,s)}let t=null;function i(s){s.preventDefault(),s.stopImmediatePropagation(),t=s.getTargetRanges()[0]}return n.contentDOM.addEventListener("beforeinput",i,!0),n.dom.ownerDocument.execCommand("indent"),n.contentDOM.removeEventListener("beforeinput",i,!0),t?Vl(n,t):null}var Tr=class{constructor(e){this.from=0,this.to=0,this.pendingContextChange=null,this.handlers=Object.create(null),this.composing=null,this.resetRange(e.state);let t=this.editContext=new window.EditContext({text:e.state.doc.sliceString(this.from,this.to),selectionStart:this.toContextPos(Math.max(this.from,Math.min(this.to,e.state.selection.main.anchor))),selectionEnd:this.toContextPos(e.state.selection.main.head)});this.handlers.textupdate=i=>{let s=e.state.selection.main,{anchor:r,head:o}=s,l=this.toEditorPos(i.updateRangeStart),a=this.toEditorPos(i.updateRangeEnd);e.inputState.composing>=0&&!this.composing&&(this.composing={contextBase:i.updateRangeStart,editorBase:l,drifted:!1});let h=a-l>i.text.length;l==this.from&&rthis.to&&(a=r);let f=Pa(e.state.sliceDoc(l,a),i.text,(h?s.from:s.to)-l,h?"end":null);if(!f){let u=b.single(this.toEditorPos(i.selectionStart),this.toEditorPos(i.selectionEnd));Mn(u,s)||e.dispatch({selection:u,userEvent:"select"});return}let c={from:f.from+l,to:f.toA+l,insert:M.of(i.text.slice(f.from,f.toB).split(` +`))};if((x.mac||x.android)&&c.from==o-1&&/^\. ?$/.test(i.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(c={from:l,to:a,insert:M.of([i.text.replace("."," ")])}),this.pendingContextChange=c,!e.state.readOnly){let u=this.to-this.from+(c.to-c.from+c.insert.length);$r(e,c,b.single(this.toEditorPos(i.selectionStart,u),this.toEditorPos(i.selectionEnd,u)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),c.from=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(t.text.slice(Math.max(0,i.updateRangeStart-1),Math.min(t.text.length,i.updateRangeStart+1)))&&this.handlers.compositionend(i)},this.handlers.characterboundsupdate=i=>{let s=[],r=null;for(let o=this.toEditorPos(i.rangeStart),l=this.toEditorPos(i.rangeEnd);o{let s=[];for(let r of i.getTextFormats()){let o=r.underlineStyle,l=r.underlineThickness;if(!/none/i.test(o)&&!/none/i.test(l)){let a=this.toEditorPos(r.rangeStart),h=this.toEditorPos(r.rangeEnd);if(a{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:i}=this.composing;this.composing=null,i&&this.reset(e.state)}};for(let i in this.handlers)t.addEventListener(i,this.handlers[i]);this.measureReq={read:i=>{let s=Wi(i.root);s&&s.rangeCount&&this.editContext.updateSelectionBounds(s.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,i=!1,s=this.pendingContextChange;return e.changes.iterChanges((r,o,l,a,h)=>{if(i)return;let f=h.length-(o-r);if(s&&o>=s.to)if(s.from==r&&s.to==o&&s.insert.eq(h)){s=this.pendingContextChange=null,t+=f,this.to+=f;return}else s=null,this.revertPending(e.state);if(r+=t,o+=t,o<=this.from)this.from+=f,this.to+=f;else if(rthis.to||this.to-this.from+h.length>3e4){i=!0;return}this.editContext.updateText(this.toContextPos(r),this.toContextPos(o),h.toString()),this.to+=f}t+=f}),s&&!i&&this.revertPending(e.state),!i}update(e){let t=this.pendingContextChange,i=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(i.from,i.to)&&e.transactions.some(s=>!s.isUserEvent("input.type")&&s.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||t)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:t}=e.selection.main;this.from=Math.max(0,t-1e4),this.to=Math.min(e.doc.length,t+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.from+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,i=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),s=this.toContextPos(t.head);(this.editContext.selectionStart!=i||this.editContext.selectionEnd!=s)&&this.editContext.updateSelection(i,s)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to1e4*3)}toEditorPos(e,t=this.to-this.from){e=Math.min(e,t);let i=this.composing;return i&&i.drifted?i.editorBase+(e-i.contextBase):e+this.from}toContextPos(e){let t=this.composing;return t&&t.drifted?t.contextBase+(e-t.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}},C=class n{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){var t;this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.clearAnnouncement=-1,this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:i}=e;this.dispatchTransactions=e.dispatchTransactions||i&&(s=>s.forEach(r=>i(r,this)))||(s=>this.update(s)),this.dispatch=this.dispatch.bind(this),this._root=e.root||bc(e.parent)||document,this.viewState=new Bn(this,e.state||z.create(e)),e.scrollTo&&e.scrollTo.is(dn)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(Kt).map(s=>new Ai(s));for(let s of this.plugins)s.update(this);this.observer=new vr(this),this.inputState=new cr(this),this.inputState.ensureHandlers(this.plugins),this.docView=new An(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),!((t=document.fonts)===null||t===void 0)&&t.ready&&document.fonts.ready.then(()=>{this.viewState.mustMeasureContent="refresh",this.requestMeasure()})}dispatch(...e){let t=e.length==1&&e[0]instanceof G?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(t,this)}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let t=!1,i=!1,s,r=this.state;for(let u of e){if(u.startState!=r)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");r=u.state}if(this.destroyed){this.viewState.state=r;return}let o=this.hasFocus,l=0,a=null;e.some(u=>u.annotation(Ba))?(this.inputState.notifiedFocused=o,l=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,a=qa(r,o),a||(l=1));let h=this.observer.delayedAndroidKey,f=null;if(h?(this.observer.clearDelayedAndroidKey(),f=this.observer.readChange(),(f&&!this.state.doc.eq(r.doc)||!this.state.selection.eq(r.selection))&&(f=null)):this.observer.clear(),r.facet(z.phrases)!=this.state.facet(z.phrases))return this.setState(r);s=Qn.create(this,r,e),s.flags|=l;let c=this.viewState.scrollTarget;try{this.updateState=2;for(let u of e){if(c&&(c=c.map(u.changes)),u.scrollIntoView){let{main:d}=u.state.selection,{x:p,y:m}=this.state.facet(n.cursorScrollMargin);c=new Pi(d.empty?d:b.cursor(d.head,d.head>d.anchor?-1:1),"nearest","nearest",m,p)}for(let d of u.effects)d.is(dn)&&(c=d.value.clip(this.state))}this.viewState.update(s,c),this.bidiCache=qn.update(this.bidiCache,s.changes),s.empty||(this.updatePlugins(s),this.inputState.update(s)),t=this.docView.update(s),this.state.facet(vi)!=this.styleModules&&this.mountStyles(),i=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(u=>u.isUserEvent("select.pointer")))}finally{this.updateState=0}if(s.startState.facet(yn)!=s.state.facet(yn)&&(this.viewState.mustMeasureContent=!0),(t||i||c||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),t&&this.docViewUpdate(),!s.empty)for(let u of this.state.facet(Ks))try{u(s)}catch(d){ke(this.state,d,"update listener")}(a||f)&&Promise.resolve().then(()=>{a&&this.state==a.startState&&this.dispatch(a),f&&!Qa(this,f)&&h.force&&ii(this.contentDOM,h.key,h.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let i of this.plugins)i.destroy(this);this.viewState=new Bn(this,e),this.plugins=e.facet(Kt).map(i=>new Ai(i)),this.pluginMap.clear();for(let i of this.plugins)i.update(this);this.docView.destroy(),this.docView=new An(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(Kt),i=e.state.facet(Kt);if(t!=i){let s=[];for(let r of i){let o=t.indexOf(r);if(o<0)s.push(new Ai(r));else{let l=this.plugins[o];l.mustUpdate=e,s.push(l)}}for(let r of this.plugins)r.mustUpdate!=e&&r.destroy(this);this.plugins=s,this.pluginMap.clear()}else for(let s of this.plugins)s.mustUpdate=e;for(let s=0;s-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,i=this.viewState.scrollParent,s=this.viewState.getScrollOffset(),{scrollAnchorPos:r,scrollAnchorHeight:o,scaleY:l}=this.viewState;Math.abs(s-this.viewState.scrollOffset)>1&&(o=-1),this.viewState.scrollAnchorHeight=-1;try{for(let a=0;;a++){if(o<0){if(ta(i||this.win))r=-1,o=this.viewState.heightMap.height/this.viewState.scaleY;else{let p=this.viewState.scrollAnchorAt(s);r=p.from,o=p.top}l=this.viewState.scaleY}this.updateState=1;let h=this.viewState.measure();if(!h&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(a>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let f=[];h&4||([this.measureRequests,f]=[f,this.measureRequests]);let c=f.map(p=>{try{return p.read(this)}catch(m){return ke(this.state,m),Xl}}),u=Qn.create(this,this.state,[]),d=!1;u.flags|=h,t?t.flags|=h:t=u,this.updateState=2,u.empty||(this.updatePlugins(u),this.inputState.update(u),this.updateAttrs(),d=this.docView.update(u),d&&this.docViewUpdate());for(let p=0;p1||m<-1)&&!(x.ios&&this.inputState.lastIOSMomentumScroll>Date.now()-100)&&(i==this.scrollDOM||this.hasFocus||Math.max(this.inputState.lastWheelEvent,this.inputState.lastTouchTime)>Date.now()-100)){s=s+m,i?r<0?i.scrollTop=i.scrollHeight:i.scrollTop+=m:this.win.scrollBy(0,m),o=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let a of this.state.facet(Ks))a(t)}get themeClasses(){return kr+" "+(this.state.facet(xr)?La:$a)+" "+this.state.facet(yn)}updateAttrs(){let e=Fl(this,ya,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",translate:"no",contenteditable:this.state.facet(Ge)?"true":"false",class:"cm-content",style:`${x.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),Fl(this,qr,t);let i=this.observer.ignore(()=>{let s=kl(this.contentDOM,this.contentAttrs,t),r=kl(this.dom,this.editorAttrs,e);return s||r});return this.editorAttrs=e,this.contentAttrs=t,i}showAnnouncements(e){let t=!0;for(let i of e)for(let s of i.effects)if(s.is(n.announce)){t&&(this.announceDOM.textContent="",this.win.clearTimeout(this.clearAnnouncement),this.clearAnnouncement=this.win.setTimeout(()=>{this.announceDOM.textContent="\xA0"},200),t=!1);let r=this.announceDOM.appendChild(document.createElement("div"));r.textContent=s.value}}mountStyles(){this.styleModules=this.state.facet(vi);let e=this.state.facet(n.cspNonce);ye.mount(this.root,this.styleModules.concat(Cu).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let t=0;ti.plugin==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,i){return zs(this,e,Pl(this,e,t,i))}moveByGroup(e,t){return zs(this,e,Pl(this,e,t,i=>Zc(this,e.head,i)))}visualLineSide(e,t){return t?b.cursor(e.to,1):b.cursor(e.from,-1)}moveToLineBoundary(e,t,i=!0){return Gc(this,e,t,i)}moveVertically(e,t,i){return zs(this,e,Yc(this,e,t,i))}domAtPos(e,t=1){return this.docView.domAtPos(e,t)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){this.readMeasured();let i=lr(this,e,t);return i&&i.pos}posAndSideAtCoords(e,t=!0){return this.readMeasured(),lr(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let i=this.state.doc.lineAt(e),s=this.bidiSpans(i),r=s[xe.find(s,e-i.from,-1,t)];return i.length&&(e==i.from&&t<0||e==i.to&&t>0)&&r.dir!=this.textDirectionAt(i.from)&&(e==i.to?(e=i.from+r.from,t=1):(e=i.from+r.to,t=-1)),this.docView.coordsAt(e,t,r.dir==F.RTL)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(ma)||ethis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>Au)return la(e.length);let t=this.textDirectionAt(e.from),i;for(let r of this.bidiCache)if(r.from==e.from&&r.dir==t&&(r.fresh||oa(r.isolates,i=Tl(this,e))))return r.order;i||(i=Tl(this,e));let s=Qc(e.text,t,i);return this.bidiCache.push(new qn(e.from,e.to,t,i,!0,s)),s}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||x.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{ea(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.win.clearTimeout(this.clearAnnouncement),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){var i,s,r,o;return dn.of(new Pi(typeof e=="number"?b.cursor(e):e,(i=t.y)!==null&&i!==void 0?i:"nearest",(s=t.x)!==null&&s!==void 0?s:"nearest",(r=t.yMargin)!==null&&r!==void 0?r:5,(o=t.xMargin)!==null&&o!==void 0?o:5))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,i=this.viewState.scrollAnchorAt(e);return dn.of(new Pi(b.cursor(i.from),"start","start",i.top-e,t,!0))}setTabFocusMode(e){e==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof e=="boolean"?this.inputState.tabFocusMode=e?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+e)}static domEventHandlers(e){return Le.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return Le.define(()=>({}),{eventObservers:e})}static theme(e,t){let i=ye.newName(),s=[yn.of(i),vi.of(wr(`.${i}`,e))];return t&&t.dark&&s.push(xr.of(!0)),s}static baseTheme(e){return at.lowest(vi.of(wr("."+kr,e,za)))}static findFromDOM(e){var t;let i=e.querySelector(".cm-content"),s=i&&_.get(i)||_.get(e);return((t=s?.root)===null||t===void 0?void 0:t.view)||null}};C.styleModule=vi;C.inputHandler=da;C.clipboardInputFilter=Dr;C.clipboardOutputFilter=Br;C.scrollHandler=ga;C.focusChangeEffect=pa;C.perLineTextDirection=ma;C.exceptionSink=ua;C.updateListener=Ks;C.editable=Ge;C.mouseSelectionStyle=ca;C.dragMovesSelection=fa;C.clickAddsSelectionRange=ha;C.decorations=zn;C.blockWrappers=ba;C.outerDecorations=Wr;C.atomicRanges=Li;C.bidiIsolatedRanges=Sa;C.cursorScrollMargin=v.define({combine:n=>{let e=5,t=5;for(let i of n)typeof i=="number"?e=t=i:{x:e,y:t}=i;return{x:e,y:t}}});C.scrollMargins=xa;C.darkTheme=xr;C.cspNonce=v.define({combine:n=>n.length?n[0]:""});C.contentAttributes=qr;C.editorAttributes=ya;C.lineWrapping=C.contentAttributes.of({class:"cm-lineWrapping"});C.announce=W.define();var Au=4096,Xl={},qn=class n{constructor(e,t,i,s,r,o){this.from=e,this.to=t,this.dir=i,this.isolates=s,this.fresh=r,this.order=o}static update(e,t){if(t.empty&&!e.some(r=>r.fresh))return e;let i=[],s=e.length?e[e.length-1].dir:F.LTR;for(let r=Math.max(0,e.length-10);r=0;s--){let r=i[s],o=typeof r=="function"?r(n):r;o&&Rr(o,t)}return t}var Ru=x.mac?"mac":x.windows?"win":x.linux?"linux":"key";function Mu(n,e){let t=n.split(/-(?!$)/),i=t[t.length-1];i=="Space"&&(i=" ");let s,r,o,l;for(let a=0;ai.concat(s),[]))),t}var ht=null,Bu=4e3;function qu(n,e=Ru){let t=Object.create(null),i=Object.create(null),s=(o,l)=>{let a=i[o];if(a==null)i[o]=l;else if(a!=l)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},r=(o,l,a,h,f)=>{var c,u;let d=t[o]||(t[o]=Object.create(null)),p=l.split(/ (?!$)/).map(y=>Mu(y,e));for(let y=1;y{let D=ht={view:k,prefix:w,scope:o};return setTimeout(()=>{ht==D&&(ht=null)},Bu),!0}]})}let m=p.join(" ");s(m,!1);let O=d[m]||(d[m]={preventDefault:!1,stopPropagation:!1,run:((u=(c=d._any)===null||c===void 0?void 0:c.run)===null||u===void 0?void 0:u.slice())||[]});a&&O.run.push(a),h&&(O.preventDefault=!0),f&&(O.stopPropagation=!0)};for(let o of n){let l=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let h of l){let f=t[h]||(t[h]=Object.create(null));f._any||(f._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:c}=o;for(let u in f)f[u].run.push(d=>c(d,Cr))}let a=o[e]||o.key;if(a)for(let h of l)r(h,a,o.run,o.preventDefault,o.stopPropagation),o.shift&&r(h,"Shift-"+a,o.shift,o.preventDefault,o.stopPropagation)}return t}var Cr=null;function Wu(n,e,t,i){Cr=e;let s=yl(e),r=lt(s,0),o=Gt(r)==s.length&&s!=" ",l="",a=!1,h=!1,f=!1;ht&&ht.view==t&&ht.scope==i&&(l=ht.prefix+" ",Ra.indexOf(e.keyCode)<0&&(h=!0,ht=null));let c=new Set,u=O=>{if(O){for(let y of O.run)if(!c.has(y)&&(c.add(y),y(t)))return O.stopPropagation&&(f=!0),!0;O.preventDefault&&(O.stopPropagation&&(f=!0),h=!0)}return!1},d=n[i],p,m;return d&&(u(d[l+bn(s,e,!o)])?a=!0:o&&(e.altKey||e.metaKey||e.ctrlKey)&&!(x.windows&&e.ctrlKey&&e.altKey)&&!(x.mac&&e.altKey&&!(e.ctrlKey||e.metaKey))&&(p=je[e.keyCode])&&p!=s?(u(d[l+bn(p,e,!0)])||e.shiftKey&&(m=Zt[e.keyCode])!=s&&m!=p&&u(d[l+bn(m,e,!1)]))&&(a=!0):o&&e.shiftKey&&u(d[l+bn(s,e,!0)])&&(a=!0),!a&&u(d._any)&&(a=!0)),h&&(a=!0),a&&f&&e.stopPropagation(),Cr=null,a}var $u=x.gecko&&x.gecko_version==153?"#ffffff01":"transparent",Lg=at.highest(C.theme({".cm-line":{"& ::selection, &::selection":{backgroundColor:`${$u} !important`},caretColor:"transparent !important"},".cm-content":{caretColor:"transparent !important","& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}}));var zg=/x/.unicode!=null?"gu":"g";var ze=class extends Oe{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}};ze.prototype.elementClass="";ze.prototype.toDOM=void 0;ze.prototype.mapMode=Y.TrackBefore;ze.prototype.startSide=ze.prototype.endSide=-1;ze.prototype.point=!0;var Ns=v.define(),Lu=v.define();var kn=v.define();var Qr=v.define({combine:n=>n.some(e=>e)});function zu(n){let e=[Iu];return n&&n.fixed===!1&&e.push(Qr.of(!0)),e}var Iu=Le.fromClass(class{constructor(n){this.view=n,this.domAfter=null,this.prevViewport=n.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters cm-gutters-before",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=n.state.facet(kn).map(e=>new Wn(n,e)),this.fixed=!n.state.facet(Qr);for(let e of this.gutters)e.config.side=="after"?this.getDOMAfter().appendChild(e.dom):this.dom.appendChild(e.dom);this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),n.scrollDOM.insertBefore(this.dom,n.contentDOM)}getDOMAfter(){return this.domAfter||(this.domAfter=document.createElement("div"),this.domAfter.className="cm-gutters cm-gutters-after",this.domAfter.setAttribute("aria-hidden","true"),this.domAfter.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.domAfter.style.position=this.fixed?"sticky":"",this.view.scrollDOM.appendChild(this.domAfter)),this.domAfter}update(n){if(this.updateGutters(n)){let e=this.prevViewport,t=n.view.viewport,i=Math.min(e.to,t.to)-Math.max(e.from,t.from);this.syncGutters(i<(t.to-t.from)*.8)}if(n.geometryChanged){let e=this.view.contentHeight/this.view.scaleY+"px";this.dom.style.minHeight=e,this.domAfter&&(this.domAfter.style.minHeight=e)}this.view.state.facet(Qr)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":"",this.domAfter&&(this.domAfter.style.position=this.fixed?"sticky":"")),this.prevViewport=n.view.viewport}syncGutters(n){let e=this.dom.nextSibling;n&&(this.dom.remove(),this.domAfter&&this.domAfter.remove());let t=B.iter(this.view.state.facet(Ns),this.view.viewport.from),i=[],s=this.gutters.map(r=>new Ar(r,this.view.viewport,-this.view.documentPadding.top));for(let r of this.view.viewportLineBlocks)if(i.length&&(i=[]),Array.isArray(r.type)){let o=!0;for(let l of r.type)if(l.type==ue.Text&&o){Pr(t,i,l.from);for(let a of s)a.line(this.view,l,i);o=!1}else if(l.widget)for(let a of s)a.widget(this.view,l)}else if(r.type==ue.Text){Pr(t,i,r.from);for(let o of s)o.line(this.view,r,i)}else if(r.widget)for(let o of s)o.widget(this.view,r);for(let r of s)r.finish();n&&(this.view.scrollDOM.insertBefore(this.dom,e),this.domAfter&&this.view.scrollDOM.appendChild(this.domAfter))}updateGutters(n){let e=n.startState.facet(kn),t=n.state.facet(kn),i=n.docChanged||n.heightChanged||n.viewportChanged||!B.eq(n.startState.facet(Ns),n.state.facet(Ns),n.view.viewport.from,n.view.viewport.to);if(e==t)for(let s of this.gutters)s.update(n)&&(i=!0);else{i=!0;let s=[];for(let r of t){let o=e.indexOf(r);o<0?s.push(new Wn(this.view,r)):(this.gutters[o].update(n),s.push(this.gutters[o]))}for(let r of this.gutters)r.dom.remove(),s.indexOf(r)<0&&r.destroy();for(let r of s)r.config.side=="after"?this.getDOMAfter().appendChild(r.dom):this.dom.appendChild(r.dom);this.gutters=s}return i}destroy(){for(let n of this.gutters)n.destroy();this.dom.remove(),this.domAfter&&this.domAfter.remove()}},{provide:n=>C.scrollMargins.of(e=>{let t=e.plugin(n);if(!t||t.gutters.length==0||!t.fixed)return null;let i=t.dom.offsetWidth*e.scaleX,s=t.domAfter?t.domAfter.offsetWidth*e.scaleX:0;return e.textDirection==F.LTR?{left:i,right:s}:{right:i,left:s}})});function Hl(n){return Array.isArray(n)?n:[n]}function Pr(n,e,t){for(;n.value&&n.from<=t;)n.from==t&&e.push(n.value),n.next()}var Ar=class{constructor(e,t,i){this.gutter=e,this.height=i,this.i=0,this.cursor=B.iter(e.markers,t.from)}addElement(e,t,i){let{gutter:s}=this,r=(t.top-this.height)/e.scaleY,o=t.height/e.scaleY;if(this.i==s.elements.length){let l=new $n(e,o,r,i);s.elements.push(l),s.dom.appendChild(l.dom)}else s.elements[this.i].update(e,o,r,i);this.height=t.bottom,this.i++}line(e,t,i){let s=[];Pr(this.cursor,s,t.from),i.length&&(s=s.concat(i));let r=this.gutter.config.lineMarker(e,t,s);r&&s.unshift(r);let o=this.gutter;s.length==0&&!o.config.renderEmptyElements||this.addElement(e,t,s)}widget(e,t){let i=this.gutter.config.widgetMarker(e,t.widget,t),s=i?[i]:null;for(let r of e.state.facet(Lu)){let o=r(e,t.widget,t);o&&(s||(s=[])).push(o)}s&&this.addElement(e,t,s)}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}},Wn=class{constructor(e,t){this.view=e,this.config=t,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let i in t.domEventHandlers)this.dom.addEventListener(i,s=>{let r=s.target,o;if(r!=this.dom&&this.dom.contains(r)){for(;r.parentNode!=this.dom;)r=r.parentNode;let a=r.getBoundingClientRect();o=(a.top+a.bottom)/2}else o=s.clientY;let l=e.lineBlockAtHeight(o-e.documentTop);t.domEventHandlers[i](e,l,s)&&s.preventDefault()});this.markers=Hl(t.markers(e)),t.initialSpacer&&(this.spacer=new $n(e,0,0,[t.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let t=this.markers;if(this.markers=Hl(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let s=this.config.updateSpacer(this.spacer.markers[0],e);s!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[s])}let i=e.view.viewport;return!B.eq(this.markers,t,i.from,i.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}},$n=class{constructor(e,t,i,s){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,t,i,s)}update(e,t,i,s){this.height!=t&&(this.height=t,this.dom.style.height=t+"px"),this.above!=i&&(this.dom.style.marginTop=(this.above=i)?i+"px":""),Nu(this.markers,s)||this.setMarkers(e,s)}setMarkers(e,t){let i="cm-gutterElement",s=this.dom.firstChild;for(let r=0,o=0;;){let l=o,a=rr(l,a,h)||o(l,a,h):o}return i}})}}),Di=class extends ze{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}};function Vs(n,e){return n.state.facet(ei).formatNumber(e,n.state)}var Fu=kn.compute([ei],n=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(Vu)},lineMarker(e,t,i){return i.some(s=>s.toDOM)?null:new Di(Vs(e,e.state.doc.lineAt(t.from).number))},widgetMarker:(e,t,i)=>{for(let s of e.state.facet(Xu)){let r=s(e,t,i);if(r)return r}return null},lineMarkerChange:e=>e.startState.facet(ei)!=e.state.facet(ei),initialSpacer(e){return new Di(Vs(e,Ul(e.state.doc.lines)))},updateSpacer(e,t){let i=Vs(t.view,Ul(t.view.state.doc.lines));return i==e.number?e:new Di(i)},domEventHandlers:n.facet(ei).domEventHandlers,side:"before"}));function Ia(n={}){return[ei.of(n),zu(),Fu]}function Ul(n){let e=9;for(;e{throw new Error("This node type doesn't define a deserialize function")}),this.combine=e.combine||null}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=ie.match(e)),t=>{let i=e(t);return i===void 0?null:[this,i]}}};R.closedBy=new R({deserialize:n=>n.split(" ")});R.openedBy=new R({deserialize:n=>n.split(" ")});R.group=new R({deserialize:n=>n.split(" ")});R.isolate=new R({deserialize:n=>{if(n&&n!="rtl"&&n!="ltr"&&n!="auto")throw new RangeError("Invalid value for isolate: "+n);return n||"auto"}});R.contextHash=new R({perNode:!0});R.lookAhead=new R({perNode:!0});R.mounted=new R({perNode:!0});var Et=class{constructor(e,t,i,s=!1){this.tree=e,this.overlay=t,this.parser=i,this.bracketed=s}static get(e){return e&&e.props&&e.props[R.mounted.id]}},Hu=Object.create(null),ie=class n{constructor(e,t,i,s=0){this.name=e,this.props=t,this.id=i,this.flags=s}static define(e){let t=e.props&&e.props.length?Object.create(null):Hu,i=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),s=new n(e.name||"",t,e.id,i);if(e.props){for(let r of e.props)if(Array.isArray(r)||(r=r(s)),r){if(r[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[r[0].id]=r[1]}}return s}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop(R.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let i in e)for(let s of i.split(" "))t[s]=e[i];return i=>{for(let s=i.prop(R.group),r=-1;r<(s?s.length:0);r++){let o=t[r<0?i.name:s[r]];if(o)return o}}}};ie.none=new ie("",Object.create(null),0,8);var Ii=class n{constructor(e){this.types=e;for(let t=0;t0;for(let a=this.cursor(o|N.IncludeAnonymous);;){let h=!1;if(a.from<=r&&a.to>=s&&(!l&&a.type.isAnonymous||t(a)!==!1)){if(a.firstChild())continue;h=!0}for(;h&&i&&(l||!a.type.isAnonymous)&&i(a),!a.nextSibling();){if(!a.parent())return;h=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:Fr(ie.none,this.children,this.positions,0,this.children.length,0,this.length,(t,i,s)=>new n(this.type,t,i,s,this.propValues),e.makeTree||((t,i,s)=>new n(ie.none,t,i,s)))}static build(e){return ju(e)}};j.empty=new j(ie.none,[],[],0);var Lr=class n{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new n(this.buffer,this.index)}},dt=class n{constructor(e,t,i){this.buffer=e,this.length=t,this.set=i}get type(){return ie.none}toString(){let e=[];for(let t=0;t0));a=o[a+3]);return l}slice(e,t,i){let s=this.buffer,r=new Uint16Array(t-e),o=0;for(let l=e,a=0;l=e&&te;case 1:return t<=e&&i>e;case 2:return i>e;case 4:return!0}}function Ni(n,e,t,i){for(var s;n.from==n.to||(t<1?n.from>=e:n.from>e)||(t>-1?n.to<=e:n.to0?l.length:-1;e!=h;e+=t){let f=l[e],c=a[e]+o.from,u;if(!(!(r&N.EnterBracketed&&f instanceof j&&(u=Et.get(f))&&!u.overlay&&u.bracketed&&i>=c&&i<=c+f.length)&&!Fa(s,i,c,c+f.length))){if(f instanceof dt){if(r&N.ExcludeBuffers)continue;let d=f.findChild(0,f.buffer.length,t,i-c,s);if(d>-1)return new Dt(new Ir(o,f,e,c),null,d)}else if(r&N.IncludeAnonymous||!f.type.isAnonymous||Xr(f)){let d;if(!(r&N.IgnoreMounts)&&(d=Et.get(f))&&!d.overlay)return new n(d.tree,c,e,o);let p=new n(f,c,e,o);return r&N.IncludeAnonymous||!p.type.isAnonymous?p:p.nextChild(t<0?f.children.length-1:0,t,i,s,r)}}}if(r&N.IncludeAnonymous||!o.type.isAnonymous||(o.index>=0?e=o.index+t:e=t<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}prop(e){return this._tree.prop(e)}enter(e,t,i=0){let s;if(!(i&N.IgnoreOverlays)&&(s=Et.get(this._tree))&&s.overlay){let r=e-this.from,o=i&N.EnterBracketed&&s.bracketed;for(let{from:l,to:a}of s.overlay)if((t>0||o?l<=r:l=r:a>r))return new n(s.tree,s.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,i)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}};function Va(n,e,t,i){let s=n.cursor(),r=[];if(!s.firstChild())return r;if(t!=null){for(let o=!1;!o;)if(o=s.type.is(t),!s.nextSibling())return r}for(;;){if(i!=null&&s.type.is(i))return r;if(s.type.is(e)&&r.push(s.node),!s.nextSibling())return i==null?r:[]}}function zr(n,e,t=e.length-1){for(let i=n;t>=0;i=i.parent){if(!i)return!1;if(!i.type.isAnonymous){if(e[t]&&e[t]!=i.name)return!1;t--}}return!0}var Ir=class{constructor(e,t,i,s){this.parent=e,this.buffer=t,this.index=i,this.start=s}},Dt=class n extends Xn{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,i){super(),this.context=e,this._parent=t,this.index=i,this.type=e.buffer.set.types[e.buffer.buffer[i]]}child(e,t,i){let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.context.start,i);return r<0?null:new n(this.context,this,r)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}prop(e){return this.type.prop(e)}enter(e,t,i=0){if(i&N.ExcludeBuffers)return null;let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return r<0?null:new n(this.context,this,r)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new n(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new n(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],t=[],{buffer:i}=this.context,s=this.index+4,r=i.buffer[this.index+3];if(r>s){let o=i.buffer[this.index+1];e.push(i.slice(s,r,o)),t.push(0)}return new j(this.type,e,t,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}};function _a(n){if(!n.length)return null;let e=0,t=n[0];for(let r=1;rt.from||o.to=e){let l=new we(o.tree,o.overlay[0].from+r.from,-1,r);(s||(s=[i])).push(Ni(l,e,t,!1))}}return s?_a(s):i}var Vi=class{get name(){return this.type.name}constructor(e,t=0){if(this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,this.mode=t&~N.EnterBracketed,e instanceof we)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let i=e._parent;i;i=i._parent)this.stack.unshift(i.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:i,buffer:s}=this.buffer;return this.type=t||s.set.types[s.buffer[e]],this.from=i+s.buffer[e+1],this.to=i+s.buffer[e+2],!0}yield(e){return e?e instanceof we?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,i){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,i,this.mode));let{buffer:s}=this.buffer,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.buffer.start,i);return r<0?!1:(this.stack.push(this.index),this.yieldBuf(r))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,i=this.mode){return this.buffer?i&N.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,i))}parent(){if(!this.buffer)return this.yieldNode(this.mode&N.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&N.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,i=this.stack.length-1;if(e<0){let s=i<0?0:this.stack[i]+4;if(this.index!=s)return this.yieldBuf(t.findChild(s,this.index,-1,0,4))}else{let s=t.buffer[this.index+3];if(s<(i<0?t.buffer.length:t.buffer[this.stack[i]+3]))return this.yieldBuf(s)}return i<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,i,{buffer:s}=this;if(s){if(e>0){if(this.index-1)for(let r=t+e,o=e<0?-1:i._tree.children.length;r!=o;r+=e){let l=i._tree.children[r];if(this.mode&N.IncludeAnonymous||l instanceof dt||!l.type.isAnonymous||Xr(l))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let o=e;o;o=o._parent)if(o.index==s){if(s==this.index)return o;t=o,i=r+1;break e}s=this.stack[--r]}for(let s=i;s=0;r--){if(r<0)return zr(this._tree,e,s);let o=i[t.buffer[this.stack[r]]];if(!o.isAnonymous){if(e[s]&&e[s]!=o.name)return!1;s--}}return!0}};function Xr(n){return n.children.some(e=>e instanceof dt||!e.type.isAnonymous||Xr(e))}function ju(n){var e;let{buffer:t,nodeSet:i,maxBufferLength:s=1024,reused:r=[],minRepeatType:o=i.types.length}=n,l=Array.isArray(t)?new Lr(t,t.length):t,a=i.types,h=0,f=0;function c(Q,P,T,V,$,U){let{id:E,start:A,end:X,size:H}=l,ee=f,Fe=h;if(H<0)if(l.next(),H==-1){let _e=r[E];T.push(_e),V.push(A-Q);return}else if(H==-3){h=E;return}else if(H==-4){f=E;return}else throw new RangeError(`Unrecognized record size: ${H}`);let Oi=a[E],en,bt,Vo=A-Q;if(X-A<=s&&(bt=O(l.pos-P,$))){let _e=new Uint16Array(bt.size-bt.skip),se=l.pos-bt.size,Ce=_e.length;for(;l.pos>se;)Ce=y(bt.start,_e,Ce);en=new dt(_e,X-bt.start,i),Vo=bt.start-Q}else{let _e=l.pos-H;l.next();let se=[],Ce=[],qe=E>=o?E:-1,He=0,Vt=X,yi=ee;for(;l.pos>_e;)qe>=0&&l.id==qe&&l.size>=0?(l.end<=Vt-s&&(p(se,Ce,A,He,l.end,Vt,qe,yi,Fe),He=se.length,Vt=l.end,yi=f),l.next()):U>2500?u(A,_e,se,Ce):(qe>=0&&l.size==-1&&r[l.id].type==i.types[qe]&&(He=0&&He>0&&He-1&&He>0){let Xo=d(Oi,Fe);en=Fr(Oi,se,Ce,0,se.length,0,X-A,Xo,Xo)}else en=m(Oi,se,Ce,X-A,ee-X,Fe)}T.push(en),V.push(Vo)}function u(Q,P,T,V){let $=[],U=0,E=-1;for(;l.pos>P;){let{id:A,start:X,end:H,size:ee}=l;if(ee>4)l.next();else{if(E>-1&&X=0;H-=3)A[ee++]=$[H],A[ee++]=$[H+1]-X,A[ee++]=$[H+2]-X,A[ee++]=ee;T.push(new dt(A,$[2]-X,i)),V.push(X-Q)}}function d(Q,P){return(T,V,$)=>{let U=0,E=T.length-1,A,X;if(E>=0&&(A=T[E])instanceof j){if(!E&&A.type==Q&&A.length==$)return A;(X=A.prop(R.lookAhead))&&(U=V[E]+A.length+X-$)}return m(Q,T,V,$,U,P)}}function p(Q,P,T,V,$,U,E,A,X){let H=[],ee=[];for(;Q.length>V;)H.push(Q.pop()),ee.push(P.pop()+T-$);Q.push(m(i.types[E],H,ee,U-$,A-U,X)),P.push($-T)}function m(Q,P,T,V,$,U,E){if(U){let A=[R.contextHash,U];E=E?[A].concat(E):[A]}if($>25){let A=[R.lookAhead,$];E=E?[A].concat(E):[A]}return new j(Q,P,T,V,E)}function O(Q,P){let T=l.fork(),V=0,$=0,U=0,E=T.end-s,A={size:0,start:0,skip:0};e:for(let X=T.pos-Q;T.pos>X;){let H=T.size;if(T.id==P&&H>=0){A.size=V,A.start=$,A.skip=U,U+=4,V+=4,T.next();continue}let ee=T.pos-H;if(H<0||ee=o?4:0,Oi=T.start;for(T.next();T.pos>ee;){if(T.size<0)if(T.size==-3||T.size==-4)Fe+=4;else break e;else T.id>=o&&(Fe+=4);T.next()}$=Oi,V+=H,U+=Fe}return(P<0||V==Q)&&(A.size=V,A.start=$,A.skip=U),A.size>4?A:void 0}function y(Q,P,T){let{id:V,start:$,end:U,size:E}=l;if(l.next(),E>=0&&V4){let X=l.pos-(E-4);for(;l.pos>X;)T=y(Q,P,T)}P[--T]=A,P[--T]=U-Q,P[--T]=$-Q,P[--T]=V}else E==-3?h=V:E==-4&&(f=V);return T}let w=[],k=[];for(;l.pos>0;)c(n.start||0,n.bufferStart||0,w,k,-1,0);let D=(e=n.length)!==null&&e!==void 0?e:w.length?k[0]+w[0].length:0;return new j(a[n.topID],w.reverse(),k.reverse(),D)}var Xa=new WeakMap;function Vn(n,e){if(!n.isAnonymous||e instanceof dt||e.type!=n)return 1;let t=Xa.get(e);if(t==null){t=1;for(let i of e.children){if(i.type!=n||!(i instanceof j)){t=1;break}t+=Vn(n,i)}Xa.set(e,t)}return t}function Fr(n,e,t,i,s,r,o,l,a){let h=0;for(let p=i;p=f)break;P+=T}if(k==D+1){if(P>f){let T=p[D];d(T.children,T.positions,0,T.children.length,m[D]+w);continue}c.push(p[D])}else{let T=m[k-1]+p[k-1].length-Q;c.push(Fr(n,p,m,D,k,Q,T,null,a))}u.push(Q+w-r)}}return d(e,t,i,s,0),(l||a)(c,u,o)}var Fn=class{constructor(){this.map=new WeakMap}setBuffer(e,t,i){let s=this.map.get(e);s||this.map.set(e,s=new Map),s.set(t,i)}getBuffer(e,t){let i=this.map.get(e);return i&&i.get(t)}set(e,t){e instanceof Dt?this.setBuffer(e.context.buffer,e.index,t):e instanceof we&&this.map.set(e.tree,t)}get(e){return e instanceof Dt?this.getBuffer(e.context.buffer,e.index):e instanceof we?this.map.get(e.tree):void 0}cursorSet(e,t){e.buffer?this.setBuffer(e.buffer.buffer,e.index,t):this.map.set(e.tree,t)}cursorGet(e){return e.buffer?this.getBuffer(e.buffer.buffer,e.index):this.map.get(e.tree)}},Bt=class n{constructor(e,t,i,s,r=!1,o=!1){this.from=e,this.to=t,this.tree=i,this.offset=s,this.open=(r?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],i=!1){let s=[new n(0,e.length,e,0,!1,i)];for(let r of t)r.to>e.length&&s.push(r);return s}static applyChanges(e,t,i=128){if(!t.length)return e;let s=[],r=1,o=e.length?e[0]:null;for(let l=0,a=0,h=0;;l++){let f=l=i)for(;o&&o.from=u.from||c<=u.to||h){let d=Math.max(u.from,a)-h,p=Math.min(u.to,c)-h;u=d>=p?null:new n(d,p,u.tree,u.offset+h,l>0,!!f)}if(u&&s.push(u),o.to>c)break;o=rnew zi(s.from,s.to)):[new zi(0,0)]:[new zi(0,e.length)],this.createParse(e,t||[],i)}parse(e,t,i){let s=this.startParse(e,t,i);for(;;){let r=s.advance();if(r)return r}}},Vr=class{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}};var Xg=new R({perNode:!0});var Gu=0,Re=class n{constructor(e,t,i,s){this.name=e,this.set=t,this.base=i,this.modified=s,this.id=Gu++}toString(){let{name:e}=this;for(let t of this.modified)t.name&&(e=`${t.name}(${e})`);return e}static define(e,t){let i=typeof e=="string"?e:"?";if(e instanceof n&&(t=e),t?.base)throw new Error("Can not derive from a modified tag");let s=new n(i,[],null,[]);if(s.set.push(s),t)for(let r of t.set)s.set.push(r);return s}static defineModifier(e){let t=new jn(e);return i=>i.modified.indexOf(t)>-1?i:jn.get(i.base||i,i.modified.concat(t).sort((s,r)=>s.id-r.id))}},Zu=0,jn=class n{constructor(e){this.name=e,this.instances=[],this.id=Zu++}static get(e,t){if(!t.length)return e;let i=t[0].instances.find(l=>l.base==e&&Yu(t,l.modified));if(i)return i;let s=[],r=new Re(e.name,s,e,t);for(let l of t)l.instances.push(r);let o=Ku(t);for(let l of e.set)if(!l.modified.length)for(let a of o)s.push(n.get(l,a));return r}};function Yu(n,e){return n.length==e.length&&n.every((t,i)=>t==e[i])}function Ku(n){let e=[[]];for(let t=0;ti.length-t.length)}function Gn(n){let e=Object.create(null);for(let t in n){let i=n[t];Array.isArray(i)||(i=[i]);for(let s of t.split(" "))if(s){let r=[],o=2,l=s;for(let c=0;;){if(l=="..."&&c>0&&c+3==s.length){o=1;break}let u=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(l);if(!u)throw new RangeError("Invalid path: "+s);if(r.push(u[0]=="*"?"":u[0][0]=='"'?JSON.parse(u[0]):u[0]),c+=u[0].length,c==s.length)break;let d=s[c++];if(c==s.length&&d=="!"){o=0;break}if(d!="/")throw new RangeError("Invalid path: "+s);l=s.slice(c)}let a=r.length-1,h=r[a];if(!h)throw new RangeError("Invalid path: "+s);let f=new Wt(i,o,a>0?r.slice(0,a):null);e[h]=f.sort(e[h])}}return ja.add(e)}var ja=new R({combine(n,e){let t,i,s;for(;n||e;){if(!n||e&&n.depth<=e.depth?(s=e,e=e.next):(s=n,n=n.next),t&&t.mode==s.mode&&!s.context&&!t.context)continue;let r=new Wt(s.tags,s.mode,s.context);t?t.next=r:i=r,t=r}return i}}),Wt=class{constructor(e,t,i,s){this.tags=e,this.mode=t,this.context=i,this.next=s}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth{let o=s;for(let l of r)for(let a of l.set){let h=t[a.id];if(h){o=o?o+" "+h:h;break}}return o},scope:i}}function Ju(n,e){let t=null;for(let i of n){let s=i.style(e);s&&(t=t?t+" "+s:s)}return t}function Ga(n,e,t,i=0,s=n.length){let r=new Hr(i,Array.isArray(e)?e:[e],t);r.highlightRange(n.cursor(),i,s,"",r.highlighters),r.flush(s)}var Hr=class{constructor(e,t,i){this.at=e,this.highlighters=t,this.span=i,this.class=""}startSpan(e,t){t!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=t)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,t,i,s,r){let{type:o,from:l,to:a}=e;if(l>=i||a<=t)return;o.isTop&&(r=this.highlighters.filter(d=>!d.scope||d.scope(o)));let h=s,f=ed(e)||Wt.empty,c=Ju(r,f.tags);if(c&&(h&&(h+=" "),h+=c,f.mode==1&&(s+=(s?" ":"")+c)),this.startSpan(Math.max(t,l),h),f.opaque)return;let u=e.tree&&e.tree.prop(R.mounted);if(u&&u.overlay){let d=e.node.enter(u.overlay[0].from+l,1),p=this.highlighters.filter(O=>!O.scope||O.scope(u.tree.type)),m=e.firstChild();for(let O=0,y=l;;O++){let w=O=k||!e.nextSibling())););if(!w||k>i)break;y=w.to+l,y>t&&(this.highlightRange(d.cursor(),Math.max(t,w.from+l),Math.min(i,y),"",p),this.startSpan(Math.min(i,y),h))}m&&e.parent()}else if(e.firstChild()){u&&(s="");do if(!(e.to<=t)){if(e.from>=i)break;this.highlightRange(e,t,i,s,r),this.startSpan(Math.min(i,e.to),h)}while(e.nextSibling());e.parent()}}};function ed(n){let e=n.type.prop(ja);for(;e&&e.context&&!n.matchContext(e.context);)e=e.next;return e||null}var S=Re.define,_n=S(),pt=S(),Ha=S(pt),Ua=S(pt),mt=S(),Hn=S(mt),_r=S(mt),Ve=S(),qt=S(Ve),Ie=S(),Ne=S(),Ur=S(),Xi=S(Ur),Un=S(),g={comment:_n,lineComment:S(_n),blockComment:S(_n),docComment:S(_n),name:pt,variableName:S(pt),typeName:Ha,tagName:S(Ha),propertyName:Ua,attributeName:S(Ua),className:S(pt),labelName:S(pt),namespace:S(pt),macroName:S(pt),literal:mt,string:Hn,docString:S(Hn),character:S(Hn),attributeValue:S(Hn),number:_r,integer:S(_r),float:S(_r),bool:S(mt),regexp:S(mt),escape:S(mt),color:S(mt),url:S(mt),keyword:Ie,self:S(Ie),null:S(Ie),atom:S(Ie),unit:S(Ie),modifier:S(Ie),operatorKeyword:S(Ie),controlKeyword:S(Ie),definitionKeyword:S(Ie),moduleKeyword:S(Ie),operator:Ne,derefOperator:S(Ne),arithmeticOperator:S(Ne),logicOperator:S(Ne),bitwiseOperator:S(Ne),compareOperator:S(Ne),updateOperator:S(Ne),definitionOperator:S(Ne),typeOperator:S(Ne),controlOperator:S(Ne),punctuation:Ur,separator:S(Ur),bracket:Xi,angleBracket:S(Xi),squareBracket:S(Xi),paren:S(Xi),brace:S(Xi),content:Ve,heading:qt,heading1:S(qt),heading2:S(qt),heading3:S(qt),heading4:S(qt),heading5:S(qt),heading6:S(qt),contentSeparator:S(Ve),list:S(Ve),quote:S(Ve),emphasis:S(Ve),strong:S(Ve),link:S(Ve),monospace:S(Ve),strikethrough:S(Ve),inserted:S(),deleted:S(),changed:S(),invalid:S(),meta:Un,documentMeta:S(Un),annotation:S(Un),processingInstruction:S(Un),definition:Re.defineModifier("definition"),constant:Re.defineModifier("constant"),function:Re.defineModifier("function"),standard:Re.defineModifier("standard"),local:Re.defineModifier("local"),special:Re.defineModifier("special")};for(let n in g){let e=g[n];e instanceof Re&&(e.name=n)}var Hg=jr([{tag:g.link,class:"tok-link"},{tag:g.heading,class:"tok-heading"},{tag:g.emphasis,class:"tok-emphasis"},{tag:g.strong,class:"tok-strong"},{tag:g.keyword,class:"tok-keyword"},{tag:g.atom,class:"tok-atom"},{tag:g.bool,class:"tok-bool"},{tag:g.url,class:"tok-url"},{tag:g.labelName,class:"tok-labelName"},{tag:g.inserted,class:"tok-inserted"},{tag:g.deleted,class:"tok-deleted"},{tag:g.literal,class:"tok-literal"},{tag:g.string,class:"tok-string"},{tag:g.number,class:"tok-number"},{tag:[g.regexp,g.escape,g.special(g.string)],class:"tok-string2"},{tag:g.variableName,class:"tok-variableName"},{tag:g.local(g.variableName),class:"tok-variableName tok-local"},{tag:g.definition(g.variableName),class:"tok-variableName tok-definition"},{tag:g.special(g.variableName),class:"tok-variableName2"},{tag:g.definition(g.propertyName),class:"tok-propertyName tok-definition"},{tag:g.typeName,class:"tok-typeName"},{tag:g.namespace,class:"tok-namespace"},{tag:g.className,class:"tok-className"},{tag:g.macroName,class:"tok-macroName"},{tag:g.propertyName,class:"tok-propertyName"},{tag:g.operator,class:"tok-operator"},{tag:g.comment,class:"tok-comment"},{tag:g.meta,class:"tok-meta"},{tag:g.invalid,class:"tok-invalid"},{tag:g.punctuation,class:"tok-punctuation"}]);var Gr,fi=new R;function td(n){return v.define({combine:n?e=>e.concat(n):void 0})}var id=new R,me=class{constructor(e,t,i=[],s=""){this.data=e,this.name=s,z.prototype.hasOwnProperty("tree")||Object.defineProperty(z.prototype,"tree",{get(){return J(this)}}),this.parser=t,this.extension=[ci.of(this),z.languageData.of((r,o,l)=>{let a=Za(r,o,l),h=a.type.prop(fi);if(!h)return[];let f=r.facet(h),c=a.type.prop(id);if(c){let u=a.resolve(o-a.from,l);for(let d of c)if(d.test(u,r)){let p=r.facet(d.facet);return d.type=="replace"?p:p.concat(f)}}return f})].concat(i)}isActiveAt(e,t,i=-1){return Za(e,t,i).type.prop(fi)==this.data}findRegions(e){let t=e.facet(ci);if(t?.data==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let i=[],s=(r,o)=>{if(r.prop(fi)==this.data){i.push({from:o,to:o+r.length});return}let l=r.prop(R.mounted);if(l){if(l.tree.prop(fi)==this.data){if(l.overlay)for(let a of l.overlay)i.push({from:a.from+o,to:a.to+o});else i.push({from:o,to:o+r.length});return}else if(l.overlay){let a=i.length;if(s(l.tree,l.overlay[0].from+o),i.length>a)return}}for(let a=0;ai.isTop?t:void 0)]}),e.name)}configure(e,t){return new n(this.data,this.parser.configure(e),t||this.name)}get allowsNesting(){return this.parser.hasWrappers()}};function J(n){let e=n.field(me.state,!1);return e?e.tree:j.empty}var Jr=class{constructor(e){this.doc=e,this.cursorPos=0,this.string="",this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,t){let i=this.cursorPos-this.string.length;return e=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-i,t-i)}},Fi=null,eo=class n{constructor(e,t,i=[],s,r,o,l,a){this.parser=e,this.state=t,this.fragments=i,this.tree=s,this.treeLen=r,this.viewport=o,this.skipped=l,this.scheduleOn=a,this.parse=null,this.tempSkipped=[]}static create(e,t,i){return new n(e,t,[],j.empty,0,i,[],null)}startParse(){return this.parser.startParse(new Jr(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=j.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var i;if(typeof e=="number"){let s=Date.now()+e;e=()=>Date.now()>s}for(this.parse||(this.parse=this.startParse()),t!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&t=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(t=this.parse.advance()););}),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped(Bt.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=Fi;Fi=this;try{return e()}finally{Fi=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=Ya(e,t.from,t.to);return e}changes(e,t){let{fragments:i,tree:s,treeLen:r,viewport:o,skipped:l}=this;if(this.takeTree(),!e.empty){let a=[];if(e.iterChangedRanges((h,f,c,u)=>a.push({fromA:h,toA:f,fromB:c,toB:u})),i=Bt.applyChanges(i,a),s=j.empty,r=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){l=[];for(let h of this.skipped){let f=e.mapPos(h.from,1),c=e.mapPos(h.to,-1);fe.from&&(this.fragments=Ya(this.fragments,s,r),this.skipped.splice(i--,1))}return this.skipped.length>=t?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends hi{createParse(t,i,s){let r=s[0].from,o=s[s.length-1].to;return{parsedPos:r,advance(){let a=Fi;if(a){for(let h of s)a.tempSkipped.push(h);e&&(a.scheduleOn=a.scheduleOn?Promise.all([a.scheduleOn,e]):e)}return this.parsedPos=o,new j(ie.none,[],[],o-r)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&t[0].from==0&&t[0].to>=e}static get(){return Fi}};function Ya(n,e,t){return Bt.applyChanges(n,[{fromA:e,toA:t,fromB:e,toB:t}])}var _i=class n{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let t=this.context.changes(e.changes,e.state),i=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,i)||t.takeTree(),new n(t)}static init(e){let t=Math.min(3e3,e.doc.length),i=eo.create(e.facet(ci).parser,e,{from:0,to:t});return i.work(20,t)||i.takeTree(),new n(i)}};me.state=he.define({create:_i.init,update(n,e){for(let t of e.effects)if(t.is(me.setState))return t.value;return e.startState.facet(ci)!=e.state.facet(ci)?_i.init(e.state):n.apply(e)}});var ih=n=>{let e=setTimeout(()=>n(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(ih=n=>{let e=-1,t=setTimeout(()=>{e=requestIdleCallback(n,{timeout:400})},100);return()=>e<0?clearTimeout(t):cancelIdleCallback(e)});var Zr=typeof navigator<"u"&&(!((Gr=navigator.scheduling)===null||Gr===void 0)&&Gr.isInputPending)?()=>navigator.scheduling.isInputPending():null,nd=Le.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(me.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(me.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=ih(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEnds+1e3,a=r.context.work(()=>Zr&&Zr()||Date.now()>o,s+(l?0:1e5));this.chunkBudget-=Date.now()-t,(a||this.chunkBudget<=0)&&(r.context.takeTree(),this.view.dispatch({effects:me.setState.of(new _i(r.context))})),this.chunkBudget>0&&!(a&&!l)&&this.scheduleWork(),this.checkAsyncSchedule(r.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(t=>ke(this.view.state,t)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),ci=v.define({combine(n){return n.length?n[0]:null},enables:n=>[me.state,nd,C.contentAttributes.compute([n],e=>{let t=e.facet(n);return t&&t.name?{"data-language":t.name}:{}})]}),Yn=class{constructor(e,t=[]){this.language=e,this.support=t,this.extension=[e,t]}};var sd=v.define(),gt=v.define({combine:n=>{if(!n.length)return" ";let e=n[0];if(!e||/\S/.test(e)||Array.from(e).some(t=>t!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(n[0]));return e}});function Hi(n){let e=n.facet(gt);return e.charCodeAt(0)==9?n.tabSize*e.length:e.length}function di(n,e){let t="",i=n.tabSize,s=n.facet(gt)[0];if(s==" "){for(;e>=i;)t+=" ",e-=i;s=" "}for(let r=0;r=e?rd(n,t,e):null}var $t=class{constructor(e,t={}){this.state=e,this.options=t,this.unit=Hi(e)}lineAt(e,t=1){let i=this.state.doc.lineAt(e),{simulateBreak:s,simulateDoubleBreak:r}=this.options;return s!=null&&s>=i.from&&s<=i.to?r&&s==e?{text:"",from:e}:(t<0?s-1&&(r+=o-this.countColumn(i,i.search(/\S|$/))),r}countColumn(e,t=e.length){return Ct(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:i,from:s}=this.lineAt(e,t),r=this.options.overrideIndentation;if(r){let o=r(s);if(o>-1)return o}return this.countColumn(i,i.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}},oo=new R;function rd(n,e,t){let i=e.resolveStack(t),s=e.resolveInner(t,-1).resolve(t,0).enterUnfinishedNodesBefore(t);if(s!=i.node){let r=[];for(let o=s;o&&!(o.fromi.node.to||o.from==i.node.from&&o.type==i.node.type);o=o.parent)r.push(o);for(let o=r.length-1;o>=0;o--)i={node:r[o],next:i}}return nh(i,n,t)}function nh(n,e,t){for(let i=n;i;i=i.next){let s=ld(i.node);if(s)return s(to.create(e,t,i))}return 0}function od(n){return n.pos==n.options.simulateBreak&&n.options.simulateDoubleBreak}function ld(n){let e=n.type.prop(oo);if(e)return e;let t=n.firstChild,i;if(t&&(i=t.type.prop(R.closedBy))){let s=n.lastChild,r=s&&i.indexOf(s.name)>-1;return o=>sh(o,!0,1,void 0,r&&!od(o)?s.from:void 0)}return n.parent==null?ad:null}function ad(){return 0}var to=class n extends $t{constructor(e,t,i){super(e.state,e.options),this.base=e,this.pos=t,this.context=i}get node(){return this.context.node}static create(e,t,i){return new n(e,t,i)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(e){let t=this.state.doc.lineAt(e.from);for(;;){let i=e.resolve(t.from);for(;i.parent&&i.parent.from==i.from;)i=i.parent;if(hd(i,e))break;t=this.state.doc.lineAt(i.from)}return this.lineIndent(t.from)}continue(){return nh(this.context.next,this.base,this.pos)}};function hd(n,e){for(let t=e;t;t=t.parent)if(n==t)return!0;return!1}function fd(n){let e=n.node,t=e.childAfter(e.from),i=e.lastChild;if(!t)return null;let s=n.options.simulateBreak,r=n.state.doc.lineAt(t.from),o=s==null||s<=r.from?r.to:Math.min(r.to,s);for(let l=t.to;;){let a=e.childAfter(l);if(!a||a==i)return null;if(!a.type.isSkipped){if(a.from>=o)return null;let h=/^ */.exec(r.text.slice(t.to-r.from))[0].length;return{from:t.from,to:t.to+h}}l=a.to}}function Jn({closing:n,align:e=!0,units:t=1}){return i=>sh(i,e,t,n)}function sh(n,e,t,i,s){let r=n.textAfter,o=r.match(/^\s*/)[0].length,l=i&&r.slice(o,o+i.length)==i||s==n.pos+o,a=e?fd(n):null;return a?l?n.column(a.from):n.column(a.to):n.baseIndent+(l?0:n.unit*t)}var cd=200;function rh(){return z.transactionFilter.of(n=>{if(!n.docChanged||!n.isUserEvent("input.type")&&!n.isUserEvent("input.complete"))return n;let e=n.startState.languageDataAt("indentOnInput",n.startState.selection.main.head);if(!e.length)return n;let t=n.newDoc,{head:i}=n.newSelection.main,s=t.lineAt(i);if(i>s.from+cd)return n;let r=t.sliceString(s.from,i);if(!e.some(h=>h.test(r)))return n;let{state:o}=n,l=-1,a=[];for(let{head:h}of o.selection.ranges){let f=o.doc.lineAt(h);if(f.from==l)continue;l=f.from;let c=Kn(o,f.from);if(c==null)continue;let u=/^\s*/.exec(f.text)[0],d=di(o,c);u!=d&&a.push({from:f.from,to:f.from+u.length,insert:d})}return a.length?[n,{changes:a,sequential:!0}]:n})}var oh=new R;function lh(n){let e=n.firstChild,t=n.lastChild;return e&&e.tol.prop(fi)==o.data:o?l=>l==o:void 0,this.style=jr(e.map(l=>({tag:l.tag,class:l.class||s(Object.assign({},l,{tag:null}))})),{all:r}).style,this.module=i?new ye(i):null,this.themeType=t.themeType}static define(e,t){return new n(e,t||{})}},io=v.define(),ah=v.define({combine(n){return n.length?[n[0]]:null}});function Yr(n){let e=n.facet(io);return e.length?e:n.facet(ah)}function es(n,e){let t=[ud],i;return n instanceof ui&&(n.module&&t.push(C.styleModule.of(n.module)),i=n.themeType),e?.fallback?t.push(ah.of(n)):i?t.push(io.computeN([C.darkTheme],s=>s.facet(C.darkTheme)==(i=="dark")?[n]:[])):t.push(io.of(n)),t}var no=class{constructor(e){this.markCache=Object.create(null),this.tree=J(e.state),this.decorations=this.buildDeco(e,Yr(e.state)),this.decoratedTo=e.viewport.to}update(e){let t=J(e.state),i=Yr(e.state),s=i!=Yr(e.startState),{viewport:r}=e.view,o=e.changes.mapPos(this.decoratedTo,1);t.length=r.to?(this.decorations=this.decorations.map(e.changes),this.decoratedTo=o):(t!=this.tree||e.viewportChanged||s)&&(this.tree=t,this.decorations=this.buildDeco(e.view,i),this.decoratedTo=r.to)}buildDeco(e,t){if(!t||!this.tree.length)return q.none;let i=new ot;for(let{from:s,to:r}of e.visibleRanges)Ga(this.tree,t,(o,l,a)=>{i.add(o,l,this.markCache[a]||(this.markCache[a]=q.mark({class:a})))},s,r);return i.finish()}},ud=at.high(Le.fromClass(no,{decorations:n=>n.decorations})),hh=ui.define([{tag:g.meta,color:"#404740"},{tag:g.link,textDecoration:"underline"},{tag:g.heading,textDecoration:"underline",fontWeight:"bold"},{tag:g.emphasis,fontStyle:"italic"},{tag:g.strong,fontWeight:"bold"},{tag:g.strikethrough,textDecoration:"line-through"},{tag:g.keyword,color:"#708"},{tag:[g.atom,g.bool,g.url,g.contentSeparator,g.labelName],color:"#219"},{tag:[g.literal,g.inserted],color:"#164"},{tag:[g.string,g.deleted],color:"#a11"},{tag:[g.regexp,g.escape,g.special(g.string)],color:"#e40"},{tag:g.definition(g.variableName),color:"#00f"},{tag:g.local(g.variableName),color:"#30a"},{tag:[g.typeName,g.namespace],color:"#085"},{tag:g.className,color:"#167"},{tag:[g.special(g.variableName),g.macroName],color:"#256"},{tag:g.definition(g.propertyName),color:"#00c"},{tag:g.comment,color:"#940"},{tag:g.invalid,color:"#f00"}]),dd=C.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),fh=1e4,ch="()[]{}",uh=v.define({combine(n){return Tt(n,{afterCursor:!0,brackets:ch,maxScanDistance:fh,renderMatch:gd})}}),pd=q.mark({class:"cm-matchingBracket"}),md=q.mark({class:"cm-nonmatchingBracket"});function gd(n){let e=[],t=n.matched?pd:md;return e.push(t.range(n.start.from,n.start.to)),n.end&&e.push(t.range(n.end.from,n.end.to)),e}function Ka(n){let e=[],t=n.facet(uh);for(let i of n.selection.ranges){if(!i.empty)continue;let s=Me(n,i.head,-1,t)||i.head>0&&Me(n,i.head-1,1,t)||t.afterCursor&&(Me(n,i.head,1,t)||i.headn.decorations}),yd=[Od,dd];function dh(n={}){return[uh.of(n),yd]}var bd=new R;function so(n,e,t){let i=n.prop(e<0?R.openedBy:R.closedBy);if(i)return i;if(n.name.length==1){let s=t.indexOf(n.name);if(s>-1&&s%2==(e<0?1:0))return[t[s+e]]}return null}function ro(n){let e=n.type.prop(bd);return e?e(n.node):n}function Me(n,e,t,i={}){let s=i.maxScanDistance||fh,r=i.brackets||ch,o=J(n),l=o.resolveInner(e,t);for(let a=l;a;a=a.parent){let h=so(a.type,t,r);if(h&&a.from0?e>=f.from&&ef.from&&e<=f.to))return Sd(n,e,t,a,f,h,r)}}return xd(n,e,t,o,l.type,s,r)}function Sd(n,e,t,i,s,r,o){let l=i.parent,a={from:s.from,to:s.to},h=0,f=l?.cursor();if(f&&(t<0?f.childBefore(i.from):f.childAfter(i.to)))do if(t<0?f.to<=i.from:f.from>=i.to){if(h==0&&r.indexOf(f.type.name)>-1&&f.from0)return null;let h={from:t<0?e-1:e,to:t>0?e+1:e},f=n.doc.iterRange(e,t>0?n.doc.length:0),c=0;for(let u=0;!f.next().done&&u<=r;){let d=f.value;t<0&&(u+=d.length);let p=e+u*t;for(let m=t>0?0:d.length-1,O=t>0?d.length:-1;m!=O;m+=t){let y=o.indexOf(d[m]);if(!(y<0||i.resolveInner(p+m,1).type!=s))if(y%2==0==t>0)c++;else{if(c==1)return{start:h,end:{from:p+m,to:p+m+1},matched:y>>1==a>>1};c--}}t>0&&(u+=d.length)}return f.done?{start:h,matched:!1}:null}var kd=Object.create(null),Ja=[ie.none];var eh=[],th=Object.create(null),wd=Object.create(null);for(let[n,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])wd[n]=vd(kd,e);function Kr(n,e){eh.indexOf(n)>-1||(eh.push(n),console.warn(e))}function vd(n,e){let t=[];for(let l of e.split(" ")){let a=[];for(let h of l.split(".")){let f=n[h]||g[h];f?typeof f=="function"?a.length?a=a.map(f):Kr(h,`Modifier ${h} used at start of tag`):a.length?Kr(h,`Tag ${h} used as modifier`):a=Array.isArray(f)?f:[f]:Kr(h,`Unknown highlighting tag ${h}`)}for(let h of a)t.push(h)}if(!t.length)return 0;let i=e.replace(/ /g,"_"),s=i+" "+t.map(l=>l.id),r=th[s];if(r)return r.id;let o=th[s]=ie.define({id:Ja.length,name:i,props:[Gn({[i]:t})]});return Ja.push(o),o.id}var tO={rtl:q.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"rtl"},bidiIsolate:F.RTL}),ltr:q.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"ltr"},bidiIsolate:F.LTR}),auto:q.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"auto"},bidiIsolate:null})};function ph(n){let e=Object.keys(n).join(""),t=/\w/.test(e);return t&&(e=e.replace(/\w/g,"")),`[${t?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function Td(n){let e=Object.create(null),t=Object.create(null);for(let{label:s}of n){e[s[0]]=!0;for(let r=1;rtypeof s=="string"?{label:s}:s),[t,i]=e.every(s=>/^\w+$/.test(s.label))?[/\w*$/,/\w+$/]:Td(e);return s=>{let r=s.matchBefore(i);return r||s.explicit?{from:r?r.from:s.pos,options:e,validFor:t}:null}}function bh(n,e){return t=>{for(let i=J(t.state).resolveInner(t.pos,-1);i;i=i.parent){if(n.indexOf(i.name)>-1)return null;if(i.type.isTop)break}return e(t)}}var Cd=fe.define();var fO=typeof navigator=="object"&&/Win/.test(navigator.platform);var Qd=C.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"\xB7\xB7\xB7"',opacity:.5,display:"block",textAlign:"center",cursor:"pointer"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box",whiteSpace:"pre-line"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'\u0192'"}},".cm-completionIcon-class":{"&:after":{content:"'\u25CB'"}},".cm-completionIcon-interface":{"&:after":{content:"'\u25CC'"}},".cm-completionIcon-variable":{"&:after":{content:"'\u{1D465}'"}},".cm-completionIcon-constant":{"&:after":{content:"'\u{1D436}'"}},".cm-completionIcon-type":{"&:after":{content:"'\u{1D461}'"}},".cm-completionIcon-enum":{"&:after":{content:"'\u222A'"}},".cm-completionIcon-property":{"&:after":{content:"'\u25A1'"}},".cm-completionIcon-keyword":{"&:after":{content:"'\u{1F511}\uFE0E'"}},".cm-completionIcon-namespace":{"&:after":{content:"'\u25A2'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}}),ao=class{constructor(e,t,i,s){this.field=e,this.line=t,this.from=i,this.to=s}},ho=class n{constructor(e,t,i){this.field=e,this.from=t,this.to=i}map(e){let t=e.mapPos(this.from,-1,Y.TrackDel),i=e.mapPos(this.to,1,Y.TrackDel);return t==null||i==null?null:new n(this.field,t,i)}},fo=class n{constructor(e,t){this.lines=e,this.fieldPositions=t}instantiate(e,t){let i=[],s=[t],r=e.doc.lineAt(t),o=/^\s*/.exec(r.text)[0];for(let a of this.lines){if(i.length){let h=o,f=/^\t*/.exec(a)[0].length;for(let c=0;cnew ho(a.field,s[a.line]+a.from,s[a.line]+a.to));return{text:i,ranges:l}}static parse(e){let t=[],i=[],s=[],r;for(let o of e.split(/\r\n?|\n/)){for(;r=/[#$]\{(?:(\d+)(?::([^{}]*))?|((?:\\[{}]|[^{}])*))\}/.exec(o);){let l=r[1]?+r[1]:null,a=r[2]||r[3]||"",h=-1;l===0&&(l=1e9);let f=a.replace(/\\[{}]/g,c=>c[1]);for(let c=0;c=h&&u.field++}for(let c of s)if(c.line==i.length&&c.from>r.index){let u=r[2]?3+(r[1]||"").length:2;c.from-=u,c.to-=u}s.push(new ao(h,i.length,r.index,r.index+f.length)),o=o.slice(0,r.index)+a+o.slice(r.index+r[0].length)}o=o.replace(/\\([{}])/g,(l,a,h)=>{for(let f of s)f.line==i.length&&f.from>h&&(f.from--,f.to--);return a}),i.push(o)}return new n(i,s)}},Pd=q.widget({widget:new class extends Ye{toDOM(){let n=document.createElement("span");return n.className="cm-snippetFieldPosition",n}ignoreEvent(){return!1}}}),Ad=q.mark({class:"cm-snippetField"}),pi=class n{constructor(e,t){this.ranges=e,this.active=t,this.deco=q.set(e.map(i=>(i.from==i.to?Pd:Ad).range(i.from,i.to)),!0)}map(e){let t=[];for(let i of this.ranges){let s=i.map(e);if(!s)return null;t.push(s)}return new n(t,this.active)}selectionInsideField(e){return e.ranges.every(t=>this.ranges.some(i=>i.field==this.active&&i.from<=t.from&&i.to>=t.to))}},Gi=W.define({map(n,e){return n&&n.map(e)}}),Rd=W.define(),Ui=he.define({create(){return null},update(n,e){for(let t of e.effects){if(t.is(Gi))return t.value;if(t.is(Rd)&&n)return new pi(n.ranges,t.value)}return n&&e.docChanged&&(n=n.map(e.changes)),n&&e.selection&&!n.selectionInsideField(e.selection)&&(n=null),n},provide:n=>C.decorations.from(n,e=>e?e.deco:q.none)});function co(n,e){return b.create(n.filter(t=>t.field==e).map(t=>b.range(t.from,t.to)))}function Md(n){let e=fo.parse(n);return(t,i,s,r)=>{let{text:o,ranges:l}=e.instantiate(t.state,s),{main:a}=t.state.selection,h={changes:{from:s,to:r==a.from?a.to:r,insert:M.of(o)},scrollIntoView:!0,annotations:i?[Cd.of(i),G.userEvent.of("input.complete")]:void 0};if(l.length&&(h.selection=co(l,0)),l.some(f=>f.field>0)){let f=new pi(l,0),c=h.effects=[Gi.of(f)];t.state.field(Ui,!1)===void 0&&c.push(W.appendConfig.of([Ui,Wd,$d,Qd]))}t.dispatch(t.state.update(h))}}function Sh(n){return({state:e,dispatch:t})=>{let i=e.field(Ui,!1);if(!i||n<0&&i.active==0)return!1;let s=i.active+n,r=n>0&&!i.ranges.some(o=>o.field==s+n);return t(e.update({selection:co(i.ranges,s),effects:Gi.of(r?null:new pi(i.ranges,s)),scrollIntoView:!0})),!0}}var Ed=({state:n,dispatch:e})=>n.field(Ui,!1)?(e(n.update({effects:Gi.of(null)})),!0):!1,Dd=Sh(1),Bd=Sh(-1);var qd=[{key:"Tab",run:Dd,shift:Bd},{key:"Escape",run:Ed}],mh=v.define({combine(n){return n.length?n[0]:qd}}),Wd=at.highest(ai.compute([mh],n=>n.facet(mh)));function Xe(n,e){return{...e,apply:Md(n)}}var $d=C.domEventHandlers({mousedown(n,e){let t=e.state.field(Ui,!1),i;if(!t||(i=e.posAtCoords({x:n.clientX,y:n.clientY}))==null)return!1;let s=t.ranges.find(r=>r.from<=i&&r.to>=i);return!s||s.field==t.active?!1:(e.dispatch({selection:co(t.ranges,s.field),effects:Gi.of(t.ranges.some(r=>r.field>s.field)?new pi(t.ranges,s.field):null),scrollIntoView:!0}),!0)}});var ji={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},Lt=W.define({map(n,e){let t=e.mapPos(n,-1,Y.TrackAfter);return t??void 0}}),uo=new class extends Oe{};uo.startSide=1;uo.endSide=-1;var xh=he.define({create(){return B.empty},update(n,e){if(n=n.map(e.changes),e.selection){let t=e.state.doc.lineAt(e.selection.main.head);n=n.update({filter:i=>i>=t.from&&i<=t.to})}for(let t of e.effects)t.is(Lt)&&(n=n.update({add:[uo.range(t.value,t.value+1)]}));return n}});function kh(){return[zd,xh]}var lo="()[]{}<>\xAB\xBB\xBB\xAB\uFF3B\uFF3D\uFF5B\uFF5D";function wh(n){for(let e=0;e{if((Ld?n.composing:n.compositionStarted)||n.state.readOnly)return!1;let s=n.state.selection.main;if(i.length>2||i.length==2&&Gt(lt(i,0))==1||e!=s.from||t!=s.to)return!1;let r=Nd(n.state,i);return r?(n.dispatch(r),!0):!1}),Id=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let i=vh(n,n.selection.main.head).brackets||ji.brackets,s=null,r=n.changeByRange(o=>{if(o.empty){let l=Vd(n.doc,o.head);for(let a of i)if(a==l&&ts(n.doc,o.head)==wh(lt(a,0)))return{changes:{from:o.head-a.length,to:o.head+a.length},range:b.cursor(o.head-a.length)}}return{range:s=o}});return s||e(n.update(r,{scrollIntoView:!0,userEvent:"delete.backward"})),!s},Th=[{key:"Backspace",run:Id}];function Nd(n,e){let t=vh(n,n.selection.main.head),i=t.brackets||ji.brackets;for(let s of i){let r=wh(lt(s,0));if(e==s)return r==s?_d(n,s,i.indexOf(s+s+s)>-1,t):Xd(n,s,r,t.before||ji.before);if(e==r&&Ch(n,n.selection.main.from))return Fd(n,s,r)}return null}function Ch(n,e){let t=!1;return n.field(xh).between(0,n.doc.length,i=>{i==e&&(t=!0)}),t}function ts(n,e){let t=n.sliceString(e,e+2);return t.slice(0,Gt(lt(t,0)))}function Vd(n,e){let t=n.sliceString(e-2,e);return Gt(lt(t,0))==t.length?t:t.slice(1)}function Xd(n,e,t,i){let s=null,r=n.changeByRange(o=>{if(!o.empty)return{changes:[{insert:e,from:o.from},{insert:t,from:o.to}],effects:Lt.of(o.to+e.length),range:b.range(o.anchor+e.length,o.head+e.length)};let l=ts(n.doc,o.head);return!l||/\s/.test(l)||i.indexOf(l)>-1?{changes:{insert:e+t,from:o.head},effects:Lt.of(o.head+e.length),range:b.cursor(o.head+e.length)}:{range:s=o}});return s?null:n.update(r,{scrollIntoView:!0,userEvent:"input.type"})}function Fd(n,e,t){let i=null,s=n.changeByRange(r=>r.empty&&ts(n.doc,r.head)==t?{changes:{from:r.head,to:r.head+t.length,insert:t},range:b.cursor(r.head+t.length)}:i={range:r});return i?null:n.update(s,{scrollIntoView:!0,userEvent:"input.type"})}function _d(n,e,t,i){let s=i.stringPrefixes||ji.stringPrefixes,r=null,o=n.changeByRange(l=>{if(!l.empty)return{changes:[{insert:e,from:l.from},{insert:e,from:l.to}],effects:Lt.of(l.to+e.length),range:b.range(l.anchor+e.length,l.head+e.length)};let a=l.head,h=ts(n.doc,a),f;if(h==e){if(gh(n,a))return{changes:{insert:e+e,from:a},effects:Lt.of(a+e.length),range:b.cursor(a+e.length)};if(Ch(n,a)){let u=t&&n.sliceDoc(a,a+e.length*3)==e+e+e?e+e+e:e;return{changes:{from:a,to:a+u.length,insert:u},range:b.cursor(a+u.length)}}}else{if(t&&n.sliceDoc(a-2*e.length,a)==e+e&&(f=Oh(n,a-2*e.length,s))>-1&&gh(n,f))return{changes:{insert:e+e+e+e,from:a},effects:Lt.of(a+e.length),range:b.cursor(a+e.length)};if(n.charCategorizer(a)(h)!=re.Word&&Oh(n,a,s)>-1&&!Hd(n,a,e,s))return{changes:{insert:e+e,from:a},effects:Lt.of(a+e.length),range:b.cursor(a+e.length)}}return{range:r=l}});return r?null:n.update(o,{scrollIntoView:!0,userEvent:"input.type"})}function gh(n,e){let t=J(n).resolveInner(e+1);return t.parent&&t.from==e}function Hd(n,e,t,i){let s=J(n).resolveInner(e,-1),r=i.reduce((o,l)=>Math.max(o,l.length),0);for(let o=0;o<5;o++){let l=n.sliceDoc(s.from,Math.min(s.to,s.from+t.length+r)),a=l.indexOf(t);if(!a||a>-1&&i.indexOf(l.slice(0,a))>-1){let f=s.firstChild;for(;f&&f.from==s.from&&f.to-f.from>t.length+a;){if(n.sliceDoc(f.to-t.length,f.to)==t)return!1;f=f.firstChild}return!0}let h=s.to==e&&s.parent;if(!h)break;s=h}return!1}function Oh(n,e,t){let i=n.charCategorizer(e);if(i(n.sliceDoc(e-1,e))!=re.Word)return e;for(let s of t){let r=e-s.length;if(n.sliceDoc(r,e)==s&&i(n.sliceDoc(r-1,r))!=re.Word)return r}return-1}var Ud=n=>{let{state:e}=n,t=e.doc.lineAt(e.selection.main.from),i=So(n.state,t.from);return i.line?jd(n):i.block?Zd(n):!1};function bo(n,e){return({state:t,dispatch:i})=>{if(t.readOnly)return!1;let s=n(e,t);return s?(i(t.update(s)),!0):!1}}var jd=bo(Jd,0);var Gd=bo(qh,0);var Zd=bo((n,e)=>qh(n,e,Kd(e)),0);function So(n,e){let t=n.languageDataAt("commentTokens",e,1);return t.length?t[0]:{}}var Zi=50;function Yd(n,{open:e,close:t},i,s){let r=n.sliceDoc(i-Zi,i),o=n.sliceDoc(s,s+Zi),l=/\s*$/.exec(r)[0].length,a=/^\s*/.exec(o)[0].length,h=r.length-l;if(r.slice(h-e.length,h)==e&&o.slice(a,a+t.length)==t)return{open:{pos:i-l,margin:l&&1},close:{pos:s+a,margin:a&&1}};let f,c;s-i<=2*Zi?f=c=n.sliceDoc(i,s):(f=n.sliceDoc(i,i+Zi),c=n.sliceDoc(s-Zi,s));let u=/^\s*/.exec(f)[0].length,d=/\s*$/.exec(c)[0].length,p=c.length-d-t.length;return f.slice(u,u+e.length)==e&&c.slice(p,p+t.length)==t?{open:{pos:i+u+e.length,margin:/\s/.test(f.charAt(u+e.length))?1:0},close:{pos:s-d-t.length,margin:/\s/.test(c.charAt(p-1))?1:0}}:null}function Kd(n){let e=[];for(let t of n.selection.ranges){let i=n.doc.lineAt(t.from),s=t.to<=i.to?i:n.doc.lineAt(t.to);s.from>i.from&&s.from==t.to&&(s=t.to==i.to+1?i:n.doc.lineAt(t.to-1));let r=e.length-1;r>=0&&e[r].to>i.from?e[r].to=s.to:e.push({from:i.from+/^\s*/.exec(i.text)[0].length,to:s.to})}return e}function qh(n,e,t=e.selection.ranges){let i=t.map(r=>So(e,r.from).block);if(!i.every(r=>r))return null;let s=t.map((r,o)=>Yd(e,i[o],r.from,r.to));if(n!=2&&!s.every(r=>r))return{changes:e.changes(t.map((r,o)=>s[o]?[]:[{from:r.from,insert:i[o].open+" "},{from:r.to,insert:" "+i[o].close}]))};if(n!=1&&s.some(r=>r)){let r=[];for(let o=0,l;os&&(r==o||o>c.from)){s=c.from;let u=/^\s*/.exec(c.text)[0].length,d=u==c.length,p=c.text.slice(u,u+h.length)==h?u:-1;ur.comment<0&&(!r.empty||r.single))){let r=[];for(let{line:l,token:a,indent:h,empty:f,single:c}of i)(c||!f)&&r.push({from:l.from+h,insert:a+" "});let o=e.changes(r);return{changes:o,selection:e.selection.map(o,1)}}else if(n!=1&&i.some(r=>r.comment>=0)){let r=[];for(let{line:o,comment:l,token:a}of i)if(l>=0){let h=o.from+l,f=h+a.length;o.text[f-o.from]==" "&&f++,r.push({from:h,to:f})}return{changes:r}}return null}var mo=fe.define(),ep=fe.define(),tp=v.define(),Wh=v.define({combine(n){return Tt(n,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(i,s)=>e(i,s)||t(i,s)})}}),$h=he.define({create(){return zt.empty},update(n,e){let t=e.state.facet(Wh),i=e.annotation(mo);if(i){let a=Ee.fromTransaction(e,i.selection),h=i.side,f=h==0?n.undone:n.done;return a?f=ns(f,f.length,t.minDepth,a):f=Nh(f,e.startState.selection),new zt(h==0?i.rest:f,h==0?f:i.rest)}let s=e.annotation(ep);if((s=="full"||s=="before")&&(n=n.isolate()),e.annotation(G.addToHistory)===!1)return e.changes.empty?n:n.addMapping(e.changes.desc);let r=Ee.fromTransaction(e),o=e.annotation(G.time),l=e.annotation(G.userEvent);return r?n=n.addChanges(r,o,l,t,e):e.selection&&(n=n.addSelection(e.startState.selection,o,l,t.newGroupDelay)),(s=="full"||s=="after")&&(n=n.isolate()),n},toJSON(n){return{done:n.done.map(e=>e.toJSON()),undone:n.undone.map(e=>e.toJSON())}},fromJSON(n){return new zt(n.done.map(Ee.fromJSON),n.undone.map(Ee.fromJSON))}});function Lh(n={}){return[$h,Wh.of(n),C.domEventHandlers({beforeinput(e,t){let i=e.inputType=="historyUndo"?zh:e.inputType=="historyRedo"?go:null;return i?(e.preventDefault(),i(t)):!1}})]}function ss(n,e){return function({state:t,dispatch:i}){if(!e&&t.readOnly)return!1;let s=t.field($h,!1);if(!s)return!1;let r=s.pop(n,t,e);return r?(i(r),!0):!1}}var zh=ss(0,!1),go=ss(1,!1),ip=ss(0,!0),np=ss(1,!0);var Ee=class n{constructor(e,t,i,s,r){this.changes=e,this.effects=t,this.mapped=i,this.startSelection=s,this.selectionsAfter=r}setSelAfter(e){return new n(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,i;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(t=this.mapped)===null||t===void 0?void 0:t.toJSON(),startSelection:(i=this.startSelection)===null||i===void 0?void 0:i.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(e){return new n(e.changes&&oe.fromJSON(e.changes),[],e.mapped&&Ue.fromJSON(e.mapped),e.startSelection&&b.fromJSON(e.startSelection),e.selectionsAfter.map(b.fromJSON))}static fromTransaction(e,t){let i=ve;for(let s of e.startState.facet(tp)){let r=s(e);r.length&&(i=i.concat(r))}return!i.length&&e.changes.empty?null:new n(e.changes.invert(e.startState.doc),i,void 0,t||e.startState.selection,ve)}static selection(e){return new n(void 0,ve,void 0,void 0,e)}};function ns(n,e,t,i){let s=e+1>t+20?e-t-1:0,r=n.slice(s,e);return r.push(i),r}function sp(n,e){let t=[],i=!1;return n.iterChangedRanges((s,r)=>t.push(s,r)),e.iterChangedRanges((s,r,o,l)=>{for(let a=0;a=h&&o<=f&&(i=!0)}}),i}function rp(n,e){return n.ranges.length==e.ranges.length&&n.ranges.filter((t,i)=>t.empty!=e.ranges[i].empty).length===0}function Ih(n,e){return n.length?e.length?n.concat(e):n:e}var ve=[],op=200;function Nh(n,e){if(n.length){let t=n[n.length-1],i=t.selectionsAfter.slice(Math.max(0,t.selectionsAfter.length-op));return i.length&&i[i.length-1].eq(e)?n:(i.push(e),ns(n,n.length-1,1e9,t.setSelAfter(i)))}else return[Ee.selection([e])]}function lp(n){let e=n[n.length-1],t=n.slice();return t[n.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),t}function po(n,e){if(!n.length)return n;let t=n.length,i=ve;for(;t;){let s=ap(n[t-1],e,i);if(s.changes&&!s.changes.empty||s.effects.length){let r=n.slice(0,t);return r[t-1]=s,r}else e=s.mapped,t--,i=s.selectionsAfter}return i.length?[Ee.selection(i)]:ve}function ap(n,e,t){let i=Ih(n.selectionsAfter.length?n.selectionsAfter.map(l=>l.map(e)):ve,t);if(!n.changes)return Ee.selection(i);let s=n.changes.map(e),r=e.mapDesc(n.changes,!0),o=n.mapped?n.mapped.composeDesc(r):r;return new Ee(s,W.mapEffects(n.effects,e),o,n.startSelection.map(r),i)}var hp=/^(input\.type|delete)($|\.)/,zt=class n{constructor(e,t,i=0,s=void 0){this.done=e,this.undone=t,this.prevTime=i,this.prevUserEvent=s}isolate(){return this.prevTime?new n(this.done,this.undone):this}addChanges(e,t,i,s,r){let o=this.done,l=o[o.length-1];return l&&l.changes&&!l.changes.empty&&e.changes&&(!i||hp.test(i))&&(!l.selectionsAfter.length&&t-this.prevTime0&&t-this.prevTimet.empty?n.moveByChar(t,e):rs(t,e))}function ne(n){return n.textDirectionAt(n.state.selection.main.head)==F.LTR}var Fh=n=>Xh(n,!ne(n)),_h=n=>Xh(n,ne(n));function Hh(n,e){return Be(n,t=>t.empty?n.moveByGroup(t,e):rs(t,e))}var fp=n=>Hh(n,!ne(n)),cp=n=>Hh(n,ne(n));var yO=typeof Intl<"u"&&Intl.Segmenter?new Intl.Segmenter(void 0,{granularity:"word"}):null;function up(n,e,t){if(e.type.prop(t))return!0;let i=e.to-e.from;return i&&(i>2||/[^\s,.;:]/.test(n.sliceDoc(e.from,e.to)))||e.firstChild}function os(n,e,t){let i=J(n).resolveInner(e.head),s=t?R.closedBy:R.openedBy;for(let a=e.head;;){let h=t?i.childAfter(a):i.childBefore(a);if(!h)break;up(n,h,s)?i=h:a=t?h.to:h.from}let r=i.type.prop(s),o,l;return r&&(o=t?Me(n,i.from,1):Me(n,i.to,-1))&&o.matched?l=t?o.end.to:o.end.from:l=t?i.to:i.from,b.cursor(l,t?-1:1)}var dp=n=>Be(n,e=>os(n.state,e,!ne(n))),pp=n=>Be(n,e=>os(n.state,e,ne(n)));function Uh(n,e){return Be(n,t=>{if(!t.empty)return rs(t,e);let i=n.moveVertically(t,e);return i.head!=t.head?i:n.moveToLineBoundary(t,e)})}var jh=n=>Uh(n,!1),Gh=n=>Uh(n,!0);function Zh(n){let e=n.scrollDOM.clientHeighto.empty?n.moveVertically(o,e,t.height):rs(o,e));if(s.eq(i.selection))return!1;let r;if(t.selfScroll){let o=n.coordsAtPos(i.selection.main.head),l=n.scrollDOM.getBoundingClientRect(),a=l.top+t.marginTop,h=l.bottom-t.marginBottom;o&&o.top>a&&o.bottomYh(n,!1),Oo=n=>Yh(n,!0);function Ot(n,e,t){let i=n.lineBlockAt(e.head),s=n.moveToLineBoundary(e,t);if(s.head==e.head&&s.head!=(t?i.to:i.from)&&(s=n.moveToLineBoundary(e,t,!1)),!t&&s.head==i.from&&i.length){let r=/^\s*/.exec(n.state.sliceDoc(i.from,Math.min(i.from+100,i.to)))[0].length;r&&e.head!=i.from+r&&(s=b.cursor(i.from+r))}return s}var mp=n=>Be(n,e=>Ot(n,e,!0)),gp=n=>Be(n,e=>Ot(n,e,!1)),Op=n=>Be(n,e=>Ot(n,e,!ne(n))),yp=n=>Be(n,e=>Ot(n,e,ne(n))),bp=n=>Be(n,e=>n.moveToLineBoundary(e,!1,!1)),Sp=n=>Be(n,e=>n.moveToLineBoundary(e,!0,!1));function xp(n,e,t){let i=!1,s=mi(n.selection,r=>{let o=Me(n,r.head,-1)||Me(n,r.head,1)||r.head>0&&Me(n,r.head-1,1)||r.headxp(n,e,!1);function Te(n,e,t){let i=mi(n.state.selection,s=>{s.undirectional&&s.head>=s.anchor!=e&&(s=b.range(s.head,s.anchor));let r=t(s);return b.range(s.anchor,r.head,r.goalColumn,r.bidiLevel||void 0,r.assoc)});return i.eq(n.state.selection)?!1:(n.dispatch(De(n.state,i)),!0)}function Kh(n,e){return Te(n,e,t=>n.moveByChar(t,e))}var Jh=n=>Kh(n,!ne(n)),ef=n=>Kh(n,ne(n));function tf(n,e){return Te(n,e,t=>n.moveByGroup(t,e))}var wp=n=>tf(n,!ne(n)),vp=n=>tf(n,ne(n));var Tp=n=>{let e=!ne(n);return Te(n,e,t=>os(n.state,t,e))},Cp=n=>{let e=ne(n);return Te(n,e,t=>os(n.state,t,e))};function nf(n,e){return Te(n,e,t=>n.moveVertically(t,e))}var sf=n=>nf(n,!1),rf=n=>nf(n,!0);function of(n,e){return Te(n,e,t=>n.moveVertically(t,e,Zh(n).height))}var Ph=n=>of(n,!1),Ah=n=>of(n,!0),Qp=n=>Te(n,!0,e=>Ot(n,e,!0)),Pp=n=>Te(n,!1,e=>Ot(n,e,!1)),Ap=n=>{let e=!ne(n);return Te(n,e,t=>Ot(n,t,e))},Rp=n=>{let e=ne(n);return Te(n,e,t=>Ot(n,t,e))},Mp=n=>Te(n,!1,e=>b.cursor(n.lineBlockAt(e.head).from)),Ep=n=>Te(n,!0,e=>b.cursor(n.lineBlockAt(e.head).to)),Rh=({state:n,dispatch:e})=>(e(De(n,{anchor:0})),!0),Mh=({state:n,dispatch:e})=>(e(De(n,{anchor:n.doc.length})),!0),Eh=({state:n,dispatch:e})=>(e(De(n,{anchor:n.selection.main.anchor,head:0})),!0),Dh=({state:n,dispatch:e})=>(e(De(n,{anchor:n.selection.main.anchor,head:n.doc.length})),!0),Dp=({state:n,dispatch:e})=>(e(n.update({selection:{anchor:0,head:n.doc.length},userEvent:"select"})),!0),Bp=({state:n,dispatch:e})=>{let t=ls(n).map(({from:i,to:s})=>b.undirectionalRange(i,Math.min(s+1,n.doc.length)));return e(n.update({selection:b.create(t),userEvent:"select"})),!0},qp=({state:n,dispatch:e})=>{let t=mi(n.selection,i=>{let s=J(n),r=s.resolveStack(i.from,1);if(i.empty){let o=s.resolveStack(i.from,-1);o.node.from>=r.node.from&&o.node.to<=r.node.to&&(r=o)}for(let o=r;o;o=o.next){let{node:l}=o;if((l.from=i.to||l.to>i.to&&l.from<=i.from)&&o.next)return b.undirectionalRange(l.from,l.to)}return i});return t.eq(n.selection)?!1:(e(De(n,t)),!0)};function lf(n,e){let{state:t}=n,i=t.selection,s=t.selection.ranges.slice();for(let r of t.selection.ranges){let o=t.doc.lineAt(r.head);if(e?o.to0)for(let l=r;;){let a=n.moveVertically(l,e);if(a.heado.to){s.some(h=>h.head==a.head)||s.push(a);break}else{if(a.head==l.head)break;l=a}}}return s.length==i.ranges.length?!1:(n.dispatch(De(t,b.create(s,s.length-1))),!0)}var Wp=n=>lf(n,!1),$p=n=>lf(n,!0),Lp=({state:n,dispatch:e})=>{let t=n.selection,i=null;return t.ranges.length>1?i=b.create([t.main]):t.main.empty||(i=b.create([b.cursor(t.main.head)])),i?(e(De(n,i)),!0):!1};function Yi(n,e){if(n.state.readOnly)return!1;let t="delete.selection",{state:i}=n,s=i.changeByRange(r=>{let{from:o,to:l}=r;if(o==l){let a=e(r);ao&&(t="delete.forward",a=is(n,a,!0)),o=Math.min(o,a),l=Math.max(l,a)}else o=is(n,o,!1),l=is(n,l,!0);return o==l?{range:r}:{changes:{from:o,to:l},range:b.cursor(o,os(n)))i.between(e,e,(s,r)=>{se&&(e=t?r:s)});return e}var af=(n,e,t)=>Yi(n,i=>{let s=i.from,{state:r}=n,o=r.doc.lineAt(s),l,a;if(t&&!e&&s>o.from&&saf(n,!1,!0);var hf=n=>af(n,!0,!1),ff=(n,e)=>Yi(n,t=>{let i=t.head,{state:s}=n,r=s.doc.lineAt(i),o=s.charCategorizer(i);for(let l=null;;){if(i==(e?r.to:r.from)){i==t.head&&r.number!=(e?s.doc.lines:1)&&(i+=e?1:-1);break}let a=K(r.text,i-r.from,e)+r.from,h=r.text.slice(Math.min(i,a)-r.from,Math.max(i,a)-r.from),f=o(h);if(l!=null&&f!=l)break;(h!=" "||i!=t.head)&&(l=f),i=a}return i}),cf=n=>ff(n,!1),zp=n=>ff(n,!0);var Ip=n=>Yi(n,e=>{let t=n.lineBlockAt(e.head).to;return e.headYi(n,e=>{let t=n.moveToLineBoundary(e,!1).head;return e.head>t?t:Math.max(0,e.head-1)}),Vp=n=>Yi(n,e=>{let t=n.moveToLineBoundary(e,!0).head;return e.head{if(n.readOnly)return!1;let t=n.changeByRange(i=>({changes:{from:i.from,to:i.to,insert:M.of(["",""])},range:b.cursor(i.from)}));return e(n.update(t,{scrollIntoView:!0,userEvent:"input"})),!0},Fp=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(i=>{if(!i.empty||i.from==0||i.from==n.doc.length)return{range:i};let s=i.from,r=n.doc.lineAt(s),o=s==r.from?s-1:K(r.text,s-r.from,!1)+r.from,l=s==r.to?s+1:K(r.text,s-r.from,!0)+r.from;return{changes:{from:o,to:l,insert:n.doc.slice(s,l).append(n.doc.slice(o,s))},range:b.cursor(l)}});return t.changes.empty?!1:(e(n.update(t,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function ls(n){let e=[],t=-1;for(let i of n.selection.ranges){let s=n.doc.lineAt(i.from),r=n.doc.lineAt(i.to);if(!i.empty&&i.to==r.from&&(r=n.doc.lineAt(i.to-1)),t>=s.number){let o=e[e.length-1];o.to=r.to,o.ranges.push(i)}else e.push({from:s.from,to:r.to,ranges:[i]});t=r.number+1}return e}function uf(n,e,t){if(n.readOnly)return!1;let i=[],s=[];for(let r of ls(n)){if(t?r.to==n.doc.length:r.from==0)continue;let o=n.doc.lineAt(t?r.to+1:r.from-1),l=o.length+1;if(t){i.push({from:r.to,to:o.to},{from:r.from,insert:o.text+n.lineBreak});for(let a of r.ranges)s.push(b.range(Math.min(n.doc.length,a.anchor+l),Math.min(n.doc.length,a.head+l)))}else{i.push({from:o.from,to:r.from},{from:r.to,insert:n.lineBreak+o.text});for(let a of r.ranges)s.push(b.range(a.anchor-l,a.head-l))}}return i.length?(e(n.update({changes:i,scrollIntoView:!0,selection:b.create(s,n.selection.mainIndex),userEvent:"move.line"})),!0):!1}var _p=({state:n,dispatch:e})=>uf(n,e,!1),Hp=({state:n,dispatch:e})=>uf(n,e,!0);function df(n,e,t){if(n.readOnly)return!1;let i=[];for(let r of ls(n))t?i.push({from:r.from,insert:n.doc.slice(r.from,r.to)+n.lineBreak}):i.push({from:r.to,insert:n.lineBreak+n.doc.slice(r.from,r.to)});let s=n.changes(i);return e(n.update({changes:s,selection:n.selection.map(s,t?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}var Up=({state:n,dispatch:e})=>df(n,e,!1),jp=({state:n,dispatch:e})=>df(n,e,!0),Gp=n=>{if(n.state.readOnly)return!1;let{state:e}=n,t=e.changes(ls(e).map(({from:s,to:r})=>(s>0?s--:r{let r;if(n.lineWrapping){let o=n.lineBlockAt(s.head),l=n.coordsAtPos(s.head,s.assoc||1);l&&(r=o.bottom+n.documentTop-l.bottom+n.defaultLineHeight/2)}return n.moveVertically(s,!0,r)}).map(t);return n.dispatch({changes:t,selection:i,scrollIntoView:!0,userEvent:"delete.line"}),!0};function Zp(n,e){if(/\(\)|\[\]|\{\}/.test(n.sliceDoc(e-1,e+1)))return{from:e,to:e};let t=J(n).resolveInner(e),i=t.childBefore(e),s=t.childAfter(e),r;return i&&s&&i.to<=e&&s.from>=e&&(r=i.type.prop(R.closedBy))&&r.indexOf(s.name)>-1&&n.doc.lineAt(i.to).from==n.doc.lineAt(s.from).from&&!/\S/.test(n.sliceDoc(i.to,s.from))?{from:i.to,to:s.from}:null}var Bh=pf(!1),Yp=pf(!0);function pf(n){return({state:e,dispatch:t})=>{if(e.readOnly)return!1;let i=e.changeByRange(s=>{let{from:r,to:o}=s,l=e.doc.lineAt(r),a=!n&&r==o&&Zp(e,r);n&&(r=o=(o<=l.to?l:e.doc.lineAt(o)).to);let h=new $t(e,{simulateBreak:r,simulateDoubleBreak:!!a}),f=Kn(h,r);for(f==null&&(f=Ct(/^\s*/.exec(e.doc.lineAt(r).text)[0],e.tabSize));ol.from&&r{let s=[];for(let o=i.from;o<=i.to;){let l=n.doc.lineAt(o);l.number>t&&(i.empty||i.to>l.from)&&(e(l,s,i),t=l.number),o=l.to+1}let r=n.changes(s);return{changes:s,range:b.range(r.mapPos(i.anchor,1),r.mapPos(i.head,1))}})}var Kp=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=Object.create(null),i=new $t(n,{overrideIndentation:r=>{let o=t[r];return o??-1}}),s=xo(n,(r,o,l)=>{let a=Kn(i,r.from);if(a==null)return;/\S/.test(r.text)||(a=0);let h=/^\s*/.exec(r.text)[0],f=di(n,a);(h!=f||l.fromn.readOnly?!1:(e(n.update(xo(n,(t,i)=>{i.push({from:t.from,insert:n.facet(gt)})}),{userEvent:"input.indent"})),!0),gf=({state:n,dispatch:e})=>n.readOnly?!1:(e(n.update(xo(n,(t,i)=>{let s=/^\s*/.exec(t.text)[0];if(!s)return;let r=Ct(s,n.tabSize),o=0,l=di(n,Math.max(0,r-Hi(n)));for(;o(n.setTabFocusMode(),!0);var em=[{key:"Ctrl-b",run:Fh,shift:Jh,preventDefault:!0},{key:"Ctrl-f",run:_h,shift:ef},{key:"Ctrl-p",run:jh,shift:sf},{key:"Ctrl-n",run:Gh,shift:rf},{key:"Ctrl-a",run:bp,shift:Mp},{key:"Ctrl-e",run:Sp,shift:Ep},{key:"Ctrl-d",run:hf},{key:"Ctrl-h",run:yo},{key:"Ctrl-k",run:Ip},{key:"Ctrl-Alt-h",run:cf},{key:"Ctrl-o",run:Xp},{key:"Ctrl-t",run:Fp},{key:"Ctrl-v",run:Oo}],tm=[{key:"ArrowLeft",run:Fh,shift:Jh,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:fp,shift:wp,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:Op,shift:Ap,preventDefault:!0},{key:"ArrowRight",run:_h,shift:ef,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:cp,shift:vp,preventDefault:!0},{mac:"Cmd-ArrowRight",run:yp,shift:Rp,preventDefault:!0},{key:"ArrowUp",run:jh,shift:sf,preventDefault:!0},{mac:"Cmd-ArrowUp",run:Rh,shift:Eh},{mac:"Ctrl-ArrowUp",run:Qh,shift:Ph},{key:"ArrowDown",run:Gh,shift:rf,preventDefault:!0},{mac:"Cmd-ArrowDown",run:Mh,shift:Dh},{mac:"Ctrl-ArrowDown",run:Oo,shift:Ah},{key:"PageUp",run:Qh,shift:Ph},{key:"PageDown",run:Oo,shift:Ah},{key:"Home",run:gp,shift:Pp,preventDefault:!0},{key:"Mod-Home",run:Rh,shift:Eh},{key:"End",run:mp,shift:Qp,preventDefault:!0},{key:"Mod-End",run:Mh,shift:Dh},{key:"Enter",run:Bh,shift:Bh},{key:"Mod-a",run:Dp},{key:"Backspace",run:yo,shift:yo,preventDefault:!0},{key:"Delete",run:hf,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:cf,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:zp,preventDefault:!0},{mac:"Mod-Backspace",run:Np,preventDefault:!0},{mac:"Mod-Delete",run:Vp,preventDefault:!0}].concat(em.map(n=>({mac:n.key,run:n.run,shift:n.shift}))),Of=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:dp,shift:Tp},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:pp,shift:Cp},{key:"Alt-ArrowUp",run:_p},{key:"Shift-Alt-ArrowUp",run:Up},{key:"Alt-ArrowDown",run:Hp},{key:"Shift-Alt-ArrowDown",run:jp},{key:"Mod-Alt-ArrowUp",run:Wp},{key:"Mod-Alt-ArrowDown",run:$p},{key:"Escape",run:Lp},{key:"Mod-Enter",run:Yp},{key:"Alt-l",mac:"Ctrl-l",run:Bp},{key:"Mod-i",run:qp,preventDefault:!0},{key:"Mod-[",run:gf},{key:"Mod-]",run:mf},{key:"Mod-Alt-\\",run:Kp},{key:"Shift-Mod-k",run:Gp},{key:"Shift-Mod-\\",run:kp},{key:"Mod-/",run:Ud},{key:"Alt-A",mac:"Ctrl-A",run:Gd},{key:"Ctrl-m",mac:"Shift-Alt-m",run:Jp}].concat(tm),yf={key:"Tab",run:mf,shift:gf};var vo=class n{constructor(e,t,i,s,r,o,l,a,h,f=0,c){this.p=e,this.stack=t,this.state=i,this.reducePos=s,this.pos=r,this.score=o,this.buffer=l,this.bufferBase=a,this.curContext=h,this.lookAhead=f,this.parent=c}toString(){return`[${this.stack.filter((e,t)=>t%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,i=0){let s=e.parser.context;return new n(e,[],t,i,i,0,[],0,s?new as(s,s.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){var t;let i=e>>19,s=e&65535,{parser:r}=this.p,o=this.reducePos=2e3&&!(!((t=this.p.parser.nodeSet.types[s])===null||t===void 0)&&t.isAnonymous)&&(h==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=f):this.p.lastBigReductionSizea;)this.stack.pop();this.reduceContext(s,h)}storeNode(e,t,i,s=4,r=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]0&&this.buffer[o-4]==0&&this.buffer[o-1]>-1){if(t==i)return;if(this.buffer[o-2]>=t){this.buffer[o-2]=i;return}}}if(!r||this.pos==i)this.buffer.push(e,t,i,s);else{let o=this.buffer.length;if(o>0&&(this.buffer[o-4]!=0||this.buffer[o-1]<0)){let l=!1;for(let a=o;a>0&&this.buffer[a-2]>i;a-=4)if(this.buffer[a-1]>=0){l=!0;break}if(l)for(;o>0&&this.buffer[o-2]>i;)this.buffer[o]=this.buffer[o-4],this.buffer[o+1]=this.buffer[o-3],this.buffer[o+2]=this.buffer[o-2],this.buffer[o+3]=this.buffer[o-1],o-=4,s>4&&(s-=4)}this.buffer[o]=e,this.buffer[o+1]=t,this.buffer[o+2]=i,this.buffer[o+3]=s}}shift(e,t,i,s){if(e&131072)this.pushState(e&65535,this.pos);else if((e&262144)==0){let r=e,{parser:o}=this.p;this.pos=s;let l=o.stateFlag(r,1);!l&&(s>i||t<=o.maxNode)&&(this.reducePos=s),this.pushState(r,l?i:Math.min(i,this.reducePos)),this.shiftContext(t,i),t<=o.maxNode&&this.buffer.push(t,i,s,4)}else this.pos=s,this.shiftContext(t,i),t<=this.p.parser.maxNode&&this.buffer.push(t,i,s,4)}apply(e,t,i,s){e&65536?this.reduce(e):this.shift(e,t,i,s)}useNode(e,t,i){let s=this.p.reused.length-1;(s<0||this.p.reused[s]!=e)&&(this.p.reused.push(e),s++);let r=this.reducePos=this.pos=i+e.length;this.pushState(t,i),this.buffer.push(s,i,r,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(t&&e.buffer[t-4]==0&&(t-=4);t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let i=e.buffer.slice(t),s=e.bufferBase+t;for(;e&&s==e.bufferBase;)e=e.parent;return new n(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,i,s,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let i=e<=this.p.parser.maxNode;i&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,i?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new To(this);;){let i=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(i==0)return!1;if((i&65536)==0)return!0;t.reduce(i)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let s=[];for(let r=0,o;ra&1&&l==o)||s.push(t[r],o)}t=s}let i=[];for(let s=0;s>19,s=t&65535,r=this.stack.length-i*3;if(r<0||e.getGoto(this.stack[r],s,!1)<0){let o=this.findForcedReduction();if(o==null)return!1;t=o}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(t),!0}findForcedReduction(){let{parser:e}=this.p,t=[],i=(s,r)=>{if(!t.includes(s))return t.push(s),e.allActions(s,o=>{if(!(o&393216))if(o&65536){let l=(o>>19)-r;if(l>1){let a=o&65535,h=this.stack.length-l*3;if(h>=0&&e.getGoto(this.stack[h],a,!1)>=0)return l<<19|65536|a}}else{let l=i(o,r+1);if(l!=null)return l}})};return i(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.storeNode(0,this.pos,this.pos,4,!0),this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;t0&&this.emitLookAhead()}},as=class{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}},To=class{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,i=e>>19;i==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(i-1)*3;let s=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=s}},Co=class n{constructor(e,t,i){this.stack=e,this.pos=t,this.index=i,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new n(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new n(this.stack,this.pos,this.index)}};function Ki(n,e=Uint16Array){if(typeof n!="string")return n;let t=null;for(let i=0,s=0;i=92&&o--,o>=34&&o--;let a=o-32;if(a>=46&&(a-=46,l=!0),r+=a,l)break;r*=46}t?t[s++]=r:t=new e(r)}return t}var gi=class{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}},bf=new gi,Qo=class{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=bf,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let i=this.range,s=this.rangeIndex,r=this.pos+e;for(;ri.to:r>=i.to;){if(s==this.ranges.length-1)return null;let o=this.ranges[++s];r+=o.from-i.to,i=o}return r}clipPos(e){if(e>=this.range.from&&ee)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,i,s;if(t>=0&&t=this.chunk2Pos&&il.to&&(this.chunk2=this.chunk2.slice(0,l.to-i)),s=this.chunk2.charCodeAt(0)}}return i>=this.token.lookAhead&&(this.token.lookAhead=i+1),s}acceptToken(e,t=0){let i=t?this.resolveOffset(t,-1):this.pos;if(i==null||i=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=bf,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let i="";for(let s of this.ranges){if(s.from>=t)break;s.to>e&&(i+=this.input.read(Math.max(s.from,e),Math.min(s.to,t)))}return i}},yt=class{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:i}=t.p;vf(this.data,e,t,this.id,i.data,i.tokenPrecTable)}};yt.prototype.contextual=yt.prototype.fallback=yt.prototype.extend=!1;var Po=class{constructor(e,t,i){this.precTable=t,this.elseToken=i,this.data=typeof e=="string"?Ki(e):e}token(e,t){let i=e.pos,s=0;for(;;){let r=e.next<0,o=e.resolveOffset(1,1);if(vf(this.data,e,t,0,this.data,this.precTable),e.token.value>-1)break;if(this.elseToken==null)return;if(r||s++,o==null)break;e.reset(o,e.token)}s&&(e.reset(i,e.token),e.acceptToken(this.elseToken,s))}};Po.prototype.contextual=yt.prototype.fallback=yt.prototype.extend=!1;var It=class{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}};function vf(n,e,t,i,s,r){let o=0,l=1<0){let p=n[d];if(a.allows(p)&&(e.token.value==-1||e.token.value==p||nm(p,e.token.value,s,r))){e.acceptToken(p);break}}let f=e.next,c=0,u=n[o+2];if(e.next<0&&u>c&&n[h+u*3-3]==65535){o=n[h+u*3-1];continue e}for(;c>1,p=h+d+(d<<1),m=n[p],O=n[p+1]||65536;if(f=O)c=d+1;else{o=n[p+2],e.advance();continue e}}break}}function Sf(n,e,t){for(let i=e,s;(s=n[i])!=65535;i++)if(s==t)return i-e;return-1}function nm(n,e,t,i){let s=Sf(t,i,e);return s<0||Sf(t,i,n)e)&&!i.type.isError)return t<0?Math.max(0,Math.min(i.to-1,e-25)):Math.min(n.length,Math.max(i.from+1,e+25));if(t<0?i.prevSibling():i.nextSibling())break;if(!i.parent())return t<0?0:n.length}}var Ao=class{constructor(e,t){this.fragments=e,this.minRepeat=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.lastRepeat=null,this.lastRepeatPos=-1,this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?xf(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?xf(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=o,null;if(r instanceof j){let l=o>this.lastRepeatPos&&r.type.id>=this.minRepeat;if(o==e||l){let a=o+r.length,h;if(o>=this.safeFrom&&a<=this.safeTo&&(!(h=r.prop(R.lookAhead))||a+h=Math.max(this.safeFrom,e)&&(this.trees.push(r),this.start.push(o),this.index.push(0))}else this.index[t]++,this.nextStart=o+r.length}}},Ro=class{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(i=>new gi)}getActions(e){let t=0,i=null,{parser:s}=e.p,{tokenizers:r}=s,o=s.stateSlot(e.state,3),l=e.curContext?e.curContext.hash:0,a=0;for(let h=0;hc.end+25&&(a=Math.max(c.lookAhead,a)),c.value!=0)){let u=t;if(c.extended>-1&&(t=this.addActions(e,c.extended,c.end,t)),t=this.addActions(e,c.value,c.end,t),!f.extend&&(i=c,t>u))break}}for(;this.actions.length>t;)this.actions.pop();return a&&e.setLookAhead(a),!i&&e.pos==this.stream.end&&(i=new gi,i.value=e.p.parser.eofTerm,i.start=i.end=e.pos,t=this.addActions(e,i.value,i.end,t)),this.mainToken=i,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new gi,{pos:i,p:s}=e;return t.start=i,t.end=Math.min(i+1,s.stream.end),t.value=i==s.stream.end?s.parser.eofTerm:0,t}updateCachedToken(e,t,i){let s=this.stream.clipPos(i.pos);if(t.token(this.stream.reset(s,e),i),e.value>-1){let{parser:r}=i.p;for(let o=0;o=0&&i.p.parser.dialect.allows(l>>1)){(l&1)==0?e.value=l>>1:e.extended=l>>1;break}}}else e.value=0,e.end=this.stream.clipPos(s+1)}putAction(e,t,i,s){for(let r=0;re.bufferLength*4?new Ao(i,e.minRepeatTerm):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,i=this.stacks=[],s,r;if(this.bigReductionCount>300&&e.length==1){let[o]=e;for(;o.forceReduce()&&o.stack.length&&o.stack[o.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let o=0;ot)i.push(l);else{if(this.advanceStack(l,i,e))continue;{s||(s=[],r=[]),s.push(l);let a=this.tokens.getMainToken(l);r.push(a.value,a.end)}}break}}if(!i.length){let o=s&&sm(s);if(o)return ge&&console.log("Finish with "+this.stackID(o)),this.stackToTree(o);if(this.parser.strict)throw ge&&s&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+t);this.recovering||(this.recovering=5)}if(this.recovering&&s){let o=this.stoppedAt!=null&&s[0].pos>this.stoppedAt?s[0]:this.runRecovery(s,r,i);if(o)return ge&&console.log("Force-finish "+this.stackID(o)),this.stackToTree(o.forceAll())}if(this.recovering){let o=this.recovering==1?1:this.recovering*3;if(i.length>o)for(i.sort((l,a)=>a.score-l.score);i.length>o;)i.pop();i.some(l=>l.reducePos>t)&&this.recovering--}else if(i.length>1){e:for(let o=0;o500&&h.buffer.length>500)if((l.score-h.score||l.buffer.length-h.buffer.length)>0)i.splice(a--,1);else{i.splice(o--,1);continue e}}}i.length>12&&(i.sort((o,l)=>l.score-o.score),i.splice(12,i.length-12))}this.minStackPos=i[0].pos;for(let o=1;o-1&&i.length&&(!r||(i.prop(R.contextHash)||0)==o))return e.useNode(i,l,t),i;if(i.children.length==0||i.positions[0]>0)break;let a=i.children[0];if(a instanceof j&&(!s||a.type.id>=this.parser.minRepeatTerm))i=a;else break}return null}advanceStack(e,t,i){let s=e.pos,{parser:r}=this,o=ge?this.stackID(e)+" -> ":"";if(this.stoppedAt!=null&&s>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let h=e.reducePos0)return e.reduce(l),ge&&console.log(o+this.stackID(e)+` (via always-reduce ${r.getName(l&65535)})`),!0;if(e.stack.length>=8400)for(;e.stack.length>6e3&&e.forceReduce(););let a=this.tokens.getActions(e);for(let h=0;hs?t.push(p):i.push(p)}return!1}advanceFully(e,t){let i=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>i)return kf(e,t),!0}}runRecovery(e,t,i){let s=null,r=!1;for(let o=0;o ":"";if(l.deadEnd&&(r||(r=!0,l.restart(),ge&&console.log(f+this.stackID(l)+" (restarted)"),this.advanceFully(l,i))))continue;let c=l.split(),u=f;for(let d=0;d<10&&c.forceReduce()&&(ge&&console.log(u+this.stackID(c)+" (via force-reduce)"),!this.advanceFully(c,i));d++)ge&&(u=this.stackID(c)+" -> ");for(let d of l.recoverByInsert(a))ge&&console.log(f+this.stackID(d)+" (via recover-insert)"),this.advanceFully(d,i);this.stream.end>l.pos?(h==l.pos&&(h++,a=0),l.recoverByDelete(a,h),ge&&console.log(f+this.stackID(l)+` (via recover-delete ${this.parser.getName(a)})`),kf(l,i)):(!s||s.scoren,hs=class{constructor(e){this.start=e.start,this.shift=e.shift||wo,this.reduce=e.reduce||wo,this.reuse=e.reuse||wo,this.hash=e.hash||(()=>0),this.strict=e.strict!==!1}},fs=class n extends hi{constructor(e){if(super(),this.wrappers=[],e.version!=14)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let l=0;le.topRules[l][1]),s=[];for(let l=0;l=0)r(f,a,l[h++]);else{let c=l[h+-f];for(let u=-f;u>0;u--)r(l[h++],a,c);h++}}}this.nodeSet=new Ii(t.map((l,a)=>ie.define({name:a>=this.minRepeatTerm?void 0:l,id:a,props:s[a],top:i.indexOf(a)>-1,error:a==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=1024;let o=Ki(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let l=0;ltypeof l=="number"?new yt(o,l):l),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,i){let s=new Mo(this,e,t,i);for(let r of this.wrappers)s=r(s,e,t,i);return s}getGoto(e,t,i=!1){let s=this.goto;if(t>=s[0])return-1;for(let r=s[t+1];;){let o=s[r++],l=o&1,a=s[r++];if(l&&i)return a;for(let h=r+(o>>1);r0}validAction(e,t){return!!this.allActions(e,i=>i==t?!0:null)}allActions(e,t){let i=this.stateSlot(e,4),s=i?t(i):void 0;for(let r=this.stateSlot(e,1);s==null;r+=3){if(this.data[r]==65535)if(this.data[r+1]==1)r=Je(this.data,r+2);else break;s=t(Je(this.data,r+1))}return s}nextStates(e){let t=[];for(let i=this.stateSlot(e,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=Je(this.data,i+2);else break;if((this.data[i+2]&1)==0){let s=this.data[i+1];t.some((r,o)=>o&1&&r==s)||t.push(this.data[i],s)}}return t}configure(e){let t=Object.assign(Object.create(n.prototype),this);if(e.props&&(t.nodeSet=this.nodeSet.extend(...e.props)),e.top){let i=this.topRules[e.top];if(!i)throw new RangeError(`Invalid top rule name ${e.top}`);t.top=i}return e.tokenizers&&(t.tokenizers=this.tokenizers.map(i=>{let s=e.tokenizers.find(r=>r.from==i);return s?s.to:i})),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map((i,s)=>{let r=e.specializers.find(l=>l.from==i.external);if(!r)return i;let o=Object.assign(Object.assign({},i),{external:r.to});return t.specializers[s]=wf(o),o})),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),e.strict!=null&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),e.bufferLength!=null&&(t.bufferLength=e.bufferLength),t}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),i=t.map(()=>!1);if(e)for(let r of e.split(" ")){let o=t.indexOf(r);o>=0&&(i[o]=!0)}let s=null;for(let r=0;ri)&&t.p.parser.stateFlag(t.state,2)&&(!e||e.scoren.external(t,i)<<1|e}return n.get}var rm=1,Rf=194,Mf=195,om=196,Tf=197,lm=198,am=199,hm=200,fm=2,Ef=3,Cf=201,cm=24,um=25,dm=49,pm=50,mm=55,gm=56,Om=57,ym=59,bm=60,Sm=61,xm=62,km=63,wm=65,vm=238,Tm=71,Cm=241,Qm=242,Pm=243,Am=244,Rm=245,Mm=246,Em=247,Dm=248,Df=72,Bm=249,qm=250,Wm=251,$m=252,Lm=253,zm=254,Im=255,Nm=256,Vm=73,Xm=77,Fm=263,_m=112,Hm=130,Um=151,jm=152,Gm=155,Nt=10,Ji=13,Wo=32,ds=9,$o=35,Zm=40,Ym=46,qo=123,Qf=125,Bf=39,qf=34,Pf=92,Km=111,Jm=120,eg=78,tg=117,ig=85,ng=new Set([um,dm,pm,Fm,wm,Hm,gm,Om,vm,xm,km,Df,Vm,Xm,bm,Sm,Um,jm,Gm,_m]);function Do(n){return n==Nt||n==Ji}function Bo(n){return n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102}var sg=new It((n,e)=>{let t;if(n.next<0)n.acceptToken(am);else if(e.context.flags&cs)Do(n.next)&&n.acceptToken(lm,1);else if(((t=n.peek(-1))<0||Do(t))&&e.canShift(Tf)){let i=0;for(;n.next==Wo||n.next==ds;)n.advance(),i++;(n.next==Nt||n.next==Ji||n.next==$o)&&n.acceptToken(Tf,-i)}else Do(n.next)&&n.acceptToken(om,1)},{contextual:!0}),rg=new It((n,e)=>{let t=e.context;if(t.flags)return;let i=n.peek(-1);if(i==Nt||i==Ji){let s=0,r=0;for(;;){if(n.next==Wo)s++;else if(n.next==ds)s+=8-s%8;else break;n.advance(),r++}s!=t.indent&&n.next!=Nt&&n.next!=Ji&&n.next!=$o&&(s[n,e|Wf])),ag=new hs({start:og,reduce(n,e,t,i){return n.flags&cs&&ng.has(e)||(e==Tm||e==Df)&&n.flags&Wf?n.parent:n},shift(n,e,t,i){return e==Rf?new us(n,lg(i.read(i.pos,t.pos)),0):e==Mf?n.parent:e==cm||e==mm||e==ym||e==Ef?new us(n,0,cs):Af.has(e)?new us(n,0,Af.get(e)|n.flags&cs):n},hash(n){return n.hash}}),hg=new It(n=>{for(let e=0;e<5;e++){if(n.next!="print".charCodeAt(e))return;n.advance()}if(!/\w/.test(String.fromCharCode(n.next)))for(let e=0;;e++){let t=n.peek(e);if(!(t==Wo||t==ds)){t!=Zm&&t!=Ym&&t!=Nt&&t!=Ji&&t!=$o&&n.acceptToken(rm);return}}}),fg=new It((n,e)=>{let{flags:t}=e.context,i=t&et?qf:Bf,s=(t&tt)>0,r=!(t&it),o=(t&nt)>0,l=n.pos;for(;!(n.next<0);)if(o&&n.next==qo)if(n.peek(1)==qo)n.advance(2);else{if(n.pos==l){n.acceptToken(Ef,1);return}break}else if(r&&n.next==Pf){if(n.pos==l){n.advance();let a=n.next;a>=0&&(n.advance(),cg(n,a)),n.acceptToken(fm);return}break}else if(n.next==Pf&&!r&&n.peek(1)>-1)n.advance(2);else if(n.next==i&&(!s||n.peek(1)==i&&n.peek(2)==i)){if(n.pos==l){n.acceptToken(Cf,s?3:1);return}break}else if(n.next==Nt){if(s)n.advance();else if(n.pos==l){n.acceptToken(Cf);return}break}else n.advance();n.pos>l&&n.acceptToken(hm)});function cg(n,e){if(e==Km)for(let t=0;t<2&&n.next>=48&&n.next<=55;t++)n.advance();else if(e==Jm)for(let t=0;t<2&&Bo(n.next);t++)n.advance();else if(e==tg)for(let t=0;t<4&&Bo(n.next);t++)n.advance();else if(e==ig)for(let t=0;t<8&&Bo(n.next);t++)n.advance();else if(e==eg&&n.next==qo){for(n.advance();n.next>=0&&n.next!=Qf&&n.next!=Bf&&n.next!=qf&&n.next!=Nt;)n.advance();n.next==Qf&&n.advance()}}var ug=Gn({'async "*" "**" FormatConversion FormatSpec':g.modifier,"for while if elif else try except finally return raise break continue with pass assert await yield match case":g.controlKeyword,"in not and or is del":g.operatorKeyword,"from def class global nonlocal lambda":g.definitionKeyword,import:g.moduleKeyword,"with as print":g.keyword,Boolean:g.bool,None:g.null,VariableName:g.variableName,"CallExpression/VariableName":g.function(g.variableName),"FunctionDefinition/VariableName":g.function(g.definition(g.variableName)),"ClassDefinition/VariableName":g.definition(g.className),PropertyName:g.propertyName,"CallExpression/MemberExpression/PropertyName":g.function(g.propertyName),Comment:g.lineComment,Number:g.number,String:g.string,FormatString:g.special(g.string),Escape:g.escape,UpdateOp:g.updateOperator,"ArithOp!":g.arithmeticOperator,BitOp:g.bitwiseOperator,CompareOp:g.compareOperator,AssignOp:g.definitionOperator,Ellipsis:g.punctuation,At:g.meta,"( )":g.paren,"[ ]":g.squareBracket,"{ }":g.brace,".":g.derefOperator,", ;":g.separator}),dg={__proto__:null,await:44,or:54,and:56,in:60,not:62,is:64,if:70,else:72,lambda:76,yield:94,from:96,async:102,for:104,None:162,True:164,False:164,del:178,pass:182,break:186,continue:190,return:194,raise:202,import:206,as:208,global:212,nonlocal:214,assert:218,type:223,elif:236,while:240,try:246,except:248,finally:250,with:254,def:258,class:268,match:279,case:285},$f=fs.deserialize({version:14,states:"##jQ`QeOOP$}OSOOO&WQtO'#HUOOQS'#Co'#CoOOQS'#Cp'#CpO'vQdO'#CnO*UQtO'#HTOOQS'#HU'#HUOOQS'#DU'#DUOOQS'#HT'#HTO*rQdO'#D_O+VQdO'#DfO+gQdO'#DjO+zOWO'#DuO,VOWO'#DvO.[QtO'#GuOOQS'#Gu'#GuO'vQdO'#GtO0ZQtO'#GtOOQS'#Eb'#EbO0rQdO'#EcOOQS'#Gs'#GsO0|QdO'#GrOOQV'#Gr'#GrO1XQdO'#FYOOQS'#G^'#G^O1^QdO'#FXOOQV'#IS'#ISOOQV'#Gq'#GqOOQV'#Fq'#FqQ`QeOOO'vQdO'#CqO1lQdO'#C}O1sQdO'#DRO2RQdO'#HYO2cQtO'#EVO'vQdO'#EWOOQS'#EY'#EYOOQS'#E['#E[OOQS'#E^'#E^O2wQdO'#E`O3_QdO'#EdO3rQdO'#EfO3zQtO'#EfO1XQdO'#EiO0rQdO'#ElO1XQdO'#EnO0rQdO'#EtO0rQdO'#EwO4VQdO'#EyO4^QdO'#FOO4iQdO'#EzO0rQdO'#FOO1XQdO'#FQO1XQdO'#FVO4nQdO'#F[P4uOdO'#GpPOOO)CBd)CBdOOQS'#Ce'#CeOOQS'#Cf'#CfOOQS'#Cg'#CgOOQS'#Ch'#ChOOQS'#Ci'#CiOOQS'#Cj'#CjOOQS'#Cl'#ClO'vQdO,59OO'vQdO,59OO'vQdO,59OO'vQdO,59OO'vQdO,59OO'vQdO,59OO5TQdO'#DoOOQS,5:Y,5:YO5hQdO'#HdOOQS,5:],5:]O5uQ!fO,5:]O5zQtO,59YO1lQdO,59bO1lQdO,59bO1lQdO,59bO8jQdO,59bO8oQdO,59bO8vQdO,59jO8}QdO'#HTO:TQdO'#HSOOQS'#HS'#HSOOQS'#D['#D[O:lQdO,59aO'vQdO,59aO:zQdO,59aOOQS,59y,59yO;PQdO,5:RO'vQdO,5:ROOQS,5:Q,5:QO;_QdO,5:QO;dQdO,5:XO'vQdO,5:XO'vQdO,5:VOOQS,5:U,5:UO;uQdO,5:UO;zQdO,5:WOOOW'#Fy'#FyOOOOQS'#Ds'#DsOOQS1G/w1G/wOOQS1G.|1G.|O!/[QtO1G.|O!/cQtO1G.|O1lQdO1G.|O!0OQdO1G/UOOQS'#DZ'#DZO0rQdO,59tOOQS1G.{1G.{O!0VQdO1G/eO!0gQdO1G/eO!0oQdO1G/fO'vQdO'#H[O!0tQdO'#H[O!0yQtO1G.{O!1ZQdO,59iO!2aQdO,5=zO!2qQdO,5=zO!2yQdO1G/mO!3OQtO1G/mOOQS1G/l1G/lO!3`QdO,5=uO!4VQdO,5=uO0rQdO1G/qO!4tQdO1G/sO!4yQtO1G/sO!5ZQtO1G/qOOQS1G/p1G/pOOQS1G/r1G/rOOOW-E9w-E9wOOQS1G/{1G/{O!5kQdO'#HxO0rQdO'#HxO!5|QdO,5>cOOOW-E9x-E9xOOQS1G/|1G/|OOQS-E9{-E9{O!6[Q#xO1G2zO!6{QtO1G2zO'vQdO,5kOOQS1G1`1G1`O!8RQdO1G1`OOQS'#DV'#DVO0rQdO,5=qOOQS,5=q,5=qO!8WQdO'#FrO!8cQdO,59oO!8kQdO1G/XO!8uQtO,5=uOOQS1G3`1G3`OOQS,5:m,5:mO!9fQdO'#GtOOQS,5jO!;ZQdO,5>jO1XQdO,5>jO!;lQdO,5>iOOQS-E:R-E:RO!;qQdO1G0lO!;|QdO1G0lO!lO!lO!hO!=VQdO,5>hO!=hQdO'#EpO0rQdO1G0tO!=sQdO1G0tO!=xQgO1G0zO!AvQgO1G0}O!EqQdO,5>oO!E{QdO,5>oO!FTQtO,5>oO0rQdO1G1PO!F_QdO1G1PO4iQdO1G1UO!!vQdO1G1WOOQV,5;a,5;aO!FdQfO,5;aO!FiQgO1G1QO!JjQdO'#GZO4iQdO1G1QO4iQdO1G1QO!JzQdO,5>pO!KXQdO,5>pO1XQdO,5>pOOQV1G1U1G1UO!KaQdO'#FSO!KrQ!fO1G1WO!KzQdO1G1WOOQV1G1]1G1]O4iQdO1G1]O!LPQdO1G1]O!LXQdO'#F^OOQV1G1b1G1bO!#ZQtO1G1bPOOO1G2v1G2vP!L^OSO1G2vOOQS,5=},5=}OOQS'#Dp'#DpO0rQdO,5=}O!LfQdO,5=|O!LyQdO,5=|OOQS1G/u1G/uO!MRQdO,5>PO!McQdO,5>PO!MkQdO,5>PO!NOQdO,5>PO!N`QdO,5>POOQS1G3j1G3jOOQS7+$h7+$hO!8kQdO7+$pO#!RQdO1G.|O#!YQdO1G.|OOQS1G/`1G/`OOQS,5<`,5<`O'vQdO,5<`OOQS7+%P7+%PO#!aQdO7+%POOQS-E9r-E9rOOQS7+%Q7+%QO#!qQdO,5=vO'vQdO,5=vOOQS7+$g7+$gO#!vQdO7+%PO##OQdO7+%QO##TQdO1G3fOOQS7+%X7+%XO##eQdO1G3fO##mQdO7+%XOOQS,5<_,5<_O'vQdO,5<_O##rQdO1G3aOOQS-E9q-E9qO#$iQdO7+%]OOQS7+%_7+%_O#$wQdO1G3aO#%fQdO7+%_O#%kQdO1G3gO#%{QdO1G3gO#&TQdO7+%]O#&YQdO,5>dO#&sQdO,5>dO#&sQdO,5>dOOQS'#Dx'#DxO#'UO&jO'#DzO#'aO`O'#HyOOOW1G3}1G3}O#'fQdO1G3}O#'nQdO1G3}O#'yQ#xO7+(fO#(jQtO1G2UP#)TQdO'#GOOOQS,5nQdO,5sQdO1G4OOOQS-E9y-E9yO#?^QdO1G4OO<[QdO'#H{OOOO'#D{'#D{OOOO'#F|'#F|O#?oO&jO,5:fOOOW,5>e,5>eOOOW7+)i7+)iO#?zQdO7+)iO#@SQdO1G2zO#@mQdO1G2zP'vQdO'#FuO0rQdO<mO#BQQdO,5>mOOQS1G0v1G0vOOQS<rO#KgQdO,5>rO#KrQdO,5>rO#K}QdO,5>qO#L`QdO,5>qOOQS1G1Y1G1YOOQS,5;p,5;pOOQV<VAN>VO$ oQdO<cAN>cO0rQdO1G1|O$!PQtO1G1|P$!ZQdO'#FvOOQS1G2R1G2RP$!hQdO'#F{O$!uQdO7+)jO$#`QdO,5>gOOOO-E9z-E9zOOOW<tO$4{QdO,5>tO1XQdO,5vO$)nQdO,5>vOOQS1G1p1G1pOOQS,5<[,5<[OOQU7+'P7+'PO$+zQdO1G/iO$)nQdO,5wO$8zQdO,5>wOOQS1G1s1G1sOOQS7+'S7+'SP$)nQdO'#GdO$9SQdO1G4bO$9^QdO1G4bO$9fQdO1G4bOOQS7+%T7+%TO$9tQdO1G1tO$:SQtO'#FaO$:ZQdO,5<}OOQS,5<},5<}O$:iQdO1G4cOOQS-E:a-E:aO$)nQdO,5<|O$:pQdO,5<|O$:uQdO7+)|OOQS-E:`-E:`O$;PQdO7+)|O$)nQdO,5S~O%cOS%^OSSOS%]PQ~OPdOVaOfoOhYOopOs!POvqO!PrO!Q{O!T!SO!U!RO!XZO!][O!h`O!r`O!s`O!t`O!{tO!}uO#PvO#RwO#TxO#XyO#ZzO#^|O#_|O#a}O#c!OO#l!QO#o!TO#s!UO#u!VO#z!WO#}hO$P!XO%oRO%pRO%tSO%uWO&Z]O&[]O&]]O&^]O&_]O&`]O&a]O&b]O&c^O&d^O&e^O&f^O&g^O&h^O&i^O&j^O~O%]!YO~OV!aO_!aOa!bOh!iO!X!kO!f!mO%j![O%k!]O%l!^O%m!_O%n!_O%o!`O%p!`O%q!aO%r!aO%s!aO~Ok%xXl%xXm%xXn%xXo%xXp%xXs%xXz%xX{%xX!x%xX#g%xX%[%xX%_%xX%z%xXg%xX!T%xX!U%xX%{%xX!W%xX![%xX!Q%xX#[%xXt%xX!m%xX~P%SOfoOhYO!XZO!][O!h`O!r`O!s`O!t`O%oRO%pRO%tSO%uWO&Z]O&[]O&]]O&^]O&_]O&`]O&a]O&b]O&c^O&d^O&e^O&f^O&g^O&h^O&i^O&j^O~Oz%wX{%wX#g%wX%[%wX%_%wX%z%wX~Ok!pOl!qOm!oOn!oOo!rOp!sOs!tO!x%wX~P)pOV!zOg!|Oo0cOv0qO!PrO~P'vOV#OOo0cOv0qO!W#PO~P'vOV#SOa#TOo0cOv0qO![#UO~P'vOQ#XO%`#XO%a#ZO~OQ#^OR#[O%`#^O%a#`O~OV%iX_%iXa%iXh%iXk%iXl%iXm%iXn%iXo%iXp%iXs%iXz%iX!X%iX!f%iX%j%iX%k%iX%l%iX%m%iX%n%iX%o%iX%p%iX%q%iX%r%iX%s%iXg%iX!T%iX!U%iX~O&Z]O&[]O&]]O&^]O&_]O&`]O&a]O&b]O&c^O&d^O&e^O&f^O&g^O&h^O&i^O&j^O{%iX!x%iX#g%iX%[%iX%_%iX%z%iX%{%iX!W%iX![%iX!Q%iX#[%iXt%iX!m%iX~P,eOz#dO{%hX!x%hX#g%hX%[%hX%_%hX%z%hX~Oo0cOv0qO~P'vO#g#gO%[#iO%_#iO~O%uWO~O!T#nO#u!VO#z!WO#}hO~OopO~P'vOV#sOa#tO%uWO{wP~OV#xOo0cOv0qO!Q#yO~P'vO{#{O!x$QO%z#|O#g!yX%[!yX%_!yX~OV#xOo0cOv0qO#g#SX%[#SX%_#SX~P'vOo0cOv0qO#g#WX%[#WX%_#WX~P'vOh$WO%uWO~O!f$YO!r$YO%uWO~OV$eO~P'vO!U$gO#s$hO#u$iO~O{$jO~OV$qO~P'vOS$sO%[$rO%_$rO%c$tO~OV$}Oa$}Og%POo0cOv0qO~P'vOo0cOv0qO{%SO~P'vO&Y%UO~Oa!bOh!iO!X!kO!f!mOVba_bakbalbambanbaobapbasbazba{ba!xba#gba%[ba%_ba%jba%kba%lba%mba%nba%oba%pba%qba%rba%sba%zbagba!Tba!Uba%{ba!Wba![ba!Qba#[batba!mba~On%ZO~Oo%ZO~P'vOo0cO~P'vOk0eOl0fOm0dOn0dOo0mOp0nOs0rOg%wX!T%wX!U%wX%{%wX!W%wX![%wX!Q%wX#[%wX!m%wX~P)pO%{%]Og%vXz%vX!T%vX!U%vX!W%vX{%vX~Og%_Oz%`O!T%dO!U%cO~Og%_O~Oz%gO!T%dO!U%cO!W&SX~O!W%kO~Oz%lO{%nO!T%dO!U%cO![%}X~O![%rO~O![%sO~OQ#XO%`#XO%a%uO~OV%wOo0cOv0qO!PrO~P'vOQ#^OR#[O%`#^O%a%zO~OV!qa_!qaa!qah!qak!qal!qam!qan!qao!qap!qas!qaz!qa{!qa!X!qa!f!qa!x!qa#g!qa%[!qa%_!qa%j!qa%k!qa%l!qa%m!qa%n!qa%o!qa%p!qa%q!qa%r!qa%s!qa%z!qag!qa!T!qa!U!qa%{!qa!W!qa![!qa!Q!qa#[!qat!qa!m!qa~P#yOz%|O{%ha!x%ha#g%ha%[%ha%_%ha%z%ha~P%SOV&OOopOvqO{%ha!x%ha#g%ha%[%ha%_%ha%z%ha~P'vOz%|O{%ha!x%ha#g%ha%[%ha%_%ha%z%ha~OPdOVaOopOvqO!PrO!Q{O!{tO!}uO#PvO#RwO#TxO#XyO#ZzO#^|O#_|O#a}O#c!OO#g$zX%[$zX%_$zX~P'vO#g#gO%[&TO%_&TO~O!f&UOh&sX%[&sXz&sX#[&sX#g&sX%_&sX#Z&sXg&sX~Oh!iO%[&WO~Okealeameaneaoeapeaseazea{ea!xea#gea%[ea%_ea%zeagea!Tea!Uea%{ea!Wea![ea!Qea#[eatea!mea~P%SOsqazqa{qa#gqa%[qa%_qa%zqa~Ok!pOl!qOm!oOn!oOo!rOp!sO!xqa~PEcO%z&YOz%yX{%yX~O%uWOz%yX{%yX~Oz&]O{wX~O{&_O~Oz%lO#g%}X%[%}X%_%}Xg%}X{%}X![%}X!m%}X%z%}X~OV0lOo0cOv0qO!PrO~P'vO%z#|O#gUa%[Ua%_Ua~Oz&hO#g&PX%[&PX%_&PXn&PX~P%SOz&kO!Q&jO#g#Wa%[#Wa%_#Wa~Oz&lO#[&nO#g&rX%[&rX%_&rXg&rX~O!f$YO!r$YO#Z&qO%uWO~O#Z&qO~Oz&sO#g&tX%[&tX%_&tX~Oz&uO#g&pX%[&pX%_&pX{&pX~O!X&wO%z&xO~Oz&|On&wX~P%SOn'PO~OPdOVaOopOvqO!PrO!Q{O!{tO!}uO#PvO#RwO#TxO#XyO#ZzO#^|O#_|O#a}O#c!OO%['UO~P'vOt'YO#p'WO#q'XOP#naV#naf#nah#nao#nas#nav#na!P#na!Q#na!T#na!U#na!X#na!]#na!h#na!r#na!s#na!t#na!{#na!}#na#P#na#R#na#T#na#X#na#Z#na#^#na#_#na#a#na#c#na#l#na#o#na#s#na#u#na#z#na#}#na$P#na%X#na%o#na%p#na%t#na%u#na&Z#na&[#na&]#na&^#na&_#na&`#na&a#na&b#na&c#na&d#na&e#na&f#na&g#na&h#na&i#na&j#na%Z#na%_#na~Oz'ZO#[']O{&xX~Oh'_O!X&wO~Oh!iO{$jO!X&wO~O{'eO~P%SO%['hO%_'hO~OS'iO%['hO%_'hO~OV!aO_!aOa!bOh!iO!X!kO!f!mO%l!^O%m!_O%n!_O%o!`O%p!`O%q!aO%r!aO%s!aOkWilWimWinWioWipWisWizWi{Wi!xWi#gWi%[Wi%_Wi%jWi%zWigWi!TWi!UWi%{Wi!WWi![Wi!QWi#[WitWi!mWi~O%k!]O~P!#uO%kWi~P!#uOV!aO_!aOa!bOh!iO!X!kO!f!mO%o!`O%p!`O%q!aO%r!aO%s!aOkWilWimWinWioWipWisWizWi{Wi!xWi#gWi%[Wi%_Wi%jWi%kWi%lWi%zWigWi!TWi!UWi%{Wi!WWi![Wi!QWi#[WitWi!mWi~O%m!_O%n!_O~P!&pO%mWi%nWi~P!&pOa!bOh!iO!X!kO!f!mOkWilWimWinWioWipWisWizWi{Wi!xWi#gWi%[Wi%_Wi%jWi%kWi%lWi%mWi%nWi%oWi%pWi%zWigWi!TWi!UWi%{Wi!WWi![Wi!QWi#[WitWi!mWi~OV!aO_!aO%q!aO%r!aO%s!aO~P!)nOVWi_Wi%qWi%rWi%sWi~P!)nO!T%dO!U%cOg&VXz&VX~O%z'kO%{'kO~P,eOz'mOg&UX~Og'oO~Oz'pO{'rO!W&XX~Oo0cOv0qOz'pO{'sO!W&XX~P'vO!W'uO~Om!oOn!oOo!rOp!sOkjisjizji{ji!xji#gji%[ji%_ji%zji~Ol!qO~P!.aOlji~P!.aOk0eOl0fOm0dOn0dOo0mOp0nO~Ot'wO~P!/jOV'|Og'}Oo0cOv0qO~P'vOg'}Oz(OO~Og(QO~O!U(SO~Og(TOz(OO!T%dO!U%cO~P%SOk0eOl0fOm0dOn0dOo0mOp0nOgqa!Tqa!Uqa%{qa!Wqa![qa!Qqa#[qatqa!mqa~PEcOV'|Oo0cOv0qO!W&Sa~P'vOz(WO!W&Sa~O!W(XO~Oz(WO!T%dO!U%cO!W&Sa~P%SOV(]Oo0cOv0qO![%}a#g%}a%[%}a%_%}ag%}a{%}a!m%}a%z%}a~P'vOz(^O![%}a#g%}a%[%}a%_%}ag%}a{%}a!m%}a%z%}a~O![(aO~Oz(^O!T%dO!U%cO![%}a~P%SOz(dO!T%dO!U%cO![&Ta~P%SOz(gO{&lX![&lX!m&lX%z&lX~O{(kO![(mO!m(nO%z(jO~OV&OOopOvqO{%hi!x%hi#g%hi%[%hi%_%hi%z%hi~P'vOz(pO{%hi!x%hi#g%hi%[%hi%_%hi%z%hi~O!f&UOh&sa%[&saz&sa#[&sa#g&sa%_&sa#Z&sag&sa~O%[(uO~OV#sOa#tO%uWO~Oz&]O{wa~OopOvqO~P'vOz(^O#g%}a%[%}a%_%}ag%}a{%}a![%}a!m%}a%z%}a~P%SOz(zO#g%hX%[%hX%_%hX%z%hX~O%z#|O#gUi%[Ui%_Ui~O#g&Pa%[&Pa%_&Pan&Pa~P'vOz(}O#g&Pa%[&Pa%_&Pan&Pa~O%uWO#g&ra%[&ra%_&rag&ra~Oz)SO#g&ra%[&ra%_&rag&ra~Og)VO~OV)WOh$WO%uWO~O#Z)XO~O%uWO#g&ta%[&ta%_&ta~Oz)ZO#g&ta%[&ta%_&ta~Oo0cOv0qO#g&pa%[&pa%_&pa{&pa~P'vOz)^O#g&pa%[&pa%_&pa{&pa~OV)`Oa)`O%uWO~O%z)eO~Ot)hO#j)gOP#hiV#hif#hih#hio#his#hiv#hi!P#hi!Q#hi!T#hi!U#hi!X#hi!]#hi!h#hi!r#hi!s#hi!t#hi!{#hi!}#hi#P#hi#R#hi#T#hi#X#hi#Z#hi#^#hi#_#hi#a#hi#c#hi#l#hi#o#hi#s#hi#u#hi#z#hi#}#hi$P#hi%X#hi%o#hi%p#hi%t#hi%u#hi&Z#hi&[#hi&]#hi&^#hi&_#hi&`#hi&a#hi&b#hi&c#hi&d#hi&e#hi&f#hi&g#hi&h#hi&i#hi&j#hi%Z#hi%_#hi~Ot)iOP#kiV#kif#kih#kio#kis#kiv#ki!P#ki!Q#ki!T#ki!U#ki!X#ki!]#ki!h#ki!r#ki!s#ki!t#ki!{#ki!}#ki#P#ki#R#ki#T#ki#X#ki#Z#ki#^#ki#_#ki#a#ki#c#ki#l#ki#o#ki#s#ki#u#ki#z#ki#}#ki$P#ki%X#ki%o#ki%p#ki%t#ki%u#ki&Z#ki&[#ki&]#ki&^#ki&_#ki&`#ki&a#ki&b#ki&c#ki&d#ki&e#ki&f#ki&g#ki&h#ki&i#ki&j#ki%Z#ki%_#ki~OV)kOn&wa~P'vOz)lOn&wa~Oz)lOn&wa~P%SOn)pO~O%Y)tO~Ot)wO#p'WO#q)vOP#niV#nif#nih#nio#nis#niv#ni!P#ni!Q#ni!T#ni!U#ni!X#ni!]#ni!h#ni!r#ni!s#ni!t#ni!{#ni!}#ni#P#ni#R#ni#T#ni#X#ni#Z#ni#^#ni#_#ni#a#ni#c#ni#l#ni#o#ni#s#ni#u#ni#z#ni#}#ni$P#ni%X#ni%o#ni%p#ni%t#ni%u#ni&Z#ni&[#ni&]#ni&^#ni&_#ni&`#ni&a#ni&b#ni&c#ni&d#ni&e#ni&f#ni&g#ni&h#ni&i#ni&j#ni%Z#ni%_#ni~OV)zOo0cOv0qO{$jO~P'vOo0cOv0qO{&xa~P'vOz*OO{&xa~OV*SOa*TOg*WO%q*UO%uWO~O{$jO&{*YO~Oh'_O~Oh!iO{$jO~O%[*_O~O%[*aO%_*aO~OV$}Oa$}Oo0cOv0qOg&Ua~P'vOz*dOg&Ua~Oo0cOv0qO{*gO!W&Xa~P'vOz*hO!W&Xa~Oo0cOv0qOz*hO{*kO!W&Xa~P'vOo0cOv0qOz*hO!W&Xa~P'vOz*hO{*kO!W&Xa~Om0dOn0dOo0mOp0nOgjikjisjizji!Tji!Uji%{ji!Wji{ji![ji#gji%[ji%_ji!Qji#[jitji!mji%zji~Ol0fO~P!NkOlji~P!NkOV'|Og*pOo0cOv0qO~P'vOn*rO~Og*pOz*tO~Og*uO~OV'|Oo0cOv0qO!W&Si~P'vOz*vO!W&Si~O!W*wO~OV(]Oo0cOv0qO![%}i#g%}i%[%}i%_%}ig%}i{%}i!m%}i%z%}i~P'vOz*zO!T%dO!U%cO![&Ti~Oz*}O![%}i#g%}i%[%}i%_%}ig%}i{%}i!m%}i%z%}i~O![+OO~Oa+QOo0cOv0qO![&Ti~P'vOz*zO![&Ti~O![+SO~OV+UOo0cOv0qO{&la![&la!m&la%z&la~P'vOz+VO{&la![&la!m&la%z&la~O!]+YO&n+[O![!nX~O![+^O~O{(kO![+_O~O{(kO![+_O!m+`O~OV&OOopOvqO{%hq!x%hq#g%hq%[%hq%_%hq%z%hq~P'vOz$ri{$ri!x$ri#g$ri%[$ri%_$ri%z$ri~P%SOV&OOopOvqO~P'vOV&OOo0cOv0qO#g%ha%[%ha%_%ha%z%ha~P'vOz+aO#g%ha%[%ha%_%ha%z%ha~Oz$ia#g$ia%[$ia%_$ian$ia~P%SO#g&Pi%[&Pi%_&Pin&Pi~P'vOz+dO#g#Wq%[#Wq%_#Wq~O#[+eOz$va#g$va%[$va%_$vag$va~O%uWO#g&ri%[&ri%_&rig&ri~Oz+gO#g&ri%[&ri%_&rig&ri~OV+iOh$WO%uWO~O%uWO#g&ti%[&ti%_&ti~Oo0cOv0qO#g&pi%[&pi%_&pi{&pi~P'vO{#{Oz#eX!W#eX~Oz+mO!W&uX~O!W+oO~Ot+rO#j)gOP#hqV#hqf#hqh#hqo#hqs#hqv#hq!P#hq!Q#hq!T#hq!U#hq!X#hq!]#hq!h#hq!r#hq!s#hq!t#hq!{#hq!}#hq#P#hq#R#hq#T#hq#X#hq#Z#hq#^#hq#_#hq#a#hq#c#hq#l#hq#o#hq#s#hq#u#hq#z#hq#}#hq$P#hq%X#hq%o#hq%p#hq%t#hq%u#hq&Z#hq&[#hq&]#hq&^#hq&_#hq&`#hq&a#hq&b#hq&c#hq&d#hq&e#hq&f#hq&g#hq&h#hq&i#hq&j#hq%Z#hq%_#hq~On$|az$|a~P%SOV)kOn&wi~P'vOz+yOn&wi~Oz,TO{$jO#[,TO~O#q,VOP#nqV#nqf#nqh#nqo#nqs#nqv#nq!P#nq!Q#nq!T#nq!U#nq!X#nq!]#nq!h#nq!r#nq!s#nq!t#nq!{#nq!}#nq#P#nq#R#nq#T#nq#X#nq#Z#nq#^#nq#_#nq#a#nq#c#nq#l#nq#o#nq#s#nq#u#nq#z#nq#}#nq$P#nq%X#nq%o#nq%p#nq%t#nq%u#nq&Z#nq&[#nq&]#nq&^#nq&_#nq&`#nq&a#nq&b#nq&c#nq&d#nq&e#nq&f#nq&g#nq&h#nq&i#nq&j#nq%Z#nq%_#nq~O#[,WOz%Oa{%Oa~Oo0cOv0qO{&xi~P'vOz,YO{&xi~O{#{O%z,[Og&zXz&zX~O%uWOg&zXz&zX~Oz,`Og&yX~Og,bO~O%Y,eO~O!T%dO!U%cOg&Viz&Vi~OV$}Oa$}Oo0cOv0qOg&Ui~P'vO{,hOz$la!W$la~Oo0cOv0qO{,iOz$la!W$la~P'vOo0cOv0qO{*gO!W&Xi~P'vOz,lO!W&Xi~Oo0cOv0qOz,lO!W&Xi~P'vOz,lO{,oO!W&Xi~Og$hiz$hi!W$hi~P%SOV'|Oo0cOv0qO~P'vOn,qO~OV'|Og,rOo0cOv0qO~P'vOV'|Oo0cOv0qO!W&Sq~P'vOz$gi![$gi#g$gi%[$gi%_$gig$gi{$gi!m$gi%z$gi~P%SOV(]Oo0cOv0qO~P'vOa+QOo0cOv0qO![&Tq~P'vOz,sO![&Tq~O![,tO~OV(]Oo0cOv0qO![%}q#g%}q%[%}q%_%}qg%}q{%}q!m%}q%z%}q~P'vO{,uO~OV+UOo0cOv0qO{&li![&li!m&li%z&li~P'vOz,zO{&li![&li!m&li%z&li~O!]+YO&n+[O![!na~O{(kO![,}O~OV&OOo0cOv0qO#g%hi%[%hi%_%hi%z%hi~P'vOz-OO#g%hi%[%hi%_%hi%z%hi~O%uWO#g&rq%[&rq%_&rqg&rq~Oz-RO#g&rq%[&rq%_&rqg&rq~OV)`Oa)`O%uWO!W&ua~Oz-TO!W&ua~On$|iz$|i~P%SOV)kO~P'vOV)kOn&wq~P'vOt-XOP#myV#myf#myh#myo#mys#myv#my!P#my!Q#my!T#my!U#my!X#my!]#my!h#my!r#my!s#my!t#my!{#my!}#my#P#my#R#my#T#my#X#my#Z#my#^#my#_#my#a#my#c#my#l#my#o#my#s#my#u#my#z#my#}#my$P#my%X#my%o#my%p#my%t#my%u#my&Z#my&[#my&]#my&^#my&_#my&`#my&a#my&b#my&c#my&d#my&e#my&f#my&g#my&h#my&i#my&j#my%Z#my%_#my~O%Z-]O%_-]O~P`O#q-^OP#nyV#nyf#nyh#nyo#nys#nyv#ny!P#ny!Q#ny!T#ny!U#ny!X#ny!]#ny!h#ny!r#ny!s#ny!t#ny!{#ny!}#ny#P#ny#R#ny#T#ny#X#ny#Z#ny#^#ny#_#ny#a#ny#c#ny#l#ny#o#ny#s#ny#u#ny#z#ny#}#ny$P#ny%X#ny%o#ny%p#ny%t#ny%u#ny&Z#ny&[#ny&]#ny&^#ny&_#ny&`#ny&a#ny&b#ny&c#ny&d#ny&e#ny&f#ny&g#ny&h#ny&i#ny&j#ny%Z#ny%_#ny~Oz-aO{$jO#[-aO~Oo0cOv0qO{&xq~P'vOz-dO{&xq~O%z,[Og&zaz&za~O{#{Og&zaz&za~OV*SOa*TO%q*UO%uWOg&ya~Oz-hOg&ya~O$S-lO~OV$}Oa$}Oo0cOv0qO~P'vOo0cOv0qO{-mOz$li!W$li~P'vOo0cOv0qOz$li!W$li~P'vO{-mOz$li!W$li~Oo0cOv0qO{*gO~P'vOo0cOv0qO{*gO!W&Xq~P'vOz-pO!W&Xq~Oo0cOv0qOz-pO!W&Xq~P'vOs-sO!T%dO!U%cOg&Oq!W&Oq![&Oqz&Oq~P!/jOa+QOo0cOv0qO![&Ty~P'vOz$ji![$ji~P%SOa+QOo0cOv0qO~P'vOV+UOo0cOv0qO~P'vOV+UOo0cOv0qO{&lq![&lq!m&lq%z&lq~P'vO{(kO![-xO!m-yO%z-wO~OV&OOo0cOv0qO#g%hq%[%hq%_%hq%z%hq~P'vO%uWO#g&ry%[&ry%_&ryg&ry~OV)`Oa)`O%uWO!W&ui~Ot-}OP#m!RV#m!Rf#m!Rh#m!Ro#m!Rs#m!Rv#m!R!P#m!R!Q#m!R!T#m!R!U#m!R!X#m!R!]#m!R!h#m!R!r#m!R!s#m!R!t#m!R!{#m!R!}#m!R#P#m!R#R#m!R#T#m!R#X#m!R#Z#m!R#^#m!R#_#m!R#a#m!R#c#m!R#l#m!R#o#m!R#s#m!R#u#m!R#z#m!R#}#m!R$P#m!R%X#m!R%o#m!R%p#m!R%t#m!R%u#m!R&Z#m!R&[#m!R&]#m!R&^#m!R&_#m!R&`#m!R&a#m!R&b#m!R&c#m!R&d#m!R&e#m!R&f#m!R&g#m!R&h#m!R&i#m!R&j#m!R%Z#m!R%_#m!R~Oo0cOv0qO{&xy~P'vOV*SOa*TO%q*UO%uWOg&yi~O$S-lO%Z.VO%_.VO~OV.aOh._O!X.^O!].`O!h.YO!s.[O!t.[O%p.XO%uWO&Z]O&[]O&]]O&^]O&_]O&`]O&a]O&b]O~Oo0cOv0qOz$lq!W$lq~P'vO{.fOz$lq!W$lq~Oo0cOv0qO{*gO!W&Xy~P'vOz.gO!W&Xy~Oo0cOv.kO~P'vOs-sO!T%dO!U%cOg&Oy!W&Oy![&Oyz&Oy~P!/jO{(kO![.nO~O{(kO![.nO!m.oO~OV*SOa*TO%q*UO%uWO~Oh.tO!f.rOz$TX#[$TX%j$TXg$TX~Os$TX{$TX!W$TX![$TX~P$-bO%o.vO%p.vOs$UXz$UX{$UX#[$UX%j$UX!W$UXg$UX![$UX~O!h.xO~Oz.|O#[/OO%j.yOs&|X{&|X!W&|Xg&|X~Oa/RO~P$)zOh.tOs&}Xz&}X{&}X#[&}X%j&}X!W&}Xg&}X![&}X~Os/VO{$jO~Oo0cOv0qOz$ly!W$ly~P'vOo0cOv0qO{*gO!W&X!R~P'vOz/ZO!W&X!R~Og&RXs&RX!T&RX!U&RX!W&RX![&RXz&RX~P!/jOs-sO!T%dO!U%cOg&Qa!W&Qa![&Qaz&Qa~O{(kO![/^O~O!f.rOh$[as$[az$[a{$[a#[$[a%j$[a!W$[ag$[a![$[a~O!h/eO~O%o.vO%p.vOs$Uaz$Ua{$Ua#[$Ua%j$Ua!W$Uag$Ua![$Ua~O%j.yOs$Yaz$Ya{$Ya#[$Ya!W$Yag$Ya![$Ya~Os&|a{&|a!W&|ag&|a~P$)nOz/jOs&|a{&|a!W&|ag&|a~O!W/mO~Og/mO~O{/oO~O![/pO~Oo0cOv0qO{*gO!W&X!Z~P'vO{/sO~O%z/tO~P$-bOz/uO#[/OO%j.yOg'PX~Oz/uOg'PX~Og/wO~O!h/xO~O#[/OOs%Saz%Sa{%Sa%j%Sa!W%Sag%Sa![%Sa~O#[/OO%j.yOs%Waz%Wa{%Wa!W%Wag%Wa~Os&|i{&|i!W&|ig&|i~P$)nOz/zO#[/OO%j.yO!['Oa~Og'Pa~P$)nOz0SOg'Pa~Oa0UO!['Oi~P$)zOz0WO!['Oi~Oz0WO#[/OO%j.yO!['Oi~O#[/OO%j.yOg$biz$bi~O%z0ZO~P$-bO#[/OO%j.yOg%Vaz%Va~Og'Pi~P$)nO{0^O~Oa0UO!['Oq~P$)zOz0`O!['Oq~O#[/OO%j.yOz%Ui![%Ui~Oa0UO~P$)zOa0UO!['Oy~P$)zO#[/OO%j.yOg$ciz$ci~O#[/OO%j.yOz%Uq![%Uq~Oz+aO#g%ha%[%ha%_%ha%z%ha~P%SOV&OOo0cOv0qO~P'vOn0hO~Oo0hO~P'vO{0iO~Ot0jO~P!/jO&]&Z&j&h&i&g&f&d&e&c&b&`&a&_&^&[%u~",goto:"!=j'QPPPPPP'RP'Z*s+[+t,_,y-fP.SP'Z.r.r'ZPPP'Z2[PPPPPP2[5PPP5PP7b7k=sPP=v>h>kPP'Z'ZPP>zPP'Z'ZPP'Z'Z'Z'Z'Z?O?w'ZP?zP@QDXGuGyPG|HWH['ZPPPH_Hk'RP'R'RP'RP'RP'RP'RP'R'R'RP'RPP'RPP'RP'RPHqH}IVPI^IdPI^PI^I^PPPI^PKrPK{LVL]KrPI^LfPI^PLmLsPLwM]MzNeLwLwNkNxLwLwLwLw! ^! d! g! l! o! y!!P!!]!!o!!u!#P!#V!#s!#y!$P!$Z!$a!$g!$y!%T!%Z!%a!%k!%q!%w!%}!&T!&Z!&e!&k!&u!&{!'U!'[!'k!'s!'}!(UPPPPPPPPPPP!([!(_!(e!(n!(x!)TPPPPPPPPPPPP!-u!/Z!3^!6oPP!6w!7W!7a!8Y!8P!8c!8i!8l!8o!8r!8z!9jPPPPPPPPPPPPPPPPP!9m!9q!9wP!:]!:a!:m!:v!;S!;j!;m!;p!;v!;|!_![!]Do!]!^Es!^!_FZ!_!`Gk!`!aHX!a!b%T!b!cIf!c!dJU!d!eK^!e!hJU!h!i!#f!i!tJU!t!u!,|!u!wJU!w!x!.t!x!}JU!}#O!0S#O#P&o#P#Q!0j#Q#R!1Q#R#SJU#S#T%T#T#UJU#U#VK^#V#YJU#Y#Z!#f#Z#fJU#f#g!,|#g#iJU#i#j!.t#j#oJU#o#p!1n#p#q!1s#q#r!2a#r#s!2f#s$g%T$g;'SJU;'S;=`KW<%lOJU`%YT&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%T`%lP;=`<%l%To%v]&n`%c_OX%TXY%oY[%T[]%o]p%Tpq%oq#O%T#O#P&o#P#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To&tX&n`OY%TYZ%oZ]%T]^%o^#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc'f[&n`O!_%T!_!`([!`#T%T#T#U(r#U#f%T#f#g(r#g#h(r#h#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc(cTmR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc(yT!mR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk)aV&n`&[ZOr%Trs)vs#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk){V&n`Or%Trs*bs#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk*iT&n`&^ZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To+PZS_&n`OY*xYZ%TZ]*x]^%T^#o*x#o#p+r#p#q*x#q#r+r#r;'S*x;'S;=`,^<%lO*x_+wTS_OY+rZ]+r^;'S+r;'S;=`,W<%lO+r_,ZP;=`<%l+ro,aP;=`<%l*xj,kV%rQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tj-XT!xY&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tj-oV%lQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk.]V&n`&ZZOw%Twx.rx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk.wV&n`Ow%Twx/^x#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk/eT&n`&]ZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk/{ThZ&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc0cTgR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk0yXVZ&n`Oz%Tz{1f{!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk1mVaR&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk2ZV%oZ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc2wTzR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To3_W%pZ&n`O!_%T!_!`-Q!`!a3w!a#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Td4OT&{S&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk4fX!fQ&n`O!O%T!O!P5R!P!Q%T!Q![6T![#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk5WV&n`O!O%T!O!P5m!P#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk5tT!rZ&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti6[a!hX&n`O!Q%T!Q![6T![!g%T!g!h7a!h!l%T!l!m9s!m#R%T#R#S6T#S#X%T#X#Y7a#Y#^%T#^#_9s#_#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti7fZ&n`O{%T{|8X|}%T}!O8X!O!Q%T!Q![8s![#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti8^V&n`O!Q%T!Q![8s![#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti8z]!hX&n`O!Q%T!Q![8s![!l%T!l!m9s!m#R%T#R#S8s#S#^%T#^#_9s#_#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti9zT!hX&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk:bX%qR&n`O!P%T!P!Q:}!Q!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tj;UV%sQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti;ro!hX&n`O!O%T!O!P=s!P!Q%T!Q![>_![!d%T!d!e?q!e!g%T!g!h7a!h!l%T!l!m9s!m!q%T!q!rA]!r!z%T!z!{Bq!{#R%T#R#S>_#S#U%T#U#V?q#V#X%T#X#Y7a#Y#^%T#^#_9s#_#c%T#c#dA]#d#l%T#l#mBq#m#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti=xV&n`O!Q%T!Q![6T![#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti>fc!hX&n`O!O%T!O!P=s!P!Q%T!Q![>_![!g%T!g!h7a!h!l%T!l!m9s!m#R%T#R#S>_#S#X%T#X#Y7a#Y#^%T#^#_9s#_#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti?vY&n`O!Q%T!Q!R@f!R!S@f!S#R%T#R#S@f#S#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti@mY!hX&n`O!Q%T!Q!R@f!R!S@f!S#R%T#R#S@f#S#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TiAbX&n`O!Q%T!Q!YA}!Y#R%T#R#SA}#S#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TiBUX!hX&n`O!Q%T!Q!YA}!Y#R%T#R#SA}#S#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TiBv]&n`O!Q%T!Q![Co![!c%T!c!iCo!i#R%T#R#SCo#S#T%T#T#ZCo#Z#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TiCv]!hX&n`O!Q%T!Q![Co![!c%T!c!iCo!i#R%T#R#SCo#S#T%T#T#ZCo#Z#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%ToDvV{_&n`O!_%T!_!`E]!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TcEdT%{R&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkEzT#gZ&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkFbXmR&n`O!^%T!^!_F}!_!`([!`!a([!a#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TjGUV%mQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkGrV%zZ&n`O!_%T!_!`([!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkH`WmR&n`O!_%T!_!`([!`!aHx!a#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TjIPV%nQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkIoV_Q#}P&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%ToJ_]&n`&YS%uZO!Q%T!Q![JU![!c%T!c!}JU!}#R%T#R#SJU#S#T%T#T#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUoKZP;=`<%lJUoKge&n`&YS%uZOr%Trs)Ysw%Twx.Ux!Q%T!Q![JU![!c%T!c!tJU!t!uLx!u!}JU!}#R%T#R#SJU#S#T%T#T#fJU#f#gLx#g#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUoMRa&n`&YS%uZOr%TrsNWsw%Twx! vx!Q%T!Q![JU![!c%T!c!}JU!}#R%T#R#SJU#S#T%T#T#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUkN_V&n`&`ZOr%TrsNts#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkNyV&n`Or%Trs! `s#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk! gT&n`&bZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk! }V&n`&_ZOw%Twx!!dx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!!iV&n`Ow%Twx!#Ox#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!#VT&n`&aZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To!#oe&n`&YS%uZOr%Trs!%Qsw%Twx!&px!Q%T!Q![JU![!c%T!c!tJU!t!u!(`!u!}JU!}#R%T#R#SJU#S#T%T#T#fJU#f#g!(`#g#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUk!%XV&n`&dZOr%Trs!%ns#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!%sV&n`Or%Trs!&Ys#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!&aT&n`&fZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!&wV&n`&cZOw%Twx!'^x#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!'cV&n`Ow%Twx!'xx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!(PT&n`&eZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To!(ia&n`&YS%uZOr%Trs!)nsw%Twx!+^x!Q%T!Q![JU![!c%T!c!}JU!}#R%T#R#SJU#S#T%T#T#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUk!)uV&n`&hZOr%Trs!*[s#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!*aV&n`Or%Trs!*vs#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!*}T&n`&jZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!+eV&n`&gZOw%Twx!+zx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!,PV&n`Ow%Twx!,fx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!,mT&n`&iZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To!-Vi&n`&YS%uZOr%TrsNWsw%Twx! vx!Q%T!Q![JU![!c%T!c!dJU!d!eLx!e!hJU!h!i!(`!i!}JU!}#R%T#R#SJU#S#T%T#T#UJU#U#VLx#V#YJU#Y#Z!(`#Z#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUo!.}a&n`&YS%uZOr%Trs)Ysw%Twx.Ux!Q%T!Q![JU![!c%T!c!}JU!}#R%T#R#SJU#S#T%T#T#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUk!0ZT!XZ&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc!0qT!WR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tj!1XV%kQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%T~!1sO!]~k!1zV%jR&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%T~!2fO![~i!2mT%tX&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%T",tokenizers:[hg,rg,sg,fg,0,1,2,3,4],topRules:{Script:[0,5]},specialized:[{term:221,get:n=>dg[n]||-1}],tokenPrec:7668});var Lf=new Fn,If=new Set(["Script","Body","FunctionDefinition","ClassDefinition","LambdaExpression","ForStatement","MatchClause"]);function ps(n){return(e,t,i)=>{if(i)return!1;let s=e.node.getChild("VariableName");return s&&t(s,n),!0}}var pg={FunctionDefinition:ps("function"),ClassDefinition:ps("class"),ForStatement(n,e,t){if(t){for(let i=n.node.firstChild;i;i=i.nextSibling)if(i.name=="VariableName")e(i,"variable");else if(i.name=="in")break}},ImportStatement(n,e){var t,i;let{node:s}=n,r=((t=s.firstChild)===null||t===void 0?void 0:t.name)=="from";for(let o=s.getChild("import");o;o=o.nextSibling)o.name=="VariableName"&&((i=o.nextSibling)===null||i===void 0?void 0:i.name)!="as"&&e(o,r?"variable":"namespace")},AssignStatement(n,e){for(let t=n.node.firstChild;t;t=t.nextSibling)if(t.name=="VariableName")e(t,"variable");else if(t.name==":"||t.name=="AssignOp")break},ParamList(n,e){for(let t=null,i=n.node.firstChild;i;i=i.nextSibling)i.name=="VariableName"&&(!t||!/\*|AssignOp/.test(t.name))&&e(i,"variable"),t=i},CapturePattern:ps("variable"),AsPattern:ps("variable"),__proto__:null};function Nf(n,e){let t=Lf.get(e);if(t)return t;let i=[],s=!0;function r(o,l){let a=n.sliceString(o.from,o.to);i.push({label:a,type:l})}return e.cursor(N.IncludeAnonymous).iterate(o=>{if(o.name){let l=pg[o.name];if(l&&l(o,r,s)||!s&&If.has(o.name))return!1;s=!1}else if(o.to-o.from>8192){for(let l of Nf(n,o.node))i.push(l);return!1}}),Lf.set(e,i),i}var zf=/^[\w\xa1-\uffff][\w\d\xa1-\uffff]*$/,Vf=["String","FormatString","Comment","PropertyName"];function mg(n){let e=J(n.state).resolveInner(n.pos,-1);if(Vf.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&zf.test(n.state.sliceDoc(e.from,e.to));if(!t&&!n.explicit)return null;let i=[];for(let s=e;s;s=s.parent)If.has(s.name)&&(i=i.concat(Nf(n.state.doc,s)));return{options:i,from:t?e.from:n.pos,validFor:zf}}var gg=["__annotations__","__builtins__","__debug__","__doc__","__import__","__name__","__loader__","__package__","__spec__","False","None","True"].map(n=>({label:n,type:"constant"})).concat(["ArithmeticError","AssertionError","AttributeError","BaseException","BlockingIOError","BrokenPipeError","BufferError","BytesWarning","ChildProcessError","ConnectionAbortedError","ConnectionError","ConnectionRefusedError","ConnectionResetError","DeprecationWarning","EOFError","Ellipsis","EncodingWarning","EnvironmentError","Exception","FileExistsError","FileNotFoundError","FloatingPointError","FutureWarning","GeneratorExit","IOError","ImportError","ImportWarning","IndentationError","IndexError","InterruptedError","IsADirectoryError","KeyError","KeyboardInterrupt","LookupError","MemoryError","ModuleNotFoundError","NameError","NotADirectoryError","NotImplemented","NotImplementedError","OSError","OverflowError","PendingDeprecationWarning","PermissionError","ProcessLookupError","RecursionError","ReferenceError","ResourceWarning","RuntimeError","RuntimeWarning","StopAsyncIteration","StopIteration","SyntaxError","SyntaxWarning","SystemError","SystemExit","TabError","TimeoutError","TypeError","UnboundLocalError","UnicodeDecodeError","UnicodeEncodeError","UnicodeError","UnicodeTranslateError","UnicodeWarning","UserWarning","ValueError","Warning","ZeroDivisionError"].map(n=>({label:n,type:"type"}))).concat(["bool","bytearray","bytes","classmethod","complex","float","frozenset","int","list","map","memoryview","object","range","set","staticmethod","str","super","tuple","type"].map(n=>({label:n,type:"class"}))).concat(["abs","aiter","all","anext","any","ascii","bin","breakpoint","callable","chr","compile","delattr","dict","dir","divmod","enumerate","eval","exec","exit","filter","format","getattr","globals","hasattr","hash","help","hex","id","input","isinstance","issubclass","iter","len","license","locals","max","min","next","oct","open","ord","pow","print","property","quit","repr","reversed","round","setattr","slice","sorted","sum","vars","zip"].map(n=>({label:n,type:"function"}))),Og=[Xe("def ${name}(${params}):\n ${}",{label:"def",detail:"function",type:"keyword"}),Xe("for ${name} in ${collection}:\n ${}",{label:"for",detail:"loop",type:"keyword"}),Xe("while ${}:\n ${}",{label:"while",detail:"loop",type:"keyword"}),Xe("try:\n ${}\nexcept ${error}:\n ${}",{label:"try",detail:"/ except block",type:"keyword"}),Xe(`if \${}: + +`,{label:"if",detail:"block",type:"keyword"}),Xe("if ${}:\n ${}\nelse:\n ${}",{label:"if",detail:"/ else block",type:"keyword"}),Xe("class ${name}:\n def __init__(self, ${params}):\n ${}",{label:"class",detail:"definition",type:"keyword"}),Xe("import ${module}",{label:"import",detail:"statement",type:"keyword"}),Xe("from ${module} import ${names}",{label:"from",detail:"import",type:"keyword"})],yg=bh(Vf,yh(gg.concat(Og)));function Lo(n){let{node:e,pos:t}=n,i=n.lineIndent(t,-1),s=null;for(;;){let r=e.childBefore(t);if(r)if(r.name=="Comment")t=r.from;else if(r.name=="Body"||r.name=="MatchBody")n.baseIndentFor(r)+n.unit<=i&&(s=r),e=r;else if(r.name=="MatchClause")e=r;else if(r.type.is("Statement"))e=r;else break;else break}return s}function zo(n,e){let t=n.baseIndentFor(e),i=n.lineAt(n.pos,-1),s=i.from+i.text.length;return/^\s*($|#)/.test(i.text)&&n.node.tot?null:t+n.unit}var Io=Zn.define({name:"python",parser:$f.configure({props:[oo.add({Body:n=>{var e;let t=/^\s*(#|$)/.test(n.textAfter)&&Lo(n)||n.node;return(e=zo(n,t))!==null&&e!==void 0?e:n.continue()},MatchBody:n=>{var e;let t=Lo(n);return(e=zo(n,t||n.node))!==null&&e!==void 0?e:n.continue()},IfStatement:n=>/^\s*(else:|elif )/.test(n.textAfter)?n.baseIndent:n.continue(),"ForStatement WhileStatement":n=>/^\s*else:/.test(n.textAfter)?n.baseIndent:n.continue(),TryStatement:n=>/^\s*(except[ :]|finally:|else:)/.test(n.textAfter)?n.baseIndent:n.continue(),MatchStatement:n=>/^\s*case /.test(n.textAfter)?n.baseIndent+n.unit:n.continue(),"TupleExpression ComprehensionExpression ParamList ArgList ParenthesizedExpression":Jn({closing:")"}),"DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression":Jn({closing:"}"}),"ArrayExpression ArrayComprehensionExpression":Jn({closing:"]"}),MemberExpression:n=>n.baseIndent+n.unit,"String FormatString":()=>null,Script:n=>{var e;let t=Lo(n);return(e=t&&zo(n,t))!==null&&e!==void 0?e:n.continue()}}),oh.add({"ArrayExpression DictionaryExpression SetExpression TupleExpression":lh,Body:(n,e)=>({from:n.from+1,to:n.to-(n.to==e.doc.length?0:1)}),"String FormatString":(n,e)=>({from:e.doc.lineAt(n.from).to,to:n.to})})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"'''",'"""'],stringPrefixes:["f","fr","rf","r","u","b","br","rb","F","FR","RF","R","U","B","BR","RB"]},commentTokens:{line:"#"},indentOnInput:/^\s*([\}\]\)]|else:|elif |except |finally:|case\s+[^:]*:?)$/}});function Xf(){return new Yn(Io,[Io.data.of({autocomplete:mg}),Io.data.of({autocomplete:yg})])}var bg="#e5c07b",Ff="#e06c75",Sg="#56b6c2",xg="#ffffff",kg="#abb2bf",_f="#7d8799",wg="#61afef",vg="#98c379",Hf="#d19a66",Tg="#c678dd";var Uf=ui.define([{tag:g.keyword,color:Tg},{tag:[g.name,g.deleted,g.character,g.propertyName,g.macroName],color:Ff},{tag:[g.function(g.variableName),g.labelName],color:wg},{tag:[g.color,g.constant(g.name),g.standard(g.name)],color:Hf},{tag:[g.definition(g.name),g.separator],color:kg},{tag:[g.typeName,g.className,g.number,g.changed,g.annotation,g.modifier,g.self,g.namespace],color:bg},{tag:[g.operator,g.operatorKeyword,g.url,g.escape,g.regexp,g.link,g.special(g.string)],color:Sg},{tag:[g.meta,g.comment],color:_f},{tag:g.strong,fontWeight:"bold"},{tag:g.emphasis,fontStyle:"italic"},{tag:g.strikethrough,textDecoration:"line-through"},{tag:g.link,color:_f,textDecoration:"underline"},{tag:g.heading,fontWeight:"bold",color:Ff},{tag:[g.atom,g.bool,g.special(g.variableName)],color:Hf},{tag:[g.processingInstruction,g.string,g.inserted],color:vg},{tag:g.invalid,color:xg}]);var Zf=window.matchMedia("(prefers-color-scheme: dark)"),jf=()=>Zf.matches?Uf:hh,Gf=new jt,st=document.getElementById("code-editor"),No=document.querySelector("form.runner-editor");if(st&&No){let i=function(){e.dom.style.minHeight="";let l=Number.parseFloat(getComputedStyle(e.dom).minHeight)||0;e.dom.style.minHeight=`${Math.max(l,e.contentDOM.scrollHeight)}px`},s=function(){requestAnimationFrame(i)},r=function(l){e.dispatch({changes:{from:0,to:e.state.doc.length,insert:l}}),st.value=l,s()},o=function(){st.value=e.state.doc.toString()};st.classList.add("textarea-fallback");let n=[{key:"Mod-Enter",preventDefault:!0,run:()=>(No.requestSubmit(),!0)}],e=new C({state:z.create({doc:st.value,extensions:[ai.of(n),Lh(),Xf(),gt.of(" "),z.tabSize.of(4),rh(),dh(),kh(),Gf.of(es(jf())),Ia(),C.lineWrapping,ai.of([...Th,...Of,...Vh,yf]),C.contentAttributes.of({"aria-label":st.getAttribute("aria-label")||"Editable Python example code","aria-describedby":"editor-keys-hint"}),C.updateListener.of(l=>{l.docChanged&&(st.value=l.state.doc.toString())})]})});st.insertAdjacentElement("afterend",e.dom),st.hidden=!0;let t=document.getElementById("editor-keys-hint");t&&(t.hidden=!1),Zf.addEventListener?.("change",()=>{e.dispatch({effects:Gf.reconfigure(es(jf()))})}),i(),No.addEventListener("submit",o),window.pythonByExampleEditor={setValue:r,syncTextarea:o,resize:s,focus:()=>e.focus()}} diff --git a/public/editor.js b/public/editor.js index 067c444..41f95e1 100644 --- a/public/editor.js +++ b/public/editor.js @@ -1,65 +1,12 @@ -import { Compartment, EditorState } from 'https://esm.sh/@codemirror/state@6.7.6'; -import { EditorView, lineNumbers } from 'https://esm.sh/@codemirror/view@6.43.13?deps=@codemirror/state@6.7.6'; -import { defaultHighlightStyle, syntaxHighlighting } from 'https://esm.sh/@codemirror/language@6.12.4?deps=@codemirror/state@6.7.6,@codemirror/view@6.43.13'; -import { python } from 'https://esm.sh/@codemirror/lang-python@6.2.1?deps=@codemirror/state@6.7.6,@codemirror/view@6.43.13,@codemirror/language@6.12.4'; -import { oneDarkHighlightStyle } from 'https://esm.sh/@codemirror/theme-one-dark@6.1.3?deps=@codemirror/state@6.7.6,@codemirror/view@6.43.13,@codemirror/language@6.12.4'; - -const themePreference = window.matchMedia('(prefers-color-scheme: dark)'); -const highlightStyle = () => themePreference.matches ? oneDarkHighlightStyle : defaultHighlightStyle; -const highlightCompartment = new Compartment(); - -const textarea = document.getElementById('code-editor'); -const form = document.querySelector('form.runner-editor'); - -if (textarea && form) { - textarea.classList.add('textarea-fallback'); - - const view = new EditorView({ - state: EditorState.create({ - doc: textarea.value, - extensions: [ - python(), - highlightCompartment.of(syntaxHighlighting(highlightStyle())), - lineNumbers(), - EditorView.lineWrapping, - EditorView.contentAttributes.of({ - 'aria-label': textarea.getAttribute('aria-label') || 'Editable Python example code', - }), - EditorView.updateListener.of((update) => { - if (update.docChanged) textarea.value = update.state.doc.toString(); - }), - ], - }), - }); - - textarea.insertAdjacentElement('afterend', view.dom); - textarea.hidden = true; - themePreference.addEventListener?.('change', () => { - view.dispatch({ effects: highlightCompartment.reconfigure(syntaxHighlighting(highlightStyle())) }); - }); - - function resize() { - view.dom.style.minHeight = ''; - const minimum = Number.parseFloat(getComputedStyle(view.dom).minHeight) || 0; - view.dom.style.minHeight = `${Math.max(minimum, view.contentDOM.scrollHeight)}px`; - } - - function scheduleResize() { - requestAnimationFrame(resize); - } - - function setValue(value) { - view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: value } }); - textarea.value = value; - scheduleResize(); - } - - resize(); - - function syncTextarea() { - textarea.value = view.state.doc.toString(); - } - - form.addEventListener('submit', syncTextarea); - window.pythonByExampleEditor = { setValue, syncTextarea, resize: scheduleResize, focus: () => view.focus() }; -} +var gs=[],Uo=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Uo[i])e=i+1;else return!0;if(e==t)return!1}}function Fo(n){return n>=127462&&n<=127487}var _o=8205;function jo(n,e,t=!0,i=!0){return(t?Go:Kf)(n,e,i)}function Go(n,e,t){if(e==n.length)return e;e&&Zo(n.charCodeAt(e))&&Yo(n.charCodeAt(e-1))&&e--;let i=ms(n,e);for(e+=Ho(i);e=0&&Fo(ms(n,o));)r++,o-=2;if(r%2==0)break;e+=2}else break}return e}function Kf(n,e,t){for(;e>1;){let i=Go(n,e-2,t);if(i=56320&&n<57344}function Yo(n){return n>=55296&&n<56320}function Ho(n){return n<65536?1:2}var M=class n{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=Ut(this,e,t);let s=[];return this.decompose(0,e,s,2),i.length&&i.decompose(0,i.length,s,3),this.decompose(t,this.length,s,1),Ft.from(s,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=Ut(this,e,t);let i=[];return this.decompose(e,t,i,0),Ft.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),s=new wt(this),r=new wt(e);for(let o=t,l=t;;){if(s.next(o),r.next(o),o=0,s.lineBreak!=r.lineBreak||s.done!=r.done||s.value!=r.value)return!1;if(l+=s.value.length,s.done||l>=i)return!0}}iter(e=1){return new wt(this,e)}iterRange(e,t=this.length){return new on(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let s=this.line(e).from;i=this.iterRange(s,Math.max(s,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new ln(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?n.empty:e.length<=32?new de(e):Ft.from(de.split(e,[]))}},de=class n extends M{constructor(e,t=Jf(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.text[r],l=s+o.length;if((t?i:l)>=e)return new ys(s,l,i,o);s=l+1,i++}}decompose(e,t,i,s){let r=e<=0&&t>=this.length?this:new n(Ko(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(s&1){let o=i.pop(),l=rn(r.text,o.text.slice(),0,r.length);if(l.length<=32)i.push(new n(l,o.length+r.length));else{let a=l.length>>1;i.push(new n(l.slice(0,a)),new n(l.slice(a)))}}else i.push(r)}replace(e,t,i){if(!(i instanceof n))return super.replace(e,t,i);[e,t]=Ut(this,e,t);let s=rn(this.text,rn(i.text,Ko(this.text,0,e)),t),r=this.length+i.length-(t-e);return s.length<=32?new n(s,r):Ft.from(n.split(s,[]),r)}sliceString(e,t=this.length,i=` +`){[e,t]=Ut(this,e,t);let s="";for(let r=0,o=0;r<=t&&oe&&o&&(s+=i),er&&(s+=l.slice(Math.max(0,e-r),t-r)),r=a+1}return s}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],s=-1;for(let r of e)i.push(r),s+=r.length+1,i.length==32&&(t.push(new n(i,s)),i=[],s=-1);return s>-1&&t.push(new n(i,s)),t}},Ft=class n extends M{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.children[r],l=s+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,s);s=l+1,i=a+1}}decompose(e,t,i,s){for(let r=0,o=0;o<=t&&r=o){let h=s&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=Ut(this,e,t),i.lines=r&&t<=l){let a=o.replace(e-r,t-r,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let f=this.children.slice();return f[s]=a,new n(f,this.length-(t-e)+i.length)}return super.replace(r,l,a)}r=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` +`){[e,t]=Ut(this,e,t);let s="";for(let r=0,o=0;re&&r&&(s+=i),eo&&(s+=l.sliceString(e-o,t-o,i)),o=a+1}return s}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof n))return 0;let i=0,[s,r,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;s+=t,r+=t){if(s==o||r==l)return i;let a=this.children[s],h=e.children[r];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,s)=>i+s.length+1,-1)){let i=0;for(let d of e)i+=d.lines;if(i<32){let d=[];for(let p of e)p.flatten(d);return new de(d,t)}let s=Math.max(32,i>>5),r=s<<1,o=s>>1,l=[],a=0,h=-1,f=[];function c(d){let p;if(d.lines>r&&d instanceof n)for(let m of d.children)c(m);else d.lines>o&&(a>o||!a)?(u(),l.push(d)):d instanceof de&&a&&(p=f[f.length-1])instanceof de&&d.lines+p.lines<=32?(a+=d.lines,h+=d.length+1,f[f.length-1]=new de(p.text.concat(d.text),p.length+1+d.length)):(a+d.lines>s&&u(),a+=d.lines,h+=d.length+1,f.push(d))}function u(){a!=0&&(l.push(f.length==1?f[0]:n.from(f,h)),h=-1,a=f.length=0)}for(let d of e)c(d);return u(),l.length==1?l[0]:new n(l,t)}};M.empty=new de([""],0);function Jf(n){let e=-1;for(let t of n)e+=t.length+1;return e}function rn(n,e,t=0,i=1e9){for(let s=0,r=0,o=!0;r=t&&(a>i&&(l=l.slice(0,i-s)),s0?1:(e instanceof de?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,s=this.nodes[i],r=this.offsets[i],o=r>>1,l=s instanceof de?s.text.length:s.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((r&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` +`,this;e--}else if(s instanceof de){let a=s.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=s.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof de?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},on=class{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new wt(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:s}=this.cursor.next(e);return this.pos+=(s.length+e)*t,this.value=s.length<=i?s:t<0?s.slice(s.length-i):s.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}},ln=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:s}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=s,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<"u"&&(M.prototype[Symbol.iterator]=function(){return this.iter()},wt.prototype[Symbol.iterator]=on.prototype[Symbol.iterator]=ln.prototype[Symbol.iterator]=function(){return this});var ys=class{constructor(e,t,i,s){this.from=e,this.to=t,this.number=i,this.text=s}get length(){return this.to-this.from}};function Ut(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function K(n,e,t=!0,i=!0){return jo(n,e,t,i)}function ec(n){return n>=56320&&n<57344}function tc(n){return n>=55296&&n<56320}function lt(n,e){let t=n.charCodeAt(e);if(!tc(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return ec(i)?(t-55296<<10)+(i-56320)+65536:t}function nl(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Gt(n){return n<65536?1:2}var bs=/\r\n?|\n/,Y=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(Y||(Y={})),Ue=class n{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return r+(e-s);r+=l}else{if(i!=Y.Simple&&h>=e&&(i==Y.TrackDel&&se||i==Y.TrackBefore&&se))return null;if(h>e||h==e&&t<0&&!l)return e==s||t<0?r:r+a;r+=a}s=h}if(e>s)throw new RangeError(`Position ${e} is out of range for changeset of length ${s}`);return r}touchesRange(e,t=e){for(let i=0,s=0;i=0&&s<=t&&l>=e)return st?"cover":!0;s=l}return!1}toString(){let e="";for(let t=0;t=0?":"+s:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new n(e)}static create(e){return new n(e)}},oe=class n extends Ue{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Ss(this,(t,i,s,r,o)=>e=e.replace(s,s+(i-t),o),!1),e}mapDesc(e,t=!1){return xs(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let s=0,r=0;s=0){t[s]=l,t[s+1]=o;let a=s>>1;for(;i.length0&&rt(i,t,r.text),r.forward(f),l+=f}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let s=[],r=[],o=0,l=null;function a(f=!1){if(!f&&!s.length)return;ou||c<0||u>t)throw new RangeError(`Invalid change range ${c} to ${u} (in doc of length ${t})`);let p=d?typeof d=="string"?M.of(d.split(i||bs)):d:M.empty,m=p.length;if(c==u&&m==0)return;co&&te(s,c-o,-1),te(s,u-c,m),rt(r,s,p),o=u}}return h(e),a(!l),l}static empty(e){return new n(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let s=0;sl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(r.length==1)t.push(r[0],0);else{for(;i.length=0&&t<=0&&t==n[s+1]?n[s]+=e:s>=0&&e==0&&n[s]==0?n[s+1]+=t:i?(n[s]+=e,n[s+1]+=t):n.push(e,t)}function rt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(s,h,r,f,c),s=h,r=f}}}function xs(n,e,t,i=!1){let s=[],r=i?[]:null,o=new vt(n),l=new vt(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);te(s,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,f=o.len;for(;f;)if(l.ins==-1){let c=Math.min(f,l.len);h+=c,f-=c,l.forward(c)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),r.forward2(a),o.forward(a)}}}}var vt=class{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?M.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?M.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}},St=class n{constructor(e,t,i,s){this.from=e,this.to=t,this.flags=i,this.goalColumn=s}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,s;return this.empty?i=s=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),s=e.mapPos(this.to,-1)),i==this.from&&s==this.to?this:new n(i,s,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return b.range(e,t,void 0,void 0,i);let s=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return b.range(this.anchor,s,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return b.range(e.anchor,e.head)}static create(e,t,i,s){return new n(e,t,i,s)}},b=class n{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:n.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new n(e.ranges.map(t=>St.fromJSON(t)),e.main)}static single(e,t=e){return new n([n.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,s=0;ss.from-r.from),t=e.indexOf(i);for(let s=1;sr.head?n.range(a,l):n.range(l,a))}}return new n(e,t)}};function rl(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}var Ms=0,v=class n{constructor(e,t,i,s,r){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=s,this.id=Ms++,this.default=e([]),this.extensions=typeof r=="function"?r(this):r}get reader(){return this}static define(e={}){return new n(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Es),!!e.static,e.enables)}of(e){return new _t([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new _t(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new _t(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}};function Es(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}var _t=class{constructor(e,t,i,s){this.dependencies=e,this.facet=t,this.type=i,this.value=s,this.id=Ms++}dynamicSlot(e){var t;let i=this.value,s=this.facet.compareInput,r=this.id,o=e[r]>>1,l=this.type==2,a=!1,h=!1,f=[];for(let c of this.dependencies)c=="doc"?a=!0:c=="selection"?h=!0:(((t=e[c.id])!==null&&t!==void 0?t:1)&1)==0&&f.push(e[c.id]);return{create(c){return c.values[o]=i(c),1},update(c,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||ks(c,f)){let d=i(c);if(l?!Jo(d,c.values[o],s):!s(d,c.values[o]))return c.values[o]=d,1}return 0},reconfigure:(c,u)=>{let d,p=u.config.address[r];if(p!=null){let m=fn(u,p);if(this.dependencies.every(O=>O instanceof v?u.facet(O)===c.facet(O):O instanceof he?u.field(O,!1)==c.field(O,!1):!0)||(l?Jo(d=i(c),m,s):s(d=i(c),m)))return c.values[o]=m,0}else d=i(c);return c.values[o]=d,1}}}get extension(){return this}};function Jo(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),s=t.map(a=>a.type),r=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let f=0;fi===s),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(tn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,s)=>{let r=i.values[t],o=this.updateF(r,s);return this.compareF(r,o)?0:(i.values[t]=o,1)},reconfigure:(i,s)=>{let r=i.facet(tn),o=s.facet(tn),l;return(l=r.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):s.config.address[this.id]!=null?(i.values[t]=s.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,tn.of({field:this,create:e})]}get extension(){return this}},xt={lowest:4,low:3,default:2,high:1,highest:0};function bi(n){return e=>new an(e,n)}var at={highest:bi(xt.highest),high:bi(xt.high),default:bi(xt.default),low:bi(xt.low),lowest:bi(xt.lowest)},an=class{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}},jt=class n{of(e){return new xi(this,e)}reconfigure(e){return n.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}},xi=class{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}},hn=class n{constructor(e,t,i,s,r,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=s,this.staticValues=r,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let s=[],r=Object.create(null),o=new Map;for(let u of nc(e,t,o))u instanceof he?s.push(u):(r[u.facet.id]||(r[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of s)l[u.id]=h.length<<1,h.push(d=>u.slot(d));let f=i?.config.facets;for(let u in r){let d=r[u],p=d[0].facet,m=f&&f[u]||[];if(d.every(O=>O.type==0))if(l[p.id]=a.length<<1|1,Es(m,d))a.push(i.facet(p));else{let O=p.combine(d.map(y=>y.value));a.push(i&&p.compare(O,i.facet(p))?i.facet(p):O)}else{for(let O of d)O.type==0?(l[O.id]=a.length<<1|1,a.push(O.value)):(l[O.id]=h.length<<1,h.push(y=>O.dynamicSlot(y)));l[p.id]=h.length<<1,h.push(O=>ic(O,p,d))}}let c=h.map(u=>u(l));return new n(e,o,c,l,a,r)}};function nc(n,e,t){let i=[[],[],[],[],[]],s=new Map;function r(o,l){let a=s.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof xi&&t.delete(o.compartment)}if(s.set(o,l),Array.isArray(o))for(let h of o)r(h,l);else if(o instanceof xi){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),r(h,l)}else if(o instanceof an)r(o.inner,o.prec);else if(o instanceof he)i[l].push(o),o.provides&&r(o.provides,l);else if(o instanceof _t)i[l].push(o),o.facet.extensions&&r(o.facet.extensions,xt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(h==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);r(h,l)}}return r(n,xt.default),i.reduce((o,l)=>o.concat(l))}function Si(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let s=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|s}function fn(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}var ol=v.define(),ws=v.define({combine:n=>n.some(e=>e),static:!0}),ll=v.define({combine:n=>n.length?n[0]:void 0,static:!0}),al=v.define(),hl=v.define(),fl=v.define(),cl=v.define({combine:n=>n.length?n[0]:!1}),fe=class{constructor(e,t){this.type=e,this.value=t}static define(){return new vs}},vs=class{of(e){return new fe(this,e)}},Ts=class{constructor(e){this.map=e}of(e){return new W(this,e)}},W=class n{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new n(this.type,t)}is(e){return this.type==e}static define(e={}){return new Ts(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let s of e){let r=s.map(t);r&&i.push(r)}return i}};W.reconfigure=W.define();W.appendConfig=W.define();var G=class n{constructor(e,t,i,s,r,o){this.startState=e,this.changes=t,this.selection=i,this.effects=s,this.annotations=r,this.scrollIntoView=o,this._doc=null,this._state=null,i&&rl(i,t.newLength),r.some(l=>l.type==n.time)||(this.annotations=r.concat(n.time.of(Date.now())))}static create(e,t,i,s,r,o){return new n(e,t,i,s,r,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(n.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}};G.time=fe.define();G.userEvent=fe.define();G.addToHistory=fe.define();G.remote=fe.define();function sc(n,e){let t=[];for(let i=0,s=0;;){let r,o;if(i=n[i]))r=n[i++],o=n[i++];else if(s=0;s--){let r=i[s](n);r instanceof G?n=r:Array.isArray(r)&&r.length==1&&r[0]instanceof G?n=r[0]:n=dl(e,Ht(r),!1)}return n}function oc(n){let e=n.startState,t=e.facet(fl),i=n;for(let s=t.length-1;s>=0;s--){let r=t[s](n);r&&Object.keys(r).length&&(i=ul(i,Cs(e,r,n.changes.newLength),!0))}return i==n?n:G.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}var lc=[];function Ht(n){return n==null?lc:Array.isArray(n)?n:[n]}var re=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(re||(re={})),ac=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Qs;try{Qs=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function hc(n){if(Qs)return Qs.test(n);for(let e=0;e"\x80"&&(t.toUpperCase()!=t.toLowerCase()||ac.test(t)))return!0}return!1}function fc(n){return e=>{if(!/\S/.test(e))return re.Space;if(hc(e))return re.Word;for(let t=0;t-1)return re.Word;return re.Other}}var z=class n{constructor(e,t,i,s,r,o){this.config=e,this.doc=t,this.selection=i,this.values=s,this.status=e.statusTemplate.slice(),this.computeSlot=r,o&&(o._state=this);for(let l=0;ls.set(h,a)),t=null),s.set(l.value.compartment,l.value.extension)):l.is(W.reconfigure)?(t=null,i=l.value):l.is(W.appendConfig)&&(t=null,i=Ht(i).concat(l.value));let r;t?r=e.startState.values.slice():(t=hn.resolve(i,s,this),r=new n(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(ws)?e.newSelection:e.newSelection.asSingle();new n(t,e.newDoc,o,r,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:b.cursor(t.from+e.length,-1)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),s=this.changes(i.changes),r=[i.range],o=Ht(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return n.create({doc:e.doc,selection:b.fromJSON(e.selection),extensions:t.extensions?s.concat([t.extensions]):s})}static create(e={}){let t=hn.resolve(e.extensions||[],new Map),i=e.doc instanceof M?e.doc:M.of((e.doc||"").split(t.staticFacet(n.lineSeparator)||bs)),s=e.selection?e.selection instanceof b?e.selection:b.single(e.selection.anchor,e.selection.head):b.single(0);return rl(s,i.length),t.staticFacet(ws)||(s=s.asSingle()),new n(t,i,s,t.dynamicSlots.map(()=>null),(r,o)=>o.create(r),null)}get tabSize(){return this.facet(n.tabSize)}get lineBreak(){return this.facet(n.lineSeparator)||` +`}get readOnly(){return this.facet(cl)}phrase(e,...t){for(let i of this.facet(n.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,s)=>{if(s=="$")return"$";let r=+(s||1);return!r||r>t.length?i:t[r-1]})),e}languageDataAt(e,t,i=-1){let s=[];for(let r of this.facet(ol))for(let o of r(this,t,i))Object.prototype.hasOwnProperty.call(o,e)&&s.push(o[e]);return s}charCategorizer(e){let t=this.languageDataAt("wordChars",e);return fc(t.length?t[0]:"")}wordAt(e){let{text:t,from:i,length:s}=this.doc.lineAt(e),r=this.charCategorizer(e),o=e-i,l=e-i;for(;o>0;){let a=K(t,o,!1);if(r(t.slice(a,o))!=re.Word)break;o=a}for(;ln.length?n[0]:4});z.lineSeparator=ll;z.readOnly=cl;z.phrases=v.define({compare(n,e){let t=Object.keys(n),i=Object.keys(e);return t.length==i.length&&t.every(s=>n[s]==e[s])}});z.languageData=ol;z.changeFilter=al;z.transactionFilter=hl;z.transactionExtender=fl;jt.reconfigure=W.define();function Tt(n,e,t={}){let i={};for(let s of n)for(let r of Object.keys(s)){let o=s[r],l=i[r];if(l===void 0)i[r]=o;else if(!(l===o||o===void 0))if(Object.hasOwnProperty.call(t,r))i[r]=t[r](l,o);else throw new Error("Config merge conflict for field "+r)}for(let s in e)i[s]===void 0&&(i[s]=e[s]);return i}var Oe=class{eq(e){return this==e}range(e,t=e){return ki.create(e,t,this)}};Oe.prototype.startSide=Oe.prototype.endSide=0;Oe.prototype.point=!1;Oe.prototype.mapMode=Y.TrackDel;function Ds(n,e){return n==e||n.constructor==e.constructor&&n.eq(e)}var ki=class n{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new n(e,t,i)}};function Ps(n,e){return n.from-e.from||n.value.startSide-e.value.startSide}var As=class n{constructor(e,t,i,s){this.from=e,this.to=t,this.value=i,this.maxPoint=s}get length(){return Xt(this.to)}findIndex(e,t,i,s=0){let r=i?this.to:this.from;for(let o=s,l=r.length;;){if(o==l)return o;let a=o+l>>1,h=r[a]-e||(i?this.value[a].endSide:this.value[a].startSide)-t;if(a==o)return h>=0?o:l;h>=0?l=a:o=a+1}}between(e,t,i,s){for(let r=this.findIndex(t,-1e9,!0),o=this.findIndex(i,1e9,!1,r);rO||m==O&&u.startSide>0&&u.endSide<=0)continue;if(!((O-m||u.endSide-u.startSide)<0))if(h<0&&(h=m),u.point&&(f=Math.max(f,O-m)),(m-i||u.startSide-s)>=0)o.push(u),l.push(m-h),a.push(O-h),i=O,s=u.endSide;else{if(m==O)for(let y=o.length;y>0;y--){if((m-(a[y-1]+h)||u.startSide-o[y-1].endSide)>=0){o.splice(y,0,u),l.splice(y,0,m-h),a.splice(y,0,O-h);continue e}if((m-(l[y-1]+h)||u.endSide-o[y-1].startSide)>0)break}r(m,O,u)}}return{mapped:o.length?new n(l,a,o,f):null,pos:h}}},B=class n{constructor(e,t,i,s){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=s}static create(e,t,i,s){return new n(e,t,i,s)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:i=!1,filterFrom:s=0,filterTo:r=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(i&&(t=t.slice().sort(Ps)),this.isEmpty)return t.length?n.of(t):this;let l=new cn(this,null,-1).goto(0),a=0,h=[],f=new ot;for(;l.value||a=0){let c=t[a++];f.addInner(c.from,c.to,c.value,!1)||h.push(c)}else l.rangeIndex==1&&l.chunkIndexthis.chunkEnd(l.chunkIndex)||rl.to||r{r||(r=new ot),r.addRange(a,h,f,!1)};for(let a=0;a=r&&e<=r+o.length&&o.between(r,e-r,t-r,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return wi.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return wi.from(e).goto(t)}static compare(e,t,i,s,r=-1){let o=e.filter(c=>c.maxPoint>0||!c.isEmpty&&c.maxPoint>=r),l=t.filter(c=>c.maxPoint>0||!c.isEmpty&&c.maxPoint>=r),a=el(o,l,i),h=new kt(o,a,r),f=new kt(l,a,r);i.iterGaps((c,u,d)=>tl(h,c,f,u,d,s)),i.empty&&i.length==0&&tl(h,0,f,0,0,s)}static eq(e,t,i=0,s){s==null&&(s=999999999);let r=e.filter(f=>!f.isEmpty&&t.indexOf(f)<0),o=t.filter(f=>!f.isEmpty&&e.indexOf(f)<0);if(r.length!=o.length)return!1;if(!r.length)return!0;let l=el(r,o),a=new kt(r,l,0).goto(i),h=new kt(o,l,0).goto(i);for(;;){if(a.to!=h.to||!Rs(a.active,h.active)||a.point&&(!h.point||!Ds(a.point,h.point)))return!1;if(a.to>s)return!0;a.next(),h.next()}}static spans(e,t,i,s,r=-1){let o=new kt(e,null,r).goto(t),l=t,a=o.openStart;for(;;){let h=Math.min(o.to,i);if(o.point){let f=o.activeForPoint(o.to),c=o.pointFroml&&(s.span(l,h,o.active,a),a=o.openEnd(h));if(o.to>i)return a+(o.point&&o.to>i?1:0);l=o.to,o.next()}}static of(e,t=!1){let i=new ot;for(let s of e instanceof ki?[e]:t?cc(e):e)i.add(s.from,s.to,s.value);return i.finish()}static join(e){if(!e.length)return n.empty;let t=Xt(e);for(let i=e.length-2;i>=0;i--)for(let s=e[i];s!=n.empty;s=s.nextLayer)t=new n(s.chunkPos,s.chunk,t,Math.max(s.maxPoint,t.maxPoint));return t}};B.empty=new B([],[],null,-1);function Xt(n){return n[n.length-1]}function cc(n){if(n.length>1)for(let e=n[0],t=1;t0)return n.slice().sort(Ps);e=i}return n}B.empty.nextLayer=B.empty;var ot=class n{finishChunk(e){this.chunks.push(new As(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(e,t,i){this.addRange(e,t,i,!0)}addRange(e,t,i,s){this.addInner(e,t,i,s)||(this.nextLayer||(this.nextLayer=new n)).addRange(e,t,i,s)}addInner(e,t,i,s){let r=e-this.lastTo||i.startSide-this.last.endSide;if(s&&r<=0&&(e-this.lastFrom||i.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return r<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=i,this.lastFrom=e,this.lastTo=t,this.value.push(i),i.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let i=t.value.length-1;return this.last=t.value[i],this.lastFrom=t.from[i]+e,this.lastTo=t.to[i]+e,!0}finish(){return this.finishInner(B.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=B.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}};function el(n,e,t){let i=new Map;for(let r of n)for(let o=0;o=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex=i&&s.push(new cn(o,t,i,r));return s.length==1?s[0]:new n(s)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let i of this.heap)i.goto(e,t);for(let i=this.heap.length>>1;i>=0;i--)Os(this.heap,i);return this.next(),this}forward(e,t){for(let i of this.heap)i.forward(e,t);for(let i=this.heap.length>>1;i>=0;i--)Os(this.heap,i);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),Os(this.heap,0)}}};function Os(n,e){for(let t=n[e];;){let i=(e<<1)+1;if(i>=n.length)break;let s=n[i];if(i+1=0&&(s=n[i+1],i++),t.compare(s)<0)break;n[i]=t,n[e]=s,e=i}}var kt=class{constructor(e,t,i){this.minPoint=i,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=wi.from(e,t,i)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){nn(this.active,e),nn(this.activeTo,e),nn(this.activeRank,e),this.minActive=il(this.active,this.activeTo)}addActive(e){let t=0,{value:i,to:s,rank:r}=this.cursor;for(;t0;)t++;sn(this.active,t,i),sn(this.activeTo,t,s),sn(this.activeRank,t,r),e&&sn(e,t,this.cursor.from),this.minActive=il(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let i=this.openStart<0?[]:null;for(;;){let s=this.minActive;if(s>-1&&(this.activeTo[s]-this.cursor.from||this.active[s].endSide-this.cursor.startSide)<0){if(this.activeTo[s]>e){this.to=this.activeTo[s],this.endSide=this.active[s].endSide;break}this.removeActive(s),i&&nn(i,s)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let r=this.cursor.value;if(!r.point)this.addActive(i),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from=0&&i[s]=0&&!(this.activeRank[i]e||this.activeTo[i]==e&&this.active[i].endSide>=this.point.endSide)&&t.push(this.active[i]);return t.reverse()}openEnd(e){let t=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>e;i--)t++;return t}};function tl(n,e,t,i,s,r){n.goto(e),t.goto(i);let o=i+s,l=i,a=i-e,h=!!r.boundChange;for(let f=!1;;){let c=n.to+a-t.to,u=c||n.endSide-t.endSide,d=u<0?n.to+a:t.to,p=Math.min(d,o);if(n.point||t.point?(n.point&&t.point&&Ds(n.point,t.point)&&Rs(n.activeForPoint(n.to),t.activeForPoint(t.to))||r.comparePoint(l,p,n.point,t.point),f=!1):(f&&(r.boundChange(l),f=!1),p>l&&!Rs(n.active,t.active)&&r.compareRange(l,p,n.active,t.active),h&&po)break;l=d,u<=0&&n.next(),u>=0&&t.next()}}function Rs(n,e){if(n.length!=e.length)return!1;for(let t=0;t=e;i--)n[i+1]=n[i];n[e]=t}function il(n,e){let t=-1,i=1e9;for(let s=0;s=e)return s;if(s==n.length)break;r+=n.charCodeAt(s)==9?t-r%t:1,s=K(n,s)}return i===!0?-1:n.length}var ml=typeof Symbol>"u"?"__\u037C":Symbol.for("\u037C"),Bs=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),gl=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{},ye=class{constructor(e,t){this.rules=[];let{finish:i}=t||{};function s(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function r(o,l,a,h){let f=[],c=/^@(\w+)\b/.exec(o[0]),u=c&&c[1]=="keyframes";if(c&&l==null)return a.push(o[0]+";");for(let d in l){let p=l[d];if(/&/.test(d))r(d.split(/,\s*/).map(m=>o.map(O=>m.replace(/&/,O))).reduce((m,O)=>m.concat(O)),p,a);else if(p&&typeof p=="object"){if(!c)throw new RangeError("The value of a property ("+d+") should be a primitive value.");r(s(d),p,f,u)}else p!=null&&f.push(d.replace(/_.*/,"").replace(/[A-Z]/g,m=>"-"+m.toLowerCase())+": "+p+";")}(f.length||u)&&a.push((i&&!c&&!h?o.map(i):o).join(", ")+" {"+f.join(" ")+"}")}for(let o in e)r(s(o),e[o],this.rules)}getRules(){return this.rules.join(` +`)}static newName(){let e=gl[ml]||1;return gl[ml]=e+1,"\u037C"+e.toString(36)}static mount(e,t,i){let s=e[Bs],r=i&&i.nonce;s?r&&s.setNonce(r):s=new qs(e,r),s.mount(Array.isArray(t)?t:[t],e)}},Ol=new Map,qs=class{constructor(e,t){let i=e.ownerDocument||e,s=i.defaultView;if(!e.head&&e.adoptedStyleSheets&&s.CSSStyleSheet){let r=Ol.get(i);if(r)return e[Bs]=r;this.sheet=new s.CSSStyleSheet,Ol.set(i,this)}else this.styleTag=i.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[Bs]=this}mount(e,t){let i=this.sheet,s=0,r=0,o=!1;for(let l=0;l-1&&(this.modules.splice(h,1),o=!0,r--,h=-1),h==-1){if(this.modules.splice(r++,0,a),o=!0,i)for(let f=0;f",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},uc=typeof navigator<"u"&&/Mac/.test(navigator.platform),dc=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(Z=0;Z<10;Z++)je[48+Z]=je[96+Z]=String(Z);var Z;for(Z=1;Z<=24;Z++)je[Z+111]="F"+Z;var Z;for(Z=65;Z<=90;Z++)je[Z]=String.fromCharCode(Z+32),Zt[Z]=String.fromCharCode(Z);var Z;for(un in je)Zt.hasOwnProperty(un)||(Zt[un]=je[un]);var un;function yl(n){var e=uc&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||dc&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?Zt:je)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}var le=typeof navigator<"u"?navigator:{userAgent:"",vendor:"",platform:""},Xs=typeof document<"u"?document:{documentElement:{style:{}}},Fs=/Edge\/(\d+)/.exec(le.userAgent),jl=/MSIE \d/.test(le.userAgent),_s=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(le.userAgent),Ln=!!(jl||_s||Fs),bl=!Ln&&/gecko\/(\d+)/i.test(le.userAgent),Ws=!Ln&&/Chrome\/(\d+)/.exec(le.userAgent),Sl="webkitFontSmoothing"in Xs.documentElement.style,Hs=!Ln&&/Apple Computer/.test(le.vendor),xl=Hs&&(/Mobile\/\w+/.test(le.userAgent)||le.maxTouchPoints>2),x={mac:xl||/Mac/.test(le.platform),windows:/Win/.test(le.platform),linux:/Linux|X11/.test(le.platform),ie:Ln,ie_version:jl?Xs.documentMode||6:_s?+_s[1]:Fs?+Fs[1]:0,gecko:bl,gecko_version:bl?+(/Firefox\/(\d+)/.exec(le.userAgent)||[0,0])[1]:0,chrome:!!Ws,chrome_version:Ws?+Ws[1]:0,ios:xl,android:/Android\b/.test(le.userAgent),webkit:Sl,webkit_version:Sl?+(/\bAppleWebKit\/(\d+)/.exec(le.userAgent)||[0,0])[1]:0,safari:Hs,safari_version:Hs?+(/\bVersion\/(\d+(\.\d+)?)/.exec(le.userAgent)||[0,0])[1]:0,tabSize:Xs.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};function Rr(n,e){for(let t in n)t=="class"&&e.class?e.class+=" "+n.class:t=="style"&&e.style?e.style+=";"+n.style:e[t]=n[t];return e}var wn=Object.create(null);function Mr(n,e,t){if(n==e)return!0;n||(n=wn),e||(e=wn);let i=Object.keys(n),s=Object.keys(e);if(i.length-(t&&i.indexOf(t)>-1?1:0)!=s.length-(t&&s.indexOf(t)>-1?1:0))return!1;for(let r of i)if(r!=t&&(s.indexOf(r)==-1||n[r]!==e[r]))return!1;return!0}function pc(n,e){for(let t=n.attributes.length-1;t>=0;t--){let i=n.attributes[t].name;e[i]==null&&n.removeAttribute(i)}for(let t in e){let i=e[t];t=="style"?n.style.cssText=i:n.getAttribute(t)!=i&&n.setAttribute(t,i)}}function kl(n,e,t){let i=!1;if(e)for(let s in e)t&&s in t||(i=!0,s=="style"?n.style.cssText="":n.removeAttribute(s));if(t)for(let s in t)e&&e[s]==t[s]||(i=!0,s=="style"?n.style.cssText=t[s]:n.setAttribute(s,t[s]));return i}function mc(n){let e=Object.create(null);for(let t=0;t0?3e8:-4e8:t>0?1e8:-1e8,new At(e,t,t,i,e.widget||null,!1)}static replace(e){let t=!!e.block,i,s;if(e.isBlockGap)i=-5e8,s=4e8;else{let{start:r,end:o}=Gl(e,t);i=(r?t?-3e8:-1:5e8)-1,s=(o?t?2e8:1:-6e8)+1}return new At(e,i,s,t,e.widget||null,!0)}static line(e){return new qi(e)}static set(e,t=!1){return B.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}};q.none=B.empty;var Bi=class n extends q{constructor(e){let{start:t,end:i}=Gl(e);super(t?-1:5e8,i?1:-6e8,null,e),this.tagName=e.tagName||"span",this.attrs=e.class&&e.attributes?Rr(e.attributes,{class:e.class}):e.class?{class:e.class}:e.attributes||wn}eq(e){return this==e||e instanceof n&&this.tagName==e.tagName&&Mr(this.attrs,e.attrs)}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}};Bi.prototype.point=!1;var qi=class n extends q{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof n&&this.spec.class==e.spec.class&&Mr(this.spec.attributes,e.spec.attributes)}range(e,t=e){if(t!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,t)}};qi.prototype.mapMode=Y.TrackBefore;qi.prototype.point=!0;var At=class n extends q{constructor(e,t,i,s,r,o){super(t,i,r,e),this.block=s,this.isReplace=o,this.mapMode=s?t<=0?Y.TrackBefore:Y.TrackAfter:Y.TrackDel}get type(){return this.startSide!=this.endSide?ue.WidgetRange:this.startSide<=0?ue.WidgetBefore:ue.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof n&&gc(this.widget,e.widget)&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide}range(e,t=e){if(this.isReplace&&(e>t||e==t&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&t!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,t)}};At.prototype.point=!0;function Gl(n,e=!1){let{inclusiveStart:t,inclusiveEnd:i}=n;return t==null&&(t=n.inclusive),i==null&&(i=n.inclusive),{start:t??e,end:i??e}}function gc(n,e){return n==e||!!(n&&e&&n.compare(e))}function ti(n,e,t,i=0){let s=t.length-1;s>=0&&t[s]+i>=n?t[s]=Math.max(t[s],e):t.push(n,e)}var vn=class n extends Oe{constructor(e,t,i){super(),this.tagName=e,this.attributes=t,this.rank=i}eq(e){return e==this||e instanceof n&&this.tagName==e.tagName&&Mr(this.attributes,e.attributes)}static create(e){return new n(e.tagName,e.attributes||wn,e.rank==null?50:Math.max(0,Math.min(e.rank,100)))}static set(e,t=!1){return B.of(e,t)}};vn.prototype.startSide=vn.prototype.endSide=-1;function Wi(n){let e;return n.nodeType==11?e=n.getSelection?n:n.ownerDocument:e=n,e.getSelection()}function Us(n,e){return e?n==e||n.contains(e.nodeType!=1?e.parentNode:e):!1}function Ci(n,e){if(!e.anchorNode)return!1;try{return Us(n,e.anchorNode)}catch{return!1}}function Sn(n){return n.nodeType==3?$i(n,0,n.nodeValue.length).getClientRects():n.nodeType==1?n.getClientRects():[]}function Qi(n,e,t,i){return t?wl(n,e,t,i,-1)||wl(n,e,t,i,1):!1}function ct(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e}function Tn(n){return n.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(n.nodeName)}function wl(n,e,t,i,s){for(;;){if(n==t&&e==i)return!0;if(e==(s<0?0:Ke(n))){if(n.nodeName=="DIV")return!1;let r=n.parentNode;if(!r||r.nodeType!=1)return!1;e=ct(n)+(s<0?0:1),n=r}else if(n.nodeType==1){if(n=n.childNodes[e+(s<0?-1:0)],n.nodeType==1&&n.contentEditable=="false")return!1;e=s<0?Ke(n):0}else return!1}}function Ke(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Cn(n,e){let{left:t,right:i}=n;if(t==i)return n;let s=e?t:i;return{left:s,right:s,top:n.top,bottom:n.bottom}}function Oc(n){let e=n.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.innerWidth,top:0,bottom:n.innerHeight}}function Zl(n,e){let t=e.width/n.offsetWidth,i=e.height/n.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-n.offsetWidth)<1)&&(t=1),(i>.995&&i<1.005||!isFinite(i)||Math.abs(e.height-n.offsetHeight)<1)&&(i=1),{scaleX:t,scaleY:i}}function yc(n,e,t,i,s,r,o,l){let a=n.ownerDocument,h=a.defaultView||window;for(let f=n,c=!1;f&&!c;)if(f.nodeType==1){let u,d=f==a.body,p=1,m=1;if(d)u=Oc(h);else{if(/^(fixed|sticky)$/.test(getComputedStyle(f).position)&&(c=!0),f.scrollHeight<=f.clientHeight&&f.scrollWidth<=f.clientWidth){f=f.assignedSlot||f.parentNode;continue}let w=f.getBoundingClientRect();({scaleX:p,scaleY:m}=Zl(f,w)),u={left:w.left,right:w.left+f.clientWidth*p,top:w.top,bottom:w.top+f.clientHeight*m}}let O=0,y=0;if(s=="nearest")e.top0&&e.bottom>u.bottom+y&&(y=e.bottom-u.bottom+o)):e.bottom>u.bottom-o&&(y=e.bottom-u.bottom+o,t<0&&e.top-y0&&e.right>u.right+O&&(O=e.right-u.right+r)):e.right>u.right-r&&(O=e.right-u.right+r,t<0&&e.leftu.bottom||e.leftu.right)&&(e={left:Math.max(e.left,u.left),right:Math.min(e.right,u.right),top:Math.max(e.top,u.top),bottom:Math.min(e.bottom,u.bottom)}),f=f.assignedSlot||f.parentNode}else if(f.nodeType==11)f=f.host;else break}function Yl(n,e=!0){let t=n.ownerDocument,i=null,s=null;for(let r=n.parentNode;r&&!(r==t.body||(!e||i)&&s);)if(r.nodeType==1)!s&&r.scrollHeight>r.clientHeight&&(s=r),e&&!i&&r.scrollWidth>r.clientWidth&&(i=r),r=r.assignedSlot||r.parentNode;else if(r.nodeType==11)r=r.host;else break;return{x:i,y:s}}var js=class{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:t,focusNode:i}=e;this.set(t,Math.min(e.anchorOffset,t?Ke(t):0),i,Math.min(e.focusOffset,i?Ke(i):0))}set(e,t,i,s){this.anchorNode=e,this.anchorOffset=t,this.focusNode=i,this.focusOffset=s}};function Kl(n){let e=[];for(let t=n;t;t=t.nodeType==11?t.host:t.parentNode)t.nodeType==1&&e.push({node:t,left:t.scrollLeft,top:t.scrollTop});return e}function Jl(n,e=!0){for(let{node:t,left:i,top:s}of n)e&&t.scrollTop!=s&&(t.scrollTop=s),t.scrollLeft!=i&&(t.scrollLeft=i)}var Qt=null;x.safari&&x.safari_version>=26&&(Qt=!1);function ea(n){if(n.setActive)return n.setActive();if(Qt)return n.focus(Qt);let e=Kl(n);n.focus(Qt==null?{get preventScroll(){return Qt={preventScroll:!0},!0}}:void 0),Qt||(Qt=!1,Jl(e))}var vl;function $i(n,e,t=e){let i=vl||(vl=document.createRange());return i.setEnd(n,t),i.setStart(n,e),i}function ii(n,e,t,i){let s={key:e,code:e,keyCode:t,which:t,cancelable:!0};i&&({altKey:s.altKey,ctrlKey:s.ctrlKey,shiftKey:s.shiftKey,metaKey:s.metaKey}=i);let r=new KeyboardEvent("keydown",s);r.synthetic=!0,n.dispatchEvent(r);let o=new KeyboardEvent("keyup",s);return o.synthetic=!0,n.dispatchEvent(o),r.defaultPrevented||o.defaultPrevented}function bc(n){for(;n;){if(n&&(n.nodeType==9||n.nodeType==11&&n.host))return n;n=n.assignedSlot||n.parentNode}return null}function Sc(n,e){let t=e.focusNode,i=e.focusOffset;if(!t||e.anchorNode!=t||e.anchorOffset!=i)return!1;for(i=Math.min(i,Ke(t));;)if(i){if(t.nodeType!=1)return!1;let s=t.childNodes[i-1];s.contentEditable=="false"?i--:(t=s,i=Ke(t))}else{if(t==n)return!0;i=ct(t),t=t.parentNode}}function ta(n){return n instanceof Window?n.pageYOffset>Math.max(0,n.document.documentElement.scrollHeight-n.innerHeight-4):n.scrollTop>Math.max(1,n.scrollHeight-n.clientHeight-4)}function ia(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i>0)return{node:t,offset:i};if(t.nodeType==1&&i>0){if(t.contentEditable=="false")return null;t=t.childNodes[i-1],i=Ke(t)}else if(t.parentNode&&!Tn(t))i=ct(t),t=t.parentNode;else return null}}function na(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i=t){if(l.level==i)return o;(r<0||(s!=0?s<0?l.fromt:e[r].level>l.level))&&(r=o)}}if(r<0)throw new RangeError("Index out of range");return r}};function oa(n,e){if(n.length!=e.length)return!1;for(let t=0;t=0;m-=3)if(We[m+1]==-d){let O=We[m+2],y=O&2?s:O&4?O&1?r:s:0;y&&(L[c]=L[We[m]]=y),l=m;break}}else{if(We.length==189)break;We[l++]=c,We[l++]=u,We[l++]=a}else if((p=L[c])==2||p==1){let m=p==s;a=m?0:1;for(let O=l-3;O>=0;O-=3){let y=We[O+2];if(y&2)break;if(m)We[O+2]|=2;else{if(y&4)break;We[O+2]|=4}}}}}function Cc(n,e,t,i){for(let s=0,r=i;s<=t.length;s++){let o=s?t[s-1].to:n,l=sa;)p==O&&(p=t[--m].from,O=m?t[m-1].to:n),L[--p]=d;a=f}else r=h,a++}}}function Zs(n,e,t,i,s,r,o){let l=i%2?2:1;if(i%2==s%2)for(let a=e,h=0;aa&&o.push(new xe(a,m.from,d));let O=m.direction==Rt!=!(d%2);Ys(n,O?i+1:i,s,m.inner,m.from,m.to,o),a=m.to}p=m.to}else{if(p==t||(f?L[p]!=l:L[p]==l))break;p++}u?Zs(n,a,p,i+1,s,u,o):ae;){let f=!0,c=!1;if(!h||a>r[h-1].to){let m=L[a-1];m!=l&&(f=!1,c=m==16)}let u=!f&&l==1?[]:null,d=f?i:i+1,p=a;e:for(;;)if(h&&p==r[h-1].to){if(c)break e;let m=r[--h];if(!f)for(let O=m.from,y=h;;){if(O==e)break e;if(y&&r[y-1].to==O)O=r[--y].from;else{if(L[O-1]==l)break e;break}}if(u)u.push(m);else{m.toL.length;)L[L.length]=256;let i=[],s=e==Rt?0:1;return Ys(n,s,s,t,0,n.length,i),i}function la(n){return[new xe(0,n,0)]}var aa="";function Pc(n,e,t,i,s){var r;if(!n.length)return null;let o=i.head-n.from,l;if(i.head==n.from&&i.assoc<0){if(!s)return null;o=e[l=0].side(!1,t)}else if(i.head==n.to&&i.assoc>0){if(s)return null;o=e[l=e.length-1].side(!0,t)}else l=xe.find(e,o,(r=i.bidiLevel)!==null&&r!==void 0?r:-1,i.assoc);let a=e[l],h=a.side(s,t);if(o==h){let u=l+=s?1:-1;if(u<0||u>=e.length)return null;a=e[l=u],o=a.side(!s,t),h=a.side(s,t)}let f=K(n.text,o,a.forward(s,t));(fa.to)&&(f=h),aa=n.text.slice(Math.min(o,f),Math.max(o,f));let c=l==(s?e.length-1:0)?null:e[l+(s?1:-1)];if(f==h){if(!c)return s?b.cursor(n.to,1):b.cursor(n.from,-1);if(c.level+(s?0:1)n.some(e=>e)}),Rc=v.define({combine:n=>n.some(e=>e)}),ga=v.define(),Pi=class n{constructor(e,t,i,s,r,o=!1){this.range=e,this.y=t,this.x=i,this.yMargin=s,this.xMargin=r,this.isSnapshot=o}map(e){return e.empty?this:new n(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(e){return this.range.to<=e.doc.length?this:new n(b.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}},dn=W.define({map:(n,e)=>n.map(e)}),Oa=W.define();function ke(n,e,t){let i=n.facet(ua);i.length?i[0](e):window.onerror&&window.onerror(String(e),t,void 0,void 0,e)||(t?console.error(t+":",e):console.error(e))}var Ge=v.define({combine:n=>n.length?n[0]:!0}),Mc=0,Kt=v.define({combine(n){return n.filter((e,t)=>{for(let i=0;i{let a=[];return o&&a.push(zn.of(h=>{let f=h.plugin(l);return f?o(f):q.none})),r&&a.push(r(l)),a})}static fromClass(e,t){return n.define((i,s)=>new e(i,s),t)}},Ai=class{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}get plugin(){return this.spec&&this.spec.plugin}update(e){if(this.value){if(this.mustUpdate){let t=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(t)}catch(i){if(ke(t.state,i,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.plugin.create(e,this.spec.arg)}catch(t){ke(e.state,t,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var t;if(!((t=this.value)===null||t===void 0)&&t.destroy)try{this.value.destroy()}catch(i){ke(e.state,i,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}},ya=v.define(),qr=v.define(),zn=v.define(),ba=v.define(),Wr=v.define(),Li=v.define(),Sa=v.define();function Tl(n,e){let t=n.state.facet(Sa);if(!t.length)return t;let i=t.map(r=>r instanceof Function?r(n):r),s=[];return B.spans(i,e.from,e.to,{point(){},span(r,o,l,a){let h=r-e.from,f=o-e.from,c=s;for(let u=l.length-1;u>=0;u--,a--){let d=l[u].spec.bidiIsolate,p;if(d==null&&(d=Ac(e.text,h,f)),a>0&&c.length&&(p=c[c.length-1]).to==h&&p.direction==d)p.to=f,c=p.inner;else{let m={from:h,to:f,direction:d,inner:[]};c.push(m),c=m.inner}}}}),s}var xa=v.define();function ka(n){let e=0,t=0,i=0,s=0;for(let r of n.state.facet(xa)){let o=r(n);o&&(o.left!=null&&(e=Math.max(e,o.left)),o.right!=null&&(t=Math.max(t,o.right)),o.top!=null&&(i=Math.max(i,o.top)),o.bottom!=null&&(s=Math.max(s,o.bottom)))}return{left:e,right:t,top:i,bottom:s}}var vi=v.define(),Pe=class n{constructor(e,t,i,s){this.fromA=e,this.toA=t,this.fromB=i,this.toB=s}join(e){return new n(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let t=e.length,i=this;for(;t>0;t--){let s=e[t-1];if(!(s.fromA>i.toA)){if(s.toAs.push(new Pe(r,o,l,a))),this.changedRanges=s}static create(e,t,i){return new n(e,t,i)}get viewportChanged(){return(this.flags&4)>0}get viewportMoved(){return(this.flags&8)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&18)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}},Ec=[],_=class{constructor(e,t,i=0){this.dom=e,this.length=t,this.flags=i,this.parent=null,e.cmTile=this}get breakAfter(){return this.flags&1}get children(){return Ec}isWidget(){return!1}get isHidden(){return!1}isComposite(){return!1}isLine(){return!1}isText(){return!1}isBlock(){return!1}get domAttrs(){return null}sync(e){if(this.flags|=2,this.flags&4){this.flags&=-5;let t=this.domAttrs;t&&pc(this.dom,t)}}toString(){return this.constructor.name+(this.children.length?`(${this.children})`:"")+(this.breakAfter?"#":"")}destroy(){this.parent=null}setDOM(e){this.dom=e,e.cmTile=this}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e,t=this.posAtStart){let i=t;for(let s of this.children){if(s==e)return i;i+=s.length+s.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}covers(e){return!0}coordsIn(e,t,i){return null}domPosFor(e,t){let i=ct(this.dom),s=this.length?e>0:t>0;return new $e(this.parent.dom,i+(s?1:0),e==0||e==this.length)}markDirty(e){this.flags&=-3,e&&(this.flags|=4),this.parent&&this.parent.flags&2&&this.parent.markDirty(!1)}get overrideDOMText(){return null}get root(){for(let e=this;e;e=e.parent)if(e instanceof si)return e;return null}static get(e){return e.cmTile}},ni=class extends _{constructor(e){super(e,0),this._children=[]}isComposite(){return!0}get children(){return this._children}get lastChild(){return this.children.length?this.children[this.children.length-1]:null}append(e){this.children.push(e),e.parent=this}sync(e){if(this.flags&2)return;super.sync(e);let t=this.dom,i=null,s,r=e?.node==t?e:null,o=0;for(let l of this.children){if(l.sync(e),o+=l.length+l.breakAfter,s=i?i.nextSibling:t.firstChild,r&&s!=l.dom&&(r.written=!0),l.dom.parentNode==t)for(;s&&s!=l.dom;)s=Cl(s);else t.insertBefore(l.dom,s);i=l.dom}for(s=i?i.nextSibling:t.firstChild,r&&s&&(r.written=!0);s;)s=Cl(s);this.length=o}};function Cl(n){let e=n.nextSibling;return n.parentNode.removeChild(n),e}var si=class extends ni{constructor(e,t){super(t),this.view=e}owns(e){for(;e;e=e.parent)if(e==this)return!0;return!1}isBlock(){return!0}nearest(e){for(;;){if(!e)return null;let t=_.get(e);if(t&&this.owns(t))return t;e=e.parentNode}}blockTiles(e){for(let t=[],i=this,s=0,r=0;;)if(s==i.children.length){if(!t.length)return;i=i.parent,i.breakAfter&&r++,s=t.pop()}else{let o=i.children[s++];if(o instanceof Ze)t.push(s),i=o,s=0;else{let l=r+o.length,a=e(o,r);if(a!==void 0)return a;r=l+o.breakAfter}}}resolveBlock(e,t){let i,s=-1,r,o=-1;if(this.blockTiles((l,a)=>{let h=a+l.length;if(e>=a&&e<=h){if(l.isWidget()&&t>=-1&&t<=1){if(l.flags&32)return!0;l.flags&16&&(i=void 0)}(ae||e==a&&(t>1?l.length:l.covers(-1)))&&(!r||!l.isWidget()&&r.isWidget())&&(r=l,o=e-a)}}),!i&&!r)throw new Error("No tile at position "+e);return i&&t<0||!r?{tile:i,offset:s}:{tile:r,offset:o}}},Ze=class n extends ni{constructor(e,t){super(e),this.wrapper=t}isBlock(){return!0}covers(e){return this.children.length?e<0?this.children[0].covers(-1):this.lastChild.covers(1):!1}get domAttrs(){return this.wrapper.attributes}static of(e,t){let i=new n(t||document.createElement(e.tagName),e);return t||(i.flags|=4),i}},ri=class n extends ni{constructor(e,t){super(e),this.attrs=t}isLine(){return!0}static start(e,t,i){let s=new n(t||document.createElement("div"),e);return(!t||!i)&&(s.flags|=4),s}get domAttrs(){return this.attrs}resolveInline(e,t,i){let s=null,r=-1,o=null,l=-1;function a(f,c){for(let u=0,d=0;u=c&&(p.isComposite()?a(p,c-d):(!o||o.isHidden&&(t>0&&!(o.flags&32)||i&&Bc(o,p)))&&(m>c||p.flags&32&&t<=1)?(o=p,l=c-d):(d=-1)&&(s=p,r=c-d)),d=m}}a(this,e);let h=(t<0?s:o)||s||o;return h?{tile:h,offset:h==s?r:l}:null}coordsIn(e,t,i){let s=this.resolveInline(e,t,!0);return s?s.tile.coordsIn(Math.max(0,s.offset),t,i):Dc(this)}domIn(e,t){let i=this.resolveInline(e,t);if(i){let{tile:s,offset:r}=i;if(this.dom.contains(s.dom))return s.isText()?new $e(s.dom,Math.min(s.dom.nodeValue.length,r)):s.domPosFor(r,s.flags&16?1:s.flags&32?-1:t);let o=i.tile.parent,l=!1;for(let a of o.children){if(l)return new $e(a.dom,0);a==i.tile&&(l=!0)}}return new $e(this.dom,0)}};function Dc(n){let e=n.dom.lastChild;if(!e)return n.dom.getBoundingClientRect();let t=Sn(e);return t[t.length-1]||null}function Bc(n,e){let t=n.coordsIn(0,1),i=e.coordsIn(0,1);return t&&i&&i.tops&&(e=s);let r=e,o=e,l=0;e==0&&t<0||e==s&&t>=0?x.chrome||x.gecko||(e?(r--,l=1):o=0)?0:a.length-1];return x.safari&&!l&&h.width==0&&(h=Array.prototype.find.call(a,f=>f.width)||h),i==null?h:Cn(h,(l?l>0:t<0)==i)}static of(e,t){let i=new n(t||document.createTextNode(e),e);return t||(i.flags|=2),i}},Mt=class n extends _{constructor(e,t,i,s){super(e,t,s),this.widget=i}isWidget(){return!0}get isHidden(){return this.widget.isHidden}covers(e){return this.flags&48?!1:(this.flags&(e<0?64:128))>0}coordsIn(e,t){return this.coordsInWidget(e,t,!1)}coordsInWidget(e,t,i){let s=this.widget.coordsAt(this.dom,e,t);if(s)return s;if(i)return Cn(this.dom.getBoundingClientRect(),this.length?e==0:t<=0);{let r=this.dom.getClientRects(),o=null;if(!r.length)return null;let l=this.flags&16?!0:this.flags&32?!1:e>0;for(let a=l?r.length-1:0;o=r[a],!(e>0?a==0:a==r.length-1||o.top0==i)}},Js=class{constructor(e){this.index=0,this.beforeBreak=!1,this.parents=[],this.tile=e}advance(e,t,i){let{tile:s,index:r,beforeBreak:o,parents:l}=this;for(;e||t>0;)if(s.isComposite())if(o){if(!e)break;i&&i.break(),e--,o=!1}else if(r==s.children.length){if(!e&&!l.length)break;i&&i.leave(s),o=!!s.breakAfter,{tile:s,index:r}=l.pop(),r++}else{let a=s.children[r],h=a.breakAfter;(t>0?a.length<=e:a.length=0;l--){let a=t.marks[l],h=s.lastChild;if(h instanceof ce&&h.mark.eq(a.mark))h.dom!=a.dom&&h.setDOM($s(a.dom)),s=h;else{let{dom:f}=a;this.cache.reused.get(a)&&_.get(a.dom)&&(f=$s(a.dom));let c=ce.of(a.mark,f);s.append(c),s=c}this.cache.reused.set(a,2)}let r=_.get(e.text);r&&this.cache.reused.set(r,2);let o=new Pt(e.text,e.text.nodeValue);o.flags|=8,this.pos=e.range.toB,s.append(o)}addInlineWidget(e,t,i){let s=this.afterWidget&&e.flags&48&&(this.afterWidget.flags&48)==(e.flags&48);s||this.flushBuffer();let r=this.ensureMarks(t,i);!s&&!(e.flags&16)&&r.append(this.getBuffer(1)),r.append(e),this.pos+=e.length,this.afterWidget=e}addMark(e,t,i){this.flushBuffer(),this.ensureMarks(t,i).append(e),this.pos+=e.length,this.afterWidget=null}addBlockWidget(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}continueWidget(e){let t=this.afterWidget||this.lastBlock;t.length+=e,this.pos+=e}addLineStart(e,t){var i;e||(e=wa);let s=ri.start(e,t||((i=this.cache.find(ri))===null||i===void 0?void 0:i.dom),!!t);this.getBlockPos().append(this.lastBlock=this.curLine=s)}addLine(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}addBreak(){this.lastBlock.flags|=1,this.endLine(),this.pos++}addLineStartIfNotCovered(e){this.blockPosCovered()||this.addLineStart(e)}ensureLine(e){this.curLine||this.addLineStart(e)}ensureMarks(e,t){var i;let s=this.curLine;for(let r=e.length-1;r>=0;r--){let o=e[r],l;if(t>0&&(l=s.lastChild)&&l instanceof ce&&l.mark.eq(o))s=l,t--;else{let a=ce.of(o,(i=this.cache.find(ce,h=>h.mark.eq(o)))===null||i===void 0?void 0:i.dom);s.append(a),s=a,t=0}}return s}endLine(){if(this.curLine){this.flushBuffer();let e=this.curLine.lastChild;(!e||!Ql(this.curLine,!1)||e.dom.nodeName!="BR"&&e.isWidget()&&!(x.ios&&Ql(this.curLine,!0)))&&this.curLine.append(this.cache.findWidget(Ls,0,32)||new Mt(Ls.toDOM(),0,Ls,32)),this.curLine=this.afterWidget=null}}updateBlockWrappers(){this.wrapperPos>this.pos+1e4&&(this.blockWrappers.goto(this.pos),this.wrappers.length=0);for(let e=this.wrappers.length-1;e>=0;e--)this.wrappers[e].to=this.pos){let t=e.rank*102+e.value.rank,i=new er(e.from,e.to,e.value,t),s=this.wrappers.length;for(;s>0&&(this.wrappers[s-1].rank-i.rank||this.wrappers[s-1].to-i.to)<0;)s--;this.wrappers.splice(s,0,i)}this.wrapperPos=this.pos}getBlockPos(){var e;this.updateBlockWrappers();let t=this.root;for(let i of this.wrappers){let s=t.lastChild;if(i.fromo.wrapper.eq(i.wrapper)))===null||e===void 0?void 0:e.dom);t.append(r),t=r}}return t}blockPosCovered(){let e=this.lastBlock;return e!=null&&!e.breakAfter&&(!e.isWidget()||(e.flags&160)>0)}getBuffer(e){let t=2|(e<0?16:32),i=this.cache.find(oi,void 0,1);return i&&(i.flags=t),i||new oi(t)}flushBuffer(){this.afterWidget&&!(this.afterWidget.flags&32)&&(this.afterWidget.parent.append(this.getBuffer(-1)),this.afterWidget=null)}},ir=class{constructor(e){this.skipCount=0,this.text="",this.textOff=0,this.cursor=e.iter()}skip(e){this.textOff+e<=this.text.length?this.textOff+=e:(this.skipCount+=e-(this.text.length-this.textOff),this.text="",this.textOff=0)}next(e){if(this.textOff==this.text.length){let{value:s,lineBreak:r,done:o}=this.cursor.next(this.skipCount);if(this.skipCount=0,o)throw new Error("Ran out of text content when drawing inline views");this.text=s;let l=this.textOff=Math.min(e,s.length);return r?null:s.slice(0,l)}let t=Math.min(this.text.length,this.textOff+e),i=this.text.slice(this.textOff,t);return this.textOff=t,i}},Pn=[Mt,ri,Pt,ce,oi,Ze,si];for(let n=0;n[]),this.index=Pn.map(()=>0),this.reused=new Map}add(e){let t=e.constructor.bucket,i=this.buckets[t];i.length<6?i.push(e):i[this.index[t]=(this.index[t]+1)%6]=e}find(e,t,i=2){let s=e.bucket,r=this.buckets[s],o=this.index[s];for(let l=0;l{if(this.cache.add(o),o.isComposite())return!1},enter:o=>this.cache.add(o),leave:()=>{},break:()=>{}}}run(e,t){let i=t&&this.getCompositionContext(t.text);for(let s=0,r=0,o=0;;){let l=os){let h=a-s;this.preserve(h,!o,!l),s=a,r+=h}if(!l)break;t&&l.fromA<=t.range.fromA&&l.toA>=t.range.toA?(this.forward(l.fromA,t.range.fromA,t.range.fromA{if(o.isWidget())if(this.openWidget)this.builder.continueWidget(a-l);else{let h=a>0||l{o.isLine()?this.builder.addLineStart(o.attrs,this.cache.maybeReuse(o)):(this.cache.add(o),o instanceof ce&&s.unshift(o.mark)),this.openWidget=!1},leave:o=>{o.isLine()?s.length&&(s.length=r=0):o instanceof ce&&(s.shift(),r=Math.min(r,s.length))},break:()=>{this.builder.addBreak(),this.openWidget=!1}}),this.text.skip(e)}emit(e,t){let i=null,s=this.builder,r=-1,o=B.spans(this.decorations,e,t,{point:(l,a,h,f,c,u)=>{if(h instanceof At){if(this.disallowBlockEffectsFor[u]){if(h.block)throw new RangeError("Block decorations may not be specified via plugins");if(a>this.view.state.doc.lineAt(l).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}if(r=f.length,c>f.length)s.continueWidget(a-l);else{let d=h.widget||(h.block?ut.block:ut.inline),p=qc(h),m=this.cache.findWidget(d,a-l,p)||Mt.of(d,this.view,a-l,p);h.block?(h.startSide>0&&s.addLineStartIfNotCovered(i),s.addBlockWidget(m)):(s.ensureLine(i),s.addInlineWidget(m,f,c))}i=null}else i=Wc(i,h);a>l&&this.text.skip(a-l)},span:(l,a,h,f)=>{for(let c=l;c-1&&(this.openWidget=o>r),this.openWidget||s.addLineStartIfNotCovered(i),this.openMarks=o}forward(e,t,i=1){t-e<=10?this.old.advance(t-e,i,this.reuseWalker):(this.old.advance(5,-1,this.reuseWalker),this.old.advance(t-e-10,-1),this.old.advance(5,i,this.reuseWalker))}getCompositionContext(e){let t=[],i=null;for(let s=e.parentNode;;s=s.parentNode){let r=_.get(s);if(s==this.view.contentDOM)break;r instanceof ce?t.push(r):r?.isLine()?i=r:r instanceof Ze||(s.nodeName=="DIV"&&!i?i=new ri(s,wa):i||t.push(ce.of(new Bi({tagName:s.nodeName.toLowerCase(),attributes:mc(s)}),s)))}return i?{line:i,marks:t}:null}};function Ql(n,e){let t=i=>{for(let s of i.children)if((e?s.isText():s.length)||t(s))return!0;return!1};return t(n)}function qc(n){let e=n.isReplace?(n.startSide<0?64:0)|(n.endSide>0?128:0):n.startSide>0?32:16;return n.block&&(e|=256),e}var wa={class:"cm-line"};function Wc(n,e){let t=e.spec.attributes,i=e.spec.class;return!t&&!i||(n||(n={class:"cm-line"}),t&&Rr(t,n),i&&(n.class+=" "+i)),n}function $c(n){let e=[];for(let t=n.parents.length;t>1;t--){let i=t==n.parents.length?n.tile:n.parents[t].tile;i instanceof ce&&e.push(i.mark)}return e}function $s(n){let e=_.get(n);return e&&e.setDOM(n.cloneNode()),n}var ut=class extends Ye{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}};ut.inline=new ut("span");ut.block=new ut("div");var Ls=new class extends Ye{toDOM(){return document.createElement("br")}get isHidden(){return!0}get editable(){return!0}},An=class{constructor(e){this.view=e,this.decorations=[],this.blockWrappers=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.editContextFormatting=q.none,this.lastCompositionAfterCursor=!1,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.updateDeco(),this.tile=new si(e,e.contentDOM),this.updateInner([new Pe(0,0,0,e.state.doc.length)],null)}update(e){var t;let i=e.changedRanges;this.minWidth>0&&i.length&&(i.every(({fromA:f,toA:c})=>cthis.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.updateEditContextFormatting(e);let s=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&(!((t=this.domChanged)===null||t===void 0)&&t.newSel?s=this.domChanged.newSel.head:!_c(e.changes,this.hasComposition)&&!e.selectionSet&&(s=e.state.selection.main.head));let r=s>-1?zc(this.view,e.changes,s):null;if(this.domChanged=null,this.hasComposition){let{from:f,to:c}=this.hasComposition;i=new Pe(f,c,e.changes.mapPos(f,-1),e.changes.mapPos(c,1)).addToSet(i.slice())}this.hasComposition=r?{from:r.range.fromB,to:r.range.toB}:null,(x.ie||x.chrome)&&!r&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=this.decorations,l=this.blockWrappers;this.updateDeco();let a=Vc(o,this.decorations,e.changes);a.length&&(i=Pe.extendWithRanges(i,a));let h=Xc(l,this.blockWrappers,e.changes);return h.length&&(i=Pe.extendWithRanges(i,h)),r&&!i.some(f=>f.fromA<=r.range.fromA&&f.toA>=r.range.toA)&&(i=r.range.addToSet(i.slice())),this.tile.flags&2&&i.length==0?!1:(this.updateInner(i,r),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t){this.view.viewState.mustMeasureContent=!0;let{observer:i}=this.view;i.ignore(()=>{if(t||e.length){let o=this.tile,l=new sr(this.view,o,this.blockWrappers,this.decorations,this.dynamicDecorationMap);t&&_.get(t.text)&&l.cache.reused.set(_.get(t.text),2),this.tile=l.run(e,t),rr(o,l.cache.reused)}this.tile.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.tile.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let r=x.chrome||x.ios?{node:i.selectionRange.focusNode,written:!1}:void 0;this.tile.sync(r),r&&(r.written||i.selectionRange.focusNode!=r.node||!this.tile.dom.contains(r.node))&&(this.forceSelection=!0),this.tile.dom.style.height=""});let s=[];if(this.view.viewport.from||this.view.viewport.to-1)&&Ci(i,this.view.observer.selectionRange)&&!(s&&i.contains(s));if(!(r||t||o))return;let l=this.forceSelection;this.forceSelection=!1;let a=this.view.state.selection.main,h,f;if(a.empty?f=h=this.inlineDOMNearPos(a.anchor,a.assoc||1):(f=this.inlineDOMNearPos(a.head,a.head==a.from?1:-1),h=this.inlineDOMNearPos(a.anchor,a.anchor==a.from?1:-1)),x.gecko&&a.empty&&!this.hasComposition&&Lc(h)){let u=document.createTextNode("");this.view.observer.ignore(()=>h.node.insertBefore(u,h.node.childNodes[h.offset]||null)),h=f=new $e(u,0),l=!0}let c=this.view.observer.selectionRange;(l||!c.focusNode||(!Qi(h.node,h.offset,c.anchorNode,c.anchorOffset)||!Qi(f.node,f.offset,c.focusNode,c.focusOffset))&&!this.suppressWidgetCursorChange(c,a))&&(this.view.observer.ignore(()=>{x.android&&x.chrome&&i.contains(c.focusNode)&&Fc(c.focusNode,i)&&(i.blur(),i.focus({preventScroll:!0}));let u=Wi(this.view.root);if(u)if(a.empty){if(x.gecko){let d=Ic(h.node,h.offset);if(d&&d!=3){let p=(d==1?ia:na)(h.node,h.offset);p&&(h=new $e(p.node,p.offset))}}u.collapse(h.node,h.offset),a.bidiLevel!=null&&u.caretBidiLevel!==void 0&&(u.caretBidiLevel=a.bidiLevel)}else if(u.extend){u.collapse(h.node,h.offset);try{u.extend(f.node,f.offset)}catch{}}else{let d=document.createRange();a.anchor>a.head&&([h,f]=[f,h]),d.setEnd(f.node,f.offset),d.setStart(h.node,h.offset),u.removeAllRanges(),u.addRange(d)}o&&this.view.root.activeElement==i&&(i.blur(),s&&s.focus())}),this.view.observer.setSelectionRange(h,f)),this.impreciseAnchor=h.precise?null:new $e(c.anchorNode,c.anchorOffset),this.impreciseHead=f.precise?null:new $e(c.focusNode,c.focusOffset)}suppressWidgetCursorChange(e,t){return this.hasComposition&&t.empty&&Qi(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)&&this.posFromDOM(e.focusNode,e.focusOffset)==t.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,t=e.state.selection.main,i=Wi(e.root),{anchorNode:s,anchorOffset:r}=e.observer.selectionRange;if(!i||!t.empty||!t.assoc||!i.modify)return;let o=this.lineAt(t.head,t.assoc);if(!o)return;let l=o.posAtStart;if(t.head==l||t.head==l+o.length)return;let a=this.coordsAt(t.head,-1),h=this.coordsAt(t.head,1);if(!a||!h||a.bottom>h.top)return;let f=this.domAtPos(t.head+t.assoc,t.assoc);i.collapse(f.node,f.offset),i.modify("move",t.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let c=e.observer.selectionRange;e.docView.posFromDOM(c.anchorNode,c.anchorOffset)!=t.from&&i.collapse(s,r)}posFromDOM(e,t){let i=this.tile.nearest(e);if(!i)return this.tile.dom.compareDocumentPosition(e)&2?0:this.view.state.doc.length;let s=i.posAtStart;if(i.isComposite()){let r;if(e==i.dom)r=i.dom.childNodes[t];else{let o=Ke(e)==0?0:t==0?-1:1;for(;;){let l=e.parentNode;if(l==i.dom)break;o==0&&l.firstChild!=l.lastChild&&(e==l.firstChild?o=-1:o=1),e=l}o<0?r=e:r=e.nextSibling}if(r==i.dom.firstChild)return s;for(;r&&!_.get(r);)r=r.nextSibling;if(!r)return s+i.length;for(let o=0,l=s;;o++){let a=i.children[o];if(a.dom==r)return l;l+=a.length+a.breakAfter}}else return i.isText()?e==i.dom?s+t:s+(t?i.length:0):s}domAtPos(e,t){let{tile:i,offset:s}=this.tile.resolveBlock(e,t);return i.isWidget()?i.domPosFor(s,t):i.domIn(s,t)}inlineDOMNearPos(e,t){let i,s=-1,r=!1,o,l=-1,a=!1;return this.tile.blockTiles((h,f)=>{if(h.isWidget()){if(h.flags&32&&f>=e)return!0;h.flags&16&&(r=!0)}else{let c=f+h.length;if(f<=e&&(i=h,s=e-f,r=c=e&&!o&&(o=h,l=e-f,a=f>e),f>e&&o)return!0}}),!i&&!o?this.domAtPos(e,t):(r&&o?i=null:a&&i&&(o=null),i&&t<0||!o?i.domIn(s,t):o.domIn(l,t))}coordsAt(e,t,i){let{tile:s,offset:r}=this.tile.resolveBlock(e,t);return s.isWidget()?s.widget instanceof Ri?null:s.coordsInWidget(r,t,!0):s.coordsIn(r,t,i)}lineAt(e,t){let{tile:i}=this.tile.resolveBlock(e,t);return i.isLine()?i:null}coordsForChar(e){let{tile:t,offset:i}=this.tile.resolveBlock(e,1);if(!t.isLine())return null;function s(r,o){if(r.isComposite())for(let l of r.children){if(l.length>=o){let a=s(l,o);if(a)return a}if(o-=l.length,o<0)break}else if(r.isText()&&oMath.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,l=-1,a=this.view.textDirection==F.LTR,h=0,f=(c,u,d)=>{for(let p=0;ps);p++){let m=c.children[p],O=u+m.length,y=m.dom.getBoundingClientRect(),{height:w}=y;if(d&&!p&&(h+=y.top-d.top),m instanceof Ze)O>i&&f(m,u,y);else if(u>=i&&(h>0&&t.push(-h),t.push(w+h),h=0,o)){let k=m.dom.lastChild,D=k?Sn(k):[];if(D.length){let Q=D[D.length-1],P=a?Q.right-y.left:y.right-Q.left;P>l&&(l=P,this.minWidth=r,this.minWidthFrom=u,this.minWidthTo=O)}}d&&p==c.children.length-1&&(h+=d.bottom-y.bottom),u=O+m.breakAfter}};return f(this.tile,0,null),t}textDirectionAt(e){let{tile:t}=this.tile.resolveBlock(e,1);return getComputedStyle(t.dom).direction=="rtl"?F.RTL:F.LTR}measureTextSize(){let e=this.tile.blockTiles(o=>{if(o.isLine()&&o.children.length&&o.length<=20){let l=0,a;for(let h of o.children){if(!h.isText()||/[^ -~]/.test(h.text))return;let f=Sn(h.dom);if(f.length!=1)return;l+=f[0].width,a=f[0].height}if(l)return{lineHeight:o.dom.getBoundingClientRect().height,charWidth:l/o.length,textHeight:a}}});if(e)return e;let t=document.createElement("div"),i,s,r;return t.className="cm-line",t.style.width="99999px",t.style.position="absolute",t.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.tile.dom.appendChild(t);let o=Sn(t.firstChild)[0];i=t.getBoundingClientRect().height,s=o&&o.width?o.width/27:7,r=o&&o.height?o.height:i,t.remove()}),{lineHeight:i,charWidth:s,textHeight:r}}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let i=0,s=0;;s++){let r=s==t.viewports.length?null:t.viewports[s],o=r?r.from-1:this.view.state.doc.length;if(o>i){let l=(t.lineBlockAt(o).bottom-t.lineBlockAt(i).top)/this.view.scaleY;e.push(q.replace({widget:new Ri(l),block:!0,inclusive:!0,isBlockGap:!0}).range(i,o))}if(!r)break;i=r.to+1}return q.set(e)}updateDeco(){let e=1,t=this.view.state.facet(zn).map(r=>(this.dynamicDecorationMap[e++]=typeof r=="function")?r(this.view):r),i=!1,s=this.view.state.facet(Wr).map((r,o)=>{let l=typeof r=="function";return l&&(i=!0),l?r(this.view):r});for(s.length&&(this.dynamicDecorationMap[e++]=i,t.push(B.join(s))),this.decorations=[this.editContextFormatting,...t,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];etypeof r=="function"?r(this.view):r)}scrollIntoView(e){if(e.isSnapshot){let h=this.view.viewState.lineBlockAt(e.range.head);this.view.scrollDOM.scrollTop=h.top-e.yMargin,this.view.scrollDOM.scrollLeft=e.xMargin;return}for(let h of this.view.state.facet(ga))try{if(h(this.view,e.range,e))return!0}catch(f){ke(this.view.state,f,"scroll handler")}let{range:t}=e,i=this.coordsAt(t.head,t.assoc||(t.head>t.anchor?-1:1)),s;if(!i)return;!t.empty&&(s=this.coordsAt(t.anchor,t.anchor>t.head?-1:1))&&(i={left:Math.min(i.left,s.left),top:Math.min(i.top,s.top),right:Math.max(i.right,s.right),bottom:Math.max(i.bottom,s.bottom)});let r=ka(this.view),o={left:i.left-r.left,top:i.top-r.top,right:i.right+r.right,bottom:i.bottom+r.bottom},{offsetWidth:l,offsetHeight:a}=this.view.scrollDOM;if(yc(this.view.scrollDOM,o,t.head1&&(i.top>window.visualViewport.offsetTop+window.visualViewport.height||i.bottomi.isWidget()||i.children.some(t);return t(this.tile.resolveBlock(e,1).tile)}destroy(){rr(this.tile)}};function rr(n,e){let t=e?.get(n);if(t!=1){t==null&&n.destroy();for(let i of n.children)rr(i,e)}}function Lc(n){return n.node.nodeType==1&&n.node.firstChild&&(n.offset==0||n.node.childNodes[n.offset-1].contentEditable=="false")&&(n.offset==n.node.childNodes.length||n.node.childNodes[n.offset].contentEditable=="false")}function va(n,e){let t=n.observer.selectionRange;if(!t.focusNode)return null;let i=ia(t.focusNode,t.focusOffset),s=na(t.focusNode,t.focusOffset),r=i||s;if(s&&i&&s.node!=i.node){let l=_.get(s.node);if(!l||l.isText()&&l.text!=s.node.nodeValue)r=s;else if(n.docView.lastCompositionAfterCursor){let a=_.get(i.node);!a||a.isText()&&a.text!=i.node.nodeValue||(r=s)}}if(n.docView.lastCompositionAfterCursor=r!=i,!r)return null;let o=e-r.offset;return{from:o,to:o+r.node.nodeValue.length,node:r.node}}function zc(n,e,t){let i=va(n,t);if(!i)return null;let{node:s,from:r,to:o}=i,l=s.nodeValue;if(/[\n\r]/.test(l)||n.state.doc.sliceString(i.from,i.to)!=l)return null;let a=e.invertedDesc;return{range:new Pe(a.mapPos(r),a.mapPos(o),r,o),text:s}}function Ic(n,e){return n.nodeType!=1?0:(e&&n.childNodes[e-1].contentEditable=="false"?1:0)|(e{ie.from&&(t=!0)}),t}var Ri=class extends Ye{constructor(e){super(),this.height=e}toDOM(){let e=document.createElement("div");return e.className="cm-gap",this.updateDOM(e),e}eq(e){return e.height==this.height}updateDOM(e){return e.style.height=this.height+"px",!0}get editable(){return!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}};function Hc(n,e,t=1){let i=n.charCategorizer(e),s=n.doc.lineAt(e),r=e-s.from;if(s.length==0)return b.cursor(e);r==0?t=1:r==s.length&&(t=-1);let o=r,l=r;t<0?o=K(s.text,r,!1):l=K(s.text,r);let a=i(s.text.slice(o,l));for(;o>0;){let h=K(s.text,o,!1);if(i(s.text.slice(h,o))!=a)break;o=h}for(;ln.defaultLineHeight*1.5){let l=n.viewState.heightOracle.textHeight,a=Math.floor((s-t.top-(n.defaultLineHeight-l)*.5)/l);r+=a*n.viewState.heightOracle.lineLength}let o=n.state.sliceDoc(t.from,t.to);return t.from+pl(o,r,n.state.tabSize)}function jc(n,e,t){let i=n.lineBlockAt(e);if(Array.isArray(i.type)){let s;for(let r of i.type){if(r.from>e)break;if(!(r.toe)return r;(!s||r.type==ue.Text&&(s.type!=r.type||(t<0?r.frome)))&&(s=r)}}return s||i}return i}function Gc(n,e,t,i){let s=jc(n,e.head,e.assoc||-1),r=!i||s.type!=ue.Text||!(n.lineWrapping||s.widgetLineBreaks)?null:n.coordsAtPos(e.assoc<0&&e.head>s.from?e.head-1:e.head);if(r){let o=n.dom.getBoundingClientRect(),l=n.textDirectionAt(s.from),a=n.posAtCoords({x:t==(l==F.LTR)?o.right-1:o.left+1,y:(r.top+r.bottom)/2});if(a!=null)return b.cursor(a,t?-1:1)}return b.cursor(t?s.to:s.from,t?-1:1)}function Pl(n,e,t,i){let s=n.state.doc.lineAt(e.head),r=n.bidiSpans(s),o=n.textDirectionAt(s.from);for(let l=e,a=null;;){let h=Pc(s,r,o,l,t),f=aa;if(!h){if(s.number==(t?n.state.doc.lines:1))return l;f=` +`,s=n.state.doc.line(s.number+(t?1:-1)),r=n.bidiSpans(s),h=t?b.cursor(s.from,-1):b.cursor(s.to,1)}if(a){if(!a(f))return l}else{if(!i)return h;a=i(f)}l=h}}function Zc(n,e,t){let i=n.state.charCategorizer(e),s=i(t);return r=>{let o=i(r);return s==re.Space&&(s=o),s==o}}function Yc(n,e,t,i){let s=e.head,r=t?1:-1;if(s==(t?n.state.doc.length:0))return b.cursor(s,e.assoc);let o=e.goalColumn,l,a=n.contentDOM.getBoundingClientRect(),h=n.coordsAtPos(s,e.assoc||((e.empty?t:e.head==e.from)?1:-1)),f=n.documentTop;if(h)o==null&&(o=h.left-a.left),l=r<0?h.top:h.bottom;else{let p=n.viewState.lineBlockAt(s);o==null&&(o=Math.min(a.right-a.left,n.defaultCharacterWidth*(s-p.from))),l=(r<0?p.top:p.bottom)+f}let c=a.left+o,u=n.viewState.heightOracle.textHeight>>1,d=i??u;for(let p=0;;p+=u){let m=l+(d+p)*r,O=lr(n,{x:c,y:m},!1,r);if(t?m>a.bottom:ml:w{if(e>r&&es(n)),t.from,e.head>t.from?-1:1);return i==t.from?t:b.cursor(i,in.viewState.docHeight)return new Se(n.state.doc.length,-1);if(h=n.elementAtHeight(a),i==null)break;if(h.type==ue.Text){if(i<0?h.ton.viewport.to)break;let u=n.docView.coordsAt(i<0?h.from:h.to,i>0?-1:1);if(u&&(i<0?u.top<=a+r:u.bottom>=a+r))break}let c=n.viewState.heightOracle.textHeight/2;a=i>0?h.bottom+c:h.top-c}if(n.viewport.from>=h.to||n.viewport.to<=h.from){if(t)return null;if(h.type==ue.Text){let c=Uc(n,s,h,o,l);return new Se(c,c==h.from?1:-1)}}if(h.type!=ue.Text)return a<(h.top+h.bottom)/2?new Se(h.from,1):new Se(h.to,-1);let f=n.docView.lineAt(h.from,2);return(!f||f.length!=h.length)&&(f=n.docView.lineAt(h.from,-2)),new ar(n,o,l,n.textDirectionAt(h.from)).scanTile(f,h.from)}var ar=class{constructor(e,t,i,s){this.view=e,this.x=t,this.y=i,this.baseDir=s,this.line=null,this.spans=null}bidiSpansAt(e){return(!this.line||this.line.from>e||this.line.to1||i.length&&(i[0].level!=this.baseDir||i[0].to+s.from>1;t:if(o.has(m)){for(let w=1;w=r&&(k-=p),!o.has(k)){m=k;break t}}break e}o.add(m);let O=t(m),y=0;if(O)for(let w=0;w1))if(k.bottomthis.y)(!h||h.top>k.top)&&(h=k),y=-1;else{let D=k.left>this.x?this.x-k.left:k.right(p+p+m)/3)return this.y=a.bottom-1,this.scan(e,t,!0);if(h&&h.top<(p+m+m)/3)return this.y=h.top+1,this.scan(e,t,!0)}let d=(l?this.dirAt(e[f],1):this.baseDir)==F.LTR;return{i:f,after:this.x>(u.left+u.right)/2==d}}scanText(e,t){let i=[];for(let r=0;r{let o=i[r]-t,l=i[r+1]-t;return $i(e.dom,o,l).getClientRects()});return s.after?new Se(i[s.i+1],-1):new Se(i[s.i],1)}scanTile(e,t){if(!e.length)return new Se(t,1);if(e.children.length==1){let l=e.children[0];if(l.isText())return this.scanText(l,t);if(l.isComposite())return this.scanTile(l,t)}let i=[t];for(let l=0,a=t;l{let a=e.children[l];return a.flags&48?null:(a.dom.nodeType==1?a.dom:$i(a.dom,0,a.length)).getClientRects()}),r=e.children[s.i],o=i[s.i];return r.isText()?this.scanText(r,o):r.isComposite()?this.scanTile(r,o):s.after?new Se(i[s.i+1],-1):new Se(o,1)}},Yt="\uFFFF",hr=class{constructor(e,t){this.points=e,this.view=t,this.text="",this.lineSeparator=t.state.facet(z.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=Yt}readRange(e,t){if(!e)return this;let i=e.parentNode;for(let s=e;;){this.findPointBefore(i,s);let r=this.text.length;this.readNode(s);let o=_.get(s),l=s.nextSibling;if(l==t){o?.breakAfter&&!l&&i!=this.view.contentDOM&&this.lineBreak();break}let a=_.get(l);(o&&a?o.breakAfter:(o?o.breakAfter:Tn(s))||Tn(l)&&(s.nodeName!="BR"||o?.isWidget())&&this.text.length>r)&&!Jc(l,t)&&this.lineBreak(),s=l}return this.findPointBefore(i,t),this}readTextNode(e){let t=e.nodeValue;for(let i of this.points)i.node==e&&(i.pos=this.text.length+Math.min(i.offset,t.length));for(let i=0,s=this.lineSeparator?null:/\r\n?|\n/g;;){let r=-1,o=1,l;if(this.lineSeparator?(r=t.indexOf(this.lineSeparator,i),o=this.lineSeparator.length):(l=s.exec(t))&&(r=l.index,o=l[0].length),this.append(t.slice(i,r<0?t.length:r)),r<0)break;if(this.lineBreak(),o>1)for(let a of this.points)a.node==e&&a.pos>this.text.length&&(a.pos-=o-1);i=r+o}}readNode(e){let t=_.get(e),i=t&&t.overrideDOMText;if(i!=null){this.findPointInside(e,i.length);for(let s=i.iter();!s.next().done;)s.lineBreak?this.lineBreak():this.append(s.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let i of this.points)i.node==e&&e.childNodes[i.offset]==t&&(i.pos=this.text.length)}findPointInside(e,t){for(let i of this.points)(e.nodeType==3?i.node==e:e.contains(i.node))&&(i.pos=this.text.length+(Kc(e,i.node,i.offset)?t:0))}};function Kc(n,e,t){for(;;){if(!e||t-1;let{impreciseHead:r,impreciseAnchor:o}=e.docView,l=e.state.selection;if(e.state.readOnly&&t>-1)this.newSel=null;else if(t>-1&&(this.bounds=Ca(e.docView.tile,t,i,0))){let a=r||o?[]:tu(e),h=new hr(a,e);h.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=h.text,this.newSel=iu(a,this.bounds.from)}else{let a=e.observer.selectionRange,h=r&&r.node==a.focusNode&&r.offset==a.focusOffset||!Us(e.contentDOM,a.focusNode)?l.main.head:e.docView.posFromDOM(a.focusNode,a.focusOffset),f=o&&o.node==a.anchorNode&&o.offset==a.anchorOffset||!Us(e.contentDOM,a.anchorNode)?l.main.anchor:e.docView.posFromDOM(a.anchorNode,a.anchorOffset),c=e.viewport;if((x.ios||x.chrome)&&h!=f&&Math.min(h,f)<=l.main.from&&Math.max(h,f)>=l.main.to&&(c.from>0||c.to-1&&l.ranges.length>1)this.newSel=l.replaceRange(b.range(f,h));else if(e.lineWrapping&&f==h&&!(l.main.empty&&l.main.head==h)&&e.inputState.lastTouchTime>Date.now()-100){let u=e.coordsAtPos(h,-1),d=0;u&&(d=e.inputState.lastTouchY<=u.bottom?-1:1),this.newSel=b.create([b.cursor(h,d)])}else this.newSel=b.single(f,h)}}};function Ca(n,e,t,i){if(n.isComposite()){let s=-1,r=-1,o=-1,l=-1;for(let a=0,h=i,f=i;at)return Ca(c,e,t,h);if(u>=e&&s==-1&&(s=a,r=h),h>t&&c.dom.parentNode==n.dom){o=a,l=f;break}f=u,h=u+c.breakAfter}return{from:r,to:l<0?i+n.length:l,startDOM:(s?n.children[s-1].dom.nextSibling:null)||n.dom.firstChild,endDOM:o=0?n.children[o].dom:null}}else return n.isText()?{from:i,to:i+n.length,startDOM:n.dom,endDOM:n.dom.nextSibling}:null}function Qa(n,e){let t,{newSel:i}=e,{state:s}=n,r=s.selection.main,o=n.inputState.lastKeyTime>Date.now()-100?n.inputState.lastKeyCode:-1;if(e.bounds){let{from:l,to:a}=e.bounds,h=r.from,f=null;(o===8||x.android&&e.text.length=l&&r.to<=a&&(e.typeOver||c!=e.text)&&c.slice(0,r.from-l)==e.text.slice(0,r.from-l)&&c.slice(r.to-l)==e.text.slice(u=e.text.length-(c.length-(r.to-l)))?t={from:r.from,to:r.to,insert:M.of(e.text.slice(r.from-l,u).split(Yt))}:(d=Pa(c,e.text,h-l,f))&&(x.chrome&&o==13&&d.toB==d.from+2&&e.text.slice(d.from,d.toB)==Yt+Yt&&d.toB--,t={from:l+d.from,to:l+d.toA,insert:M.of(e.text.slice(d.from,d.toB).split(Yt))})}else i&&(!n.hasFocus&&s.facet(Ge)||Mn(i,r))&&(i=null);if(!t&&!i)return!1;if((x.mac||x.android)&&t&&t.from==t.to&&t.from==r.head-1&&/^\. ?$/.test(t.insert.toString())&&n.contentDOM.getAttribute("autocorrect")=="off"?(i&&t.insert.length==2&&(i=b.single(i.main.anchor-1,i.main.head-1)),t={from:t.from,to:t.to,insert:M.of([t.insert.toString().replace("."," ")])}):s.doc.lineAt(r.from).toDate.now()-50?t={from:r.from,to:r.to,insert:s.toText(n.inputState.insertingText)}:x.chrome&&t&&t.from==t.to&&t.from==r.head&&t.insert.toString()==` + `&&n.lineWrapping&&(i&&(i=b.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:M.of([" "])}),t)return $r(n,t,i,o);if(i&&!Mn(i,r)){let l=!1,a="select";return n.inputState.lastSelectionTime>Date.now()-50&&(n.inputState.lastSelectionOrigin=="select"&&(l=!0),a=n.inputState.lastSelectionOrigin,a=="select.pointer"&&(i=Ta(s.facet(Li).map(h=>h(n)),i))),n.dispatch({selection:i,scrollIntoView:l,userEvent:a}),!0}else return!1}function $r(n,e,t,i=-1){if(x.ios&&n.inputState.flushIOSKey(e))return!0;let s=n.state.selection.main;if(x.android&&(e.to==s.to&&(e.from==s.from||e.from==s.from-1&&n.state.sliceDoc(e.from,s.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&ii(n.contentDOM,"Enter",13)||(e.from==s.from-1&&e.to==s.to&&e.insert.length==0||i==8&&e.insert.lengths.head)&&ii(n.contentDOM,"Backspace",8)||e.from==s.from&&e.to==s.to+1&&e.insert.length==0&&ii(n.contentDOM,"Delete",46)))return!0;let r=e.insert.toString();n.inputState.composing>=0&&n.inputState.composing++;let o,l=()=>o||(o=eu(n,e,t));return n.state.facet(da).some(a=>a(n,e.from,e.to,r,l))||n.dispatch(l()),!0}function eu(n,e,t){let i,s=n.state,r=s.selection.main,o=-1;if(e.from==e.to&&e.fromr.to){let a=e.fromc(n)),h,a);e.from==f&&(o=f)}if(o>-1)i={changes:e,selection:b.cursor(e.from+e.insert.length,-1)};else if(e.from>=r.from&&e.to<=r.to&&e.to-e.from>=(r.to-r.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&n.inputState.composing<0){let a=r.frome.to?s.sliceDoc(e.to,r.to):"";i=s.replaceSelection(n.state.toText(a+e.insert.sliceString(0,void 0,n.state.lineBreak)+h))}else{let a=s.changes(e),h=t&&t.main.to<=a.newLength?t.main:void 0;if(s.selection.ranges.length>1&&(n.inputState.composing>=0||n.inputState.compositionPendingChange)&&e.to<=r.to+10&&e.to>=r.to-10){let f=n.state.sliceDoc(e.from,e.to),c,u=t&&va(n,t.main.head);if(u){let p=e.insert.length-(e.to-e.from);c={from:u.from,to:u.to-p}}else c=n.state.doc.lineAt(r.head);let d=r.to-e.to;i=s.changeByRange(p=>{if(p.from==r.from&&p.to==r.to)return{changes:a,range:h||p.map(a)};let m=p.to-d,O=m-f.length;if(n.state.sliceDoc(O,m)!=f||m>=c.from&&O<=c.to)return{range:p};let y=s.changes({from:O,to:m,insert:e.insert}),w=p.to-r.to;return{changes:y,range:h?b.range(Math.max(0,h.anchor+w),Math.max(0,h.head+w)):p.map(y)}})}else i={changes:a,selection:h&&s.selection.replaceRange(h)}}let l="input.type";return(n.composing||n.inputState.compositionPendingChange&&n.inputState.compositionEndedAt>Date.now()-50)&&(n.inputState.compositionPendingChange=!1,l+=".compose",n.inputState.compositionFirstChange&&(l+=".start",n.inputState.compositionFirstChange=!1)),s.update(i,{userEvent:l,scrollIntoView:!0})}function Pa(n,e,t,i){let s=Math.min(n.length,e.length),r=0;for(;r0&&l>0&&n.charCodeAt(o-1)==e.charCodeAt(l-1);)o--,l--;if(i=="end"){let a=Math.max(0,r-Math.min(o,l));t-=o+a-r}if(o=o?r-t:0;r-=a,l=r+(l-o),o=r}else if(l=l?r-t:0;r-=a,o=r+(o-l),l=r}return{from:r,toA:o,toB:l}}function tu(n){let e=[];if(n.root.activeElement!=n.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}=n.observer.selectionRange;return t&&(e.push(new Rn(t,i)),(s!=t||r!=i)&&e.push(new Rn(s,r))),e}function iu(n,e){if(n.length==0)return null;let t=n[0].pos,i=n.length==2?n[1].pos:t;return t<0||i<0?null:t==i?b.create([b.cursor(i+e,-1)]):b.single(t+e,i+e)}function Mn(n,e){return e.head==n.main.head&&e.anchor==n.main.anchor}var cr=class{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.touchActive=!1,this.lastTouchTime=0,this.lastTouchX=0,this.lastTouchY=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.lastWheelEvent=0,this.pendingIOSKey=void 0,this.lastIOSMomentumScroll=0,this.tabFocusMode=-1,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.insertingText="",this.insertingTextAt=0,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,x.safari&&e.contentDOM.addEventListener("input",()=>null),x.gecko&&Ou(e.contentDOM.ownerDocument)}handleEvent(e){!fu(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||(this.view.updateState!=0?Promise.resolve().then(()=>this.runHandlers(e.type,e)):this.runHandlers(e.type,e))}runHandlers(e,t){let i=this.handlers[e];if(i){for(let s of i.observers)s(this.view,t);for(let s of i.handlers){if(t.defaultPrevented)break;if(s(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=su(e),i=this.handlers,s=this.view.contentDOM;for(let r in t)if(r!="scroll"){let o=!t[r].handlers.length,l=i[r];l&&o!=!l.handlers.length&&(s.removeEventListener(r,this.handleEvent),l=null),l||s.addEventListener(r,this.handleEvent,{passive:o})}for(let r in i)r!="scroll"&&!t[r]&&s.removeEventListener(r,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&this.tabFocusMode>-1&&(!this.tabFocusMode||Date.now()<=this.tabFocusMode))return!0;if(this.tabFocusMode>0&&e.keyCode!=27&&Ra.indexOf(e.keyCode)<0&&(this.tabFocusMode=-1),x.android&&x.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;if(x.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&(Aa.some(t=>t.keyCode==e.keyCode)&&!e.ctrlKey||ru.indexOf(e.key)>-1&&e.ctrlKey)){let t={ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey,shiftKey:e.shiftKey};t.shiftKey&&x.ios&&!/^(off|none)$/.test(this.view.contentDOM.autocapitalize)&&nu(this.view.win)&&(t.shiftKey=!1);let i=this.pendingIOSKey={key:e.key,keyCode:e.keyCode,mods:t};return setTimeout(()=>{this.pendingIOSKey==i&&this.flushIOSKey()},50),!0}return e.keyCode!=229&&this.view.observer.forceFlush(),!1}flushIOSKey(e){let t=this.pendingIOSKey;return!t||this.view.observer.pendingRecords().length||t.key=="Enter"&&e&&e.from0?!0:x.safari&&!x.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.view.observer.update(e),this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}};function nu(n){return n.visualViewport?n.visualViewport.height*n.visualViewport.scale/n.document.documentElement.clientHeight<.85:!1}function Al(n,e){return(t,i)=>{try{return e.call(n,i,t)}catch(s){ke(t.state,s)}}}function su(n){let e=Object.create(null);function t(i){return e[i]||(e[i]={observers:[],handlers:[]})}for(let i of n){let s=i.spec,r=s&&s.plugin.domEventHandlers,o=s&&s.plugin.domEventObservers;if(r)for(let l in r){let a=r[l];a&&t(l).handlers.push(Al(i.value,a))}if(o)for(let l in o){let a=o[l];a&&t(l).observers.push(Al(i.value,a))}}for(let i in Ae)t(i).handlers.push(Ae[i]);for(let i in ae)t(i).observers.push(ae[i]);return e}var Aa=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],ru="dthko",Ra=[16,17,18,20,91,92,224,225],pn=6;function mn(n){return Math.max(0,n)*.7+8}function ou(n,e){return Math.max(Math.abs(n.clientX-e.clientX),Math.abs(n.clientY-e.clientY))}var ur=class{constructor(e,t,i,s){this.view=e,this.startEvent=t,this.style=i,this.mustSelect=s,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParents=Yl(e.contentDOM),this.atoms=e.state.facet(Li).map(o=>o(e));let r=e.contentDOM.ownerDocument;r.addEventListener("mousemove",this.move=this.move.bind(this)),r.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(z.allowMultipleSelections)&&lu(e,t),this.dragging=hu(e,t)&&Da(t)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&ou(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let t=0,i=0,s=0,r=0,o=this.view.win.innerWidth,l=this.view.win.innerHeight;this.scrollParents.x&&({left:s,right:o}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:r,bottom:l}=this.scrollParents.y.getBoundingClientRect());let a=ka(this.view);e.clientX-a.left<=s+pn?t=-mn(s-e.clientX):e.clientX+a.right>=o-pn&&(t=mn(e.clientX-o)),e.clientY-a.top<=r+pn?i=-mn(r-e.clientY):e.clientY+a.bottom>=l-pn&&(i=mn(e.clientY-l)),this.setScrollSpeed(t,i)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,t){this.scrollSpeed={x:e,y:t},e||t?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){let{x:e,y:t}=this.scrollSpeed;e&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=e,e=0),t&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=t,t=0),(e||t)&&this.view.win.scrollBy(e,t),this.dragging===!1&&this.select(this.lastEvent)}select(e){let{view:t}=this,i=Ta(this.atoms,this.style.get(e,this.extend,this.multiple));(this.mustSelect||!i.eq(t.state.selection,this.dragging===!1))&&this.view.dispatch({selection:i,userEvent:"select.pointer"}),this.mustSelect=!1}update(e){e.transactions.some(t=>t.isUserEvent("input.type"))?this.destroy():this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}};function lu(n,e){let t=n.state.facet(ha);return t.length?t[0](e):x.mac?e.metaKey:e.ctrlKey}function au(n,e){let t=n.state.facet(fa);return t.length?t[0](e):x.mac?!e.altKey:!e.ctrlKey}function hu(n,e){let{main:t}=n.state.selection;if(t.empty)return!1;let i=Wi(n.root);if(!i||i.rangeCount==0)return!0;let s=i.getRangeAt(0).getClientRects();for(let r=0;r=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function fu(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,i;t!=n.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(i=_.get(t))&&i.isWidget()&&!i.isHidden&&i.widget.ignoreEvent(e))return!1;return!0}var Ae=Object.create(null),ae=Object.create(null),Ma=x.ie&&x.ie_version<15||x.ios&&x.webkit_version<604;function cu(n){let e=n.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{n.focus(),t.remove(),Ea(n,t.value)},50)}function In(n,e,t){for(let i of n.facet(e))t=i(t,n);return t}function Ea(n,e){e=In(n.state,Dr,e);let{state:t}=n,i,s=1,r=t.toText(e),o=r.lines==t.selection.ranges.length;if(dr!=null&&t.selection.ranges.every(a=>a.empty)&&dr==r.toString()){let a=-1;i=t.changeByRange(h=>{let f=t.doc.lineAt(h.from);if(f.from==a)return{range:h};a=f.from;let c=t.toText((o?r.line(s++).text:e)+t.lineBreak);return{changes:{from:f.from,insert:c},range:b.cursor(h.from+c.length,-1)}})}else o?i=t.changeByRange(a=>{let h=r.line(s++);return{changes:{from:a.from,to:a.to,insert:h.text},range:b.cursor(a.from+h.length,-1)}}):i=t.replaceSelection(r);n.dispatch(i,{userEvent:"input.paste",scrollIntoView:!0})}ae.scroll=n=>{let e=n.inputState;e.lastScrollTop=n.scrollDOM.scrollTop,e.lastScrollLeft=n.scrollDOM.scrollLeft,x.ios&&!e.touchActive&&(e.lastIOSMomentumScroll=Date.now())};ae.wheel=ae.mousewheel=n=>{n.inputState.lastWheelEvent=Date.now()};Ae.keydown=(n,e)=>(n.inputState.setSelectionOrigin("select"),e.keyCode==27&&n.inputState.tabFocusMode!=0&&(n.inputState.tabFocusMode=Date.now()+2e3),!1);ae.touchstart=(n,e)=>{let t=n.inputState,i=e.targetTouches[0];t.touchActive=!0,t.lastTouchTime=Date.now(),i&&(t.lastTouchX=i.clientX,t.lastTouchY=i.clientY),t.setSelectionOrigin("select.pointer")};ae.touchmove=n=>{n.inputState.setSelectionOrigin("select.pointer")};ae.touchend=(n,e)=>{n.inputState.touchActive=!1};Ae.mousedown=(n,e)=>{if(n.observer.flush(),n.inputState.lastTouchTime>Date.now()-2e3)return!1;let t=null;for(let i of n.state.facet(ca))if(t=i(n,e),t)break;if(!t&&e.button==0&&(t=du(n,e)),t){let i=!n.hasFocus;n.inputState.startMouseSelection(new ur(n,e,t,i)),i&&n.observer.ignore(()=>{ea(n.contentDOM);let r=n.root.activeElement;r&&!r.contains(n.contentDOM)&&r.blur()});let s=n.inputState.mouseSelection;if(s)return s.start(e),s.dragging===!1}else n.inputState.setSelectionOrigin("select.pointer");return!1};function Rl(n,e,t,i){if(i==1)return b.cursor(e,t);if(i==2)return Hc(n.state,e,t);{let s=n.docView.lineAt(e,t),r=n.state.doc.lineAt(s?s.posAtEnd:e),o=s?s.posAtStart:r.from,l=s?s.posAtEnd:r.to;return lDate.now()-400&&Math.abs(e.clientX-n.clientX)<2&&Math.abs(e.clientY-n.clientY)<2?(El+1)%3:1}function du(n,e){let t=n.posAndSideAtCoords({x:e.clientX,y:e.clientY},!1),i=Da(e),s=n.state.selection;return{update(r){r.docChanged&&(t.pos=r.changes.mapPos(t.pos),s=s.map(r.changes))},get(r,o,l){let a=n.posAndSideAtCoords({x:r.clientX,y:r.clientY},!1),h,f=Rl(n,a.pos,a.assoc,i);if(t.pos!=a.pos&&!o){let c=Rl(n,t.pos,t.assoc,i),u=Math.min(c.from,f.from),d=Math.max(c.to,f.to);f=u1&&(h=pu(s,a.pos))?h:l?s.addRange(f):b.create([f])}}}function pu(n,e){for(let t=0;t=e)return b.create(n.ranges.slice(0,t).concat(n.ranges.slice(t+1)),n.mainIndex==t?0:n.mainIndex-(n.mainIndex>t?1:0))}return null}Ae.dragstart=(n,e)=>{let{selection:{main:t}}=n.state;if(e.target.draggable){let s=n.docView.tile.nearest(e.target);if(s&&s.isWidget()){let r=s.posAtStart,o=r+s.length;(r>=t.to||o<=t.from)&&(t=b.undirectionalRange(r,o))}}let{inputState:i}=n;return i.mouseSelection&&(i.mouseSelection.dragging=!0),i.draggedContent=t,e.dataTransfer&&(e.dataTransfer.setData("Text",In(n.state,Br,n.state.sliceDoc(t.from,t.to))),e.dataTransfer.effectAllowed="copyMove"),!1};Ae.dragend=n=>(n.inputState.draggedContent=null,!1);function Bl(n,e,t,i){if(t=In(n.state,Dr,t),!t)return;let s=n.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:r}=n.inputState,o=i&&r&&au(n,e)?{from:r.from,to:r.to}:null,l={from:s,insert:t},a=n.state.changes(o?[o,l]:l);n.focus(),n.dispatch({changes:a,selection:{anchor:a.mapPos(s,-1),head:a.mapPos(s,1)},userEvent:o?"move.drop":"input.drop"}),n.inputState.draggedContent=null}Ae.drop=(n,e)=>{if(!e.dataTransfer)return!1;if(n.state.readOnly)return!0;let t=e.dataTransfer.files;if(t&&t.length){let i=Array(t.length),s=0,r=()=>{++s==t.length&&Bl(n,e,i.filter(o=>o!=null).join(n.state.lineBreak),!1)};for(let o=0;o{/[\x00-\x08\x0e-\x1f]{2}/.test(l.result)||(i[o]=l.result),r()},l.readAsText(t[o])}return!0}else{let i=e.dataTransfer.getData("Text");if(i)return Bl(n,e,i,!0),!0}return!1};Ae.paste=(n,e)=>{if(n.state.readOnly)return!0;n.observer.flush();let t=Ma?null:e.clipboardData;return t?(Ea(n,t.getData("text/plain")||t.getData("text/uri-list")),!0):(cu(n),!1)};function mu(n,e){let t=n.dom.parentNode;if(!t)return;let i=t.appendChild(document.createElement("textarea"));i.style.cssText="position: fixed; left: -10000px; top: 10px",i.value=e,i.focus(),i.selectionEnd=e.length,i.selectionStart=0,setTimeout(()=>{i.remove(),n.focus()},50)}function gu(n){let e=[],t=[],i=!1;for(let s of n.selection.ranges)s.empty||(e.push(n.sliceDoc(s.from,s.to)),t.push(s));if(!e.length){let s=-1;for(let{from:r}of n.selection.ranges){let o=n.doc.lineAt(r);o.number>s&&(e.push(o.text),t.push({from:o.from,to:Math.min(n.doc.length,o.to+1)})),s=o.number}i=!0}return{text:In(n,Br,e.join(n.lineBreak)),ranges:t,linewise:i}}var dr=null;Ae.copy=Ae.cut=(n,e)=>{if(!Ci(n.contentDOM,n.observer.selectionRange))return!1;let{text:t,ranges:i,linewise:s}=gu(n.state);if(!t&&!s)return!1;dr=s?t:null,e.type=="cut"&&!n.state.readOnly&&n.dispatch({changes:i,scrollIntoView:!0,userEvent:"delete.cut"});let r=Ma?null:e.clipboardData;return r?(r.clearData(),r.setData("text/plain",t),!0):(mu(n,t),!1)};var Ba=fe.define();function qa(n,e){let t=[];for(let i of n.facet(pa)){let s=i(n,e);s&&t.push(s)}return t.length?n.update({effects:t,annotations:Ba.of(!0)}):null}function Wa(n){setTimeout(()=>{let e=n.hasFocus;if(e!=n.inputState.notifiedFocused){let t=qa(n.state,e);t?n.dispatch(t):n.update([])}},10)}ae.focus=n=>{n.inputState.lastFocusTime=Date.now(),!n.scrollDOM.scrollTop&&(n.inputState.lastScrollTop||n.inputState.lastScrollLeft)&&(n.scrollDOM.scrollTop=n.inputState.lastScrollTop,n.scrollDOM.scrollLeft=n.inputState.lastScrollLeft),Wa(n)};ae.blur=n=>{n.observer.clearSelectionRange(),Wa(n)};ae.compositionstart=ae.compositionupdate=n=>{if(!n.observer.editContext&&(n.inputState.compositionFirstChange==null&&(n.inputState.compositionFirstChange=!0),n.inputState.composing<0)){let{main:e}=n.state.selection;!e.empty&&n.lineBlockAt(e.from).from!=n.lineBlockAt(e.to).from&&n.dispatch({changes:n.state.selection.ranges.filter(t=>!t.empty).map(t=>({from:t.from,to:t.to})),userEvent:"input"}),n.inputState.composing=0}};ae.compositionend=n=>{n.observer.editContext||(n.inputState.composing=-1,n.inputState.compositionEndedAt=Date.now(),n.inputState.compositionPendingKey=!0,n.inputState.compositionPendingChange=n.observer.pendingRecords().length>0,n.inputState.compositionFirstChange=null,x.chrome&&x.android?n.observer.flushSoon():n.inputState.compositionPendingChange?Promise.resolve().then(()=>n.observer.flush()):setTimeout(()=>{n.inputState.composing<0&&n.docView.hasComposition&&n.update([])},50))};ae.contextmenu=n=>{n.inputState.lastContextMenu=Date.now()};Ae.beforeinput=(n,e)=>{var t,i;if((e.inputType=="insertText"||e.inputType=="insertCompositionText")&&(n.inputState.insertingText=e.data,n.inputState.insertingTextAt=Date.now()),e.inputType=="insertReplacementText"&&n.observer.editContext){let r=(t=e.dataTransfer)===null||t===void 0?void 0:t.getData("text/plain"),o=e.getTargetRanges();if(r&&o.length){let l=o[0],a=n.posAtDOM(l.startContainer,l.startOffset),h=n.posAtDOM(l.endContainer,l.endOffset);return $r(n,{from:a,to:h,insert:n.state.toText(r)},null),!0}}let s;if(x.chrome&&x.android&&(s=Aa.find(r=>r.inputType==e.inputType))&&(n.observer.delayAndroidKey(s.key,s.keyCode),s.key=="Backspace"||s.key=="Delete")){let r=((i=window.visualViewport)===null||i===void 0?void 0:i.height)||0;setTimeout(()=>{var o;(((o=window.visualViewport)===null||o===void 0?void 0:o.height)||0)>r+10&&n.hasFocus&&(n.contentDOM.blur(),n.focus())},100)}return x.ios&&e.inputType=="deleteContentForward"&&n.observer.flushSoon(),x.safari&&e.inputType=="insertText"&&n.inputState.composing>=0&&setTimeout(()=>ae.compositionend(n,e),20),!1};var ql=new Set;function Ou(n){ql.has(n)||(ql.add(n),n.addEventListener("copy",()=>{}),n.addEventListener("cut",()=>{}))}var Wl=["pre-wrap","normal","pre-line","break-spaces"],li=!1;function $l(){li=!1}var pr=class{constructor(e){this.lineWrapping=e,this.doc=M.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30}heightForGap(e,t){let i=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(i+=Math.max(0,Math.ceil((t-e-i*this.lineLength*.5)/this.lineLength))),this.lineHeight*i}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/Math.max(1,this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return Wl.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let i=0;i-1,a=Math.abs(t-this.lineHeight)>.3||this.lineWrapping!=l;if(this.lineWrapping=l,this.lineHeight=t,this.charWidth=i,this.textHeight=s,this.lineLength=r,a){this.heightSamples={};for(let h=0;h0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e){this.height!=e&&(Math.abs(this.height-e)>xn&&(li=!0),this.height=e)}replace(e,t,i){return n.of(i)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,i,s){let r=this,o=i.doc;for(let l=s.length-1;l>=0;l--){let{fromA:a,toA:h,fromB:f,toB:c}=s[l],u=r.lineAt(a,I.ByPosNoHeight,i.setDoc(t),0,0),d=u.to>=h?u:r.lineAt(h,I.ByPosNoHeight,i,0,0);for(c+=d.to-h,h=d.to;l>0&&u.from<=s[l-1].toA;)a=s[l-1].fromA,f=s[l-1].fromB,l--,ar*2){let l=e[t-1];l.break?e.splice(--t,1,l.left,null,l.right):e.splice(--t,1,l.left,l.right),i+=1+l.break,s-=l.size}else if(r>s*2){let l=e[i];l.break?e.splice(i,1,l.left,null,l.right):e.splice(i,1,l.left,l.right),i+=2+l.break,r-=l.size}else break;else if(s=r&&o(this.lineAt(0,I.ByPos,i,s,r))}setMeasuredHeight(e){let t=e.heights[e.index++];t<0?(this.spaceAbove=-t,t=e.heights[e.index++]):this.spaceAbove=0,this.setHeight(t)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more&&this.setMeasuredHeight(s),this.outdated=!1,this}toString(){return`block(${this.length})`}},be=class n extends Dn{constructor(e,t,i){super(e,t,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0,this.spaceAbove=i}mainBlock(e,t){return new Qe(t,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.breaks)}replace(e,t,i){let s=i[0];return i.length==1&&(s instanceof n||s instanceof ft&&s.flags&4)&&Math.abs(this.length-s.length)<10?(s instanceof ft?s=new n(s.length,this.height,this.spaceAbove):s.height=this.height,this.outdated||(s.outdated=!1),s):pe.of(i)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more?this.setMeasuredHeight(s):(i||this.outdated)&&(this.spaceAbove=0,this.setHeight(Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))+this.breaks*e.lineHeight)),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}},ft=class n extends pe{constructor(e){super(e,0)}heightMetrics(e,t){let i=e.doc.lineAt(t).number,s=e.doc.lineAt(t+this.length).number,r=s-i+1,o,l=0;if(e.lineWrapping){let a=Math.min(this.height,e.lineHeight*r);o=a/r,this.length>r+1&&(l=(this.height-a)/(this.length-r-1))}else o=this.height/r;return{firstLine:i,lastLine:s,perLine:o,perChar:l}}blockAt(e,t,i,s){let{firstLine:r,lastLine:o,perLine:l,perChar:a}=this.heightMetrics(t,s);if(t.lineWrapping){let h=s+(e0){let r=i[i.length-1];r instanceof n?i[i.length-1]=new n(r.length+s):i.push(null,new n(s-1))}if(e>0){let r=i[0];r instanceof n?i[0]=new n(e+r.length):i.unshift(new n(e-1),null)}return pe.of(i)}decomposeLeft(e,t){t.push(new n(e-1),null)}decomposeRight(e,t){t.push(null,new n(this.length-e-1))}updateHeight(e,t=0,i=!1,s){let r=t+this.length;if(s&&s.from<=t+this.length&&s.more){let o=[],l=Math.max(t,s.from),a=-1;for(s.from>t&&o.push(new n(s.from-t-1).updateHeight(e,t));l<=r&&s.more;){let f=e.doc.lineAt(l).length;o.length&&o.push(null);let c=s.heights[s.index++],u=0;c<0&&(u=-c,c=s.heights[s.index++]),a==-1?a=c:Math.abs(c-a)>=xn&&(a=-2);let d=new be(f,c,u);d.outdated=!1,o.push(d),l+=f+1}l<=r&&o.push(null,new n(r-l).updateHeight(e,l));let h=pe.of(o);return(a<0||Math.abs(h.height-this.height)>=xn||Math.abs(a-this.heightMetrics(e,t).perLine)>=xn)&&(li=!0),En(this,h)}else(i||this.outdated)&&(this.setHeight(e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}},gr=class extends pe{constructor(e,t,i){super(e.length+(t?1:0)+i.length,e.height+i.height,(t?1:0)|(e.outdated||i.outdated?2:0)),this.left=e,this.right=i,this.size=e.size+i.size}get break(){return this.flags&1}blockAt(e,t,i,s){let r=i+this.left.height;return el))return h;let f=t==I.ByPosNoHeight?I.ByPosNoHeight:I.ByPos;return a?h.join(this.right.lineAt(l,f,i,o,l)):this.left.lineAt(l,f,i,s,r).join(h)}forEachLine(e,t,i,s,r,o){let l=s+this.left.height,a=r+this.left.length+this.break;if(this.break)e=a&&this.right.forEachLine(e,t,i,l,a,o);else{let h=this.lineAt(a,I.ByPos,i,s,r);e=e&&h.from<=t&&o(h),t>h.to&&this.right.forEachLine(Math.max(e,h.to+1),t,i,l,a,o)}}replace(e,t,i){let s=this.left.length+this.break;if(tthis.left.length)return this.balanced(this.left,this.right.replace(e-s,t-s,i));let r=[];e>0&&this.decomposeLeft(e,r);let o=r.length;for(let l of i)r.push(l);if(e>0&&Ll(r,o-1),t=i&&t.push(null)),e>i&&this.right.decomposeLeft(e-i,t)}decomposeRight(e,t){let i=this.left.length,s=i+this.break;if(e>=s)return this.right.decomposeRight(e-s,t);e2*t.size||t.size>2*e.size?pe.of(this.break?[e,null,t]:[e,t]):(this.left=En(this.left,e),this.right=En(this.right,t),this.setHeight(e.height+t.height),this.outdated=e.outdated||t.outdated,this.size=e.size+t.size,this.length=e.length+this.break+t.length,this)}updateHeight(e,t=0,i=!1,s){let{left:r,right:o}=this,l=t+r.length+this.break,a=null;return s&&s.from<=t+r.length&&s.more?a=r=r.updateHeight(e,t,i,s):r.updateHeight(e,t,i),s&&s.from<=l+o.length&&s.more?a=o=o.updateHeight(e,l,i,s):o.updateHeight(e,l,i),a?this.balanced(r,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}};function Ll(n,e){let t,i;n[e]==null&&(t=n[e-1])instanceof ft&&(i=n[e+1])instanceof ft&&n.splice(e-1,3,new ft(t.length+1+i.length))}var bu=5,Or=class n{constructor(e,t){this.pos=e,this.oracle=t,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let i=Math.min(t,this.lineEnd),s=this.nodes[this.nodes.length-1];s instanceof be?s.length+=i-this.pos:(i>this.pos||!this.isCovered)&&this.nodes.push(new be(i-this.pos,-1,0)),this.writtenTo=i,t>i&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,i){if(e=bu)&&this.addLineDeco(s,r,o)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenToe&&this.nodes.push(new be(this.pos-e,-1,0)),this.writtenTo=this.pos}blankContent(e,t){let i=new ft(t-e);return this.oracle.doc.lineAt(e).to==t&&(i.flags|=4),i}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof be)return e;let t=new be(0,-1,0);return this.nodes.push(t),t}addBlock(e){this.enterLine();let t=e.deco;t&&t.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,t&&t.endSide>0&&(this.covering=e)}addLineDeco(e,t,i){let s=this.ensureLine();s.length+=i,s.collapsed+=i,s.widgetHeight=Math.max(s.widgetHeight,e),s.breaks+=t,this.writtenTo=this.pos=this.pos+i}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof be)&&!this.isCovered?this.nodes.push(new be(0,-1,0)):(this.writtenTof.clientHeight||f.scrollWidth>f.clientWidth)&&c.overflow!="visible"){let u=f.getBoundingClientRect();r=Math.max(r,u.left),o=Math.min(o,u.right),l=Math.max(l,u.top),a=Math.min(h==n.parentNode?s.innerHeight:a,u.bottom)}h=c.position=="absolute"||c.position=="fixed"?f.offsetParent:f.parentNode}else if(h.nodeType==11)h=h.host;else break;return{left:r-t.left,right:Math.max(r,o)-t.left,top:l-(t.top+e),bottom:Math.max(l,a)-(t.top+e)}}function ku(n){let e=n.getBoundingClientRect(),t=n.ownerDocument.defaultView||window;return e.left0&&e.top0}function wu(n,e){let t=n.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}var Ei=class{constructor(e,t,i,s){this.from=e,this.to=t,this.size=i,this.displaySize=s}static same(e,t){if(e.length!=t.length)return!1;for(let i=0;itypeof s!="function"&&s.class=="cm-lineWrapping");this.heightOracle=new pr(i),this.stateDeco=Il(t),this.heightMap=pe.empty().applyChanges(this.stateDeco,M.empty,this.heightOracle.setDoc(t.doc),[new Pe(0,0,0,t.doc.length)]);for(let s=0;s<2&&(this.viewport=this.getViewport(0,null),!!this.updateForViewport());s++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=q.set(this.lineGaps.map(s=>s.draw(this,!1))),this.scrollParent=e.scrollDOM,this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let i=0;i<=1;i++){let s=i?t.head:t.anchor;if(!e.some(({from:r,to:o})=>s>=r&&s<=o)){let{from:r,to:o}=this.lineBlockAt(s);e.push(new Jt(r,o))}}return this.viewports=e.sort((i,s)=>i.from-s.from),this.updateScaler()}updateScaler(){let e=this.scaler;return this.scaler=this.heightMap.height<=7e6?zl:new Sr(this.heightOracle,this.heightMap,this.viewports),e.eq(this.scaler)?0:2}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(Ti(e,this.scaler))})}update(e,t=null){this.state=e.state;let i=this.stateDeco;this.stateDeco=Il(this.state);let s=e.changedRanges,r=Pe.extendWithRanges(s,Su(i,this.stateDeco,e?e.changes:oe.empty(this.state.doc.length))),o=this.heightMap.height,l=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollOffset);$l(),this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),r),(this.heightMap.height!=o||li)&&(e.flags|=2),l?(this.scrollAnchorPos=e.changes.mapPos(l.from,-1),this.scrollAnchorHeight=l.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=o);let a=r.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.heada.to)||!this.viewportIsAppropriate(a))&&(a=this.getViewport(0,t));let h=a.from!=this.viewport.from||a.to!=this.viewport.to;this.viewport=a,e.flags|=this.updateForViewport(),(h||!e.changes.empty||e.flags&2)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(e.changes),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&(e.selectionSet||e.focusChanged)&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(Rc)&&(this.mustEnforceCursorAssoc=!0)}measure(){let{view:e}=this,t=e.contentDOM,i=window.getComputedStyle(t),s=this.heightOracle,r=i.whiteSpace;this.defaultTextDirection=i.direction=="rtl"?F.RTL:F.LTR;let o=this.heightOracle.mustRefreshForWrapping(r)||this.mustMeasureContent==="refresh",l=t.getBoundingClientRect(),a=o||this.mustMeasureContent||this.contentDOMHeight!=l.height;this.contentDOMHeight=l.height,this.mustMeasureContent=!1;let h=0,f=0;if(l.width&&l.height){let{scaleX:Q,scaleY:P}=Zl(t,l);(Q>.005&&Math.abs(this.scaleX-Q)>.005||P>.005&&Math.abs(this.scaleY-P)>.005)&&(this.scaleX=Q,this.scaleY=P,h|=16,o=a=!0)}let c=(parseInt(i.paddingTop)||0)*this.scaleY,u=(parseInt(i.paddingBottom)||0)*this.scaleY;(this.paddingTop!=c||this.paddingBottom!=u)&&(this.paddingTop=c,this.paddingBottom=u,h|=18),this.editorWidth!=e.scrollDOM.clientWidth&&(s.lineWrapping&&(a=!0),this.editorWidth=e.scrollDOM.clientWidth,h|=16);let d=Yl(this.view.contentDOM,!1).y;d!=this.scrollParent&&(this.scrollParent=d,this.scrollAnchorHeight=-1,this.scrollOffset=0);let p=this.getScrollOffset();this.scrollOffset!=p&&(this.scrollAnchorHeight=-1,this.scrollOffset=p),this.scrolledToBottom=ta(this.scrollParent||e.win);let m=(this.printing?wu:xu)(t,this.paddingTop),O=m.top-this.pixelViewport.top,y=m.bottom-this.pixelViewport.bottom;this.pixelViewport=m;let w=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(w!=this.inView&&(this.inView=w,w&&(a=!0)),!this.inView&&!this.scrollTarget&&!ku(e.dom))return 0;let k=l.width;if((this.contentDOMWidth!=k||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=l.width,this.editorHeight=e.scrollDOM.clientHeight,h|=16),a){let Q=e.docView.measureVisibleLineHeights(this.viewport);if(s.mustRefreshForHeights(Q)&&(o=!0),o||s.lineWrapping&&Math.abs(k-this.contentDOMWidth)>s.charWidth){let{lineHeight:P,charWidth:T,textHeight:V}=e.docView.measureTextSize();o=P>0&&s.refresh(r,P,T,V,Math.max(5,k/T),Q),o&&(e.docView.minWidth=0,h|=16)}O>0&&y>0?f=Math.max(O,y):O<0&&y<0&&(f=Math.min(O,y)),$l();for(let P of this.viewports){let T=P.from==this.viewport.from?Q:e.docView.measureVisibleLineHeights(P);this.heightMap=(o?pe.empty().applyChanges(this.stateDeco,M.empty,this.heightOracle,[new Pe(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(s,0,o,new mr(P.from,T))}li&&(h|=2)}let D=!this.viewportIsAppropriate(this.viewport,f)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return D&&(h&2&&(h|=this.updateScaler()),this.viewport=this.getViewport(f,this.scrollTarget),h|=this.updateForViewport()),(h&2||D)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,e)),h|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),h}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let i=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),s=this.heightMap,r=this.heightOracle,{visibleTop:o,visibleBottom:l}=this,a=new Jt(s.lineAt(o-i*1e3,I.ByHeight,r,0,0).from,s.lineAt(l+(1-i)*1e3,I.ByHeight,r,0,0).to);if(t){let{head:h}=t.range;if(ha.to){let f=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),c=s.lineAt(h,I.ByPos,r,0,0),u;t.y=="center"?u=(c.top+c.bottom)/2-f/2:t.y=="start"||t.y=="nearest"&&h=l+Math.max(10,Math.min(i,250)))&&s>o-2*1e3&&r>1,o=s<<1;if(this.defaultTextDirection!=F.LTR&&!i)return[];let l=[],a=(f,c,u,d)=>{if(c-ff&&yy.from>=u.from&&y.to<=u.to&&Math.abs(y.from-f)y.fromw));if(!O){if(ck.from<=c&&k.to>=c)){let k=t.moveToLineBoundary(b.cursor(c),!1,!0).head;k>f&&(c=k)}let y=this.gapSize(u,f,c,d),w=i||y<2e6?y:2e6;O=new Ei(f,c,y,w)}l.push(O)},h=f=>{if(f.length2e6)for(let P of e)P.from>=f.from&&P.fromf.from&&a(f.from,d,f,c),pt.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(e){let t=this.stateDeco;this.lineGaps.length&&(t=t.concat(this.lineGapDeco));let i=[];B.spans(t,this.viewport.from,this.viewport.to,{span(r,o){i.push({from:r,to:o})},point(){}},20);let s=0;if(i.length!=this.visibleRanges.length)s=12;else for(let r=0;r=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||Ti(this.heightMap.lineAt(e,I.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return e>=this.viewportLines[0].top&&e<=this.viewportLines[this.viewportLines.length-1].bottom&&this.viewportLines.find(t=>t.top<=e&&t.bottom>=e)||Ti(this.heightMap.lineAt(this.scaler.fromDOM(e),I.ByHeight,this.heightOracle,0,0),this.scaler)}getScrollOffset(){return this.scrollParent==this.view.scrollDOM?this.scrollParent.scrollTop*this.scaleY:(this.scrollParent?this.scrollParent.getBoundingClientRect().top:0)-this.view.contentDOM.getBoundingClientRect().top}scrollAnchorAt(e){let t=this.lineBlockAtHeight(e+8);return t.from>=this.viewport.from||this.viewportLines[0].top-e>200?t:this.viewportLines[0]}elementAtHeight(e){return Ti(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}},Jt=class{constructor(e,t){this.from=e,this.to=t}};function vu(n,e,t){let i=[],s=n,r=0;return B.spans(t,n,e,{span(){},point(o,l){o>s&&(i.push({from:s,to:o}),r+=o-s),s=l}},20),s=1)return e[e.length-1].to;let i=Math.floor(n*t);for(let s=0;;s++){let{from:r,to:o}=e[s],l=o-r;if(i<=l)return r+i;i-=l}}function On(n,e){let t=0;for(let{from:i,to:s}of n.ranges){if(e<=s){t+=e-i;break}t+=s-i}return t/n.total}function Tu(n,e){for(let t of n)if(e(t))return t}var zl={toDOM(n){return n},fromDOM(n){return n},scale:1,eq(n){return n==this}};function Il(n){let e=n.facet(zn).filter(i=>typeof i!="function"),t=n.facet(Wr).filter(i=>typeof i!="function");return t.length&&e.push(B.join(t)),e}var Sr=class n{constructor(e,t,i){let s=0,r=0,o=0;this.viewports=i.map(({from:l,to:a})=>{let h=t.lineAt(l,I.ByPos,e,0,0).top,f=t.lineAt(a,I.ByPos,e,0,0).bottom;return s+=f-h,{from:l,to:a,top:h,bottom:f,domTop:0,domBottom:0}}),this.scale=(7e6-s)/(t.height-s);for(let l of this.viewports)l.domTop=o+(l.top-r)*this.scale,o=l.domBottom=l.domTop+(l.bottom-l.top),r=l.bottom}toDOM(e){for(let t=0,i=0,s=0;;t++){let r=tt.from==e.viewports[i].from&&t.to==e.viewports[i].to):!1}};function Ti(n,e){if(e.scale==1)return n;let t=e.toDOM(n.top),i=e.toDOM(n.bottom);return new Qe(n.from,n.length,t,i-t,Array.isArray(n._content)?n._content.map(s=>Ti(s,e)):n._content)}var yn=v.define({combine:n=>n.join(" ")}),xr=v.define({combine:n=>n.indexOf(!0)>-1}),kr=ye.newName(),$a=ye.newName(),La=ye.newName(),za={"&light":"."+$a,"&dark":"."+La};function wr(n,e,t){return new ye(e,{finish(i){return/&/.test(i)?i.replace(/&\w*/,s=>{if(s=="&")return n;if(!t||!t[s])throw new RangeError(`Unsupported selector: ${s}`);return t[s]}):n+" "+i}})}var Cu=wr("."+kr,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0,overflowAnchor:"none"},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{userSelect:"none",position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#ddd"},".cm-selectionHandle":{backgroundColor:"currentColor",width:"1.5px"},".cm-selectionHandle-start::before, .cm-selectionHandle-end::before":{content:'""',backgroundColor:"inherit",borderRadius:"50%",width:"8px",height:"8px",position:"absolute",left:"-3.25px"},".cm-selectionHandle-start::before":{top:"-8px"},".cm-selectionHandle-end::before":{bottom:"-8px"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",zIndex:200},".cm-gutters-before":{insetInlineStart:0},".cm-gutters-after":{insetInlineEnd:0},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",border:"0px solid #ddd","&.cm-gutters-before":{borderRightWidth:"1px"},"&.cm-gutters-after":{borderLeftWidth:"1px"}},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0,zIndex:300},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},".cm-panels-top":{top:"0"},".cm-panels-bottom":{bottom:"0"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-dialog":{padding:"2px 19px 4px 6px",position:"relative","& label":{fontSize:"80%"}},".cm-dialog-close":{position:"absolute",top:"3px",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",fontSize:"14px",padding:"0"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top",userSelect:"none"},".cm-highlightSpace":{background:"radial-gradient(circle at 50% 55%, #aaa 20%, transparent 0) no-repeat",backgroundSize:".4em",backgroundPosition:"calc(min(50%, 0px)) center"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},za),Qu={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Is=x.ie&&x.ie_version<=11,vr=class{constructor(e){this.view=e,this.active=!1,this.editContext=null,this.selectionRange=new js,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let i of t)this.queue.push(i);(x.ie&&x.ie_version<=11||x.ios&&e.composing)&&t.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),window.EditContext&&x.android&&e.constructor.EDIT_CONTEXT!==!1&&!(x.chrome&&x.chrome_version<126)&&(this.editContext=new Tr(e),e.state.facet(Ge)&&(e.contentDOM.editContext=this.editContext.editContext)),Is&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate){this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(t=>{t.length>0&&t[t.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.editContext&&this.view.requestMeasure(this.editContext.measureReq),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(e){(e.type=="change"||!e.type)&&!e.matches||(this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500))}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((t,i)=>t!=e[i]))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:i}=this,s=this.selectionRange;if(i.state.facet(Ge)?i.root.activeElement!=this.dom:!Ci(this.dom,s))return;let r=s.anchorNode&&i.docView.tile.nearest(s.anchorNode);if(r&&r.isWidget()&&r.widget.ignoreEvent(e)){t||(this.selectionChanged=!1);return}(x.ie&&x.ie_version<=11||x.android&&x.chrome)&&!i.state.selection.main.empty&&s.focusNode&&Qi(s.focusNode,s.focusOffset,s.anchorNode,s.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=Wi(e.root);if(!t)return!1;let i=x.safari&&e.root.nodeType==11&&e.root.activeElement==this.dom&&Pu(this.view,t)||t;if(!i||this.selectionRange.eq(i))return!1;let s=Ci(this.dom,i);return s&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime{let r=this.delayedAndroidKey;r&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=r.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&r.force&&ii(this.dom,r.key,r.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(s)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let t=-1,i=-1,s=!1;for(let r of e){let o=this.readMutation(r);o&&(o.typeOver&&(s=!0),t==-1?{from:t,to:i}=o:(t=Math.min(o.from,t),i=Math.max(o.to,i)))}return{from:t,to:i,typeOver:s}}readChange(){let{from:e,to:t,typeOver:i}=this.processRecords(),s=this.selectionChanged&&Ci(this.dom,this.selectionRange);if(e<0&&!s)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let r=new fr(this.view,e,t,i);return this.view.docView.domChanged={newSel:r.newSel?r.newSel.main:null},r}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return this.view.requestMeasure(),!1;let i=this.view.state,s=Qa(this.view,t);return this.view.state==i&&(t.domChanged||t.newSel&&!Mn(this.view.state.selection,t.newSel.main))&&this.view.update([]),s}readMutation(e){let t=this.view.docView.tile.nearest(e.target);if(!t||t.isWidget())return null;if(t.markDirty(e.type=="attributes"),e.type=="childList"){let i=Nl(t,e.previousSibling||e.target.previousSibling,-1),s=Nl(t,e.nextSibling||e.target.nextSibling,1);return{from:i?t.posAfter(i):t.posAtStart,to:s?t.posBefore(s):t.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),this.printQuery?this.printQuery.addEventListener?this.printQuery.addEventListener("change",this.onPrint):this.printQuery.addListener(this.onPrint):e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),this.printQuery?this.printQuery.removeEventListener?this.printQuery.removeEventListener("change",this.onPrint):this.printQuery.removeListener(this.onPrint):e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}update(e){this.editContext&&(this.editContext.update(e),e.startState.facet(Ge)!=e.state.facet(Ge)&&(e.view.contentDOM.editContext=e.state.facet(Ge)?this.editContext.editContext:null))}destroy(){var e,t,i;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(t=this.gapIntersection)===null||t===void 0||t.disconnect(),(i=this.resizeScroll)===null||i===void 0||i.disconnect();for(let s of this.scrollTargets)s.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}};function Nl(n,e,t){for(;e;){let i=_.get(e);if(i&&i.parent==n)return i;let s=e.parentNode;e=s!=n.dom?s:t>0?e.nextSibling:e.previousSibling}return null}function Vl(n,e){let t=e.startContainer,i=e.startOffset,s=e.endContainer,r=e.endOffset,o=n.docView.domAtPos(n.state.selection.main.anchor,1);return Qi(o.node,o.offset,s,r)&&([t,i,s,r]=[s,r,t,i]),{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}}function Pu(n,e){if(e.getComposedRanges){let s=e.getComposedRanges(n.root)[0];if(s)return Vl(n,s)}let t=null;function i(s){s.preventDefault(),s.stopImmediatePropagation(),t=s.getTargetRanges()[0]}return n.contentDOM.addEventListener("beforeinput",i,!0),n.dom.ownerDocument.execCommand("indent"),n.contentDOM.removeEventListener("beforeinput",i,!0),t?Vl(n,t):null}var Tr=class{constructor(e){this.from=0,this.to=0,this.pendingContextChange=null,this.handlers=Object.create(null),this.composing=null,this.resetRange(e.state);let t=this.editContext=new window.EditContext({text:e.state.doc.sliceString(this.from,this.to),selectionStart:this.toContextPos(Math.max(this.from,Math.min(this.to,e.state.selection.main.anchor))),selectionEnd:this.toContextPos(e.state.selection.main.head)});this.handlers.textupdate=i=>{let s=e.state.selection.main,{anchor:r,head:o}=s,l=this.toEditorPos(i.updateRangeStart),a=this.toEditorPos(i.updateRangeEnd);e.inputState.composing>=0&&!this.composing&&(this.composing={contextBase:i.updateRangeStart,editorBase:l,drifted:!1});let h=a-l>i.text.length;l==this.from&&rthis.to&&(a=r);let f=Pa(e.state.sliceDoc(l,a),i.text,(h?s.from:s.to)-l,h?"end":null);if(!f){let u=b.single(this.toEditorPos(i.selectionStart),this.toEditorPos(i.selectionEnd));Mn(u,s)||e.dispatch({selection:u,userEvent:"select"});return}let c={from:f.from+l,to:f.toA+l,insert:M.of(i.text.slice(f.from,f.toB).split(` +`))};if((x.mac||x.android)&&c.from==o-1&&/^\. ?$/.test(i.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(c={from:l,to:a,insert:M.of([i.text.replace("."," ")])}),this.pendingContextChange=c,!e.state.readOnly){let u=this.to-this.from+(c.to-c.from+c.insert.length);$r(e,c,b.single(this.toEditorPos(i.selectionStart,u),this.toEditorPos(i.selectionEnd,u)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),c.from=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(t.text.slice(Math.max(0,i.updateRangeStart-1),Math.min(t.text.length,i.updateRangeStart+1)))&&this.handlers.compositionend(i)},this.handlers.characterboundsupdate=i=>{let s=[],r=null;for(let o=this.toEditorPos(i.rangeStart),l=this.toEditorPos(i.rangeEnd);o{let s=[];for(let r of i.getTextFormats()){let o=r.underlineStyle,l=r.underlineThickness;if(!/none/i.test(o)&&!/none/i.test(l)){let a=this.toEditorPos(r.rangeStart),h=this.toEditorPos(r.rangeEnd);if(a{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:i}=this.composing;this.composing=null,i&&this.reset(e.state)}};for(let i in this.handlers)t.addEventListener(i,this.handlers[i]);this.measureReq={read:i=>{let s=Wi(i.root);s&&s.rangeCount&&this.editContext.updateSelectionBounds(s.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,i=!1,s=this.pendingContextChange;return e.changes.iterChanges((r,o,l,a,h)=>{if(i)return;let f=h.length-(o-r);if(s&&o>=s.to)if(s.from==r&&s.to==o&&s.insert.eq(h)){s=this.pendingContextChange=null,t+=f,this.to+=f;return}else s=null,this.revertPending(e.state);if(r+=t,o+=t,o<=this.from)this.from+=f,this.to+=f;else if(rthis.to||this.to-this.from+h.length>3e4){i=!0;return}this.editContext.updateText(this.toContextPos(r),this.toContextPos(o),h.toString()),this.to+=f}t+=f}),s&&!i&&this.revertPending(e.state),!i}update(e){let t=this.pendingContextChange,i=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(i.from,i.to)&&e.transactions.some(s=>!s.isUserEvent("input.type")&&s.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||t)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:t}=e.selection.main;this.from=Math.max(0,t-1e4),this.to=Math.min(e.doc.length,t+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.from+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,i=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),s=this.toContextPos(t.head);(this.editContext.selectionStart!=i||this.editContext.selectionEnd!=s)&&this.editContext.updateSelection(i,s)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to1e4*3)}toEditorPos(e,t=this.to-this.from){e=Math.min(e,t);let i=this.composing;return i&&i.drifted?i.editorBase+(e-i.contextBase):e+this.from}toContextPos(e){let t=this.composing;return t&&t.drifted?t.contextBase+(e-t.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}},C=class n{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){var t;this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.clearAnnouncement=-1,this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:i}=e;this.dispatchTransactions=e.dispatchTransactions||i&&(s=>s.forEach(r=>i(r,this)))||(s=>this.update(s)),this.dispatch=this.dispatch.bind(this),this._root=e.root||bc(e.parent)||document,this.viewState=new Bn(this,e.state||z.create(e)),e.scrollTo&&e.scrollTo.is(dn)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(Kt).map(s=>new Ai(s));for(let s of this.plugins)s.update(this);this.observer=new vr(this),this.inputState=new cr(this),this.inputState.ensureHandlers(this.plugins),this.docView=new An(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),!((t=document.fonts)===null||t===void 0)&&t.ready&&document.fonts.ready.then(()=>{this.viewState.mustMeasureContent="refresh",this.requestMeasure()})}dispatch(...e){let t=e.length==1&&e[0]instanceof G?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(t,this)}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let t=!1,i=!1,s,r=this.state;for(let u of e){if(u.startState!=r)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");r=u.state}if(this.destroyed){this.viewState.state=r;return}let o=this.hasFocus,l=0,a=null;e.some(u=>u.annotation(Ba))?(this.inputState.notifiedFocused=o,l=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,a=qa(r,o),a||(l=1));let h=this.observer.delayedAndroidKey,f=null;if(h?(this.observer.clearDelayedAndroidKey(),f=this.observer.readChange(),(f&&!this.state.doc.eq(r.doc)||!this.state.selection.eq(r.selection))&&(f=null)):this.observer.clear(),r.facet(z.phrases)!=this.state.facet(z.phrases))return this.setState(r);s=Qn.create(this,r,e),s.flags|=l;let c=this.viewState.scrollTarget;try{this.updateState=2;for(let u of e){if(c&&(c=c.map(u.changes)),u.scrollIntoView){let{main:d}=u.state.selection,{x:p,y:m}=this.state.facet(n.cursorScrollMargin);c=new Pi(d.empty?d:b.cursor(d.head,d.head>d.anchor?-1:1),"nearest","nearest",m,p)}for(let d of u.effects)d.is(dn)&&(c=d.value.clip(this.state))}this.viewState.update(s,c),this.bidiCache=qn.update(this.bidiCache,s.changes),s.empty||(this.updatePlugins(s),this.inputState.update(s)),t=this.docView.update(s),this.state.facet(vi)!=this.styleModules&&this.mountStyles(),i=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(u=>u.isUserEvent("select.pointer")))}finally{this.updateState=0}if(s.startState.facet(yn)!=s.state.facet(yn)&&(this.viewState.mustMeasureContent=!0),(t||i||c||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),t&&this.docViewUpdate(),!s.empty)for(let u of this.state.facet(Ks))try{u(s)}catch(d){ke(this.state,d,"update listener")}(a||f)&&Promise.resolve().then(()=>{a&&this.state==a.startState&&this.dispatch(a),f&&!Qa(this,f)&&h.force&&ii(this.contentDOM,h.key,h.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let i of this.plugins)i.destroy(this);this.viewState=new Bn(this,e),this.plugins=e.facet(Kt).map(i=>new Ai(i)),this.pluginMap.clear();for(let i of this.plugins)i.update(this);this.docView.destroy(),this.docView=new An(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(Kt),i=e.state.facet(Kt);if(t!=i){let s=[];for(let r of i){let o=t.indexOf(r);if(o<0)s.push(new Ai(r));else{let l=this.plugins[o];l.mustUpdate=e,s.push(l)}}for(let r of this.plugins)r.mustUpdate!=e&&r.destroy(this);this.plugins=s,this.pluginMap.clear()}else for(let s of this.plugins)s.mustUpdate=e;for(let s=0;s-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,i=this.viewState.scrollParent,s=this.viewState.getScrollOffset(),{scrollAnchorPos:r,scrollAnchorHeight:o,scaleY:l}=this.viewState;Math.abs(s-this.viewState.scrollOffset)>1&&(o=-1),this.viewState.scrollAnchorHeight=-1;try{for(let a=0;;a++){if(o<0){if(ta(i||this.win))r=-1,o=this.viewState.heightMap.height/this.viewState.scaleY;else{let p=this.viewState.scrollAnchorAt(s);r=p.from,o=p.top}l=this.viewState.scaleY}this.updateState=1;let h=this.viewState.measure();if(!h&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(a>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let f=[];h&4||([this.measureRequests,f]=[f,this.measureRequests]);let c=f.map(p=>{try{return p.read(this)}catch(m){return ke(this.state,m),Xl}}),u=Qn.create(this,this.state,[]),d=!1;u.flags|=h,t?t.flags|=h:t=u,this.updateState=2,u.empty||(this.updatePlugins(u),this.inputState.update(u),this.updateAttrs(),d=this.docView.update(u),d&&this.docViewUpdate());for(let p=0;p1||m<-1)&&!(x.ios&&this.inputState.lastIOSMomentumScroll>Date.now()-100)&&(i==this.scrollDOM||this.hasFocus||Math.max(this.inputState.lastWheelEvent,this.inputState.lastTouchTime)>Date.now()-100)){s=s+m,i?r<0?i.scrollTop=i.scrollHeight:i.scrollTop+=m:this.win.scrollBy(0,m),o=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let a of this.state.facet(Ks))a(t)}get themeClasses(){return kr+" "+(this.state.facet(xr)?La:$a)+" "+this.state.facet(yn)}updateAttrs(){let e=Fl(this,ya,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",translate:"no",contenteditable:this.state.facet(Ge)?"true":"false",class:"cm-content",style:`${x.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),Fl(this,qr,t);let i=this.observer.ignore(()=>{let s=kl(this.contentDOM,this.contentAttrs,t),r=kl(this.dom,this.editorAttrs,e);return s||r});return this.editorAttrs=e,this.contentAttrs=t,i}showAnnouncements(e){let t=!0;for(let i of e)for(let s of i.effects)if(s.is(n.announce)){t&&(this.announceDOM.textContent="",this.win.clearTimeout(this.clearAnnouncement),this.clearAnnouncement=this.win.setTimeout(()=>{this.announceDOM.textContent="\xA0"},200),t=!1);let r=this.announceDOM.appendChild(document.createElement("div"));r.textContent=s.value}}mountStyles(){this.styleModules=this.state.facet(vi);let e=this.state.facet(n.cspNonce);ye.mount(this.root,this.styleModules.concat(Cu).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let t=0;ti.plugin==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,i){return zs(this,e,Pl(this,e,t,i))}moveByGroup(e,t){return zs(this,e,Pl(this,e,t,i=>Zc(this,e.head,i)))}visualLineSide(e,t){return t?b.cursor(e.to,1):b.cursor(e.from,-1)}moveToLineBoundary(e,t,i=!0){return Gc(this,e,t,i)}moveVertically(e,t,i){return zs(this,e,Yc(this,e,t,i))}domAtPos(e,t=1){return this.docView.domAtPos(e,t)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){this.readMeasured();let i=lr(this,e,t);return i&&i.pos}posAndSideAtCoords(e,t=!0){return this.readMeasured(),lr(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let i=this.state.doc.lineAt(e),s=this.bidiSpans(i),r=s[xe.find(s,e-i.from,-1,t)];return i.length&&(e==i.from&&t<0||e==i.to&&t>0)&&r.dir!=this.textDirectionAt(i.from)&&(e==i.to?(e=i.from+r.from,t=1):(e=i.from+r.to,t=-1)),this.docView.coordsAt(e,t,r.dir==F.RTL)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(ma)||ethis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>Au)return la(e.length);let t=this.textDirectionAt(e.from),i;for(let r of this.bidiCache)if(r.from==e.from&&r.dir==t&&(r.fresh||oa(r.isolates,i=Tl(this,e))))return r.order;i||(i=Tl(this,e));let s=Qc(e.text,t,i);return this.bidiCache.push(new qn(e.from,e.to,t,i,!0,s)),s}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||x.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{ea(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.win.clearTimeout(this.clearAnnouncement),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){var i,s,r,o;return dn.of(new Pi(typeof e=="number"?b.cursor(e):e,(i=t.y)!==null&&i!==void 0?i:"nearest",(s=t.x)!==null&&s!==void 0?s:"nearest",(r=t.yMargin)!==null&&r!==void 0?r:5,(o=t.xMargin)!==null&&o!==void 0?o:5))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,i=this.viewState.scrollAnchorAt(e);return dn.of(new Pi(b.cursor(i.from),"start","start",i.top-e,t,!0))}setTabFocusMode(e){e==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof e=="boolean"?this.inputState.tabFocusMode=e?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+e)}static domEventHandlers(e){return Le.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return Le.define(()=>({}),{eventObservers:e})}static theme(e,t){let i=ye.newName(),s=[yn.of(i),vi.of(wr(`.${i}`,e))];return t&&t.dark&&s.push(xr.of(!0)),s}static baseTheme(e){return at.lowest(vi.of(wr("."+kr,e,za)))}static findFromDOM(e){var t;let i=e.querySelector(".cm-content"),s=i&&_.get(i)||_.get(e);return((t=s?.root)===null||t===void 0?void 0:t.view)||null}};C.styleModule=vi;C.inputHandler=da;C.clipboardInputFilter=Dr;C.clipboardOutputFilter=Br;C.scrollHandler=ga;C.focusChangeEffect=pa;C.perLineTextDirection=ma;C.exceptionSink=ua;C.updateListener=Ks;C.editable=Ge;C.mouseSelectionStyle=ca;C.dragMovesSelection=fa;C.clickAddsSelectionRange=ha;C.decorations=zn;C.blockWrappers=ba;C.outerDecorations=Wr;C.atomicRanges=Li;C.bidiIsolatedRanges=Sa;C.cursorScrollMargin=v.define({combine:n=>{let e=5,t=5;for(let i of n)typeof i=="number"?e=t=i:{x:e,y:t}=i;return{x:e,y:t}}});C.scrollMargins=xa;C.darkTheme=xr;C.cspNonce=v.define({combine:n=>n.length?n[0]:""});C.contentAttributes=qr;C.editorAttributes=ya;C.lineWrapping=C.contentAttributes.of({class:"cm-lineWrapping"});C.announce=W.define();var Au=4096,Xl={},qn=class n{constructor(e,t,i,s,r,o){this.from=e,this.to=t,this.dir=i,this.isolates=s,this.fresh=r,this.order=o}static update(e,t){if(t.empty&&!e.some(r=>r.fresh))return e;let i=[],s=e.length?e[e.length-1].dir:F.LTR;for(let r=Math.max(0,e.length-10);r=0;s--){let r=i[s],o=typeof r=="function"?r(n):r;o&&Rr(o,t)}return t}var Ru=x.mac?"mac":x.windows?"win":x.linux?"linux":"key";function Mu(n,e){let t=n.split(/-(?!$)/),i=t[t.length-1];i=="Space"&&(i=" ");let s,r,o,l;for(let a=0;ai.concat(s),[]))),t}var ht=null,Bu=4e3;function qu(n,e=Ru){let t=Object.create(null),i=Object.create(null),s=(o,l)=>{let a=i[o];if(a==null)i[o]=l;else if(a!=l)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},r=(o,l,a,h,f)=>{var c,u;let d=t[o]||(t[o]=Object.create(null)),p=l.split(/ (?!$)/).map(y=>Mu(y,e));for(let y=1;y{let D=ht={view:k,prefix:w,scope:o};return setTimeout(()=>{ht==D&&(ht=null)},Bu),!0}]})}let m=p.join(" ");s(m,!1);let O=d[m]||(d[m]={preventDefault:!1,stopPropagation:!1,run:((u=(c=d._any)===null||c===void 0?void 0:c.run)===null||u===void 0?void 0:u.slice())||[]});a&&O.run.push(a),h&&(O.preventDefault=!0),f&&(O.stopPropagation=!0)};for(let o of n){let l=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let h of l){let f=t[h]||(t[h]=Object.create(null));f._any||(f._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:c}=o;for(let u in f)f[u].run.push(d=>c(d,Cr))}let a=o[e]||o.key;if(a)for(let h of l)r(h,a,o.run,o.preventDefault,o.stopPropagation),o.shift&&r(h,"Shift-"+a,o.shift,o.preventDefault,o.stopPropagation)}return t}var Cr=null;function Wu(n,e,t,i){Cr=e;let s=yl(e),r=lt(s,0),o=Gt(r)==s.length&&s!=" ",l="",a=!1,h=!1,f=!1;ht&&ht.view==t&&ht.scope==i&&(l=ht.prefix+" ",Ra.indexOf(e.keyCode)<0&&(h=!0,ht=null));let c=new Set,u=O=>{if(O){for(let y of O.run)if(!c.has(y)&&(c.add(y),y(t)))return O.stopPropagation&&(f=!0),!0;O.preventDefault&&(O.stopPropagation&&(f=!0),h=!0)}return!1},d=n[i],p,m;return d&&(u(d[l+bn(s,e,!o)])?a=!0:o&&(e.altKey||e.metaKey||e.ctrlKey)&&!(x.windows&&e.ctrlKey&&e.altKey)&&!(x.mac&&e.altKey&&!(e.ctrlKey||e.metaKey))&&(p=je[e.keyCode])&&p!=s?(u(d[l+bn(p,e,!0)])||e.shiftKey&&(m=Zt[e.keyCode])!=s&&m!=p&&u(d[l+bn(m,e,!1)]))&&(a=!0):o&&e.shiftKey&&u(d[l+bn(s,e,!0)])&&(a=!0),!a&&u(d._any)&&(a=!0)),h&&(a=!0),a&&f&&e.stopPropagation(),Cr=null,a}var $u=x.gecko&&x.gecko_version==153?"#ffffff01":"transparent",Lg=at.highest(C.theme({".cm-line":{"& ::selection, &::selection":{backgroundColor:`${$u} !important`},caretColor:"transparent !important"},".cm-content":{caretColor:"transparent !important","& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}}));var zg=/x/.unicode!=null?"gu":"g";var ze=class extends Oe{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}};ze.prototype.elementClass="";ze.prototype.toDOM=void 0;ze.prototype.mapMode=Y.TrackBefore;ze.prototype.startSide=ze.prototype.endSide=-1;ze.prototype.point=!0;var Ns=v.define(),Lu=v.define();var kn=v.define();var Qr=v.define({combine:n=>n.some(e=>e)});function zu(n){let e=[Iu];return n&&n.fixed===!1&&e.push(Qr.of(!0)),e}var Iu=Le.fromClass(class{constructor(n){this.view=n,this.domAfter=null,this.prevViewport=n.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters cm-gutters-before",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=n.state.facet(kn).map(e=>new Wn(n,e)),this.fixed=!n.state.facet(Qr);for(let e of this.gutters)e.config.side=="after"?this.getDOMAfter().appendChild(e.dom):this.dom.appendChild(e.dom);this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),n.scrollDOM.insertBefore(this.dom,n.contentDOM)}getDOMAfter(){return this.domAfter||(this.domAfter=document.createElement("div"),this.domAfter.className="cm-gutters cm-gutters-after",this.domAfter.setAttribute("aria-hidden","true"),this.domAfter.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.domAfter.style.position=this.fixed?"sticky":"",this.view.scrollDOM.appendChild(this.domAfter)),this.domAfter}update(n){if(this.updateGutters(n)){let e=this.prevViewport,t=n.view.viewport,i=Math.min(e.to,t.to)-Math.max(e.from,t.from);this.syncGutters(i<(t.to-t.from)*.8)}if(n.geometryChanged){let e=this.view.contentHeight/this.view.scaleY+"px";this.dom.style.minHeight=e,this.domAfter&&(this.domAfter.style.minHeight=e)}this.view.state.facet(Qr)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":"",this.domAfter&&(this.domAfter.style.position=this.fixed?"sticky":"")),this.prevViewport=n.view.viewport}syncGutters(n){let e=this.dom.nextSibling;n&&(this.dom.remove(),this.domAfter&&this.domAfter.remove());let t=B.iter(this.view.state.facet(Ns),this.view.viewport.from),i=[],s=this.gutters.map(r=>new Ar(r,this.view.viewport,-this.view.documentPadding.top));for(let r of this.view.viewportLineBlocks)if(i.length&&(i=[]),Array.isArray(r.type)){let o=!0;for(let l of r.type)if(l.type==ue.Text&&o){Pr(t,i,l.from);for(let a of s)a.line(this.view,l,i);o=!1}else if(l.widget)for(let a of s)a.widget(this.view,l)}else if(r.type==ue.Text){Pr(t,i,r.from);for(let o of s)o.line(this.view,r,i)}else if(r.widget)for(let o of s)o.widget(this.view,r);for(let r of s)r.finish();n&&(this.view.scrollDOM.insertBefore(this.dom,e),this.domAfter&&this.view.scrollDOM.appendChild(this.domAfter))}updateGutters(n){let e=n.startState.facet(kn),t=n.state.facet(kn),i=n.docChanged||n.heightChanged||n.viewportChanged||!B.eq(n.startState.facet(Ns),n.state.facet(Ns),n.view.viewport.from,n.view.viewport.to);if(e==t)for(let s of this.gutters)s.update(n)&&(i=!0);else{i=!0;let s=[];for(let r of t){let o=e.indexOf(r);o<0?s.push(new Wn(this.view,r)):(this.gutters[o].update(n),s.push(this.gutters[o]))}for(let r of this.gutters)r.dom.remove(),s.indexOf(r)<0&&r.destroy();for(let r of s)r.config.side=="after"?this.getDOMAfter().appendChild(r.dom):this.dom.appendChild(r.dom);this.gutters=s}return i}destroy(){for(let n of this.gutters)n.destroy();this.dom.remove(),this.domAfter&&this.domAfter.remove()}},{provide:n=>C.scrollMargins.of(e=>{let t=e.plugin(n);if(!t||t.gutters.length==0||!t.fixed)return null;let i=t.dom.offsetWidth*e.scaleX,s=t.domAfter?t.domAfter.offsetWidth*e.scaleX:0;return e.textDirection==F.LTR?{left:i,right:s}:{right:i,left:s}})});function Hl(n){return Array.isArray(n)?n:[n]}function Pr(n,e,t){for(;n.value&&n.from<=t;)n.from==t&&e.push(n.value),n.next()}var Ar=class{constructor(e,t,i){this.gutter=e,this.height=i,this.i=0,this.cursor=B.iter(e.markers,t.from)}addElement(e,t,i){let{gutter:s}=this,r=(t.top-this.height)/e.scaleY,o=t.height/e.scaleY;if(this.i==s.elements.length){let l=new $n(e,o,r,i);s.elements.push(l),s.dom.appendChild(l.dom)}else s.elements[this.i].update(e,o,r,i);this.height=t.bottom,this.i++}line(e,t,i){let s=[];Pr(this.cursor,s,t.from),i.length&&(s=s.concat(i));let r=this.gutter.config.lineMarker(e,t,s);r&&s.unshift(r);let o=this.gutter;s.length==0&&!o.config.renderEmptyElements||this.addElement(e,t,s)}widget(e,t){let i=this.gutter.config.widgetMarker(e,t.widget,t),s=i?[i]:null;for(let r of e.state.facet(Lu)){let o=r(e,t.widget,t);o&&(s||(s=[])).push(o)}s&&this.addElement(e,t,s)}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}},Wn=class{constructor(e,t){this.view=e,this.config=t,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let i in t.domEventHandlers)this.dom.addEventListener(i,s=>{let r=s.target,o;if(r!=this.dom&&this.dom.contains(r)){for(;r.parentNode!=this.dom;)r=r.parentNode;let a=r.getBoundingClientRect();o=(a.top+a.bottom)/2}else o=s.clientY;let l=e.lineBlockAtHeight(o-e.documentTop);t.domEventHandlers[i](e,l,s)&&s.preventDefault()});this.markers=Hl(t.markers(e)),t.initialSpacer&&(this.spacer=new $n(e,0,0,[t.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let t=this.markers;if(this.markers=Hl(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let s=this.config.updateSpacer(this.spacer.markers[0],e);s!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[s])}let i=e.view.viewport;return!B.eq(this.markers,t,i.from,i.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}},$n=class{constructor(e,t,i,s){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,t,i,s)}update(e,t,i,s){this.height!=t&&(this.height=t,this.dom.style.height=t+"px"),this.above!=i&&(this.dom.style.marginTop=(this.above=i)?i+"px":""),Nu(this.markers,s)||this.setMarkers(e,s)}setMarkers(e,t){let i="cm-gutterElement",s=this.dom.firstChild;for(let r=0,o=0;;){let l=o,a=rr(l,a,h)||o(l,a,h):o}return i}})}}),Di=class extends ze{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}};function Vs(n,e){return n.state.facet(ei).formatNumber(e,n.state)}var Fu=kn.compute([ei],n=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(Vu)},lineMarker(e,t,i){return i.some(s=>s.toDOM)?null:new Di(Vs(e,e.state.doc.lineAt(t.from).number))},widgetMarker:(e,t,i)=>{for(let s of e.state.facet(Xu)){let r=s(e,t,i);if(r)return r}return null},lineMarkerChange:e=>e.startState.facet(ei)!=e.state.facet(ei),initialSpacer(e){return new Di(Vs(e,Ul(e.state.doc.lines)))},updateSpacer(e,t){let i=Vs(t.view,Ul(t.view.state.doc.lines));return i==e.number?e:new Di(i)},domEventHandlers:n.facet(ei).domEventHandlers,side:"before"}));function Ia(n={}){return[ei.of(n),zu(),Fu]}function Ul(n){let e=9;for(;e{throw new Error("This node type doesn't define a deserialize function")}),this.combine=e.combine||null}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=ie.match(e)),t=>{let i=e(t);return i===void 0?null:[this,i]}}};R.closedBy=new R({deserialize:n=>n.split(" ")});R.openedBy=new R({deserialize:n=>n.split(" ")});R.group=new R({deserialize:n=>n.split(" ")});R.isolate=new R({deserialize:n=>{if(n&&n!="rtl"&&n!="ltr"&&n!="auto")throw new RangeError("Invalid value for isolate: "+n);return n||"auto"}});R.contextHash=new R({perNode:!0});R.lookAhead=new R({perNode:!0});R.mounted=new R({perNode:!0});var Et=class{constructor(e,t,i,s=!1){this.tree=e,this.overlay=t,this.parser=i,this.bracketed=s}static get(e){return e&&e.props&&e.props[R.mounted.id]}},Hu=Object.create(null),ie=class n{constructor(e,t,i,s=0){this.name=e,this.props=t,this.id=i,this.flags=s}static define(e){let t=e.props&&e.props.length?Object.create(null):Hu,i=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),s=new n(e.name||"",t,e.id,i);if(e.props){for(let r of e.props)if(Array.isArray(r)||(r=r(s)),r){if(r[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[r[0].id]=r[1]}}return s}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop(R.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let i in e)for(let s of i.split(" "))t[s]=e[i];return i=>{for(let s=i.prop(R.group),r=-1;r<(s?s.length:0);r++){let o=t[r<0?i.name:s[r]];if(o)return o}}}};ie.none=new ie("",Object.create(null),0,8);var Ii=class n{constructor(e){this.types=e;for(let t=0;t0;for(let a=this.cursor(o|N.IncludeAnonymous);;){let h=!1;if(a.from<=r&&a.to>=s&&(!l&&a.type.isAnonymous||t(a)!==!1)){if(a.firstChild())continue;h=!0}for(;h&&i&&(l||!a.type.isAnonymous)&&i(a),!a.nextSibling();){if(!a.parent())return;h=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:Fr(ie.none,this.children,this.positions,0,this.children.length,0,this.length,(t,i,s)=>new n(this.type,t,i,s,this.propValues),e.makeTree||((t,i,s)=>new n(ie.none,t,i,s)))}static build(e){return ju(e)}};j.empty=new j(ie.none,[],[],0);var Lr=class n{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new n(this.buffer,this.index)}},dt=class n{constructor(e,t,i){this.buffer=e,this.length=t,this.set=i}get type(){return ie.none}toString(){let e=[];for(let t=0;t0));a=o[a+3]);return l}slice(e,t,i){let s=this.buffer,r=new Uint16Array(t-e),o=0;for(let l=e,a=0;l=e&&te;case 1:return t<=e&&i>e;case 2:return i>e;case 4:return!0}}function Ni(n,e,t,i){for(var s;n.from==n.to||(t<1?n.from>=e:n.from>e)||(t>-1?n.to<=e:n.to0?l.length:-1;e!=h;e+=t){let f=l[e],c=a[e]+o.from,u;if(!(!(r&N.EnterBracketed&&f instanceof j&&(u=Et.get(f))&&!u.overlay&&u.bracketed&&i>=c&&i<=c+f.length)&&!Fa(s,i,c,c+f.length))){if(f instanceof dt){if(r&N.ExcludeBuffers)continue;let d=f.findChild(0,f.buffer.length,t,i-c,s);if(d>-1)return new Dt(new Ir(o,f,e,c),null,d)}else if(r&N.IncludeAnonymous||!f.type.isAnonymous||Xr(f)){let d;if(!(r&N.IgnoreMounts)&&(d=Et.get(f))&&!d.overlay)return new n(d.tree,c,e,o);let p=new n(f,c,e,o);return r&N.IncludeAnonymous||!p.type.isAnonymous?p:p.nextChild(t<0?f.children.length-1:0,t,i,s,r)}}}if(r&N.IncludeAnonymous||!o.type.isAnonymous||(o.index>=0?e=o.index+t:e=t<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}prop(e){return this._tree.prop(e)}enter(e,t,i=0){let s;if(!(i&N.IgnoreOverlays)&&(s=Et.get(this._tree))&&s.overlay){let r=e-this.from,o=i&N.EnterBracketed&&s.bracketed;for(let{from:l,to:a}of s.overlay)if((t>0||o?l<=r:l=r:a>r))return new n(s.tree,s.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,i)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}};function Va(n,e,t,i){let s=n.cursor(),r=[];if(!s.firstChild())return r;if(t!=null){for(let o=!1;!o;)if(o=s.type.is(t),!s.nextSibling())return r}for(;;){if(i!=null&&s.type.is(i))return r;if(s.type.is(e)&&r.push(s.node),!s.nextSibling())return i==null?r:[]}}function zr(n,e,t=e.length-1){for(let i=n;t>=0;i=i.parent){if(!i)return!1;if(!i.type.isAnonymous){if(e[t]&&e[t]!=i.name)return!1;t--}}return!0}var Ir=class{constructor(e,t,i,s){this.parent=e,this.buffer=t,this.index=i,this.start=s}},Dt=class n extends Xn{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,i){super(),this.context=e,this._parent=t,this.index=i,this.type=e.buffer.set.types[e.buffer.buffer[i]]}child(e,t,i){let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.context.start,i);return r<0?null:new n(this.context,this,r)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}prop(e){return this.type.prop(e)}enter(e,t,i=0){if(i&N.ExcludeBuffers)return null;let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return r<0?null:new n(this.context,this,r)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new n(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new n(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],t=[],{buffer:i}=this.context,s=this.index+4,r=i.buffer[this.index+3];if(r>s){let o=i.buffer[this.index+1];e.push(i.slice(s,r,o)),t.push(0)}return new j(this.type,e,t,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}};function _a(n){if(!n.length)return null;let e=0,t=n[0];for(let r=1;rt.from||o.to=e){let l=new we(o.tree,o.overlay[0].from+r.from,-1,r);(s||(s=[i])).push(Ni(l,e,t,!1))}}return s?_a(s):i}var Vi=class{get name(){return this.type.name}constructor(e,t=0){if(this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,this.mode=t&~N.EnterBracketed,e instanceof we)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let i=e._parent;i;i=i._parent)this.stack.unshift(i.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:i,buffer:s}=this.buffer;return this.type=t||s.set.types[s.buffer[e]],this.from=i+s.buffer[e+1],this.to=i+s.buffer[e+2],!0}yield(e){return e?e instanceof we?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,i){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,i,this.mode));let{buffer:s}=this.buffer,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.buffer.start,i);return r<0?!1:(this.stack.push(this.index),this.yieldBuf(r))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,i=this.mode){return this.buffer?i&N.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,i))}parent(){if(!this.buffer)return this.yieldNode(this.mode&N.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&N.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,i=this.stack.length-1;if(e<0){let s=i<0?0:this.stack[i]+4;if(this.index!=s)return this.yieldBuf(t.findChild(s,this.index,-1,0,4))}else{let s=t.buffer[this.index+3];if(s<(i<0?t.buffer.length:t.buffer[this.stack[i]+3]))return this.yieldBuf(s)}return i<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,i,{buffer:s}=this;if(s){if(e>0){if(this.index-1)for(let r=t+e,o=e<0?-1:i._tree.children.length;r!=o;r+=e){let l=i._tree.children[r];if(this.mode&N.IncludeAnonymous||l instanceof dt||!l.type.isAnonymous||Xr(l))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let o=e;o;o=o._parent)if(o.index==s){if(s==this.index)return o;t=o,i=r+1;break e}s=this.stack[--r]}for(let s=i;s=0;r--){if(r<0)return zr(this._tree,e,s);let o=i[t.buffer[this.stack[r]]];if(!o.isAnonymous){if(e[s]&&e[s]!=o.name)return!1;s--}}return!0}};function Xr(n){return n.children.some(e=>e instanceof dt||!e.type.isAnonymous||Xr(e))}function ju(n){var e;let{buffer:t,nodeSet:i,maxBufferLength:s=1024,reused:r=[],minRepeatType:o=i.types.length}=n,l=Array.isArray(t)?new Lr(t,t.length):t,a=i.types,h=0,f=0;function c(Q,P,T,V,$,U){let{id:E,start:A,end:X,size:H}=l,ee=f,Fe=h;if(H<0)if(l.next(),H==-1){let _e=r[E];T.push(_e),V.push(A-Q);return}else if(H==-3){h=E;return}else if(H==-4){f=E;return}else throw new RangeError(`Unrecognized record size: ${H}`);let Oi=a[E],en,bt,Vo=A-Q;if(X-A<=s&&(bt=O(l.pos-P,$))){let _e=new Uint16Array(bt.size-bt.skip),se=l.pos-bt.size,Ce=_e.length;for(;l.pos>se;)Ce=y(bt.start,_e,Ce);en=new dt(_e,X-bt.start,i),Vo=bt.start-Q}else{let _e=l.pos-H;l.next();let se=[],Ce=[],qe=E>=o?E:-1,He=0,Vt=X,yi=ee;for(;l.pos>_e;)qe>=0&&l.id==qe&&l.size>=0?(l.end<=Vt-s&&(p(se,Ce,A,He,l.end,Vt,qe,yi,Fe),He=se.length,Vt=l.end,yi=f),l.next()):U>2500?u(A,_e,se,Ce):(qe>=0&&l.size==-1&&r[l.id].type==i.types[qe]&&(He=0&&He>0&&He-1&&He>0){let Xo=d(Oi,Fe);en=Fr(Oi,se,Ce,0,se.length,0,X-A,Xo,Xo)}else en=m(Oi,se,Ce,X-A,ee-X,Fe)}T.push(en),V.push(Vo)}function u(Q,P,T,V){let $=[],U=0,E=-1;for(;l.pos>P;){let{id:A,start:X,end:H,size:ee}=l;if(ee>4)l.next();else{if(E>-1&&X=0;H-=3)A[ee++]=$[H],A[ee++]=$[H+1]-X,A[ee++]=$[H+2]-X,A[ee++]=ee;T.push(new dt(A,$[2]-X,i)),V.push(X-Q)}}function d(Q,P){return(T,V,$)=>{let U=0,E=T.length-1,A,X;if(E>=0&&(A=T[E])instanceof j){if(!E&&A.type==Q&&A.length==$)return A;(X=A.prop(R.lookAhead))&&(U=V[E]+A.length+X-$)}return m(Q,T,V,$,U,P)}}function p(Q,P,T,V,$,U,E,A,X){let H=[],ee=[];for(;Q.length>V;)H.push(Q.pop()),ee.push(P.pop()+T-$);Q.push(m(i.types[E],H,ee,U-$,A-U,X)),P.push($-T)}function m(Q,P,T,V,$,U,E){if(U){let A=[R.contextHash,U];E=E?[A].concat(E):[A]}if($>25){let A=[R.lookAhead,$];E=E?[A].concat(E):[A]}return new j(Q,P,T,V,E)}function O(Q,P){let T=l.fork(),V=0,$=0,U=0,E=T.end-s,A={size:0,start:0,skip:0};e:for(let X=T.pos-Q;T.pos>X;){let H=T.size;if(T.id==P&&H>=0){A.size=V,A.start=$,A.skip=U,U+=4,V+=4,T.next();continue}let ee=T.pos-H;if(H<0||ee=o?4:0,Oi=T.start;for(T.next();T.pos>ee;){if(T.size<0)if(T.size==-3||T.size==-4)Fe+=4;else break e;else T.id>=o&&(Fe+=4);T.next()}$=Oi,V+=H,U+=Fe}return(P<0||V==Q)&&(A.size=V,A.start=$,A.skip=U),A.size>4?A:void 0}function y(Q,P,T){let{id:V,start:$,end:U,size:E}=l;if(l.next(),E>=0&&V4){let X=l.pos-(E-4);for(;l.pos>X;)T=y(Q,P,T)}P[--T]=A,P[--T]=U-Q,P[--T]=$-Q,P[--T]=V}else E==-3?h=V:E==-4&&(f=V);return T}let w=[],k=[];for(;l.pos>0;)c(n.start||0,n.bufferStart||0,w,k,-1,0);let D=(e=n.length)!==null&&e!==void 0?e:w.length?k[0]+w[0].length:0;return new j(a[n.topID],w.reverse(),k.reverse(),D)}var Xa=new WeakMap;function Vn(n,e){if(!n.isAnonymous||e instanceof dt||e.type!=n)return 1;let t=Xa.get(e);if(t==null){t=1;for(let i of e.children){if(i.type!=n||!(i instanceof j)){t=1;break}t+=Vn(n,i)}Xa.set(e,t)}return t}function Fr(n,e,t,i,s,r,o,l,a){let h=0;for(let p=i;p=f)break;P+=T}if(k==D+1){if(P>f){let T=p[D];d(T.children,T.positions,0,T.children.length,m[D]+w);continue}c.push(p[D])}else{let T=m[k-1]+p[k-1].length-Q;c.push(Fr(n,p,m,D,k,Q,T,null,a))}u.push(Q+w-r)}}return d(e,t,i,s,0),(l||a)(c,u,o)}var Fn=class{constructor(){this.map=new WeakMap}setBuffer(e,t,i){let s=this.map.get(e);s||this.map.set(e,s=new Map),s.set(t,i)}getBuffer(e,t){let i=this.map.get(e);return i&&i.get(t)}set(e,t){e instanceof Dt?this.setBuffer(e.context.buffer,e.index,t):e instanceof we&&this.map.set(e.tree,t)}get(e){return e instanceof Dt?this.getBuffer(e.context.buffer,e.index):e instanceof we?this.map.get(e.tree):void 0}cursorSet(e,t){e.buffer?this.setBuffer(e.buffer.buffer,e.index,t):this.map.set(e.tree,t)}cursorGet(e){return e.buffer?this.getBuffer(e.buffer.buffer,e.index):this.map.get(e.tree)}},Bt=class n{constructor(e,t,i,s,r=!1,o=!1){this.from=e,this.to=t,this.tree=i,this.offset=s,this.open=(r?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],i=!1){let s=[new n(0,e.length,e,0,!1,i)];for(let r of t)r.to>e.length&&s.push(r);return s}static applyChanges(e,t,i=128){if(!t.length)return e;let s=[],r=1,o=e.length?e[0]:null;for(let l=0,a=0,h=0;;l++){let f=l=i)for(;o&&o.from=u.from||c<=u.to||h){let d=Math.max(u.from,a)-h,p=Math.min(u.to,c)-h;u=d>=p?null:new n(d,p,u.tree,u.offset+h,l>0,!!f)}if(u&&s.push(u),o.to>c)break;o=rnew zi(s.from,s.to)):[new zi(0,0)]:[new zi(0,e.length)],this.createParse(e,t||[],i)}parse(e,t,i){let s=this.startParse(e,t,i);for(;;){let r=s.advance();if(r)return r}}},Vr=class{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}};var Xg=new R({perNode:!0});var Gu=0,Re=class n{constructor(e,t,i,s){this.name=e,this.set=t,this.base=i,this.modified=s,this.id=Gu++}toString(){let{name:e}=this;for(let t of this.modified)t.name&&(e=`${t.name}(${e})`);return e}static define(e,t){let i=typeof e=="string"?e:"?";if(e instanceof n&&(t=e),t?.base)throw new Error("Can not derive from a modified tag");let s=new n(i,[],null,[]);if(s.set.push(s),t)for(let r of t.set)s.set.push(r);return s}static defineModifier(e){let t=new jn(e);return i=>i.modified.indexOf(t)>-1?i:jn.get(i.base||i,i.modified.concat(t).sort((s,r)=>s.id-r.id))}},Zu=0,jn=class n{constructor(e){this.name=e,this.instances=[],this.id=Zu++}static get(e,t){if(!t.length)return e;let i=t[0].instances.find(l=>l.base==e&&Yu(t,l.modified));if(i)return i;let s=[],r=new Re(e.name,s,e,t);for(let l of t)l.instances.push(r);let o=Ku(t);for(let l of e.set)if(!l.modified.length)for(let a of o)s.push(n.get(l,a));return r}};function Yu(n,e){return n.length==e.length&&n.every((t,i)=>t==e[i])}function Ku(n){let e=[[]];for(let t=0;ti.length-t.length)}function Gn(n){let e=Object.create(null);for(let t in n){let i=n[t];Array.isArray(i)||(i=[i]);for(let s of t.split(" "))if(s){let r=[],o=2,l=s;for(let c=0;;){if(l=="..."&&c>0&&c+3==s.length){o=1;break}let u=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(l);if(!u)throw new RangeError("Invalid path: "+s);if(r.push(u[0]=="*"?"":u[0][0]=='"'?JSON.parse(u[0]):u[0]),c+=u[0].length,c==s.length)break;let d=s[c++];if(c==s.length&&d=="!"){o=0;break}if(d!="/")throw new RangeError("Invalid path: "+s);l=s.slice(c)}let a=r.length-1,h=r[a];if(!h)throw new RangeError("Invalid path: "+s);let f=new Wt(i,o,a>0?r.slice(0,a):null);e[h]=f.sort(e[h])}}return ja.add(e)}var ja=new R({combine(n,e){let t,i,s;for(;n||e;){if(!n||e&&n.depth<=e.depth?(s=e,e=e.next):(s=n,n=n.next),t&&t.mode==s.mode&&!s.context&&!t.context)continue;let r=new Wt(s.tags,s.mode,s.context);t?t.next=r:i=r,t=r}return i}}),Wt=class{constructor(e,t,i,s){this.tags=e,this.mode=t,this.context=i,this.next=s}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth{let o=s;for(let l of r)for(let a of l.set){let h=t[a.id];if(h){o=o?o+" "+h:h;break}}return o},scope:i}}function Ju(n,e){let t=null;for(let i of n){let s=i.style(e);s&&(t=t?t+" "+s:s)}return t}function Ga(n,e,t,i=0,s=n.length){let r=new Hr(i,Array.isArray(e)?e:[e],t);r.highlightRange(n.cursor(),i,s,"",r.highlighters),r.flush(s)}var Hr=class{constructor(e,t,i){this.at=e,this.highlighters=t,this.span=i,this.class=""}startSpan(e,t){t!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=t)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,t,i,s,r){let{type:o,from:l,to:a}=e;if(l>=i||a<=t)return;o.isTop&&(r=this.highlighters.filter(d=>!d.scope||d.scope(o)));let h=s,f=ed(e)||Wt.empty,c=Ju(r,f.tags);if(c&&(h&&(h+=" "),h+=c,f.mode==1&&(s+=(s?" ":"")+c)),this.startSpan(Math.max(t,l),h),f.opaque)return;let u=e.tree&&e.tree.prop(R.mounted);if(u&&u.overlay){let d=e.node.enter(u.overlay[0].from+l,1),p=this.highlighters.filter(O=>!O.scope||O.scope(u.tree.type)),m=e.firstChild();for(let O=0,y=l;;O++){let w=O=k||!e.nextSibling())););if(!w||k>i)break;y=w.to+l,y>t&&(this.highlightRange(d.cursor(),Math.max(t,w.from+l),Math.min(i,y),"",p),this.startSpan(Math.min(i,y),h))}m&&e.parent()}else if(e.firstChild()){u&&(s="");do if(!(e.to<=t)){if(e.from>=i)break;this.highlightRange(e,t,i,s,r),this.startSpan(Math.min(i,e.to),h)}while(e.nextSibling());e.parent()}}};function ed(n){let e=n.type.prop(ja);for(;e&&e.context&&!n.matchContext(e.context);)e=e.next;return e||null}var S=Re.define,_n=S(),pt=S(),Ha=S(pt),Ua=S(pt),mt=S(),Hn=S(mt),_r=S(mt),Ve=S(),qt=S(Ve),Ie=S(),Ne=S(),Ur=S(),Xi=S(Ur),Un=S(),g={comment:_n,lineComment:S(_n),blockComment:S(_n),docComment:S(_n),name:pt,variableName:S(pt),typeName:Ha,tagName:S(Ha),propertyName:Ua,attributeName:S(Ua),className:S(pt),labelName:S(pt),namespace:S(pt),macroName:S(pt),literal:mt,string:Hn,docString:S(Hn),character:S(Hn),attributeValue:S(Hn),number:_r,integer:S(_r),float:S(_r),bool:S(mt),regexp:S(mt),escape:S(mt),color:S(mt),url:S(mt),keyword:Ie,self:S(Ie),null:S(Ie),atom:S(Ie),unit:S(Ie),modifier:S(Ie),operatorKeyword:S(Ie),controlKeyword:S(Ie),definitionKeyword:S(Ie),moduleKeyword:S(Ie),operator:Ne,derefOperator:S(Ne),arithmeticOperator:S(Ne),logicOperator:S(Ne),bitwiseOperator:S(Ne),compareOperator:S(Ne),updateOperator:S(Ne),definitionOperator:S(Ne),typeOperator:S(Ne),controlOperator:S(Ne),punctuation:Ur,separator:S(Ur),bracket:Xi,angleBracket:S(Xi),squareBracket:S(Xi),paren:S(Xi),brace:S(Xi),content:Ve,heading:qt,heading1:S(qt),heading2:S(qt),heading3:S(qt),heading4:S(qt),heading5:S(qt),heading6:S(qt),contentSeparator:S(Ve),list:S(Ve),quote:S(Ve),emphasis:S(Ve),strong:S(Ve),link:S(Ve),monospace:S(Ve),strikethrough:S(Ve),inserted:S(),deleted:S(),changed:S(),invalid:S(),meta:Un,documentMeta:S(Un),annotation:S(Un),processingInstruction:S(Un),definition:Re.defineModifier("definition"),constant:Re.defineModifier("constant"),function:Re.defineModifier("function"),standard:Re.defineModifier("standard"),local:Re.defineModifier("local"),special:Re.defineModifier("special")};for(let n in g){let e=g[n];e instanceof Re&&(e.name=n)}var Hg=jr([{tag:g.link,class:"tok-link"},{tag:g.heading,class:"tok-heading"},{tag:g.emphasis,class:"tok-emphasis"},{tag:g.strong,class:"tok-strong"},{tag:g.keyword,class:"tok-keyword"},{tag:g.atom,class:"tok-atom"},{tag:g.bool,class:"tok-bool"},{tag:g.url,class:"tok-url"},{tag:g.labelName,class:"tok-labelName"},{tag:g.inserted,class:"tok-inserted"},{tag:g.deleted,class:"tok-deleted"},{tag:g.literal,class:"tok-literal"},{tag:g.string,class:"tok-string"},{tag:g.number,class:"tok-number"},{tag:[g.regexp,g.escape,g.special(g.string)],class:"tok-string2"},{tag:g.variableName,class:"tok-variableName"},{tag:g.local(g.variableName),class:"tok-variableName tok-local"},{tag:g.definition(g.variableName),class:"tok-variableName tok-definition"},{tag:g.special(g.variableName),class:"tok-variableName2"},{tag:g.definition(g.propertyName),class:"tok-propertyName tok-definition"},{tag:g.typeName,class:"tok-typeName"},{tag:g.namespace,class:"tok-namespace"},{tag:g.className,class:"tok-className"},{tag:g.macroName,class:"tok-macroName"},{tag:g.propertyName,class:"tok-propertyName"},{tag:g.operator,class:"tok-operator"},{tag:g.comment,class:"tok-comment"},{tag:g.meta,class:"tok-meta"},{tag:g.invalid,class:"tok-invalid"},{tag:g.punctuation,class:"tok-punctuation"}]);var Gr,fi=new R;function td(n){return v.define({combine:n?e=>e.concat(n):void 0})}var id=new R,me=class{constructor(e,t,i=[],s=""){this.data=e,this.name=s,z.prototype.hasOwnProperty("tree")||Object.defineProperty(z.prototype,"tree",{get(){return J(this)}}),this.parser=t,this.extension=[ci.of(this),z.languageData.of((r,o,l)=>{let a=Za(r,o,l),h=a.type.prop(fi);if(!h)return[];let f=r.facet(h),c=a.type.prop(id);if(c){let u=a.resolve(o-a.from,l);for(let d of c)if(d.test(u,r)){let p=r.facet(d.facet);return d.type=="replace"?p:p.concat(f)}}return f})].concat(i)}isActiveAt(e,t,i=-1){return Za(e,t,i).type.prop(fi)==this.data}findRegions(e){let t=e.facet(ci);if(t?.data==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let i=[],s=(r,o)=>{if(r.prop(fi)==this.data){i.push({from:o,to:o+r.length});return}let l=r.prop(R.mounted);if(l){if(l.tree.prop(fi)==this.data){if(l.overlay)for(let a of l.overlay)i.push({from:a.from+o,to:a.to+o});else i.push({from:o,to:o+r.length});return}else if(l.overlay){let a=i.length;if(s(l.tree,l.overlay[0].from+o),i.length>a)return}}for(let a=0;ai.isTop?t:void 0)]}),e.name)}configure(e,t){return new n(this.data,this.parser.configure(e),t||this.name)}get allowsNesting(){return this.parser.hasWrappers()}};function J(n){let e=n.field(me.state,!1);return e?e.tree:j.empty}var Jr=class{constructor(e){this.doc=e,this.cursorPos=0,this.string="",this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,t){let i=this.cursorPos-this.string.length;return e=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-i,t-i)}},Fi=null,eo=class n{constructor(e,t,i=[],s,r,o,l,a){this.parser=e,this.state=t,this.fragments=i,this.tree=s,this.treeLen=r,this.viewport=o,this.skipped=l,this.scheduleOn=a,this.parse=null,this.tempSkipped=[]}static create(e,t,i){return new n(e,t,[],j.empty,0,i,[],null)}startParse(){return this.parser.startParse(new Jr(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=j.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var i;if(typeof e=="number"){let s=Date.now()+e;e=()=>Date.now()>s}for(this.parse||(this.parse=this.startParse()),t!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&t=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(t=this.parse.advance()););}),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped(Bt.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=Fi;Fi=this;try{return e()}finally{Fi=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=Ya(e,t.from,t.to);return e}changes(e,t){let{fragments:i,tree:s,treeLen:r,viewport:o,skipped:l}=this;if(this.takeTree(),!e.empty){let a=[];if(e.iterChangedRanges((h,f,c,u)=>a.push({fromA:h,toA:f,fromB:c,toB:u})),i=Bt.applyChanges(i,a),s=j.empty,r=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){l=[];for(let h of this.skipped){let f=e.mapPos(h.from,1),c=e.mapPos(h.to,-1);fe.from&&(this.fragments=Ya(this.fragments,s,r),this.skipped.splice(i--,1))}return this.skipped.length>=t?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends hi{createParse(t,i,s){let r=s[0].from,o=s[s.length-1].to;return{parsedPos:r,advance(){let a=Fi;if(a){for(let h of s)a.tempSkipped.push(h);e&&(a.scheduleOn=a.scheduleOn?Promise.all([a.scheduleOn,e]):e)}return this.parsedPos=o,new j(ie.none,[],[],o-r)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&t[0].from==0&&t[0].to>=e}static get(){return Fi}};function Ya(n,e,t){return Bt.applyChanges(n,[{fromA:e,toA:t,fromB:e,toB:t}])}var _i=class n{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let t=this.context.changes(e.changes,e.state),i=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,i)||t.takeTree(),new n(t)}static init(e){let t=Math.min(3e3,e.doc.length),i=eo.create(e.facet(ci).parser,e,{from:0,to:t});return i.work(20,t)||i.takeTree(),new n(i)}};me.state=he.define({create:_i.init,update(n,e){for(let t of e.effects)if(t.is(me.setState))return t.value;return e.startState.facet(ci)!=e.state.facet(ci)?_i.init(e.state):n.apply(e)}});var ih=n=>{let e=setTimeout(()=>n(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(ih=n=>{let e=-1,t=setTimeout(()=>{e=requestIdleCallback(n,{timeout:400})},100);return()=>e<0?clearTimeout(t):cancelIdleCallback(e)});var Zr=typeof navigator<"u"&&(!((Gr=navigator.scheduling)===null||Gr===void 0)&&Gr.isInputPending)?()=>navigator.scheduling.isInputPending():null,nd=Le.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(me.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(me.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=ih(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEnds+1e3,a=r.context.work(()=>Zr&&Zr()||Date.now()>o,s+(l?0:1e5));this.chunkBudget-=Date.now()-t,(a||this.chunkBudget<=0)&&(r.context.takeTree(),this.view.dispatch({effects:me.setState.of(new _i(r.context))})),this.chunkBudget>0&&!(a&&!l)&&this.scheduleWork(),this.checkAsyncSchedule(r.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(t=>ke(this.view.state,t)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),ci=v.define({combine(n){return n.length?n[0]:null},enables:n=>[me.state,nd,C.contentAttributes.compute([n],e=>{let t=e.facet(n);return t&&t.name?{"data-language":t.name}:{}})]}),Yn=class{constructor(e,t=[]){this.language=e,this.support=t,this.extension=[e,t]}};var sd=v.define(),gt=v.define({combine:n=>{if(!n.length)return" ";let e=n[0];if(!e||/\S/.test(e)||Array.from(e).some(t=>t!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(n[0]));return e}});function Hi(n){let e=n.facet(gt);return e.charCodeAt(0)==9?n.tabSize*e.length:e.length}function di(n,e){let t="",i=n.tabSize,s=n.facet(gt)[0];if(s==" "){for(;e>=i;)t+=" ",e-=i;s=" "}for(let r=0;r=e?rd(n,t,e):null}var $t=class{constructor(e,t={}){this.state=e,this.options=t,this.unit=Hi(e)}lineAt(e,t=1){let i=this.state.doc.lineAt(e),{simulateBreak:s,simulateDoubleBreak:r}=this.options;return s!=null&&s>=i.from&&s<=i.to?r&&s==e?{text:"",from:e}:(t<0?s-1&&(r+=o-this.countColumn(i,i.search(/\S|$/))),r}countColumn(e,t=e.length){return Ct(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:i,from:s}=this.lineAt(e,t),r=this.options.overrideIndentation;if(r){let o=r(s);if(o>-1)return o}return this.countColumn(i,i.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}},oo=new R;function rd(n,e,t){let i=e.resolveStack(t),s=e.resolveInner(t,-1).resolve(t,0).enterUnfinishedNodesBefore(t);if(s!=i.node){let r=[];for(let o=s;o&&!(o.fromi.node.to||o.from==i.node.from&&o.type==i.node.type);o=o.parent)r.push(o);for(let o=r.length-1;o>=0;o--)i={node:r[o],next:i}}return nh(i,n,t)}function nh(n,e,t){for(let i=n;i;i=i.next){let s=ld(i.node);if(s)return s(to.create(e,t,i))}return 0}function od(n){return n.pos==n.options.simulateBreak&&n.options.simulateDoubleBreak}function ld(n){let e=n.type.prop(oo);if(e)return e;let t=n.firstChild,i;if(t&&(i=t.type.prop(R.closedBy))){let s=n.lastChild,r=s&&i.indexOf(s.name)>-1;return o=>sh(o,!0,1,void 0,r&&!od(o)?s.from:void 0)}return n.parent==null?ad:null}function ad(){return 0}var to=class n extends $t{constructor(e,t,i){super(e.state,e.options),this.base=e,this.pos=t,this.context=i}get node(){return this.context.node}static create(e,t,i){return new n(e,t,i)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(e){let t=this.state.doc.lineAt(e.from);for(;;){let i=e.resolve(t.from);for(;i.parent&&i.parent.from==i.from;)i=i.parent;if(hd(i,e))break;t=this.state.doc.lineAt(i.from)}return this.lineIndent(t.from)}continue(){return nh(this.context.next,this.base,this.pos)}};function hd(n,e){for(let t=e;t;t=t.parent)if(n==t)return!0;return!1}function fd(n){let e=n.node,t=e.childAfter(e.from),i=e.lastChild;if(!t)return null;let s=n.options.simulateBreak,r=n.state.doc.lineAt(t.from),o=s==null||s<=r.from?r.to:Math.min(r.to,s);for(let l=t.to;;){let a=e.childAfter(l);if(!a||a==i)return null;if(!a.type.isSkipped){if(a.from>=o)return null;let h=/^ */.exec(r.text.slice(t.to-r.from))[0].length;return{from:t.from,to:t.to+h}}l=a.to}}function Jn({closing:n,align:e=!0,units:t=1}){return i=>sh(i,e,t,n)}function sh(n,e,t,i,s){let r=n.textAfter,o=r.match(/^\s*/)[0].length,l=i&&r.slice(o,o+i.length)==i||s==n.pos+o,a=e?fd(n):null;return a?l?n.column(a.from):n.column(a.to):n.baseIndent+(l?0:n.unit*t)}var cd=200;function rh(){return z.transactionFilter.of(n=>{if(!n.docChanged||!n.isUserEvent("input.type")&&!n.isUserEvent("input.complete"))return n;let e=n.startState.languageDataAt("indentOnInput",n.startState.selection.main.head);if(!e.length)return n;let t=n.newDoc,{head:i}=n.newSelection.main,s=t.lineAt(i);if(i>s.from+cd)return n;let r=t.sliceString(s.from,i);if(!e.some(h=>h.test(r)))return n;let{state:o}=n,l=-1,a=[];for(let{head:h}of o.selection.ranges){let f=o.doc.lineAt(h);if(f.from==l)continue;l=f.from;let c=Kn(o,f.from);if(c==null)continue;let u=/^\s*/.exec(f.text)[0],d=di(o,c);u!=d&&a.push({from:f.from,to:f.from+u.length,insert:d})}return a.length?[n,{changes:a,sequential:!0}]:n})}var oh=new R;function lh(n){let e=n.firstChild,t=n.lastChild;return e&&e.tol.prop(fi)==o.data:o?l=>l==o:void 0,this.style=jr(e.map(l=>({tag:l.tag,class:l.class||s(Object.assign({},l,{tag:null}))})),{all:r}).style,this.module=i?new ye(i):null,this.themeType=t.themeType}static define(e,t){return new n(e,t||{})}},io=v.define(),ah=v.define({combine(n){return n.length?[n[0]]:null}});function Yr(n){let e=n.facet(io);return e.length?e:n.facet(ah)}function es(n,e){let t=[ud],i;return n instanceof ui&&(n.module&&t.push(C.styleModule.of(n.module)),i=n.themeType),e?.fallback?t.push(ah.of(n)):i?t.push(io.computeN([C.darkTheme],s=>s.facet(C.darkTheme)==(i=="dark")?[n]:[])):t.push(io.of(n)),t}var no=class{constructor(e){this.markCache=Object.create(null),this.tree=J(e.state),this.decorations=this.buildDeco(e,Yr(e.state)),this.decoratedTo=e.viewport.to}update(e){let t=J(e.state),i=Yr(e.state),s=i!=Yr(e.startState),{viewport:r}=e.view,o=e.changes.mapPos(this.decoratedTo,1);t.length=r.to?(this.decorations=this.decorations.map(e.changes),this.decoratedTo=o):(t!=this.tree||e.viewportChanged||s)&&(this.tree=t,this.decorations=this.buildDeco(e.view,i),this.decoratedTo=r.to)}buildDeco(e,t){if(!t||!this.tree.length)return q.none;let i=new ot;for(let{from:s,to:r}of e.visibleRanges)Ga(this.tree,t,(o,l,a)=>{i.add(o,l,this.markCache[a]||(this.markCache[a]=q.mark({class:a})))},s,r);return i.finish()}},ud=at.high(Le.fromClass(no,{decorations:n=>n.decorations})),hh=ui.define([{tag:g.meta,color:"#404740"},{tag:g.link,textDecoration:"underline"},{tag:g.heading,textDecoration:"underline",fontWeight:"bold"},{tag:g.emphasis,fontStyle:"italic"},{tag:g.strong,fontWeight:"bold"},{tag:g.strikethrough,textDecoration:"line-through"},{tag:g.keyword,color:"#708"},{tag:[g.atom,g.bool,g.url,g.contentSeparator,g.labelName],color:"#219"},{tag:[g.literal,g.inserted],color:"#164"},{tag:[g.string,g.deleted],color:"#a11"},{tag:[g.regexp,g.escape,g.special(g.string)],color:"#e40"},{tag:g.definition(g.variableName),color:"#00f"},{tag:g.local(g.variableName),color:"#30a"},{tag:[g.typeName,g.namespace],color:"#085"},{tag:g.className,color:"#167"},{tag:[g.special(g.variableName),g.macroName],color:"#256"},{tag:g.definition(g.propertyName),color:"#00c"},{tag:g.comment,color:"#940"},{tag:g.invalid,color:"#f00"}]),dd=C.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),fh=1e4,ch="()[]{}",uh=v.define({combine(n){return Tt(n,{afterCursor:!0,brackets:ch,maxScanDistance:fh,renderMatch:gd})}}),pd=q.mark({class:"cm-matchingBracket"}),md=q.mark({class:"cm-nonmatchingBracket"});function gd(n){let e=[],t=n.matched?pd:md;return e.push(t.range(n.start.from,n.start.to)),n.end&&e.push(t.range(n.end.from,n.end.to)),e}function Ka(n){let e=[],t=n.facet(uh);for(let i of n.selection.ranges){if(!i.empty)continue;let s=Me(n,i.head,-1,t)||i.head>0&&Me(n,i.head-1,1,t)||t.afterCursor&&(Me(n,i.head,1,t)||i.headn.decorations}),yd=[Od,dd];function dh(n={}){return[uh.of(n),yd]}var bd=new R;function so(n,e,t){let i=n.prop(e<0?R.openedBy:R.closedBy);if(i)return i;if(n.name.length==1){let s=t.indexOf(n.name);if(s>-1&&s%2==(e<0?1:0))return[t[s+e]]}return null}function ro(n){let e=n.type.prop(bd);return e?e(n.node):n}function Me(n,e,t,i={}){let s=i.maxScanDistance||fh,r=i.brackets||ch,o=J(n),l=o.resolveInner(e,t);for(let a=l;a;a=a.parent){let h=so(a.type,t,r);if(h&&a.from0?e>=f.from&&ef.from&&e<=f.to))return Sd(n,e,t,a,f,h,r)}}return xd(n,e,t,o,l.type,s,r)}function Sd(n,e,t,i,s,r,o){let l=i.parent,a={from:s.from,to:s.to},h=0,f=l?.cursor();if(f&&(t<0?f.childBefore(i.from):f.childAfter(i.to)))do if(t<0?f.to<=i.from:f.from>=i.to){if(h==0&&r.indexOf(f.type.name)>-1&&f.from0)return null;let h={from:t<0?e-1:e,to:t>0?e+1:e},f=n.doc.iterRange(e,t>0?n.doc.length:0),c=0;for(let u=0;!f.next().done&&u<=r;){let d=f.value;t<0&&(u+=d.length);let p=e+u*t;for(let m=t>0?0:d.length-1,O=t>0?d.length:-1;m!=O;m+=t){let y=o.indexOf(d[m]);if(!(y<0||i.resolveInner(p+m,1).type!=s))if(y%2==0==t>0)c++;else{if(c==1)return{start:h,end:{from:p+m,to:p+m+1},matched:y>>1==a>>1};c--}}t>0&&(u+=d.length)}return f.done?{start:h,matched:!1}:null}var kd=Object.create(null),Ja=[ie.none];var eh=[],th=Object.create(null),wd=Object.create(null);for(let[n,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])wd[n]=vd(kd,e);function Kr(n,e){eh.indexOf(n)>-1||(eh.push(n),console.warn(e))}function vd(n,e){let t=[];for(let l of e.split(" ")){let a=[];for(let h of l.split(".")){let f=n[h]||g[h];f?typeof f=="function"?a.length?a=a.map(f):Kr(h,`Modifier ${h} used at start of tag`):a.length?Kr(h,`Tag ${h} used as modifier`):a=Array.isArray(f)?f:[f]:Kr(h,`Unknown highlighting tag ${h}`)}for(let h of a)t.push(h)}if(!t.length)return 0;let i=e.replace(/ /g,"_"),s=i+" "+t.map(l=>l.id),r=th[s];if(r)return r.id;let o=th[s]=ie.define({id:Ja.length,name:i,props:[Gn({[i]:t})]});return Ja.push(o),o.id}var tO={rtl:q.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"rtl"},bidiIsolate:F.RTL}),ltr:q.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"ltr"},bidiIsolate:F.LTR}),auto:q.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"auto"},bidiIsolate:null})};function ph(n){let e=Object.keys(n).join(""),t=/\w/.test(e);return t&&(e=e.replace(/\w/g,"")),`[${t?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function Td(n){let e=Object.create(null),t=Object.create(null);for(let{label:s}of n){e[s[0]]=!0;for(let r=1;rtypeof s=="string"?{label:s}:s),[t,i]=e.every(s=>/^\w+$/.test(s.label))?[/\w*$/,/\w+$/]:Td(e);return s=>{let r=s.matchBefore(i);return r||s.explicit?{from:r?r.from:s.pos,options:e,validFor:t}:null}}function bh(n,e){return t=>{for(let i=J(t.state).resolveInner(t.pos,-1);i;i=i.parent){if(n.indexOf(i.name)>-1)return null;if(i.type.isTop)break}return e(t)}}var Cd=fe.define();var fO=typeof navigator=="object"&&/Win/.test(navigator.platform);var Qd=C.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"\xB7\xB7\xB7"',opacity:.5,display:"block",textAlign:"center",cursor:"pointer"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box",whiteSpace:"pre-line"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'\u0192'"}},".cm-completionIcon-class":{"&:after":{content:"'\u25CB'"}},".cm-completionIcon-interface":{"&:after":{content:"'\u25CC'"}},".cm-completionIcon-variable":{"&:after":{content:"'\u{1D465}'"}},".cm-completionIcon-constant":{"&:after":{content:"'\u{1D436}'"}},".cm-completionIcon-type":{"&:after":{content:"'\u{1D461}'"}},".cm-completionIcon-enum":{"&:after":{content:"'\u222A'"}},".cm-completionIcon-property":{"&:after":{content:"'\u25A1'"}},".cm-completionIcon-keyword":{"&:after":{content:"'\u{1F511}\uFE0E'"}},".cm-completionIcon-namespace":{"&:after":{content:"'\u25A2'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}}),ao=class{constructor(e,t,i,s){this.field=e,this.line=t,this.from=i,this.to=s}},ho=class n{constructor(e,t,i){this.field=e,this.from=t,this.to=i}map(e){let t=e.mapPos(this.from,-1,Y.TrackDel),i=e.mapPos(this.to,1,Y.TrackDel);return t==null||i==null?null:new n(this.field,t,i)}},fo=class n{constructor(e,t){this.lines=e,this.fieldPositions=t}instantiate(e,t){let i=[],s=[t],r=e.doc.lineAt(t),o=/^\s*/.exec(r.text)[0];for(let a of this.lines){if(i.length){let h=o,f=/^\t*/.exec(a)[0].length;for(let c=0;cnew ho(a.field,s[a.line]+a.from,s[a.line]+a.to));return{text:i,ranges:l}}static parse(e){let t=[],i=[],s=[],r;for(let o of e.split(/\r\n?|\n/)){for(;r=/[#$]\{(?:(\d+)(?::([^{}]*))?|((?:\\[{}]|[^{}])*))\}/.exec(o);){let l=r[1]?+r[1]:null,a=r[2]||r[3]||"",h=-1;l===0&&(l=1e9);let f=a.replace(/\\[{}]/g,c=>c[1]);for(let c=0;c=h&&u.field++}for(let c of s)if(c.line==i.length&&c.from>r.index){let u=r[2]?3+(r[1]||"").length:2;c.from-=u,c.to-=u}s.push(new ao(h,i.length,r.index,r.index+f.length)),o=o.slice(0,r.index)+a+o.slice(r.index+r[0].length)}o=o.replace(/\\([{}])/g,(l,a,h)=>{for(let f of s)f.line==i.length&&f.from>h&&(f.from--,f.to--);return a}),i.push(o)}return new n(i,s)}},Pd=q.widget({widget:new class extends Ye{toDOM(){let n=document.createElement("span");return n.className="cm-snippetFieldPosition",n}ignoreEvent(){return!1}}}),Ad=q.mark({class:"cm-snippetField"}),pi=class n{constructor(e,t){this.ranges=e,this.active=t,this.deco=q.set(e.map(i=>(i.from==i.to?Pd:Ad).range(i.from,i.to)),!0)}map(e){let t=[];for(let i of this.ranges){let s=i.map(e);if(!s)return null;t.push(s)}return new n(t,this.active)}selectionInsideField(e){return e.ranges.every(t=>this.ranges.some(i=>i.field==this.active&&i.from<=t.from&&i.to>=t.to))}},Gi=W.define({map(n,e){return n&&n.map(e)}}),Rd=W.define(),Ui=he.define({create(){return null},update(n,e){for(let t of e.effects){if(t.is(Gi))return t.value;if(t.is(Rd)&&n)return new pi(n.ranges,t.value)}return n&&e.docChanged&&(n=n.map(e.changes)),n&&e.selection&&!n.selectionInsideField(e.selection)&&(n=null),n},provide:n=>C.decorations.from(n,e=>e?e.deco:q.none)});function co(n,e){return b.create(n.filter(t=>t.field==e).map(t=>b.range(t.from,t.to)))}function Md(n){let e=fo.parse(n);return(t,i,s,r)=>{let{text:o,ranges:l}=e.instantiate(t.state,s),{main:a}=t.state.selection,h={changes:{from:s,to:r==a.from?a.to:r,insert:M.of(o)},scrollIntoView:!0,annotations:i?[Cd.of(i),G.userEvent.of("input.complete")]:void 0};if(l.length&&(h.selection=co(l,0)),l.some(f=>f.field>0)){let f=new pi(l,0),c=h.effects=[Gi.of(f)];t.state.field(Ui,!1)===void 0&&c.push(W.appendConfig.of([Ui,Wd,$d,Qd]))}t.dispatch(t.state.update(h))}}function Sh(n){return({state:e,dispatch:t})=>{let i=e.field(Ui,!1);if(!i||n<0&&i.active==0)return!1;let s=i.active+n,r=n>0&&!i.ranges.some(o=>o.field==s+n);return t(e.update({selection:co(i.ranges,s),effects:Gi.of(r?null:new pi(i.ranges,s)),scrollIntoView:!0})),!0}}var Ed=({state:n,dispatch:e})=>n.field(Ui,!1)?(e(n.update({effects:Gi.of(null)})),!0):!1,Dd=Sh(1),Bd=Sh(-1);var qd=[{key:"Tab",run:Dd,shift:Bd},{key:"Escape",run:Ed}],mh=v.define({combine(n){return n.length?n[0]:qd}}),Wd=at.highest(ai.compute([mh],n=>n.facet(mh)));function Xe(n,e){return{...e,apply:Md(n)}}var $d=C.domEventHandlers({mousedown(n,e){let t=e.state.field(Ui,!1),i;if(!t||(i=e.posAtCoords({x:n.clientX,y:n.clientY}))==null)return!1;let s=t.ranges.find(r=>r.from<=i&&r.to>=i);return!s||s.field==t.active?!1:(e.dispatch({selection:co(t.ranges,s.field),effects:Gi.of(t.ranges.some(r=>r.field>s.field)?new pi(t.ranges,s.field):null),scrollIntoView:!0}),!0)}});var ji={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},Lt=W.define({map(n,e){let t=e.mapPos(n,-1,Y.TrackAfter);return t??void 0}}),uo=new class extends Oe{};uo.startSide=1;uo.endSide=-1;var xh=he.define({create(){return B.empty},update(n,e){if(n=n.map(e.changes),e.selection){let t=e.state.doc.lineAt(e.selection.main.head);n=n.update({filter:i=>i>=t.from&&i<=t.to})}for(let t of e.effects)t.is(Lt)&&(n=n.update({add:[uo.range(t.value,t.value+1)]}));return n}});function kh(){return[zd,xh]}var lo="()[]{}<>\xAB\xBB\xBB\xAB\uFF3B\uFF3D\uFF5B\uFF5D";function wh(n){for(let e=0;e{if((Ld?n.composing:n.compositionStarted)||n.state.readOnly)return!1;let s=n.state.selection.main;if(i.length>2||i.length==2&&Gt(lt(i,0))==1||e!=s.from||t!=s.to)return!1;let r=Nd(n.state,i);return r?(n.dispatch(r),!0):!1}),Id=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let i=vh(n,n.selection.main.head).brackets||ji.brackets,s=null,r=n.changeByRange(o=>{if(o.empty){let l=Vd(n.doc,o.head);for(let a of i)if(a==l&&ts(n.doc,o.head)==wh(lt(a,0)))return{changes:{from:o.head-a.length,to:o.head+a.length},range:b.cursor(o.head-a.length)}}return{range:s=o}});return s||e(n.update(r,{scrollIntoView:!0,userEvent:"delete.backward"})),!s},Th=[{key:"Backspace",run:Id}];function Nd(n,e){let t=vh(n,n.selection.main.head),i=t.brackets||ji.brackets;for(let s of i){let r=wh(lt(s,0));if(e==s)return r==s?_d(n,s,i.indexOf(s+s+s)>-1,t):Xd(n,s,r,t.before||ji.before);if(e==r&&Ch(n,n.selection.main.from))return Fd(n,s,r)}return null}function Ch(n,e){let t=!1;return n.field(xh).between(0,n.doc.length,i=>{i==e&&(t=!0)}),t}function ts(n,e){let t=n.sliceString(e,e+2);return t.slice(0,Gt(lt(t,0)))}function Vd(n,e){let t=n.sliceString(e-2,e);return Gt(lt(t,0))==t.length?t:t.slice(1)}function Xd(n,e,t,i){let s=null,r=n.changeByRange(o=>{if(!o.empty)return{changes:[{insert:e,from:o.from},{insert:t,from:o.to}],effects:Lt.of(o.to+e.length),range:b.range(o.anchor+e.length,o.head+e.length)};let l=ts(n.doc,o.head);return!l||/\s/.test(l)||i.indexOf(l)>-1?{changes:{insert:e+t,from:o.head},effects:Lt.of(o.head+e.length),range:b.cursor(o.head+e.length)}:{range:s=o}});return s?null:n.update(r,{scrollIntoView:!0,userEvent:"input.type"})}function Fd(n,e,t){let i=null,s=n.changeByRange(r=>r.empty&&ts(n.doc,r.head)==t?{changes:{from:r.head,to:r.head+t.length,insert:t},range:b.cursor(r.head+t.length)}:i={range:r});return i?null:n.update(s,{scrollIntoView:!0,userEvent:"input.type"})}function _d(n,e,t,i){let s=i.stringPrefixes||ji.stringPrefixes,r=null,o=n.changeByRange(l=>{if(!l.empty)return{changes:[{insert:e,from:l.from},{insert:e,from:l.to}],effects:Lt.of(l.to+e.length),range:b.range(l.anchor+e.length,l.head+e.length)};let a=l.head,h=ts(n.doc,a),f;if(h==e){if(gh(n,a))return{changes:{insert:e+e,from:a},effects:Lt.of(a+e.length),range:b.cursor(a+e.length)};if(Ch(n,a)){let u=t&&n.sliceDoc(a,a+e.length*3)==e+e+e?e+e+e:e;return{changes:{from:a,to:a+u.length,insert:u},range:b.cursor(a+u.length)}}}else{if(t&&n.sliceDoc(a-2*e.length,a)==e+e&&(f=Oh(n,a-2*e.length,s))>-1&&gh(n,f))return{changes:{insert:e+e+e+e,from:a},effects:Lt.of(a+e.length),range:b.cursor(a+e.length)};if(n.charCategorizer(a)(h)!=re.Word&&Oh(n,a,s)>-1&&!Hd(n,a,e,s))return{changes:{insert:e+e,from:a},effects:Lt.of(a+e.length),range:b.cursor(a+e.length)}}return{range:r=l}});return r?null:n.update(o,{scrollIntoView:!0,userEvent:"input.type"})}function gh(n,e){let t=J(n).resolveInner(e+1);return t.parent&&t.from==e}function Hd(n,e,t,i){let s=J(n).resolveInner(e,-1),r=i.reduce((o,l)=>Math.max(o,l.length),0);for(let o=0;o<5;o++){let l=n.sliceDoc(s.from,Math.min(s.to,s.from+t.length+r)),a=l.indexOf(t);if(!a||a>-1&&i.indexOf(l.slice(0,a))>-1){let f=s.firstChild;for(;f&&f.from==s.from&&f.to-f.from>t.length+a;){if(n.sliceDoc(f.to-t.length,f.to)==t)return!1;f=f.firstChild}return!0}let h=s.to==e&&s.parent;if(!h)break;s=h}return!1}function Oh(n,e,t){let i=n.charCategorizer(e);if(i(n.sliceDoc(e-1,e))!=re.Word)return e;for(let s of t){let r=e-s.length;if(n.sliceDoc(r,e)==s&&i(n.sliceDoc(r-1,r))!=re.Word)return r}return-1}var Ud=n=>{let{state:e}=n,t=e.doc.lineAt(e.selection.main.from),i=So(n.state,t.from);return i.line?jd(n):i.block?Zd(n):!1};function bo(n,e){return({state:t,dispatch:i})=>{if(t.readOnly)return!1;let s=n(e,t);return s?(i(t.update(s)),!0):!1}}var jd=bo(Jd,0);var Gd=bo(qh,0);var Zd=bo((n,e)=>qh(n,e,Kd(e)),0);function So(n,e){let t=n.languageDataAt("commentTokens",e,1);return t.length?t[0]:{}}var Zi=50;function Yd(n,{open:e,close:t},i,s){let r=n.sliceDoc(i-Zi,i),o=n.sliceDoc(s,s+Zi),l=/\s*$/.exec(r)[0].length,a=/^\s*/.exec(o)[0].length,h=r.length-l;if(r.slice(h-e.length,h)==e&&o.slice(a,a+t.length)==t)return{open:{pos:i-l,margin:l&&1},close:{pos:s+a,margin:a&&1}};let f,c;s-i<=2*Zi?f=c=n.sliceDoc(i,s):(f=n.sliceDoc(i,i+Zi),c=n.sliceDoc(s-Zi,s));let u=/^\s*/.exec(f)[0].length,d=/\s*$/.exec(c)[0].length,p=c.length-d-t.length;return f.slice(u,u+e.length)==e&&c.slice(p,p+t.length)==t?{open:{pos:i+u+e.length,margin:/\s/.test(f.charAt(u+e.length))?1:0},close:{pos:s-d-t.length,margin:/\s/.test(c.charAt(p-1))?1:0}}:null}function Kd(n){let e=[];for(let t of n.selection.ranges){let i=n.doc.lineAt(t.from),s=t.to<=i.to?i:n.doc.lineAt(t.to);s.from>i.from&&s.from==t.to&&(s=t.to==i.to+1?i:n.doc.lineAt(t.to-1));let r=e.length-1;r>=0&&e[r].to>i.from?e[r].to=s.to:e.push({from:i.from+/^\s*/.exec(i.text)[0].length,to:s.to})}return e}function qh(n,e,t=e.selection.ranges){let i=t.map(r=>So(e,r.from).block);if(!i.every(r=>r))return null;let s=t.map((r,o)=>Yd(e,i[o],r.from,r.to));if(n!=2&&!s.every(r=>r))return{changes:e.changes(t.map((r,o)=>s[o]?[]:[{from:r.from,insert:i[o].open+" "},{from:r.to,insert:" "+i[o].close}]))};if(n!=1&&s.some(r=>r)){let r=[];for(let o=0,l;os&&(r==o||o>c.from)){s=c.from;let u=/^\s*/.exec(c.text)[0].length,d=u==c.length,p=c.text.slice(u,u+h.length)==h?u:-1;ur.comment<0&&(!r.empty||r.single))){let r=[];for(let{line:l,token:a,indent:h,empty:f,single:c}of i)(c||!f)&&r.push({from:l.from+h,insert:a+" "});let o=e.changes(r);return{changes:o,selection:e.selection.map(o,1)}}else if(n!=1&&i.some(r=>r.comment>=0)){let r=[];for(let{line:o,comment:l,token:a}of i)if(l>=0){let h=o.from+l,f=h+a.length;o.text[f-o.from]==" "&&f++,r.push({from:h,to:f})}return{changes:r}}return null}var mo=fe.define(),ep=fe.define(),tp=v.define(),Wh=v.define({combine(n){return Tt(n,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(i,s)=>e(i,s)||t(i,s)})}}),$h=he.define({create(){return zt.empty},update(n,e){let t=e.state.facet(Wh),i=e.annotation(mo);if(i){let a=Ee.fromTransaction(e,i.selection),h=i.side,f=h==0?n.undone:n.done;return a?f=ns(f,f.length,t.minDepth,a):f=Nh(f,e.startState.selection),new zt(h==0?i.rest:f,h==0?f:i.rest)}let s=e.annotation(ep);if((s=="full"||s=="before")&&(n=n.isolate()),e.annotation(G.addToHistory)===!1)return e.changes.empty?n:n.addMapping(e.changes.desc);let r=Ee.fromTransaction(e),o=e.annotation(G.time),l=e.annotation(G.userEvent);return r?n=n.addChanges(r,o,l,t,e):e.selection&&(n=n.addSelection(e.startState.selection,o,l,t.newGroupDelay)),(s=="full"||s=="after")&&(n=n.isolate()),n},toJSON(n){return{done:n.done.map(e=>e.toJSON()),undone:n.undone.map(e=>e.toJSON())}},fromJSON(n){return new zt(n.done.map(Ee.fromJSON),n.undone.map(Ee.fromJSON))}});function Lh(n={}){return[$h,Wh.of(n),C.domEventHandlers({beforeinput(e,t){let i=e.inputType=="historyUndo"?zh:e.inputType=="historyRedo"?go:null;return i?(e.preventDefault(),i(t)):!1}})]}function ss(n,e){return function({state:t,dispatch:i}){if(!e&&t.readOnly)return!1;let s=t.field($h,!1);if(!s)return!1;let r=s.pop(n,t,e);return r?(i(r),!0):!1}}var zh=ss(0,!1),go=ss(1,!1),ip=ss(0,!0),np=ss(1,!0);var Ee=class n{constructor(e,t,i,s,r){this.changes=e,this.effects=t,this.mapped=i,this.startSelection=s,this.selectionsAfter=r}setSelAfter(e){return new n(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,i;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(t=this.mapped)===null||t===void 0?void 0:t.toJSON(),startSelection:(i=this.startSelection)===null||i===void 0?void 0:i.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(e){return new n(e.changes&&oe.fromJSON(e.changes),[],e.mapped&&Ue.fromJSON(e.mapped),e.startSelection&&b.fromJSON(e.startSelection),e.selectionsAfter.map(b.fromJSON))}static fromTransaction(e,t){let i=ve;for(let s of e.startState.facet(tp)){let r=s(e);r.length&&(i=i.concat(r))}return!i.length&&e.changes.empty?null:new n(e.changes.invert(e.startState.doc),i,void 0,t||e.startState.selection,ve)}static selection(e){return new n(void 0,ve,void 0,void 0,e)}};function ns(n,e,t,i){let s=e+1>t+20?e-t-1:0,r=n.slice(s,e);return r.push(i),r}function sp(n,e){let t=[],i=!1;return n.iterChangedRanges((s,r)=>t.push(s,r)),e.iterChangedRanges((s,r,o,l)=>{for(let a=0;a=h&&o<=f&&(i=!0)}}),i}function rp(n,e){return n.ranges.length==e.ranges.length&&n.ranges.filter((t,i)=>t.empty!=e.ranges[i].empty).length===0}function Ih(n,e){return n.length?e.length?n.concat(e):n:e}var ve=[],op=200;function Nh(n,e){if(n.length){let t=n[n.length-1],i=t.selectionsAfter.slice(Math.max(0,t.selectionsAfter.length-op));return i.length&&i[i.length-1].eq(e)?n:(i.push(e),ns(n,n.length-1,1e9,t.setSelAfter(i)))}else return[Ee.selection([e])]}function lp(n){let e=n[n.length-1],t=n.slice();return t[n.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),t}function po(n,e){if(!n.length)return n;let t=n.length,i=ve;for(;t;){let s=ap(n[t-1],e,i);if(s.changes&&!s.changes.empty||s.effects.length){let r=n.slice(0,t);return r[t-1]=s,r}else e=s.mapped,t--,i=s.selectionsAfter}return i.length?[Ee.selection(i)]:ve}function ap(n,e,t){let i=Ih(n.selectionsAfter.length?n.selectionsAfter.map(l=>l.map(e)):ve,t);if(!n.changes)return Ee.selection(i);let s=n.changes.map(e),r=e.mapDesc(n.changes,!0),o=n.mapped?n.mapped.composeDesc(r):r;return new Ee(s,W.mapEffects(n.effects,e),o,n.startSelection.map(r),i)}var hp=/^(input\.type|delete)($|\.)/,zt=class n{constructor(e,t,i=0,s=void 0){this.done=e,this.undone=t,this.prevTime=i,this.prevUserEvent=s}isolate(){return this.prevTime?new n(this.done,this.undone):this}addChanges(e,t,i,s,r){let o=this.done,l=o[o.length-1];return l&&l.changes&&!l.changes.empty&&e.changes&&(!i||hp.test(i))&&(!l.selectionsAfter.length&&t-this.prevTime0&&t-this.prevTimet.empty?n.moveByChar(t,e):rs(t,e))}function ne(n){return n.textDirectionAt(n.state.selection.main.head)==F.LTR}var Fh=n=>Xh(n,!ne(n)),_h=n=>Xh(n,ne(n));function Hh(n,e){return Be(n,t=>t.empty?n.moveByGroup(t,e):rs(t,e))}var fp=n=>Hh(n,!ne(n)),cp=n=>Hh(n,ne(n));var yO=typeof Intl<"u"&&Intl.Segmenter?new Intl.Segmenter(void 0,{granularity:"word"}):null;function up(n,e,t){if(e.type.prop(t))return!0;let i=e.to-e.from;return i&&(i>2||/[^\s,.;:]/.test(n.sliceDoc(e.from,e.to)))||e.firstChild}function os(n,e,t){let i=J(n).resolveInner(e.head),s=t?R.closedBy:R.openedBy;for(let a=e.head;;){let h=t?i.childAfter(a):i.childBefore(a);if(!h)break;up(n,h,s)?i=h:a=t?h.to:h.from}let r=i.type.prop(s),o,l;return r&&(o=t?Me(n,i.from,1):Me(n,i.to,-1))&&o.matched?l=t?o.end.to:o.end.from:l=t?i.to:i.from,b.cursor(l,t?-1:1)}var dp=n=>Be(n,e=>os(n.state,e,!ne(n))),pp=n=>Be(n,e=>os(n.state,e,ne(n)));function Uh(n,e){return Be(n,t=>{if(!t.empty)return rs(t,e);let i=n.moveVertically(t,e);return i.head!=t.head?i:n.moveToLineBoundary(t,e)})}var jh=n=>Uh(n,!1),Gh=n=>Uh(n,!0);function Zh(n){let e=n.scrollDOM.clientHeighto.empty?n.moveVertically(o,e,t.height):rs(o,e));if(s.eq(i.selection))return!1;let r;if(t.selfScroll){let o=n.coordsAtPos(i.selection.main.head),l=n.scrollDOM.getBoundingClientRect(),a=l.top+t.marginTop,h=l.bottom-t.marginBottom;o&&o.top>a&&o.bottomYh(n,!1),Oo=n=>Yh(n,!0);function Ot(n,e,t){let i=n.lineBlockAt(e.head),s=n.moveToLineBoundary(e,t);if(s.head==e.head&&s.head!=(t?i.to:i.from)&&(s=n.moveToLineBoundary(e,t,!1)),!t&&s.head==i.from&&i.length){let r=/^\s*/.exec(n.state.sliceDoc(i.from,Math.min(i.from+100,i.to)))[0].length;r&&e.head!=i.from+r&&(s=b.cursor(i.from+r))}return s}var mp=n=>Be(n,e=>Ot(n,e,!0)),gp=n=>Be(n,e=>Ot(n,e,!1)),Op=n=>Be(n,e=>Ot(n,e,!ne(n))),yp=n=>Be(n,e=>Ot(n,e,ne(n))),bp=n=>Be(n,e=>n.moveToLineBoundary(e,!1,!1)),Sp=n=>Be(n,e=>n.moveToLineBoundary(e,!0,!1));function xp(n,e,t){let i=!1,s=mi(n.selection,r=>{let o=Me(n,r.head,-1)||Me(n,r.head,1)||r.head>0&&Me(n,r.head-1,1)||r.headxp(n,e,!1);function Te(n,e,t){let i=mi(n.state.selection,s=>{s.undirectional&&s.head>=s.anchor!=e&&(s=b.range(s.head,s.anchor));let r=t(s);return b.range(s.anchor,r.head,r.goalColumn,r.bidiLevel||void 0,r.assoc)});return i.eq(n.state.selection)?!1:(n.dispatch(De(n.state,i)),!0)}function Kh(n,e){return Te(n,e,t=>n.moveByChar(t,e))}var Jh=n=>Kh(n,!ne(n)),ef=n=>Kh(n,ne(n));function tf(n,e){return Te(n,e,t=>n.moveByGroup(t,e))}var wp=n=>tf(n,!ne(n)),vp=n=>tf(n,ne(n));var Tp=n=>{let e=!ne(n);return Te(n,e,t=>os(n.state,t,e))},Cp=n=>{let e=ne(n);return Te(n,e,t=>os(n.state,t,e))};function nf(n,e){return Te(n,e,t=>n.moveVertically(t,e))}var sf=n=>nf(n,!1),rf=n=>nf(n,!0);function of(n,e){return Te(n,e,t=>n.moveVertically(t,e,Zh(n).height))}var Ph=n=>of(n,!1),Ah=n=>of(n,!0),Qp=n=>Te(n,!0,e=>Ot(n,e,!0)),Pp=n=>Te(n,!1,e=>Ot(n,e,!1)),Ap=n=>{let e=!ne(n);return Te(n,e,t=>Ot(n,t,e))},Rp=n=>{let e=ne(n);return Te(n,e,t=>Ot(n,t,e))},Mp=n=>Te(n,!1,e=>b.cursor(n.lineBlockAt(e.head).from)),Ep=n=>Te(n,!0,e=>b.cursor(n.lineBlockAt(e.head).to)),Rh=({state:n,dispatch:e})=>(e(De(n,{anchor:0})),!0),Mh=({state:n,dispatch:e})=>(e(De(n,{anchor:n.doc.length})),!0),Eh=({state:n,dispatch:e})=>(e(De(n,{anchor:n.selection.main.anchor,head:0})),!0),Dh=({state:n,dispatch:e})=>(e(De(n,{anchor:n.selection.main.anchor,head:n.doc.length})),!0),Dp=({state:n,dispatch:e})=>(e(n.update({selection:{anchor:0,head:n.doc.length},userEvent:"select"})),!0),Bp=({state:n,dispatch:e})=>{let t=ls(n).map(({from:i,to:s})=>b.undirectionalRange(i,Math.min(s+1,n.doc.length)));return e(n.update({selection:b.create(t),userEvent:"select"})),!0},qp=({state:n,dispatch:e})=>{let t=mi(n.selection,i=>{let s=J(n),r=s.resolveStack(i.from,1);if(i.empty){let o=s.resolveStack(i.from,-1);o.node.from>=r.node.from&&o.node.to<=r.node.to&&(r=o)}for(let o=r;o;o=o.next){let{node:l}=o;if((l.from=i.to||l.to>i.to&&l.from<=i.from)&&o.next)return b.undirectionalRange(l.from,l.to)}return i});return t.eq(n.selection)?!1:(e(De(n,t)),!0)};function lf(n,e){let{state:t}=n,i=t.selection,s=t.selection.ranges.slice();for(let r of t.selection.ranges){let o=t.doc.lineAt(r.head);if(e?o.to0)for(let l=r;;){let a=n.moveVertically(l,e);if(a.heado.to){s.some(h=>h.head==a.head)||s.push(a);break}else{if(a.head==l.head)break;l=a}}}return s.length==i.ranges.length?!1:(n.dispatch(De(t,b.create(s,s.length-1))),!0)}var Wp=n=>lf(n,!1),$p=n=>lf(n,!0),Lp=({state:n,dispatch:e})=>{let t=n.selection,i=null;return t.ranges.length>1?i=b.create([t.main]):t.main.empty||(i=b.create([b.cursor(t.main.head)])),i?(e(De(n,i)),!0):!1};function Yi(n,e){if(n.state.readOnly)return!1;let t="delete.selection",{state:i}=n,s=i.changeByRange(r=>{let{from:o,to:l}=r;if(o==l){let a=e(r);ao&&(t="delete.forward",a=is(n,a,!0)),o=Math.min(o,a),l=Math.max(l,a)}else o=is(n,o,!1),l=is(n,l,!0);return o==l?{range:r}:{changes:{from:o,to:l},range:b.cursor(o,os(n)))i.between(e,e,(s,r)=>{se&&(e=t?r:s)});return e}var af=(n,e,t)=>Yi(n,i=>{let s=i.from,{state:r}=n,o=r.doc.lineAt(s),l,a;if(t&&!e&&s>o.from&&saf(n,!1,!0);var hf=n=>af(n,!0,!1),ff=(n,e)=>Yi(n,t=>{let i=t.head,{state:s}=n,r=s.doc.lineAt(i),o=s.charCategorizer(i);for(let l=null;;){if(i==(e?r.to:r.from)){i==t.head&&r.number!=(e?s.doc.lines:1)&&(i+=e?1:-1);break}let a=K(r.text,i-r.from,e)+r.from,h=r.text.slice(Math.min(i,a)-r.from,Math.max(i,a)-r.from),f=o(h);if(l!=null&&f!=l)break;(h!=" "||i!=t.head)&&(l=f),i=a}return i}),cf=n=>ff(n,!1),zp=n=>ff(n,!0);var Ip=n=>Yi(n,e=>{let t=n.lineBlockAt(e.head).to;return e.headYi(n,e=>{let t=n.moveToLineBoundary(e,!1).head;return e.head>t?t:Math.max(0,e.head-1)}),Vp=n=>Yi(n,e=>{let t=n.moveToLineBoundary(e,!0).head;return e.head{if(n.readOnly)return!1;let t=n.changeByRange(i=>({changes:{from:i.from,to:i.to,insert:M.of(["",""])},range:b.cursor(i.from)}));return e(n.update(t,{scrollIntoView:!0,userEvent:"input"})),!0},Fp=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(i=>{if(!i.empty||i.from==0||i.from==n.doc.length)return{range:i};let s=i.from,r=n.doc.lineAt(s),o=s==r.from?s-1:K(r.text,s-r.from,!1)+r.from,l=s==r.to?s+1:K(r.text,s-r.from,!0)+r.from;return{changes:{from:o,to:l,insert:n.doc.slice(s,l).append(n.doc.slice(o,s))},range:b.cursor(l)}});return t.changes.empty?!1:(e(n.update(t,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function ls(n){let e=[],t=-1;for(let i of n.selection.ranges){let s=n.doc.lineAt(i.from),r=n.doc.lineAt(i.to);if(!i.empty&&i.to==r.from&&(r=n.doc.lineAt(i.to-1)),t>=s.number){let o=e[e.length-1];o.to=r.to,o.ranges.push(i)}else e.push({from:s.from,to:r.to,ranges:[i]});t=r.number+1}return e}function uf(n,e,t){if(n.readOnly)return!1;let i=[],s=[];for(let r of ls(n)){if(t?r.to==n.doc.length:r.from==0)continue;let o=n.doc.lineAt(t?r.to+1:r.from-1),l=o.length+1;if(t){i.push({from:r.to,to:o.to},{from:r.from,insert:o.text+n.lineBreak});for(let a of r.ranges)s.push(b.range(Math.min(n.doc.length,a.anchor+l),Math.min(n.doc.length,a.head+l)))}else{i.push({from:o.from,to:r.from},{from:r.to,insert:n.lineBreak+o.text});for(let a of r.ranges)s.push(b.range(a.anchor-l,a.head-l))}}return i.length?(e(n.update({changes:i,scrollIntoView:!0,selection:b.create(s,n.selection.mainIndex),userEvent:"move.line"})),!0):!1}var _p=({state:n,dispatch:e})=>uf(n,e,!1),Hp=({state:n,dispatch:e})=>uf(n,e,!0);function df(n,e,t){if(n.readOnly)return!1;let i=[];for(let r of ls(n))t?i.push({from:r.from,insert:n.doc.slice(r.from,r.to)+n.lineBreak}):i.push({from:r.to,insert:n.lineBreak+n.doc.slice(r.from,r.to)});let s=n.changes(i);return e(n.update({changes:s,selection:n.selection.map(s,t?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}var Up=({state:n,dispatch:e})=>df(n,e,!1),jp=({state:n,dispatch:e})=>df(n,e,!0),Gp=n=>{if(n.state.readOnly)return!1;let{state:e}=n,t=e.changes(ls(e).map(({from:s,to:r})=>(s>0?s--:r{let r;if(n.lineWrapping){let o=n.lineBlockAt(s.head),l=n.coordsAtPos(s.head,s.assoc||1);l&&(r=o.bottom+n.documentTop-l.bottom+n.defaultLineHeight/2)}return n.moveVertically(s,!0,r)}).map(t);return n.dispatch({changes:t,selection:i,scrollIntoView:!0,userEvent:"delete.line"}),!0};function Zp(n,e){if(/\(\)|\[\]|\{\}/.test(n.sliceDoc(e-1,e+1)))return{from:e,to:e};let t=J(n).resolveInner(e),i=t.childBefore(e),s=t.childAfter(e),r;return i&&s&&i.to<=e&&s.from>=e&&(r=i.type.prop(R.closedBy))&&r.indexOf(s.name)>-1&&n.doc.lineAt(i.to).from==n.doc.lineAt(s.from).from&&!/\S/.test(n.sliceDoc(i.to,s.from))?{from:i.to,to:s.from}:null}var Bh=pf(!1),Yp=pf(!0);function pf(n){return({state:e,dispatch:t})=>{if(e.readOnly)return!1;let i=e.changeByRange(s=>{let{from:r,to:o}=s,l=e.doc.lineAt(r),a=!n&&r==o&&Zp(e,r);n&&(r=o=(o<=l.to?l:e.doc.lineAt(o)).to);let h=new $t(e,{simulateBreak:r,simulateDoubleBreak:!!a}),f=Kn(h,r);for(f==null&&(f=Ct(/^\s*/.exec(e.doc.lineAt(r).text)[0],e.tabSize));ol.from&&r{let s=[];for(let o=i.from;o<=i.to;){let l=n.doc.lineAt(o);l.number>t&&(i.empty||i.to>l.from)&&(e(l,s,i),t=l.number),o=l.to+1}let r=n.changes(s);return{changes:s,range:b.range(r.mapPos(i.anchor,1),r.mapPos(i.head,1))}})}var Kp=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=Object.create(null),i=new $t(n,{overrideIndentation:r=>{let o=t[r];return o??-1}}),s=xo(n,(r,o,l)=>{let a=Kn(i,r.from);if(a==null)return;/\S/.test(r.text)||(a=0);let h=/^\s*/.exec(r.text)[0],f=di(n,a);(h!=f||l.fromn.readOnly?!1:(e(n.update(xo(n,(t,i)=>{i.push({from:t.from,insert:n.facet(gt)})}),{userEvent:"input.indent"})),!0),gf=({state:n,dispatch:e})=>n.readOnly?!1:(e(n.update(xo(n,(t,i)=>{let s=/^\s*/.exec(t.text)[0];if(!s)return;let r=Ct(s,n.tabSize),o=0,l=di(n,Math.max(0,r-Hi(n)));for(;o(n.setTabFocusMode(),!0);var em=[{key:"Ctrl-b",run:Fh,shift:Jh,preventDefault:!0},{key:"Ctrl-f",run:_h,shift:ef},{key:"Ctrl-p",run:jh,shift:sf},{key:"Ctrl-n",run:Gh,shift:rf},{key:"Ctrl-a",run:bp,shift:Mp},{key:"Ctrl-e",run:Sp,shift:Ep},{key:"Ctrl-d",run:hf},{key:"Ctrl-h",run:yo},{key:"Ctrl-k",run:Ip},{key:"Ctrl-Alt-h",run:cf},{key:"Ctrl-o",run:Xp},{key:"Ctrl-t",run:Fp},{key:"Ctrl-v",run:Oo}],tm=[{key:"ArrowLeft",run:Fh,shift:Jh,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:fp,shift:wp,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:Op,shift:Ap,preventDefault:!0},{key:"ArrowRight",run:_h,shift:ef,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:cp,shift:vp,preventDefault:!0},{mac:"Cmd-ArrowRight",run:yp,shift:Rp,preventDefault:!0},{key:"ArrowUp",run:jh,shift:sf,preventDefault:!0},{mac:"Cmd-ArrowUp",run:Rh,shift:Eh},{mac:"Ctrl-ArrowUp",run:Qh,shift:Ph},{key:"ArrowDown",run:Gh,shift:rf,preventDefault:!0},{mac:"Cmd-ArrowDown",run:Mh,shift:Dh},{mac:"Ctrl-ArrowDown",run:Oo,shift:Ah},{key:"PageUp",run:Qh,shift:Ph},{key:"PageDown",run:Oo,shift:Ah},{key:"Home",run:gp,shift:Pp,preventDefault:!0},{key:"Mod-Home",run:Rh,shift:Eh},{key:"End",run:mp,shift:Qp,preventDefault:!0},{key:"Mod-End",run:Mh,shift:Dh},{key:"Enter",run:Bh,shift:Bh},{key:"Mod-a",run:Dp},{key:"Backspace",run:yo,shift:yo,preventDefault:!0},{key:"Delete",run:hf,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:cf,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:zp,preventDefault:!0},{mac:"Mod-Backspace",run:Np,preventDefault:!0},{mac:"Mod-Delete",run:Vp,preventDefault:!0}].concat(em.map(n=>({mac:n.key,run:n.run,shift:n.shift}))),Of=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:dp,shift:Tp},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:pp,shift:Cp},{key:"Alt-ArrowUp",run:_p},{key:"Shift-Alt-ArrowUp",run:Up},{key:"Alt-ArrowDown",run:Hp},{key:"Shift-Alt-ArrowDown",run:jp},{key:"Mod-Alt-ArrowUp",run:Wp},{key:"Mod-Alt-ArrowDown",run:$p},{key:"Escape",run:Lp},{key:"Mod-Enter",run:Yp},{key:"Alt-l",mac:"Ctrl-l",run:Bp},{key:"Mod-i",run:qp,preventDefault:!0},{key:"Mod-[",run:gf},{key:"Mod-]",run:mf},{key:"Mod-Alt-\\",run:Kp},{key:"Shift-Mod-k",run:Gp},{key:"Shift-Mod-\\",run:kp},{key:"Mod-/",run:Ud},{key:"Alt-A",mac:"Ctrl-A",run:Gd},{key:"Ctrl-m",mac:"Shift-Alt-m",run:Jp}].concat(tm),yf={key:"Tab",run:mf,shift:gf};var vo=class n{constructor(e,t,i,s,r,o,l,a,h,f=0,c){this.p=e,this.stack=t,this.state=i,this.reducePos=s,this.pos=r,this.score=o,this.buffer=l,this.bufferBase=a,this.curContext=h,this.lookAhead=f,this.parent=c}toString(){return`[${this.stack.filter((e,t)=>t%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,i=0){let s=e.parser.context;return new n(e,[],t,i,i,0,[],0,s?new as(s,s.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){var t;let i=e>>19,s=e&65535,{parser:r}=this.p,o=this.reducePos=2e3&&!(!((t=this.p.parser.nodeSet.types[s])===null||t===void 0)&&t.isAnonymous)&&(h==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=f):this.p.lastBigReductionSizea;)this.stack.pop();this.reduceContext(s,h)}storeNode(e,t,i,s=4,r=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]0&&this.buffer[o-4]==0&&this.buffer[o-1]>-1){if(t==i)return;if(this.buffer[o-2]>=t){this.buffer[o-2]=i;return}}}if(!r||this.pos==i)this.buffer.push(e,t,i,s);else{let o=this.buffer.length;if(o>0&&(this.buffer[o-4]!=0||this.buffer[o-1]<0)){let l=!1;for(let a=o;a>0&&this.buffer[a-2]>i;a-=4)if(this.buffer[a-1]>=0){l=!0;break}if(l)for(;o>0&&this.buffer[o-2]>i;)this.buffer[o]=this.buffer[o-4],this.buffer[o+1]=this.buffer[o-3],this.buffer[o+2]=this.buffer[o-2],this.buffer[o+3]=this.buffer[o-1],o-=4,s>4&&(s-=4)}this.buffer[o]=e,this.buffer[o+1]=t,this.buffer[o+2]=i,this.buffer[o+3]=s}}shift(e,t,i,s){if(e&131072)this.pushState(e&65535,this.pos);else if((e&262144)==0){let r=e,{parser:o}=this.p;this.pos=s;let l=o.stateFlag(r,1);!l&&(s>i||t<=o.maxNode)&&(this.reducePos=s),this.pushState(r,l?i:Math.min(i,this.reducePos)),this.shiftContext(t,i),t<=o.maxNode&&this.buffer.push(t,i,s,4)}else this.pos=s,this.shiftContext(t,i),t<=this.p.parser.maxNode&&this.buffer.push(t,i,s,4)}apply(e,t,i,s){e&65536?this.reduce(e):this.shift(e,t,i,s)}useNode(e,t,i){let s=this.p.reused.length-1;(s<0||this.p.reused[s]!=e)&&(this.p.reused.push(e),s++);let r=this.reducePos=this.pos=i+e.length;this.pushState(t,i),this.buffer.push(s,i,r,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(t&&e.buffer[t-4]==0&&(t-=4);t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let i=e.buffer.slice(t),s=e.bufferBase+t;for(;e&&s==e.bufferBase;)e=e.parent;return new n(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,i,s,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let i=e<=this.p.parser.maxNode;i&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,i?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new To(this);;){let i=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(i==0)return!1;if((i&65536)==0)return!0;t.reduce(i)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let s=[];for(let r=0,o;ra&1&&l==o)||s.push(t[r],o)}t=s}let i=[];for(let s=0;s>19,s=t&65535,r=this.stack.length-i*3;if(r<0||e.getGoto(this.stack[r],s,!1)<0){let o=this.findForcedReduction();if(o==null)return!1;t=o}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(t),!0}findForcedReduction(){let{parser:e}=this.p,t=[],i=(s,r)=>{if(!t.includes(s))return t.push(s),e.allActions(s,o=>{if(!(o&393216))if(o&65536){let l=(o>>19)-r;if(l>1){let a=o&65535,h=this.stack.length-l*3;if(h>=0&&e.getGoto(this.stack[h],a,!1)>=0)return l<<19|65536|a}}else{let l=i(o,r+1);if(l!=null)return l}})};return i(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.storeNode(0,this.pos,this.pos,4,!0),this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;t0&&this.emitLookAhead()}},as=class{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}},To=class{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,i=e>>19;i==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(i-1)*3;let s=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=s}},Co=class n{constructor(e,t,i){this.stack=e,this.pos=t,this.index=i,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new n(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new n(this.stack,this.pos,this.index)}};function Ki(n,e=Uint16Array){if(typeof n!="string")return n;let t=null;for(let i=0,s=0;i=92&&o--,o>=34&&o--;let a=o-32;if(a>=46&&(a-=46,l=!0),r+=a,l)break;r*=46}t?t[s++]=r:t=new e(r)}return t}var gi=class{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}},bf=new gi,Qo=class{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=bf,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let i=this.range,s=this.rangeIndex,r=this.pos+e;for(;ri.to:r>=i.to;){if(s==this.ranges.length-1)return null;let o=this.ranges[++s];r+=o.from-i.to,i=o}return r}clipPos(e){if(e>=this.range.from&&ee)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,i,s;if(t>=0&&t=this.chunk2Pos&&il.to&&(this.chunk2=this.chunk2.slice(0,l.to-i)),s=this.chunk2.charCodeAt(0)}}return i>=this.token.lookAhead&&(this.token.lookAhead=i+1),s}acceptToken(e,t=0){let i=t?this.resolveOffset(t,-1):this.pos;if(i==null||i=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=bf,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let i="";for(let s of this.ranges){if(s.from>=t)break;s.to>e&&(i+=this.input.read(Math.max(s.from,e),Math.min(s.to,t)))}return i}},yt=class{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:i}=t.p;vf(this.data,e,t,this.id,i.data,i.tokenPrecTable)}};yt.prototype.contextual=yt.prototype.fallback=yt.prototype.extend=!1;var Po=class{constructor(e,t,i){this.precTable=t,this.elseToken=i,this.data=typeof e=="string"?Ki(e):e}token(e,t){let i=e.pos,s=0;for(;;){let r=e.next<0,o=e.resolveOffset(1,1);if(vf(this.data,e,t,0,this.data,this.precTable),e.token.value>-1)break;if(this.elseToken==null)return;if(r||s++,o==null)break;e.reset(o,e.token)}s&&(e.reset(i,e.token),e.acceptToken(this.elseToken,s))}};Po.prototype.contextual=yt.prototype.fallback=yt.prototype.extend=!1;var It=class{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}};function vf(n,e,t,i,s,r){let o=0,l=1<0){let p=n[d];if(a.allows(p)&&(e.token.value==-1||e.token.value==p||nm(p,e.token.value,s,r))){e.acceptToken(p);break}}let f=e.next,c=0,u=n[o+2];if(e.next<0&&u>c&&n[h+u*3-3]==65535){o=n[h+u*3-1];continue e}for(;c>1,p=h+d+(d<<1),m=n[p],O=n[p+1]||65536;if(f=O)c=d+1;else{o=n[p+2],e.advance();continue e}}break}}function Sf(n,e,t){for(let i=e,s;(s=n[i])!=65535;i++)if(s==t)return i-e;return-1}function nm(n,e,t,i){let s=Sf(t,i,e);return s<0||Sf(t,i,n)e)&&!i.type.isError)return t<0?Math.max(0,Math.min(i.to-1,e-25)):Math.min(n.length,Math.max(i.from+1,e+25));if(t<0?i.prevSibling():i.nextSibling())break;if(!i.parent())return t<0?0:n.length}}var Ao=class{constructor(e,t){this.fragments=e,this.minRepeat=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.lastRepeat=null,this.lastRepeatPos=-1,this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?xf(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?xf(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=o,null;if(r instanceof j){let l=o>this.lastRepeatPos&&r.type.id>=this.minRepeat;if(o==e||l){let a=o+r.length,h;if(o>=this.safeFrom&&a<=this.safeTo&&(!(h=r.prop(R.lookAhead))||a+h=Math.max(this.safeFrom,e)&&(this.trees.push(r),this.start.push(o),this.index.push(0))}else this.index[t]++,this.nextStart=o+r.length}}},Ro=class{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(i=>new gi)}getActions(e){let t=0,i=null,{parser:s}=e.p,{tokenizers:r}=s,o=s.stateSlot(e.state,3),l=e.curContext?e.curContext.hash:0,a=0;for(let h=0;hc.end+25&&(a=Math.max(c.lookAhead,a)),c.value!=0)){let u=t;if(c.extended>-1&&(t=this.addActions(e,c.extended,c.end,t)),t=this.addActions(e,c.value,c.end,t),!f.extend&&(i=c,t>u))break}}for(;this.actions.length>t;)this.actions.pop();return a&&e.setLookAhead(a),!i&&e.pos==this.stream.end&&(i=new gi,i.value=e.p.parser.eofTerm,i.start=i.end=e.pos,t=this.addActions(e,i.value,i.end,t)),this.mainToken=i,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new gi,{pos:i,p:s}=e;return t.start=i,t.end=Math.min(i+1,s.stream.end),t.value=i==s.stream.end?s.parser.eofTerm:0,t}updateCachedToken(e,t,i){let s=this.stream.clipPos(i.pos);if(t.token(this.stream.reset(s,e),i),e.value>-1){let{parser:r}=i.p;for(let o=0;o=0&&i.p.parser.dialect.allows(l>>1)){(l&1)==0?e.value=l>>1:e.extended=l>>1;break}}}else e.value=0,e.end=this.stream.clipPos(s+1)}putAction(e,t,i,s){for(let r=0;re.bufferLength*4?new Ao(i,e.minRepeatTerm):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,i=this.stacks=[],s,r;if(this.bigReductionCount>300&&e.length==1){let[o]=e;for(;o.forceReduce()&&o.stack.length&&o.stack[o.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let o=0;ot)i.push(l);else{if(this.advanceStack(l,i,e))continue;{s||(s=[],r=[]),s.push(l);let a=this.tokens.getMainToken(l);r.push(a.value,a.end)}}break}}if(!i.length){let o=s&&sm(s);if(o)return ge&&console.log("Finish with "+this.stackID(o)),this.stackToTree(o);if(this.parser.strict)throw ge&&s&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+t);this.recovering||(this.recovering=5)}if(this.recovering&&s){let o=this.stoppedAt!=null&&s[0].pos>this.stoppedAt?s[0]:this.runRecovery(s,r,i);if(o)return ge&&console.log("Force-finish "+this.stackID(o)),this.stackToTree(o.forceAll())}if(this.recovering){let o=this.recovering==1?1:this.recovering*3;if(i.length>o)for(i.sort((l,a)=>a.score-l.score);i.length>o;)i.pop();i.some(l=>l.reducePos>t)&&this.recovering--}else if(i.length>1){e:for(let o=0;o500&&h.buffer.length>500)if((l.score-h.score||l.buffer.length-h.buffer.length)>0)i.splice(a--,1);else{i.splice(o--,1);continue e}}}i.length>12&&(i.sort((o,l)=>l.score-o.score),i.splice(12,i.length-12))}this.minStackPos=i[0].pos;for(let o=1;o-1&&i.length&&(!r||(i.prop(R.contextHash)||0)==o))return e.useNode(i,l,t),i;if(i.children.length==0||i.positions[0]>0)break;let a=i.children[0];if(a instanceof j&&(!s||a.type.id>=this.parser.minRepeatTerm))i=a;else break}return null}advanceStack(e,t,i){let s=e.pos,{parser:r}=this,o=ge?this.stackID(e)+" -> ":"";if(this.stoppedAt!=null&&s>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let h=e.reducePos0)return e.reduce(l),ge&&console.log(o+this.stackID(e)+` (via always-reduce ${r.getName(l&65535)})`),!0;if(e.stack.length>=8400)for(;e.stack.length>6e3&&e.forceReduce(););let a=this.tokens.getActions(e);for(let h=0;hs?t.push(p):i.push(p)}return!1}advanceFully(e,t){let i=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>i)return kf(e,t),!0}}runRecovery(e,t,i){let s=null,r=!1;for(let o=0;o ":"";if(l.deadEnd&&(r||(r=!0,l.restart(),ge&&console.log(f+this.stackID(l)+" (restarted)"),this.advanceFully(l,i))))continue;let c=l.split(),u=f;for(let d=0;d<10&&c.forceReduce()&&(ge&&console.log(u+this.stackID(c)+" (via force-reduce)"),!this.advanceFully(c,i));d++)ge&&(u=this.stackID(c)+" -> ");for(let d of l.recoverByInsert(a))ge&&console.log(f+this.stackID(d)+" (via recover-insert)"),this.advanceFully(d,i);this.stream.end>l.pos?(h==l.pos&&(h++,a=0),l.recoverByDelete(a,h),ge&&console.log(f+this.stackID(l)+` (via recover-delete ${this.parser.getName(a)})`),kf(l,i)):(!s||s.scoren,hs=class{constructor(e){this.start=e.start,this.shift=e.shift||wo,this.reduce=e.reduce||wo,this.reuse=e.reuse||wo,this.hash=e.hash||(()=>0),this.strict=e.strict!==!1}},fs=class n extends hi{constructor(e){if(super(),this.wrappers=[],e.version!=14)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let l=0;le.topRules[l][1]),s=[];for(let l=0;l=0)r(f,a,l[h++]);else{let c=l[h+-f];for(let u=-f;u>0;u--)r(l[h++],a,c);h++}}}this.nodeSet=new Ii(t.map((l,a)=>ie.define({name:a>=this.minRepeatTerm?void 0:l,id:a,props:s[a],top:i.indexOf(a)>-1,error:a==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=1024;let o=Ki(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let l=0;ltypeof l=="number"?new yt(o,l):l),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,i){let s=new Mo(this,e,t,i);for(let r of this.wrappers)s=r(s,e,t,i);return s}getGoto(e,t,i=!1){let s=this.goto;if(t>=s[0])return-1;for(let r=s[t+1];;){let o=s[r++],l=o&1,a=s[r++];if(l&&i)return a;for(let h=r+(o>>1);r0}validAction(e,t){return!!this.allActions(e,i=>i==t?!0:null)}allActions(e,t){let i=this.stateSlot(e,4),s=i?t(i):void 0;for(let r=this.stateSlot(e,1);s==null;r+=3){if(this.data[r]==65535)if(this.data[r+1]==1)r=Je(this.data,r+2);else break;s=t(Je(this.data,r+1))}return s}nextStates(e){let t=[];for(let i=this.stateSlot(e,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=Je(this.data,i+2);else break;if((this.data[i+2]&1)==0){let s=this.data[i+1];t.some((r,o)=>o&1&&r==s)||t.push(this.data[i],s)}}return t}configure(e){let t=Object.assign(Object.create(n.prototype),this);if(e.props&&(t.nodeSet=this.nodeSet.extend(...e.props)),e.top){let i=this.topRules[e.top];if(!i)throw new RangeError(`Invalid top rule name ${e.top}`);t.top=i}return e.tokenizers&&(t.tokenizers=this.tokenizers.map(i=>{let s=e.tokenizers.find(r=>r.from==i);return s?s.to:i})),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map((i,s)=>{let r=e.specializers.find(l=>l.from==i.external);if(!r)return i;let o=Object.assign(Object.assign({},i),{external:r.to});return t.specializers[s]=wf(o),o})),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),e.strict!=null&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),e.bufferLength!=null&&(t.bufferLength=e.bufferLength),t}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),i=t.map(()=>!1);if(e)for(let r of e.split(" ")){let o=t.indexOf(r);o>=0&&(i[o]=!0)}let s=null;for(let r=0;ri)&&t.p.parser.stateFlag(t.state,2)&&(!e||e.scoren.external(t,i)<<1|e}return n.get}var rm=1,Rf=194,Mf=195,om=196,Tf=197,lm=198,am=199,hm=200,fm=2,Ef=3,Cf=201,cm=24,um=25,dm=49,pm=50,mm=55,gm=56,Om=57,ym=59,bm=60,Sm=61,xm=62,km=63,wm=65,vm=238,Tm=71,Cm=241,Qm=242,Pm=243,Am=244,Rm=245,Mm=246,Em=247,Dm=248,Df=72,Bm=249,qm=250,Wm=251,$m=252,Lm=253,zm=254,Im=255,Nm=256,Vm=73,Xm=77,Fm=263,_m=112,Hm=130,Um=151,jm=152,Gm=155,Nt=10,Ji=13,Wo=32,ds=9,$o=35,Zm=40,Ym=46,qo=123,Qf=125,Bf=39,qf=34,Pf=92,Km=111,Jm=120,eg=78,tg=117,ig=85,ng=new Set([um,dm,pm,Fm,wm,Hm,gm,Om,vm,xm,km,Df,Vm,Xm,bm,Sm,Um,jm,Gm,_m]);function Do(n){return n==Nt||n==Ji}function Bo(n){return n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102}var sg=new It((n,e)=>{let t;if(n.next<0)n.acceptToken(am);else if(e.context.flags&cs)Do(n.next)&&n.acceptToken(lm,1);else if(((t=n.peek(-1))<0||Do(t))&&e.canShift(Tf)){let i=0;for(;n.next==Wo||n.next==ds;)n.advance(),i++;(n.next==Nt||n.next==Ji||n.next==$o)&&n.acceptToken(Tf,-i)}else Do(n.next)&&n.acceptToken(om,1)},{contextual:!0}),rg=new It((n,e)=>{let t=e.context;if(t.flags)return;let i=n.peek(-1);if(i==Nt||i==Ji){let s=0,r=0;for(;;){if(n.next==Wo)s++;else if(n.next==ds)s+=8-s%8;else break;n.advance(),r++}s!=t.indent&&n.next!=Nt&&n.next!=Ji&&n.next!=$o&&(s[n,e|Wf])),ag=new hs({start:og,reduce(n,e,t,i){return n.flags&cs&&ng.has(e)||(e==Tm||e==Df)&&n.flags&Wf?n.parent:n},shift(n,e,t,i){return e==Rf?new us(n,lg(i.read(i.pos,t.pos)),0):e==Mf?n.parent:e==cm||e==mm||e==ym||e==Ef?new us(n,0,cs):Af.has(e)?new us(n,0,Af.get(e)|n.flags&cs):n},hash(n){return n.hash}}),hg=new It(n=>{for(let e=0;e<5;e++){if(n.next!="print".charCodeAt(e))return;n.advance()}if(!/\w/.test(String.fromCharCode(n.next)))for(let e=0;;e++){let t=n.peek(e);if(!(t==Wo||t==ds)){t!=Zm&&t!=Ym&&t!=Nt&&t!=Ji&&t!=$o&&n.acceptToken(rm);return}}}),fg=new It((n,e)=>{let{flags:t}=e.context,i=t&et?qf:Bf,s=(t&tt)>0,r=!(t&it),o=(t&nt)>0,l=n.pos;for(;!(n.next<0);)if(o&&n.next==qo)if(n.peek(1)==qo)n.advance(2);else{if(n.pos==l){n.acceptToken(Ef,1);return}break}else if(r&&n.next==Pf){if(n.pos==l){n.advance();let a=n.next;a>=0&&(n.advance(),cg(n,a)),n.acceptToken(fm);return}break}else if(n.next==Pf&&!r&&n.peek(1)>-1)n.advance(2);else if(n.next==i&&(!s||n.peek(1)==i&&n.peek(2)==i)){if(n.pos==l){n.acceptToken(Cf,s?3:1);return}break}else if(n.next==Nt){if(s)n.advance();else if(n.pos==l){n.acceptToken(Cf);return}break}else n.advance();n.pos>l&&n.acceptToken(hm)});function cg(n,e){if(e==Km)for(let t=0;t<2&&n.next>=48&&n.next<=55;t++)n.advance();else if(e==Jm)for(let t=0;t<2&&Bo(n.next);t++)n.advance();else if(e==tg)for(let t=0;t<4&&Bo(n.next);t++)n.advance();else if(e==ig)for(let t=0;t<8&&Bo(n.next);t++)n.advance();else if(e==eg&&n.next==qo){for(n.advance();n.next>=0&&n.next!=Qf&&n.next!=Bf&&n.next!=qf&&n.next!=Nt;)n.advance();n.next==Qf&&n.advance()}}var ug=Gn({'async "*" "**" FormatConversion FormatSpec':g.modifier,"for while if elif else try except finally return raise break continue with pass assert await yield match case":g.controlKeyword,"in not and or is del":g.operatorKeyword,"from def class global nonlocal lambda":g.definitionKeyword,import:g.moduleKeyword,"with as print":g.keyword,Boolean:g.bool,None:g.null,VariableName:g.variableName,"CallExpression/VariableName":g.function(g.variableName),"FunctionDefinition/VariableName":g.function(g.definition(g.variableName)),"ClassDefinition/VariableName":g.definition(g.className),PropertyName:g.propertyName,"CallExpression/MemberExpression/PropertyName":g.function(g.propertyName),Comment:g.lineComment,Number:g.number,String:g.string,FormatString:g.special(g.string),Escape:g.escape,UpdateOp:g.updateOperator,"ArithOp!":g.arithmeticOperator,BitOp:g.bitwiseOperator,CompareOp:g.compareOperator,AssignOp:g.definitionOperator,Ellipsis:g.punctuation,At:g.meta,"( )":g.paren,"[ ]":g.squareBracket,"{ }":g.brace,".":g.derefOperator,", ;":g.separator}),dg={__proto__:null,await:44,or:54,and:56,in:60,not:62,is:64,if:70,else:72,lambda:76,yield:94,from:96,async:102,for:104,None:162,True:164,False:164,del:178,pass:182,break:186,continue:190,return:194,raise:202,import:206,as:208,global:212,nonlocal:214,assert:218,type:223,elif:236,while:240,try:246,except:248,finally:250,with:254,def:258,class:268,match:279,case:285},$f=fs.deserialize({version:14,states:"##jQ`QeOOP$}OSOOO&WQtO'#HUOOQS'#Co'#CoOOQS'#Cp'#CpO'vQdO'#CnO*UQtO'#HTOOQS'#HU'#HUOOQS'#DU'#DUOOQS'#HT'#HTO*rQdO'#D_O+VQdO'#DfO+gQdO'#DjO+zOWO'#DuO,VOWO'#DvO.[QtO'#GuOOQS'#Gu'#GuO'vQdO'#GtO0ZQtO'#GtOOQS'#Eb'#EbO0rQdO'#EcOOQS'#Gs'#GsO0|QdO'#GrOOQV'#Gr'#GrO1XQdO'#FYOOQS'#G^'#G^O1^QdO'#FXOOQV'#IS'#ISOOQV'#Gq'#GqOOQV'#Fq'#FqQ`QeOOO'vQdO'#CqO1lQdO'#C}O1sQdO'#DRO2RQdO'#HYO2cQtO'#EVO'vQdO'#EWOOQS'#EY'#EYOOQS'#E['#E[OOQS'#E^'#E^O2wQdO'#E`O3_QdO'#EdO3rQdO'#EfO3zQtO'#EfO1XQdO'#EiO0rQdO'#ElO1XQdO'#EnO0rQdO'#EtO0rQdO'#EwO4VQdO'#EyO4^QdO'#FOO4iQdO'#EzO0rQdO'#FOO1XQdO'#FQO1XQdO'#FVO4nQdO'#F[P4uOdO'#GpPOOO)CBd)CBdOOQS'#Ce'#CeOOQS'#Cf'#CfOOQS'#Cg'#CgOOQS'#Ch'#ChOOQS'#Ci'#CiOOQS'#Cj'#CjOOQS'#Cl'#ClO'vQdO,59OO'vQdO,59OO'vQdO,59OO'vQdO,59OO'vQdO,59OO'vQdO,59OO5TQdO'#DoOOQS,5:Y,5:YO5hQdO'#HdOOQS,5:],5:]O5uQ!fO,5:]O5zQtO,59YO1lQdO,59bO1lQdO,59bO1lQdO,59bO8jQdO,59bO8oQdO,59bO8vQdO,59jO8}QdO'#HTO:TQdO'#HSOOQS'#HS'#HSOOQS'#D['#D[O:lQdO,59aO'vQdO,59aO:zQdO,59aOOQS,59y,59yO;PQdO,5:RO'vQdO,5:ROOQS,5:Q,5:QO;_QdO,5:QO;dQdO,5:XO'vQdO,5:XO'vQdO,5:VOOQS,5:U,5:UO;uQdO,5:UO;zQdO,5:WOOOW'#Fy'#FyOOOOQS'#Ds'#DsOOQS1G/w1G/wOOQS1G.|1G.|O!/[QtO1G.|O!/cQtO1G.|O1lQdO1G.|O!0OQdO1G/UOOQS'#DZ'#DZO0rQdO,59tOOQS1G.{1G.{O!0VQdO1G/eO!0gQdO1G/eO!0oQdO1G/fO'vQdO'#H[O!0tQdO'#H[O!0yQtO1G.{O!1ZQdO,59iO!2aQdO,5=zO!2qQdO,5=zO!2yQdO1G/mO!3OQtO1G/mOOQS1G/l1G/lO!3`QdO,5=uO!4VQdO,5=uO0rQdO1G/qO!4tQdO1G/sO!4yQtO1G/sO!5ZQtO1G/qOOQS1G/p1G/pOOQS1G/r1G/rOOOW-E9w-E9wOOQS1G/{1G/{O!5kQdO'#HxO0rQdO'#HxO!5|QdO,5>cOOOW-E9x-E9xOOQS1G/|1G/|OOQS-E9{-E9{O!6[Q#xO1G2zO!6{QtO1G2zO'vQdO,5kOOQS1G1`1G1`O!8RQdO1G1`OOQS'#DV'#DVO0rQdO,5=qOOQS,5=q,5=qO!8WQdO'#FrO!8cQdO,59oO!8kQdO1G/XO!8uQtO,5=uOOQS1G3`1G3`OOQS,5:m,5:mO!9fQdO'#GtOOQS,5jO!;ZQdO,5>jO1XQdO,5>jO!;lQdO,5>iOOQS-E:R-E:RO!;qQdO1G0lO!;|QdO1G0lO!lO!lO!hO!=VQdO,5>hO!=hQdO'#EpO0rQdO1G0tO!=sQdO1G0tO!=xQgO1G0zO!AvQgO1G0}O!EqQdO,5>oO!E{QdO,5>oO!FTQtO,5>oO0rQdO1G1PO!F_QdO1G1PO4iQdO1G1UO!!vQdO1G1WOOQV,5;a,5;aO!FdQfO,5;aO!FiQgO1G1QO!JjQdO'#GZO4iQdO1G1QO4iQdO1G1QO!JzQdO,5>pO!KXQdO,5>pO1XQdO,5>pOOQV1G1U1G1UO!KaQdO'#FSO!KrQ!fO1G1WO!KzQdO1G1WOOQV1G1]1G1]O4iQdO1G1]O!LPQdO1G1]O!LXQdO'#F^OOQV1G1b1G1bO!#ZQtO1G1bPOOO1G2v1G2vP!L^OSO1G2vOOQS,5=},5=}OOQS'#Dp'#DpO0rQdO,5=}O!LfQdO,5=|O!LyQdO,5=|OOQS1G/u1G/uO!MRQdO,5>PO!McQdO,5>PO!MkQdO,5>PO!NOQdO,5>PO!N`QdO,5>POOQS1G3j1G3jOOQS7+$h7+$hO!8kQdO7+$pO#!RQdO1G.|O#!YQdO1G.|OOQS1G/`1G/`OOQS,5<`,5<`O'vQdO,5<`OOQS7+%P7+%PO#!aQdO7+%POOQS-E9r-E9rOOQS7+%Q7+%QO#!qQdO,5=vO'vQdO,5=vOOQS7+$g7+$gO#!vQdO7+%PO##OQdO7+%QO##TQdO1G3fOOQS7+%X7+%XO##eQdO1G3fO##mQdO7+%XOOQS,5<_,5<_O'vQdO,5<_O##rQdO1G3aOOQS-E9q-E9qO#$iQdO7+%]OOQS7+%_7+%_O#$wQdO1G3aO#%fQdO7+%_O#%kQdO1G3gO#%{QdO1G3gO#&TQdO7+%]O#&YQdO,5>dO#&sQdO,5>dO#&sQdO,5>dOOQS'#Dx'#DxO#'UO&jO'#DzO#'aO`O'#HyOOOW1G3}1G3}O#'fQdO1G3}O#'nQdO1G3}O#'yQ#xO7+(fO#(jQtO1G2UP#)TQdO'#GOOOQS,5nQdO,5sQdO1G4OOOQS-E9y-E9yO#?^QdO1G4OO<[QdO'#H{OOOO'#D{'#D{OOOO'#F|'#F|O#?oO&jO,5:fOOOW,5>e,5>eOOOW7+)i7+)iO#?zQdO7+)iO#@SQdO1G2zO#@mQdO1G2zP'vQdO'#FuO0rQdO<mO#BQQdO,5>mOOQS1G0v1G0vOOQS<rO#KgQdO,5>rO#KrQdO,5>rO#K}QdO,5>qO#L`QdO,5>qOOQS1G1Y1G1YOOQS,5;p,5;pOOQV<VAN>VO$ oQdO<cAN>cO0rQdO1G1|O$!PQtO1G1|P$!ZQdO'#FvOOQS1G2R1G2RP$!hQdO'#F{O$!uQdO7+)jO$#`QdO,5>gOOOO-E9z-E9zOOOW<tO$4{QdO,5>tO1XQdO,5vO$)nQdO,5>vOOQS1G1p1G1pOOQS,5<[,5<[OOQU7+'P7+'PO$+zQdO1G/iO$)nQdO,5wO$8zQdO,5>wOOQS1G1s1G1sOOQS7+'S7+'SP$)nQdO'#GdO$9SQdO1G4bO$9^QdO1G4bO$9fQdO1G4bOOQS7+%T7+%TO$9tQdO1G1tO$:SQtO'#FaO$:ZQdO,5<}OOQS,5<},5<}O$:iQdO1G4cOOQS-E:a-E:aO$)nQdO,5<|O$:pQdO,5<|O$:uQdO7+)|OOQS-E:`-E:`O$;PQdO7+)|O$)nQdO,5S~O%cOS%^OSSOS%]PQ~OPdOVaOfoOhYOopOs!POvqO!PrO!Q{O!T!SO!U!RO!XZO!][O!h`O!r`O!s`O!t`O!{tO!}uO#PvO#RwO#TxO#XyO#ZzO#^|O#_|O#a}O#c!OO#l!QO#o!TO#s!UO#u!VO#z!WO#}hO$P!XO%oRO%pRO%tSO%uWO&Z]O&[]O&]]O&^]O&_]O&`]O&a]O&b]O&c^O&d^O&e^O&f^O&g^O&h^O&i^O&j^O~O%]!YO~OV!aO_!aOa!bOh!iO!X!kO!f!mO%j![O%k!]O%l!^O%m!_O%n!_O%o!`O%p!`O%q!aO%r!aO%s!aO~Ok%xXl%xXm%xXn%xXo%xXp%xXs%xXz%xX{%xX!x%xX#g%xX%[%xX%_%xX%z%xXg%xX!T%xX!U%xX%{%xX!W%xX![%xX!Q%xX#[%xXt%xX!m%xX~P%SOfoOhYO!XZO!][O!h`O!r`O!s`O!t`O%oRO%pRO%tSO%uWO&Z]O&[]O&]]O&^]O&_]O&`]O&a]O&b]O&c^O&d^O&e^O&f^O&g^O&h^O&i^O&j^O~Oz%wX{%wX#g%wX%[%wX%_%wX%z%wX~Ok!pOl!qOm!oOn!oOo!rOp!sOs!tO!x%wX~P)pOV!zOg!|Oo0cOv0qO!PrO~P'vOV#OOo0cOv0qO!W#PO~P'vOV#SOa#TOo0cOv0qO![#UO~P'vOQ#XO%`#XO%a#ZO~OQ#^OR#[O%`#^O%a#`O~OV%iX_%iXa%iXh%iXk%iXl%iXm%iXn%iXo%iXp%iXs%iXz%iX!X%iX!f%iX%j%iX%k%iX%l%iX%m%iX%n%iX%o%iX%p%iX%q%iX%r%iX%s%iXg%iX!T%iX!U%iX~O&Z]O&[]O&]]O&^]O&_]O&`]O&a]O&b]O&c^O&d^O&e^O&f^O&g^O&h^O&i^O&j^O{%iX!x%iX#g%iX%[%iX%_%iX%z%iX%{%iX!W%iX![%iX!Q%iX#[%iXt%iX!m%iX~P,eOz#dO{%hX!x%hX#g%hX%[%hX%_%hX%z%hX~Oo0cOv0qO~P'vO#g#gO%[#iO%_#iO~O%uWO~O!T#nO#u!VO#z!WO#}hO~OopO~P'vOV#sOa#tO%uWO{wP~OV#xOo0cOv0qO!Q#yO~P'vO{#{O!x$QO%z#|O#g!yX%[!yX%_!yX~OV#xOo0cOv0qO#g#SX%[#SX%_#SX~P'vOo0cOv0qO#g#WX%[#WX%_#WX~P'vOh$WO%uWO~O!f$YO!r$YO%uWO~OV$eO~P'vO!U$gO#s$hO#u$iO~O{$jO~OV$qO~P'vOS$sO%[$rO%_$rO%c$tO~OV$}Oa$}Og%POo0cOv0qO~P'vOo0cOv0qO{%SO~P'vO&Y%UO~Oa!bOh!iO!X!kO!f!mOVba_bakbalbambanbaobapbasbazba{ba!xba#gba%[ba%_ba%jba%kba%lba%mba%nba%oba%pba%qba%rba%sba%zbagba!Tba!Uba%{ba!Wba![ba!Qba#[batba!mba~On%ZO~Oo%ZO~P'vOo0cO~P'vOk0eOl0fOm0dOn0dOo0mOp0nOs0rOg%wX!T%wX!U%wX%{%wX!W%wX![%wX!Q%wX#[%wX!m%wX~P)pO%{%]Og%vXz%vX!T%vX!U%vX!W%vX{%vX~Og%_Oz%`O!T%dO!U%cO~Og%_O~Oz%gO!T%dO!U%cO!W&SX~O!W%kO~Oz%lO{%nO!T%dO!U%cO![%}X~O![%rO~O![%sO~OQ#XO%`#XO%a%uO~OV%wOo0cOv0qO!PrO~P'vOQ#^OR#[O%`#^O%a%zO~OV!qa_!qaa!qah!qak!qal!qam!qan!qao!qap!qas!qaz!qa{!qa!X!qa!f!qa!x!qa#g!qa%[!qa%_!qa%j!qa%k!qa%l!qa%m!qa%n!qa%o!qa%p!qa%q!qa%r!qa%s!qa%z!qag!qa!T!qa!U!qa%{!qa!W!qa![!qa!Q!qa#[!qat!qa!m!qa~P#yOz%|O{%ha!x%ha#g%ha%[%ha%_%ha%z%ha~P%SOV&OOopOvqO{%ha!x%ha#g%ha%[%ha%_%ha%z%ha~P'vOz%|O{%ha!x%ha#g%ha%[%ha%_%ha%z%ha~OPdOVaOopOvqO!PrO!Q{O!{tO!}uO#PvO#RwO#TxO#XyO#ZzO#^|O#_|O#a}O#c!OO#g$zX%[$zX%_$zX~P'vO#g#gO%[&TO%_&TO~O!f&UOh&sX%[&sXz&sX#[&sX#g&sX%_&sX#Z&sXg&sX~Oh!iO%[&WO~Okealeameaneaoeapeaseazea{ea!xea#gea%[ea%_ea%zeagea!Tea!Uea%{ea!Wea![ea!Qea#[eatea!mea~P%SOsqazqa{qa#gqa%[qa%_qa%zqa~Ok!pOl!qOm!oOn!oOo!rOp!sO!xqa~PEcO%z&YOz%yX{%yX~O%uWOz%yX{%yX~Oz&]O{wX~O{&_O~Oz%lO#g%}X%[%}X%_%}Xg%}X{%}X![%}X!m%}X%z%}X~OV0lOo0cOv0qO!PrO~P'vO%z#|O#gUa%[Ua%_Ua~Oz&hO#g&PX%[&PX%_&PXn&PX~P%SOz&kO!Q&jO#g#Wa%[#Wa%_#Wa~Oz&lO#[&nO#g&rX%[&rX%_&rXg&rX~O!f$YO!r$YO#Z&qO%uWO~O#Z&qO~Oz&sO#g&tX%[&tX%_&tX~Oz&uO#g&pX%[&pX%_&pX{&pX~O!X&wO%z&xO~Oz&|On&wX~P%SOn'PO~OPdOVaOopOvqO!PrO!Q{O!{tO!}uO#PvO#RwO#TxO#XyO#ZzO#^|O#_|O#a}O#c!OO%['UO~P'vOt'YO#p'WO#q'XOP#naV#naf#nah#nao#nas#nav#na!P#na!Q#na!T#na!U#na!X#na!]#na!h#na!r#na!s#na!t#na!{#na!}#na#P#na#R#na#T#na#X#na#Z#na#^#na#_#na#a#na#c#na#l#na#o#na#s#na#u#na#z#na#}#na$P#na%X#na%o#na%p#na%t#na%u#na&Z#na&[#na&]#na&^#na&_#na&`#na&a#na&b#na&c#na&d#na&e#na&f#na&g#na&h#na&i#na&j#na%Z#na%_#na~Oz'ZO#[']O{&xX~Oh'_O!X&wO~Oh!iO{$jO!X&wO~O{'eO~P%SO%['hO%_'hO~OS'iO%['hO%_'hO~OV!aO_!aOa!bOh!iO!X!kO!f!mO%l!^O%m!_O%n!_O%o!`O%p!`O%q!aO%r!aO%s!aOkWilWimWinWioWipWisWizWi{Wi!xWi#gWi%[Wi%_Wi%jWi%zWigWi!TWi!UWi%{Wi!WWi![Wi!QWi#[WitWi!mWi~O%k!]O~P!#uO%kWi~P!#uOV!aO_!aOa!bOh!iO!X!kO!f!mO%o!`O%p!`O%q!aO%r!aO%s!aOkWilWimWinWioWipWisWizWi{Wi!xWi#gWi%[Wi%_Wi%jWi%kWi%lWi%zWigWi!TWi!UWi%{Wi!WWi![Wi!QWi#[WitWi!mWi~O%m!_O%n!_O~P!&pO%mWi%nWi~P!&pOa!bOh!iO!X!kO!f!mOkWilWimWinWioWipWisWizWi{Wi!xWi#gWi%[Wi%_Wi%jWi%kWi%lWi%mWi%nWi%oWi%pWi%zWigWi!TWi!UWi%{Wi!WWi![Wi!QWi#[WitWi!mWi~OV!aO_!aO%q!aO%r!aO%s!aO~P!)nOVWi_Wi%qWi%rWi%sWi~P!)nO!T%dO!U%cOg&VXz&VX~O%z'kO%{'kO~P,eOz'mOg&UX~Og'oO~Oz'pO{'rO!W&XX~Oo0cOv0qOz'pO{'sO!W&XX~P'vO!W'uO~Om!oOn!oOo!rOp!sOkjisjizji{ji!xji#gji%[ji%_ji%zji~Ol!qO~P!.aOlji~P!.aOk0eOl0fOm0dOn0dOo0mOp0nO~Ot'wO~P!/jOV'|Og'}Oo0cOv0qO~P'vOg'}Oz(OO~Og(QO~O!U(SO~Og(TOz(OO!T%dO!U%cO~P%SOk0eOl0fOm0dOn0dOo0mOp0nOgqa!Tqa!Uqa%{qa!Wqa![qa!Qqa#[qatqa!mqa~PEcOV'|Oo0cOv0qO!W&Sa~P'vOz(WO!W&Sa~O!W(XO~Oz(WO!T%dO!U%cO!W&Sa~P%SOV(]Oo0cOv0qO![%}a#g%}a%[%}a%_%}ag%}a{%}a!m%}a%z%}a~P'vOz(^O![%}a#g%}a%[%}a%_%}ag%}a{%}a!m%}a%z%}a~O![(aO~Oz(^O!T%dO!U%cO![%}a~P%SOz(dO!T%dO!U%cO![&Ta~P%SOz(gO{&lX![&lX!m&lX%z&lX~O{(kO![(mO!m(nO%z(jO~OV&OOopOvqO{%hi!x%hi#g%hi%[%hi%_%hi%z%hi~P'vOz(pO{%hi!x%hi#g%hi%[%hi%_%hi%z%hi~O!f&UOh&sa%[&saz&sa#[&sa#g&sa%_&sa#Z&sag&sa~O%[(uO~OV#sOa#tO%uWO~Oz&]O{wa~OopOvqO~P'vOz(^O#g%}a%[%}a%_%}ag%}a{%}a![%}a!m%}a%z%}a~P%SOz(zO#g%hX%[%hX%_%hX%z%hX~O%z#|O#gUi%[Ui%_Ui~O#g&Pa%[&Pa%_&Pan&Pa~P'vOz(}O#g&Pa%[&Pa%_&Pan&Pa~O%uWO#g&ra%[&ra%_&rag&ra~Oz)SO#g&ra%[&ra%_&rag&ra~Og)VO~OV)WOh$WO%uWO~O#Z)XO~O%uWO#g&ta%[&ta%_&ta~Oz)ZO#g&ta%[&ta%_&ta~Oo0cOv0qO#g&pa%[&pa%_&pa{&pa~P'vOz)^O#g&pa%[&pa%_&pa{&pa~OV)`Oa)`O%uWO~O%z)eO~Ot)hO#j)gOP#hiV#hif#hih#hio#his#hiv#hi!P#hi!Q#hi!T#hi!U#hi!X#hi!]#hi!h#hi!r#hi!s#hi!t#hi!{#hi!}#hi#P#hi#R#hi#T#hi#X#hi#Z#hi#^#hi#_#hi#a#hi#c#hi#l#hi#o#hi#s#hi#u#hi#z#hi#}#hi$P#hi%X#hi%o#hi%p#hi%t#hi%u#hi&Z#hi&[#hi&]#hi&^#hi&_#hi&`#hi&a#hi&b#hi&c#hi&d#hi&e#hi&f#hi&g#hi&h#hi&i#hi&j#hi%Z#hi%_#hi~Ot)iOP#kiV#kif#kih#kio#kis#kiv#ki!P#ki!Q#ki!T#ki!U#ki!X#ki!]#ki!h#ki!r#ki!s#ki!t#ki!{#ki!}#ki#P#ki#R#ki#T#ki#X#ki#Z#ki#^#ki#_#ki#a#ki#c#ki#l#ki#o#ki#s#ki#u#ki#z#ki#}#ki$P#ki%X#ki%o#ki%p#ki%t#ki%u#ki&Z#ki&[#ki&]#ki&^#ki&_#ki&`#ki&a#ki&b#ki&c#ki&d#ki&e#ki&f#ki&g#ki&h#ki&i#ki&j#ki%Z#ki%_#ki~OV)kOn&wa~P'vOz)lOn&wa~Oz)lOn&wa~P%SOn)pO~O%Y)tO~Ot)wO#p'WO#q)vOP#niV#nif#nih#nio#nis#niv#ni!P#ni!Q#ni!T#ni!U#ni!X#ni!]#ni!h#ni!r#ni!s#ni!t#ni!{#ni!}#ni#P#ni#R#ni#T#ni#X#ni#Z#ni#^#ni#_#ni#a#ni#c#ni#l#ni#o#ni#s#ni#u#ni#z#ni#}#ni$P#ni%X#ni%o#ni%p#ni%t#ni%u#ni&Z#ni&[#ni&]#ni&^#ni&_#ni&`#ni&a#ni&b#ni&c#ni&d#ni&e#ni&f#ni&g#ni&h#ni&i#ni&j#ni%Z#ni%_#ni~OV)zOo0cOv0qO{$jO~P'vOo0cOv0qO{&xa~P'vOz*OO{&xa~OV*SOa*TOg*WO%q*UO%uWO~O{$jO&{*YO~Oh'_O~Oh!iO{$jO~O%[*_O~O%[*aO%_*aO~OV$}Oa$}Oo0cOv0qOg&Ua~P'vOz*dOg&Ua~Oo0cOv0qO{*gO!W&Xa~P'vOz*hO!W&Xa~Oo0cOv0qOz*hO{*kO!W&Xa~P'vOo0cOv0qOz*hO!W&Xa~P'vOz*hO{*kO!W&Xa~Om0dOn0dOo0mOp0nOgjikjisjizji!Tji!Uji%{ji!Wji{ji![ji#gji%[ji%_ji!Qji#[jitji!mji%zji~Ol0fO~P!NkOlji~P!NkOV'|Og*pOo0cOv0qO~P'vOn*rO~Og*pOz*tO~Og*uO~OV'|Oo0cOv0qO!W&Si~P'vOz*vO!W&Si~O!W*wO~OV(]Oo0cOv0qO![%}i#g%}i%[%}i%_%}ig%}i{%}i!m%}i%z%}i~P'vOz*zO!T%dO!U%cO![&Ti~Oz*}O![%}i#g%}i%[%}i%_%}ig%}i{%}i!m%}i%z%}i~O![+OO~Oa+QOo0cOv0qO![&Ti~P'vOz*zO![&Ti~O![+SO~OV+UOo0cOv0qO{&la![&la!m&la%z&la~P'vOz+VO{&la![&la!m&la%z&la~O!]+YO&n+[O![!nX~O![+^O~O{(kO![+_O~O{(kO![+_O!m+`O~OV&OOopOvqO{%hq!x%hq#g%hq%[%hq%_%hq%z%hq~P'vOz$ri{$ri!x$ri#g$ri%[$ri%_$ri%z$ri~P%SOV&OOopOvqO~P'vOV&OOo0cOv0qO#g%ha%[%ha%_%ha%z%ha~P'vOz+aO#g%ha%[%ha%_%ha%z%ha~Oz$ia#g$ia%[$ia%_$ian$ia~P%SO#g&Pi%[&Pi%_&Pin&Pi~P'vOz+dO#g#Wq%[#Wq%_#Wq~O#[+eOz$va#g$va%[$va%_$vag$va~O%uWO#g&ri%[&ri%_&rig&ri~Oz+gO#g&ri%[&ri%_&rig&ri~OV+iOh$WO%uWO~O%uWO#g&ti%[&ti%_&ti~Oo0cOv0qO#g&pi%[&pi%_&pi{&pi~P'vO{#{Oz#eX!W#eX~Oz+mO!W&uX~O!W+oO~Ot+rO#j)gOP#hqV#hqf#hqh#hqo#hqs#hqv#hq!P#hq!Q#hq!T#hq!U#hq!X#hq!]#hq!h#hq!r#hq!s#hq!t#hq!{#hq!}#hq#P#hq#R#hq#T#hq#X#hq#Z#hq#^#hq#_#hq#a#hq#c#hq#l#hq#o#hq#s#hq#u#hq#z#hq#}#hq$P#hq%X#hq%o#hq%p#hq%t#hq%u#hq&Z#hq&[#hq&]#hq&^#hq&_#hq&`#hq&a#hq&b#hq&c#hq&d#hq&e#hq&f#hq&g#hq&h#hq&i#hq&j#hq%Z#hq%_#hq~On$|az$|a~P%SOV)kOn&wi~P'vOz+yOn&wi~Oz,TO{$jO#[,TO~O#q,VOP#nqV#nqf#nqh#nqo#nqs#nqv#nq!P#nq!Q#nq!T#nq!U#nq!X#nq!]#nq!h#nq!r#nq!s#nq!t#nq!{#nq!}#nq#P#nq#R#nq#T#nq#X#nq#Z#nq#^#nq#_#nq#a#nq#c#nq#l#nq#o#nq#s#nq#u#nq#z#nq#}#nq$P#nq%X#nq%o#nq%p#nq%t#nq%u#nq&Z#nq&[#nq&]#nq&^#nq&_#nq&`#nq&a#nq&b#nq&c#nq&d#nq&e#nq&f#nq&g#nq&h#nq&i#nq&j#nq%Z#nq%_#nq~O#[,WOz%Oa{%Oa~Oo0cOv0qO{&xi~P'vOz,YO{&xi~O{#{O%z,[Og&zXz&zX~O%uWOg&zXz&zX~Oz,`Og&yX~Og,bO~O%Y,eO~O!T%dO!U%cOg&Viz&Vi~OV$}Oa$}Oo0cOv0qOg&Ui~P'vO{,hOz$la!W$la~Oo0cOv0qO{,iOz$la!W$la~P'vOo0cOv0qO{*gO!W&Xi~P'vOz,lO!W&Xi~Oo0cOv0qOz,lO!W&Xi~P'vOz,lO{,oO!W&Xi~Og$hiz$hi!W$hi~P%SOV'|Oo0cOv0qO~P'vOn,qO~OV'|Og,rOo0cOv0qO~P'vOV'|Oo0cOv0qO!W&Sq~P'vOz$gi![$gi#g$gi%[$gi%_$gig$gi{$gi!m$gi%z$gi~P%SOV(]Oo0cOv0qO~P'vOa+QOo0cOv0qO![&Tq~P'vOz,sO![&Tq~O![,tO~OV(]Oo0cOv0qO![%}q#g%}q%[%}q%_%}qg%}q{%}q!m%}q%z%}q~P'vO{,uO~OV+UOo0cOv0qO{&li![&li!m&li%z&li~P'vOz,zO{&li![&li!m&li%z&li~O!]+YO&n+[O![!na~O{(kO![,}O~OV&OOo0cOv0qO#g%hi%[%hi%_%hi%z%hi~P'vOz-OO#g%hi%[%hi%_%hi%z%hi~O%uWO#g&rq%[&rq%_&rqg&rq~Oz-RO#g&rq%[&rq%_&rqg&rq~OV)`Oa)`O%uWO!W&ua~Oz-TO!W&ua~On$|iz$|i~P%SOV)kO~P'vOV)kOn&wq~P'vOt-XOP#myV#myf#myh#myo#mys#myv#my!P#my!Q#my!T#my!U#my!X#my!]#my!h#my!r#my!s#my!t#my!{#my!}#my#P#my#R#my#T#my#X#my#Z#my#^#my#_#my#a#my#c#my#l#my#o#my#s#my#u#my#z#my#}#my$P#my%X#my%o#my%p#my%t#my%u#my&Z#my&[#my&]#my&^#my&_#my&`#my&a#my&b#my&c#my&d#my&e#my&f#my&g#my&h#my&i#my&j#my%Z#my%_#my~O%Z-]O%_-]O~P`O#q-^OP#nyV#nyf#nyh#nyo#nys#nyv#ny!P#ny!Q#ny!T#ny!U#ny!X#ny!]#ny!h#ny!r#ny!s#ny!t#ny!{#ny!}#ny#P#ny#R#ny#T#ny#X#ny#Z#ny#^#ny#_#ny#a#ny#c#ny#l#ny#o#ny#s#ny#u#ny#z#ny#}#ny$P#ny%X#ny%o#ny%p#ny%t#ny%u#ny&Z#ny&[#ny&]#ny&^#ny&_#ny&`#ny&a#ny&b#ny&c#ny&d#ny&e#ny&f#ny&g#ny&h#ny&i#ny&j#ny%Z#ny%_#ny~Oz-aO{$jO#[-aO~Oo0cOv0qO{&xq~P'vOz-dO{&xq~O%z,[Og&zaz&za~O{#{Og&zaz&za~OV*SOa*TO%q*UO%uWOg&ya~Oz-hOg&ya~O$S-lO~OV$}Oa$}Oo0cOv0qO~P'vOo0cOv0qO{-mOz$li!W$li~P'vOo0cOv0qOz$li!W$li~P'vO{-mOz$li!W$li~Oo0cOv0qO{*gO~P'vOo0cOv0qO{*gO!W&Xq~P'vOz-pO!W&Xq~Oo0cOv0qOz-pO!W&Xq~P'vOs-sO!T%dO!U%cOg&Oq!W&Oq![&Oqz&Oq~P!/jOa+QOo0cOv0qO![&Ty~P'vOz$ji![$ji~P%SOa+QOo0cOv0qO~P'vOV+UOo0cOv0qO~P'vOV+UOo0cOv0qO{&lq![&lq!m&lq%z&lq~P'vO{(kO![-xO!m-yO%z-wO~OV&OOo0cOv0qO#g%hq%[%hq%_%hq%z%hq~P'vO%uWO#g&ry%[&ry%_&ryg&ry~OV)`Oa)`O%uWO!W&ui~Ot-}OP#m!RV#m!Rf#m!Rh#m!Ro#m!Rs#m!Rv#m!R!P#m!R!Q#m!R!T#m!R!U#m!R!X#m!R!]#m!R!h#m!R!r#m!R!s#m!R!t#m!R!{#m!R!}#m!R#P#m!R#R#m!R#T#m!R#X#m!R#Z#m!R#^#m!R#_#m!R#a#m!R#c#m!R#l#m!R#o#m!R#s#m!R#u#m!R#z#m!R#}#m!R$P#m!R%X#m!R%o#m!R%p#m!R%t#m!R%u#m!R&Z#m!R&[#m!R&]#m!R&^#m!R&_#m!R&`#m!R&a#m!R&b#m!R&c#m!R&d#m!R&e#m!R&f#m!R&g#m!R&h#m!R&i#m!R&j#m!R%Z#m!R%_#m!R~Oo0cOv0qO{&xy~P'vOV*SOa*TO%q*UO%uWOg&yi~O$S-lO%Z.VO%_.VO~OV.aOh._O!X.^O!].`O!h.YO!s.[O!t.[O%p.XO%uWO&Z]O&[]O&]]O&^]O&_]O&`]O&a]O&b]O~Oo0cOv0qOz$lq!W$lq~P'vO{.fOz$lq!W$lq~Oo0cOv0qO{*gO!W&Xy~P'vOz.gO!W&Xy~Oo0cOv.kO~P'vOs-sO!T%dO!U%cOg&Oy!W&Oy![&Oyz&Oy~P!/jO{(kO![.nO~O{(kO![.nO!m.oO~OV*SOa*TO%q*UO%uWO~Oh.tO!f.rOz$TX#[$TX%j$TXg$TX~Os$TX{$TX!W$TX![$TX~P$-bO%o.vO%p.vOs$UXz$UX{$UX#[$UX%j$UX!W$UXg$UX![$UX~O!h.xO~Oz.|O#[/OO%j.yOs&|X{&|X!W&|Xg&|X~Oa/RO~P$)zOh.tOs&}Xz&}X{&}X#[&}X%j&}X!W&}Xg&}X![&}X~Os/VO{$jO~Oo0cOv0qOz$ly!W$ly~P'vOo0cOv0qO{*gO!W&X!R~P'vOz/ZO!W&X!R~Og&RXs&RX!T&RX!U&RX!W&RX![&RXz&RX~P!/jOs-sO!T%dO!U%cOg&Qa!W&Qa![&Qaz&Qa~O{(kO![/^O~O!f.rOh$[as$[az$[a{$[a#[$[a%j$[a!W$[ag$[a![$[a~O!h/eO~O%o.vO%p.vOs$Uaz$Ua{$Ua#[$Ua%j$Ua!W$Uag$Ua![$Ua~O%j.yOs$Yaz$Ya{$Ya#[$Ya!W$Yag$Ya![$Ya~Os&|a{&|a!W&|ag&|a~P$)nOz/jOs&|a{&|a!W&|ag&|a~O!W/mO~Og/mO~O{/oO~O![/pO~Oo0cOv0qO{*gO!W&X!Z~P'vO{/sO~O%z/tO~P$-bOz/uO#[/OO%j.yOg'PX~Oz/uOg'PX~Og/wO~O!h/xO~O#[/OOs%Saz%Sa{%Sa%j%Sa!W%Sag%Sa![%Sa~O#[/OO%j.yOs%Waz%Wa{%Wa!W%Wag%Wa~Os&|i{&|i!W&|ig&|i~P$)nOz/zO#[/OO%j.yO!['Oa~Og'Pa~P$)nOz0SOg'Pa~Oa0UO!['Oi~P$)zOz0WO!['Oi~Oz0WO#[/OO%j.yO!['Oi~O#[/OO%j.yOg$biz$bi~O%z0ZO~P$-bO#[/OO%j.yOg%Vaz%Va~Og'Pi~P$)nO{0^O~Oa0UO!['Oq~P$)zOz0`O!['Oq~O#[/OO%j.yOz%Ui![%Ui~Oa0UO~P$)zOa0UO!['Oy~P$)zO#[/OO%j.yOg$ciz$ci~O#[/OO%j.yOz%Uq![%Uq~Oz+aO#g%ha%[%ha%_%ha%z%ha~P%SOV&OOo0cOv0qO~P'vOn0hO~Oo0hO~P'vO{0iO~Ot0jO~P!/jO&]&Z&j&h&i&g&f&d&e&c&b&`&a&_&^&[%u~",goto:"!=j'QPPPPPP'RP'Z*s+[+t,_,y-fP.SP'Z.r.r'ZPPP'Z2[PPPPPP2[5PPP5PP7b7k=sPP=v>h>kPP'Z'ZPP>zPP'Z'ZPP'Z'Z'Z'Z'Z?O?w'ZP?zP@QDXGuGyPG|HWH['ZPPPH_Hk'RP'R'RP'RP'RP'RP'RP'R'R'RP'RPP'RPP'RP'RPHqH}IVPI^IdPI^PI^I^PPPI^PKrPK{LVL]KrPI^LfPI^PLmLsPLwM]MzNeLwLwNkNxLwLwLwLw! ^! d! g! l! o! y!!P!!]!!o!!u!#P!#V!#s!#y!$P!$Z!$a!$g!$y!%T!%Z!%a!%k!%q!%w!%}!&T!&Z!&e!&k!&u!&{!'U!'[!'k!'s!'}!(UPPPPPPPPPPP!([!(_!(e!(n!(x!)TPPPPPPPPPPPP!-u!/Z!3^!6oPP!6w!7W!7a!8Y!8P!8c!8i!8l!8o!8r!8z!9jPPPPPPPPPPPPPPPPP!9m!9q!9wP!:]!:a!:m!:v!;S!;j!;m!;p!;v!;|!_![!]Do!]!^Es!^!_FZ!_!`Gk!`!aHX!a!b%T!b!cIf!c!dJU!d!eK^!e!hJU!h!i!#f!i!tJU!t!u!,|!u!wJU!w!x!.t!x!}JU!}#O!0S#O#P&o#P#Q!0j#Q#R!1Q#R#SJU#S#T%T#T#UJU#U#VK^#V#YJU#Y#Z!#f#Z#fJU#f#g!,|#g#iJU#i#j!.t#j#oJU#o#p!1n#p#q!1s#q#r!2a#r#s!2f#s$g%T$g;'SJU;'S;=`KW<%lOJU`%YT&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%T`%lP;=`<%l%To%v]&n`%c_OX%TXY%oY[%T[]%o]p%Tpq%oq#O%T#O#P&o#P#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To&tX&n`OY%TYZ%oZ]%T]^%o^#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc'f[&n`O!_%T!_!`([!`#T%T#T#U(r#U#f%T#f#g(r#g#h(r#h#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc(cTmR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc(yT!mR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk)aV&n`&[ZOr%Trs)vs#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk){V&n`Or%Trs*bs#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk*iT&n`&^ZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To+PZS_&n`OY*xYZ%TZ]*x]^%T^#o*x#o#p+r#p#q*x#q#r+r#r;'S*x;'S;=`,^<%lO*x_+wTS_OY+rZ]+r^;'S+r;'S;=`,W<%lO+r_,ZP;=`<%l+ro,aP;=`<%l*xj,kV%rQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tj-XT!xY&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tj-oV%lQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk.]V&n`&ZZOw%Twx.rx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk.wV&n`Ow%Twx/^x#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk/eT&n`&]ZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk/{ThZ&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc0cTgR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk0yXVZ&n`Oz%Tz{1f{!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk1mVaR&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk2ZV%oZ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc2wTzR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To3_W%pZ&n`O!_%T!_!`-Q!`!a3w!a#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Td4OT&{S&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk4fX!fQ&n`O!O%T!O!P5R!P!Q%T!Q![6T![#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk5WV&n`O!O%T!O!P5m!P#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk5tT!rZ&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti6[a!hX&n`O!Q%T!Q![6T![!g%T!g!h7a!h!l%T!l!m9s!m#R%T#R#S6T#S#X%T#X#Y7a#Y#^%T#^#_9s#_#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti7fZ&n`O{%T{|8X|}%T}!O8X!O!Q%T!Q![8s![#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti8^V&n`O!Q%T!Q![8s![#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti8z]!hX&n`O!Q%T!Q![8s![!l%T!l!m9s!m#R%T#R#S8s#S#^%T#^#_9s#_#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti9zT!hX&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk:bX%qR&n`O!P%T!P!Q:}!Q!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tj;UV%sQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti;ro!hX&n`O!O%T!O!P=s!P!Q%T!Q![>_![!d%T!d!e?q!e!g%T!g!h7a!h!l%T!l!m9s!m!q%T!q!rA]!r!z%T!z!{Bq!{#R%T#R#S>_#S#U%T#U#V?q#V#X%T#X#Y7a#Y#^%T#^#_9s#_#c%T#c#dA]#d#l%T#l#mBq#m#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti=xV&n`O!Q%T!Q![6T![#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti>fc!hX&n`O!O%T!O!P=s!P!Q%T!Q![>_![!g%T!g!h7a!h!l%T!l!m9s!m#R%T#R#S>_#S#X%T#X#Y7a#Y#^%T#^#_9s#_#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti?vY&n`O!Q%T!Q!R@f!R!S@f!S#R%T#R#S@f#S#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti@mY!hX&n`O!Q%T!Q!R@f!R!S@f!S#R%T#R#S@f#S#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TiAbX&n`O!Q%T!Q!YA}!Y#R%T#R#SA}#S#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TiBUX!hX&n`O!Q%T!Q!YA}!Y#R%T#R#SA}#S#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TiBv]&n`O!Q%T!Q![Co![!c%T!c!iCo!i#R%T#R#SCo#S#T%T#T#ZCo#Z#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TiCv]!hX&n`O!Q%T!Q![Co![!c%T!c!iCo!i#R%T#R#SCo#S#T%T#T#ZCo#Z#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%ToDvV{_&n`O!_%T!_!`E]!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TcEdT%{R&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkEzT#gZ&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkFbXmR&n`O!^%T!^!_F}!_!`([!`!a([!a#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TjGUV%mQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkGrV%zZ&n`O!_%T!_!`([!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkH`WmR&n`O!_%T!_!`([!`!aHx!a#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TjIPV%nQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkIoV_Q#}P&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%ToJ_]&n`&YS%uZO!Q%T!Q![JU![!c%T!c!}JU!}#R%T#R#SJU#S#T%T#T#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUoKZP;=`<%lJUoKge&n`&YS%uZOr%Trs)Ysw%Twx.Ux!Q%T!Q![JU![!c%T!c!tJU!t!uLx!u!}JU!}#R%T#R#SJU#S#T%T#T#fJU#f#gLx#g#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUoMRa&n`&YS%uZOr%TrsNWsw%Twx! vx!Q%T!Q![JU![!c%T!c!}JU!}#R%T#R#SJU#S#T%T#T#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUkN_V&n`&`ZOr%TrsNts#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkNyV&n`Or%Trs! `s#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk! gT&n`&bZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk! }V&n`&_ZOw%Twx!!dx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!!iV&n`Ow%Twx!#Ox#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!#VT&n`&aZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To!#oe&n`&YS%uZOr%Trs!%Qsw%Twx!&px!Q%T!Q![JU![!c%T!c!tJU!t!u!(`!u!}JU!}#R%T#R#SJU#S#T%T#T#fJU#f#g!(`#g#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUk!%XV&n`&dZOr%Trs!%ns#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!%sV&n`Or%Trs!&Ys#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!&aT&n`&fZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!&wV&n`&cZOw%Twx!'^x#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!'cV&n`Ow%Twx!'xx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!(PT&n`&eZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To!(ia&n`&YS%uZOr%Trs!)nsw%Twx!+^x!Q%T!Q![JU![!c%T!c!}JU!}#R%T#R#SJU#S#T%T#T#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUk!)uV&n`&hZOr%Trs!*[s#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!*aV&n`Or%Trs!*vs#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!*}T&n`&jZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!+eV&n`&gZOw%Twx!+zx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!,PV&n`Ow%Twx!,fx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!,mT&n`&iZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To!-Vi&n`&YS%uZOr%TrsNWsw%Twx! vx!Q%T!Q![JU![!c%T!c!dJU!d!eLx!e!hJU!h!i!(`!i!}JU!}#R%T#R#SJU#S#T%T#T#UJU#U#VLx#V#YJU#Y#Z!(`#Z#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUo!.}a&n`&YS%uZOr%Trs)Ysw%Twx.Ux!Q%T!Q![JU![!c%T!c!}JU!}#R%T#R#SJU#S#T%T#T#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUk!0ZT!XZ&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc!0qT!WR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tj!1XV%kQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%T~!1sO!]~k!1zV%jR&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%T~!2fO![~i!2mT%tX&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%T",tokenizers:[hg,rg,sg,fg,0,1,2,3,4],topRules:{Script:[0,5]},specialized:[{term:221,get:n=>dg[n]||-1}],tokenPrec:7668});var Lf=new Fn,If=new Set(["Script","Body","FunctionDefinition","ClassDefinition","LambdaExpression","ForStatement","MatchClause"]);function ps(n){return(e,t,i)=>{if(i)return!1;let s=e.node.getChild("VariableName");return s&&t(s,n),!0}}var pg={FunctionDefinition:ps("function"),ClassDefinition:ps("class"),ForStatement(n,e,t){if(t){for(let i=n.node.firstChild;i;i=i.nextSibling)if(i.name=="VariableName")e(i,"variable");else if(i.name=="in")break}},ImportStatement(n,e){var t,i;let{node:s}=n,r=((t=s.firstChild)===null||t===void 0?void 0:t.name)=="from";for(let o=s.getChild("import");o;o=o.nextSibling)o.name=="VariableName"&&((i=o.nextSibling)===null||i===void 0?void 0:i.name)!="as"&&e(o,r?"variable":"namespace")},AssignStatement(n,e){for(let t=n.node.firstChild;t;t=t.nextSibling)if(t.name=="VariableName")e(t,"variable");else if(t.name==":"||t.name=="AssignOp")break},ParamList(n,e){for(let t=null,i=n.node.firstChild;i;i=i.nextSibling)i.name=="VariableName"&&(!t||!/\*|AssignOp/.test(t.name))&&e(i,"variable"),t=i},CapturePattern:ps("variable"),AsPattern:ps("variable"),__proto__:null};function Nf(n,e){let t=Lf.get(e);if(t)return t;let i=[],s=!0;function r(o,l){let a=n.sliceString(o.from,o.to);i.push({label:a,type:l})}return e.cursor(N.IncludeAnonymous).iterate(o=>{if(o.name){let l=pg[o.name];if(l&&l(o,r,s)||!s&&If.has(o.name))return!1;s=!1}else if(o.to-o.from>8192){for(let l of Nf(n,o.node))i.push(l);return!1}}),Lf.set(e,i),i}var zf=/^[\w\xa1-\uffff][\w\d\xa1-\uffff]*$/,Vf=["String","FormatString","Comment","PropertyName"];function mg(n){let e=J(n.state).resolveInner(n.pos,-1);if(Vf.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&zf.test(n.state.sliceDoc(e.from,e.to));if(!t&&!n.explicit)return null;let i=[];for(let s=e;s;s=s.parent)If.has(s.name)&&(i=i.concat(Nf(n.state.doc,s)));return{options:i,from:t?e.from:n.pos,validFor:zf}}var gg=["__annotations__","__builtins__","__debug__","__doc__","__import__","__name__","__loader__","__package__","__spec__","False","None","True"].map(n=>({label:n,type:"constant"})).concat(["ArithmeticError","AssertionError","AttributeError","BaseException","BlockingIOError","BrokenPipeError","BufferError","BytesWarning","ChildProcessError","ConnectionAbortedError","ConnectionError","ConnectionRefusedError","ConnectionResetError","DeprecationWarning","EOFError","Ellipsis","EncodingWarning","EnvironmentError","Exception","FileExistsError","FileNotFoundError","FloatingPointError","FutureWarning","GeneratorExit","IOError","ImportError","ImportWarning","IndentationError","IndexError","InterruptedError","IsADirectoryError","KeyError","KeyboardInterrupt","LookupError","MemoryError","ModuleNotFoundError","NameError","NotADirectoryError","NotImplemented","NotImplementedError","OSError","OverflowError","PendingDeprecationWarning","PermissionError","ProcessLookupError","RecursionError","ReferenceError","ResourceWarning","RuntimeError","RuntimeWarning","StopAsyncIteration","StopIteration","SyntaxError","SyntaxWarning","SystemError","SystemExit","TabError","TimeoutError","TypeError","UnboundLocalError","UnicodeDecodeError","UnicodeEncodeError","UnicodeError","UnicodeTranslateError","UnicodeWarning","UserWarning","ValueError","Warning","ZeroDivisionError"].map(n=>({label:n,type:"type"}))).concat(["bool","bytearray","bytes","classmethod","complex","float","frozenset","int","list","map","memoryview","object","range","set","staticmethod","str","super","tuple","type"].map(n=>({label:n,type:"class"}))).concat(["abs","aiter","all","anext","any","ascii","bin","breakpoint","callable","chr","compile","delattr","dict","dir","divmod","enumerate","eval","exec","exit","filter","format","getattr","globals","hasattr","hash","help","hex","id","input","isinstance","issubclass","iter","len","license","locals","max","min","next","oct","open","ord","pow","print","property","quit","repr","reversed","round","setattr","slice","sorted","sum","vars","zip"].map(n=>({label:n,type:"function"}))),Og=[Xe("def ${name}(${params}):\n ${}",{label:"def",detail:"function",type:"keyword"}),Xe("for ${name} in ${collection}:\n ${}",{label:"for",detail:"loop",type:"keyword"}),Xe("while ${}:\n ${}",{label:"while",detail:"loop",type:"keyword"}),Xe("try:\n ${}\nexcept ${error}:\n ${}",{label:"try",detail:"/ except block",type:"keyword"}),Xe(`if \${}: + +`,{label:"if",detail:"block",type:"keyword"}),Xe("if ${}:\n ${}\nelse:\n ${}",{label:"if",detail:"/ else block",type:"keyword"}),Xe("class ${name}:\n def __init__(self, ${params}):\n ${}",{label:"class",detail:"definition",type:"keyword"}),Xe("import ${module}",{label:"import",detail:"statement",type:"keyword"}),Xe("from ${module} import ${names}",{label:"from",detail:"import",type:"keyword"})],yg=bh(Vf,yh(gg.concat(Og)));function Lo(n){let{node:e,pos:t}=n,i=n.lineIndent(t,-1),s=null;for(;;){let r=e.childBefore(t);if(r)if(r.name=="Comment")t=r.from;else if(r.name=="Body"||r.name=="MatchBody")n.baseIndentFor(r)+n.unit<=i&&(s=r),e=r;else if(r.name=="MatchClause")e=r;else if(r.type.is("Statement"))e=r;else break;else break}return s}function zo(n,e){let t=n.baseIndentFor(e),i=n.lineAt(n.pos,-1),s=i.from+i.text.length;return/^\s*($|#)/.test(i.text)&&n.node.tot?null:t+n.unit}var Io=Zn.define({name:"python",parser:$f.configure({props:[oo.add({Body:n=>{var e;let t=/^\s*(#|$)/.test(n.textAfter)&&Lo(n)||n.node;return(e=zo(n,t))!==null&&e!==void 0?e:n.continue()},MatchBody:n=>{var e;let t=Lo(n);return(e=zo(n,t||n.node))!==null&&e!==void 0?e:n.continue()},IfStatement:n=>/^\s*(else:|elif )/.test(n.textAfter)?n.baseIndent:n.continue(),"ForStatement WhileStatement":n=>/^\s*else:/.test(n.textAfter)?n.baseIndent:n.continue(),TryStatement:n=>/^\s*(except[ :]|finally:|else:)/.test(n.textAfter)?n.baseIndent:n.continue(),MatchStatement:n=>/^\s*case /.test(n.textAfter)?n.baseIndent+n.unit:n.continue(),"TupleExpression ComprehensionExpression ParamList ArgList ParenthesizedExpression":Jn({closing:")"}),"DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression":Jn({closing:"}"}),"ArrayExpression ArrayComprehensionExpression":Jn({closing:"]"}),MemberExpression:n=>n.baseIndent+n.unit,"String FormatString":()=>null,Script:n=>{var e;let t=Lo(n);return(e=t&&zo(n,t))!==null&&e!==void 0?e:n.continue()}}),oh.add({"ArrayExpression DictionaryExpression SetExpression TupleExpression":lh,Body:(n,e)=>({from:n.from+1,to:n.to-(n.to==e.doc.length?0:1)}),"String FormatString":(n,e)=>({from:e.doc.lineAt(n.from).to,to:n.to})})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"'''",'"""'],stringPrefixes:["f","fr","rf","r","u","b","br","rb","F","FR","RF","R","U","B","BR","RB"]},commentTokens:{line:"#"},indentOnInput:/^\s*([\}\]\)]|else:|elif |except |finally:|case\s+[^:]*:?)$/}});function Xf(){return new Yn(Io,[Io.data.of({autocomplete:mg}),Io.data.of({autocomplete:yg})])}var bg="#e5c07b",Ff="#e06c75",Sg="#56b6c2",xg="#ffffff",kg="#abb2bf",_f="#7d8799",wg="#61afef",vg="#98c379",Hf="#d19a66",Tg="#c678dd";var Uf=ui.define([{tag:g.keyword,color:Tg},{tag:[g.name,g.deleted,g.character,g.propertyName,g.macroName],color:Ff},{tag:[g.function(g.variableName),g.labelName],color:wg},{tag:[g.color,g.constant(g.name),g.standard(g.name)],color:Hf},{tag:[g.definition(g.name),g.separator],color:kg},{tag:[g.typeName,g.className,g.number,g.changed,g.annotation,g.modifier,g.self,g.namespace],color:bg},{tag:[g.operator,g.operatorKeyword,g.url,g.escape,g.regexp,g.link,g.special(g.string)],color:Sg},{tag:[g.meta,g.comment],color:_f},{tag:g.strong,fontWeight:"bold"},{tag:g.emphasis,fontStyle:"italic"},{tag:g.strikethrough,textDecoration:"line-through"},{tag:g.link,color:_f,textDecoration:"underline"},{tag:g.heading,fontWeight:"bold",color:Ff},{tag:[g.atom,g.bool,g.special(g.variableName)],color:Hf},{tag:[g.processingInstruction,g.string,g.inserted],color:vg},{tag:g.invalid,color:xg}]);var Zf=window.matchMedia("(prefers-color-scheme: dark)"),jf=()=>Zf.matches?Uf:hh,Gf=new jt,st=document.getElementById("code-editor"),No=document.querySelector("form.runner-editor");if(st&&No){let i=function(){e.dom.style.minHeight="";let l=Number.parseFloat(getComputedStyle(e.dom).minHeight)||0;e.dom.style.minHeight=`${Math.max(l,e.contentDOM.scrollHeight)}px`},s=function(){requestAnimationFrame(i)},r=function(l){e.dispatch({changes:{from:0,to:e.state.doc.length,insert:l}}),st.value=l,s()},o=function(){st.value=e.state.doc.toString()};st.classList.add("textarea-fallback");let n=[{key:"Mod-Enter",preventDefault:!0,run:()=>(No.requestSubmit(),!0)}],e=new C({state:z.create({doc:st.value,extensions:[ai.of(n),Lh(),Xf(),gt.of(" "),z.tabSize.of(4),rh(),dh(),kh(),Gf.of(es(jf())),Ia(),C.lineWrapping,ai.of([...Th,...Of,...Vh,yf]),C.contentAttributes.of({"aria-label":st.getAttribute("aria-label")||"Editable Python example code","aria-describedby":"editor-keys-hint"}),C.updateListener.of(l=>{l.docChanged&&(st.value=l.state.doc.toString())})]})});st.insertAdjacentElement("afterend",e.dom),st.hidden=!0;let t=document.getElementById("editor-keys-hint");t&&(t.hidden=!1),Zf.addEventListener?.("change",()=>{e.dispatch({effects:Gf.reconfigure(es(jf()))})}),i(),No.addEventListener("submit",o),window.pythonByExampleEditor={setValue:r,syncTextarea:o,resize:s,focus:()=>e.focus()}} diff --git a/public/highlighter.b1b5aad7a305.js b/public/highlighter.b1b5aad7a305.js new file mode 100644 index 0000000..68620af --- /dev/null +++ b/public/highlighter.b1b5aad7a305.js @@ -0,0 +1,152 @@ +var Qa=Object.defineProperty;var Ya=(e,t)=>{for(var n in t)Qa(e,n,{get:t[n],enumerable:!0})};var E=class extends Error{constructor(e){super(e),this.name="ShikiError"}};function Ja(e){return Dt(e)}function Dt(e){return Array.isArray(e)?Za(e):e instanceof RegExp?e:typeof e=="object"?eo(e):e}function Za(e){let t=[];for(let n=0,r=e.length;n{for(let r in n)e[r]=n[r]}),e}function qn(e){let t=~e.lastIndexOf("/")||~e.lastIndexOf("\\");return t===0?e:~t===e.length-1?qn(e.substring(0,e.length-1)):e.substr(~t+1)}var Nt=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,Ve=class{static hasCaptures(e){return e===null?!1:(Nt.lastIndex=0,Nt.test(e))}static replaceCaptures(e,t,n){return e.replace(Nt,(r,a,o,i)=>{let s=n[parseInt(a||o,10)];if(s){let l=t.substring(s.start,s.end);for(;l[0]===".";)l=l.substring(1);switch(i){case"downcase":return l.toLowerCase();case"upcase":return l.toUpperCase();default:return l}}else return r})}};function jn(e,t){return et?1:0}function Hn(e,t){if(e===null&&t===null)return 0;if(!e)return-1;if(!t)return 1;let n=e.length,r=t.length;if(n===r){for(let a=0;athis._root.match(e));getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(e){if(e===null)return this._defaults;let t=e.scopeName,r=this._cachedMatchRoot.get(t).find(a=>to(e.parent,a.parentScopes));return r?new Vn(r.fontStyle,r.foreground,r.background):null}},Tt=class Xe{constructor(t,n){this.parent=t,this.scopeName=n}parent;scopeName;static push(t,n){for(let r of n)t=new Xe(t,r);return t}static from(...t){let n=null;for(let r=0;r"){if(n===t.length-1)return!1;r=t[++n],a=!0}for(;e&&!no(e.scopeName,r);){if(a)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function no(e,t){return t===e||e.startsWith(t)&&e[t.length]==="."}var Vn=class{constructor(e,t,n){this.fontStyle=e,this.foregroundId=t,this.backgroundId=n}fontStyle;foregroundId;backgroundId};function ro(e){if(!e)return[];if(!e.settings||!Array.isArray(e.settings))return[];let t=e.settings,n=[],r=0;for(let a=0,o=t.length;a1&&(w=h.slice(0,h.length-1),w.reverse()),n[r++]=new ao(y,w,a,l,c,u)}}return n}var ao=class{constructor(e,t,n,r,a,o){this.scope=e,this.parentScopes=t,this.index=n,this.fontStyle=r,this.foreground=a,this.background=o}scope;parentScopes;index;fontStyle;foreground;background},P=(e=>(e[e.NotSet=-1]="NotSet",e[e.None=0]="None",e[e.Italic=1]="Italic",e[e.Bold=2]="Bold",e[e.Underline=4]="Underline",e[e.Strikethrough=8]="Strikethrough",e))(P||{});function oo(e,t){e.sort((l,c)=>{let u=jn(l.scope,c.scope);return u!==0||(u=Hn(l.parentScopes,c.parentScopes),u!==0)?u:l.index-c.index});let n=0,r="#000000",a="#ffffff";for(;e.length>=1&&e[0].scope==="";){let l=e.shift();l.fontStyle!==-1&&(n=l.fontStyle),l.foreground!==null&&(r=l.foreground),l.background!==null&&(a=l.background)}let o=new io(t),i=new Vn(n,o.getId(r),o.getId(a)),s=new lo(new Pt(0,null,-1,0,0),[]);for(let l=0,c=e.length;lt?console.log("how did this happen?"):this.scopeDepth=t,n!==-1&&(this.fontStyle=n),r!==0&&(this.foreground=r),a!==0&&(this.background=a)}},lo=class $t{constructor(t,n=[],r={}){this._mainRule=t,this._children=r,this._rulesWithParentScopes=n}_mainRule;_children;_rulesWithParentScopes;static _cmpBySpecificity(t,n){if(t.scopeDepth!==n.scopeDepth)return n.scopeDepth-t.scopeDepth;let r=0,a=0;for(;t.parentScopes[r]===">"&&r++,n.parentScopes[a]===">"&&a++,!(r>=t.parentScopes.length||a>=n.parentScopes.length);){let o=n.parentScopes[a].length-t.parentScopes[r].length;if(o!==0)return o;r++,a++}return n.parentScopes.length-t.parentScopes.length}match(t){if(t!==""){let r=t.indexOf("."),a,o;if(r===-1?(a=t,o=""):(a=t.substring(0,r),o=t.substring(r+1)),this._children.hasOwnProperty(a))return this._children[a].match(o)}let n=this._rulesWithParentScopes.concat(this._mainRule);return n.sort($t._cmpBySpecificity),n}insert(t,n,r,a,o,i){if(n===""){this._doInsertHere(t,r,a,o,i);return}let s=n.indexOf("."),l,c;s===-1?(l=n,c=""):(l=n.substring(0,s),c=n.substring(s+1));let u;this._children.hasOwnProperty(l)?u=this._children[l]:(u=new $t(this._mainRule.clone(),Pt.cloneArr(this._rulesWithParentScopes)),this._children[l]=u),u.insert(t+1,c,r,a,o,i)}_doInsertHere(t,n,r,a,o){if(n===null){this._mainRule.acceptOverwrite(t,r,a,o);return}for(let i=0,s=this._rulesWithParentScopes.length;i>>0}static getTokenType(t){return(t&768)>>>8}static containsBalancedBrackets(t){return(t&1024)!==0}static getFontStyle(t){return(t&30720)>>>11}static getForeground(t){return(t&16744448)>>>15}static getBackground(t){return(t&4278190080)>>>24}static set(t,n,r,a,o,i,s){let l=D.getLanguageId(t),c=D.getTokenType(t),u=D.containsBalancedBrackets(t)?1:0,p=D.getFontStyle(t),d=D.getForeground(t),g=D.getBackground(t);return n!==0&&(l=n),r!==8&&(c=r),a!==null&&(u=a?1:0),o!==-1&&(p=o),i!==0&&(d=i),s!==0&&(g=s),(l<<0|c<<8|u<<10|p<<11|d<<15|g<<24)>>>0}};function Qe(e,t){let n=[],r=co(e),a=r.next();for(;a!==null;){let l=0;if(a.length===2&&a.charAt(1)===":"){switch(a.charAt(0)){case"R":l=1;break;case"L":l=-1;break;default:console.log(`Unknown priority ${a} in scope selector`)}a=r.next()}let c=i();if(n.push({matcher:c,priority:l}),a!==",")break;a=r.next()}return n;function o(){if(a==="-"){a=r.next();let l=o();return c=>!!l&&!l(c)}if(a==="("){a=r.next();let l=s();return a===")"&&(a=r.next()),l}if(Pn(a)){let l=[];do l.push(a),a=r.next();while(Pn(a));return c=>t(l,c)}return null}function i(){let l=[],c=o();for(;c;)l.push(c),c=o();return u=>l.every(p=>p(u))}function s(){let l=[],c=i();for(;c&&(l.push(c),a==="|"||a===",");){do a=r.next();while(a==="|"||a===",");c=i()}return u=>l.some(p=>p(u))}}function Pn(e){return!!e&&!!e.match(/[\w\.:]+/)}function co(e){let t=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,n=t.exec(e);return{next:()=>{if(!n)return null;let r=n[0];return n=t.exec(e),r}}}function Kn(e){typeof e.dispose=="function"&&e.dispose()}var Ie=class{constructor(e){this.scopeName=e}scopeName;toKey(){return this.scopeName}},uo=class{constructor(e,t){this.scopeName=e,this.ruleName=t}scopeName;ruleName;toKey(){return`${this.scopeName}#${this.ruleName}`}},po=class{_references=[];_seenReferenceKeys=new Set;get references(){return this._references}visitedRule=new Set;add(e){let t=e.toKey();this._seenReferenceKeys.has(t)||(this._seenReferenceKeys.add(t),this._references.push(e))}},go=class{constructor(e,t){this.repo=e,this.initialScopeName=t,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new Ie(this.initialScopeName)]}repo;initialScopeName;seenFullScopeRequests=new Set;seenPartialScopeRequests=new Set;Q;processQueue(){let e=this.Q;this.Q=[];let t=new po;for(let n of e)ho(n,this.initialScopeName,this.repo,t);for(let n of t.references)if(n instanceof Ie){if(this.seenFullScopeRequests.has(n.scopeName))continue;this.seenFullScopeRequests.add(n.scopeName),this.Q.push(n)}else{if(this.seenFullScopeRequests.has(n.scopeName)||this.seenPartialScopeRequests.has(n.toKey()))continue;this.seenPartialScopeRequests.add(n.toKey()),this.Q.push(n)}}};function ho(e,t,n,r){let a=n.lookup(e.scopeName);if(!a){if(e.scopeName===t)throw new Error(`No grammar provided for <${t}>`);return}let o=n.lookup(t);e instanceof Ie?Ke({baseGrammar:o,selfGrammar:a},r):Mt(e.ruleName,{baseGrammar:o,selfGrammar:a,repository:a.repository},r);let i=n.injections(e.scopeName);if(i)for(let s of i)r.add(new Ie(s))}function Mt(e,t,n){if(t.repository&&t.repository[e]){let r=t.repository[e];Ye([r],t,n)}}function Ke(e,t){e.selfGrammar.patterns&&Array.isArray(e.selfGrammar.patterns)&&Ye(e.selfGrammar.patterns,{...e,repository:e.selfGrammar.repository},t),e.selfGrammar.injections&&Ye(Object.values(e.selfGrammar.injections),{...e,repository:e.selfGrammar.repository},t)}function Ye(e,t,n){for(let r of e){if(n.visitedRule.has(r))continue;n.visitedRule.add(r);let a=r.repository?Un({},t.repository,r.repository):t.repository;Array.isArray(r.patterns)&&Ye(r.patterns,{...t,repository:a},n);let o=r.include;if(!o)continue;let i=Qn(o);switch(i.kind){case 0:Ke({...t,selfGrammar:t.baseGrammar},n);break;case 1:Ke(t,n);break;case 2:Mt(i.ruleName,{...t,repository:a},n);break;case 3:case 4:let s=i.scopeName===t.selfGrammar.scopeName?t.selfGrammar:i.scopeName===t.baseGrammar.scopeName?t.baseGrammar:void 0;if(s){let l={baseGrammar:t.baseGrammar,selfGrammar:s,repository:a};i.kind===4?Mt(i.ruleName,l,n):Ke(l,n)}else i.kind===4?n.add(new uo(i.scopeName,i.ruleName)):n.add(new Ie(i.scopeName));break}}}var fo=class{kind=0},mo=class{kind=1},bo=class{constructor(e){this.ruleName=e}ruleName;kind=2},yo=class{constructor(e){this.scopeName=e}scopeName;kind=3},wo=class{constructor(e,t){this.scopeName=e,this.ruleName=t}scopeName;ruleName;kind=4};function Qn(e){if(e==="$base")return new fo;if(e==="$self")return new mo;let t=e.indexOf("#");if(t===-1)return new yo(e);if(t===0)return new bo(e.substring(1));{let n=e.substring(0,t),r=e.substring(t+1);return new wo(n,r)}}var ko=/\\(\d+)/,$n=/\\(\d+)/g,xo=-1,Yn=-2;var Te=class{$location;id;_nameIsCapturing;_name;_contentNameIsCapturing;_contentName;constructor(e,t,n,r){this.$location=e,this.id=t,this._name=n||null,this._nameIsCapturing=Ve.hasCaptures(this._name),this._contentName=r||null,this._contentNameIsCapturing=Ve.hasCaptures(this._contentName)}get debugName(){let e=this.$location?`${qn(this.$location.filename)}:${this.$location.line}`:"unknown";return`${this.constructor.name}#${this.id} @ ${e}`}getName(e,t){return!this._nameIsCapturing||this._name===null||e===null||t===null?this._name:Ve.replaceCaptures(this._name,e,t)}getContentName(e,t){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:Ve.replaceCaptures(this._contentName,e,t)}},Co=class extends Te{retokenizeCapturedWithRuleId;constructor(e,t,n,r,a){super(e,t,n,r),this.retokenizeCapturedWithRuleId=a}dispose(){}collectPatterns(e,t){throw new Error("Not supported!")}compile(e,t){throw new Error("Not supported!")}compileAG(e,t,n,r){throw new Error("Not supported!")}},vo=class extends Te{_match;captures;_cachedCompiledPatterns;constructor(e,t,n,r,a){super(e,t,n,null),this._match=new Be(r,this.id),this.captures=a,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(e,t){t.push(this._match)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new Ne,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},Mn=class extends Te{hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,a){super(e,t,n,r),this.patterns=a.patterns,this.hasMissingPatterns=a.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}collectPatterns(e,t){for(let n of this.patterns)e.getRule(n).collectPatterns(e,t)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new Ne,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},Gt=class extends Te{_begin;beginCaptures;_end;endHasBackReferences;endCaptures;applyEndPatternLast;hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,a,o,i,s,l,c){super(e,t,n,r),this._begin=new Be(a,this.id),this.beginCaptures=o,this._end=new Be(i||"\uFFFF",-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=s,this.applyEndPatternLast=l||!1,this.patterns=c.patterns,this.hasMissingPatterns=c.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(e,t){return this._end.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e,t).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e,t).compileAG(e,n,r)}_getCachedCompiledPatterns(e,t){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new Ne;for(let n of this.patterns)e.getRule(n).collectPatterns(e,this._cachedCompiledPatterns);this.applyEndPatternLast?this._cachedCompiledPatterns.push(this._end.hasBackReferences?this._end.clone():this._end):this._cachedCompiledPatterns.unshift(this._end.hasBackReferences?this._end.clone():this._end)}return this._end.hasBackReferences&&(this.applyEndPatternLast?this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length()-1,t):this._cachedCompiledPatterns.setSource(0,t)),this._cachedCompiledPatterns}},Je=class extends Te{_begin;beginCaptures;whileCaptures;_while;whileHasBackReferences;hasMissingPatterns;patterns;_cachedCompiledPatterns;_cachedCompiledWhilePatterns;constructor(e,t,n,r,a,o,i,s,l){super(e,t,n,r),this._begin=new Be(a,this.id),this.beginCaptures=o,this.whileCaptures=s,this._while=new Be(i,Yn),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=l.patterns,this.hasMissingPatterns=l.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null),this._cachedCompiledWhilePatterns&&(this._cachedCompiledWhilePatterns.dispose(),this._cachedCompiledWhilePatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(e,t){return this._while.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new Ne;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(e,t){return this._getCachedCompiledWhilePatterns(e,t).compile(e)}compileWhileAG(e,t,n,r){return this._getCachedCompiledWhilePatterns(e,t).compileAG(e,n,r)}_getCachedCompiledWhilePatterns(e,t){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new Ne,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,t||"\uFFFF"),this._cachedCompiledWhilePatterns}},Jn=class ${static createCaptureRule(t,n,r,a,o){return t.registerRule(i=>new Co(n,i,r,a,o))}static getCompiledRuleId(t,n,r){return t.id||n.registerRule(a=>{if(t.id=a,t.match)return new vo(t.$vscodeTextmateLocation,t.id,t.name,t.match,$._compileCaptures(t.captures,n,r));if(typeof t.begin>"u"){t.repository&&(r=Un({},r,t.repository));let o=t.patterns;return typeof o>"u"&&t.include&&(o=[{include:t.include}]),new Mn(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,$._compilePatterns(o,n,r))}return t.while?new Je(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,$._compileCaptures(t.beginCaptures||t.captures,n,r),t.while,$._compileCaptures(t.whileCaptures||t.captures,n,r),$._compilePatterns(t.patterns,n,r)):new Gt(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,$._compileCaptures(t.beginCaptures||t.captures,n,r),t.end,$._compileCaptures(t.endCaptures||t.captures,n,r),t.applyEndPatternLast,$._compilePatterns(t.patterns,n,r))}),t.id}static _compileCaptures(t,n,r){let a=[];if(t){let o=0;for(let i in t){if(i==="$vscodeTextmateLocation")continue;let s=parseInt(i,10);s>o&&(o=s)}for(let i=0;i<=o;i++)a[i]=null;for(let i in t){if(i==="$vscodeTextmateLocation")continue;let s=parseInt(i,10),l=0;t[i].patterns&&(l=$.getCompiledRuleId(t[i],n,r)),a[s]=$.createCaptureRule(n,t[i].$vscodeTextmateLocation,t[i].name,t[i].contentName,l)}}return a}static _compilePatterns(t,n,r){let a=[];if(t)for(let o=0,i=t.length;ot.substring(a.start,a.end));return $n.lastIndex=0,this.source.replace($n,(a,o)=>Wn(r[parseInt(o,10)]||""))}_buildAnchorCache(){if(typeof this.source!="string")throw new Error("This method should only be called if the source is a string");let t=[],n=[],r=[],a=[],o,i,s,l;for(o=0,i=this.source.length;on.source);this._cached=new Gn(e,t,this._items.map(n=>n.ruleId))}return this._cached}compileAG(e,t,n){return this._hasAnchors?t?n?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G0):n?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G0):this.compile(e)}_resolveAnchors(e,t,n){let r=this._items.map(a=>a.resolveAnchors(t,n));return new Gn(e,r,this._items.map(a=>a.ruleId))}},Gn=class{constructor(e,t,n){this.regExps=t,this.rules=n,this.scanner=e.createOnigScanner(t)}regExps;rules;scanner;dispose(){typeof this.scanner.dispose=="function"&&this.scanner.dispose()}toString(){let e=[];for(let t=0,n=this.rules.length;t{let n=this._scopeToLanguage(t),r=this._toStandardTokenType(t);return new Lt(n,r)});_scopeToLanguage(t){return this._embeddedLanguagesMatcher.match(t)||0}_toStandardTokenType(t){let n=t.match(Ft.STANDARD_TOKEN_TYPE_REGEXP);if(!n)return 8;switch(n[1]){case"comment":return 1;case"string":return 2;case"regex":return 3;case"meta.embedded":return 0}throw new Error("Unexpected match for standard token type!")}static STANDARD_TOKEN_TYPE_REGEXP=/\b(comment|string|regex|meta\.embedded)\b/},So=class{values;scopesRegExp;constructor(e){if(e.length===0)this.values=null,this.scopesRegExp=null;else{this.values=new Map(e);let t=e.map(([n,r])=>Wn(n));t.sort(),t.reverse(),this.scopesRegExp=new RegExp(`^((${t.join(")|(")}))($|\\.)`,"")}}match(e){if(!this.scopesRegExp)return;let t=e.match(this.scopesRegExp);if(t)return this.values.get(t[1])}},Vl={InDebugMode:typeof process<"u"&&!!process.env.VSCODE_TEXTMATE_DEBUG},er=!1,Fn=class{constructor(e,t){this.stack=e,this.stoppedEarly=t}stack;stoppedEarly};function tr(e,t,n,r,a,o,i,s){let l=t.content.length,c=!1,u=-1;if(i){let g=Eo(e,t,n,r,a,o);a=g.stack,r=g.linePos,n=g.isFirstLine,u=g.anchorPosition}let p=Date.now();for(;!c;){if(s!==0&&Date.now()-p>s)return new Fn(a,!0);d()}return new Fn(a,!1);function d(){let g=Ao(e,t,n,r,a,u);if(!g){o.produce(a,l),c=!0;return}let h=g.captureIndices,y=g.matchedRuleId,w=h&&h.length>0?h[0].end>r:!1;if(y===xo){let m=a.getRule(e);o.produce(a,h[0].start),a=a.withContentNameScopesList(a.nameScopesList),Ee(e,t,n,a,o,m.endCaptures,h),o.produce(a,h[0].end);let b=a;if(a=a.parent,u=b.getAnchorPos(),!w&&b.getEnterPos()===r){a=b,o.produce(a,l),c=!0;return}}else{let m=e.getRule(y);o.produce(a,h[0].start);let b=a,k=m.getName(t.content,h),v=a.contentNameScopesList.pushAttributed(k,e);if(a=a.push(y,r,u,h[0].end===l,null,v,v),m instanceof Gt){let S=m;Ee(e,t,n,a,o,S.beginCaptures,h),o.produce(a,h[0].end),u=h[0].end;let L=S.getContentName(t.content,h),M=v.pushAttributed(L,e);if(a=a.withContentNameScopesList(M),S.endHasBackReferences&&(a=a.withEndRule(S.getEndWithResolvedBackReferences(t.content,h))),!w&&b.hasSameRuleAs(a)){a=a.pop(),o.produce(a,l),c=!0;return}}else if(m instanceof Je){let S=m;Ee(e,t,n,a,o,S.beginCaptures,h),o.produce(a,h[0].end),u=h[0].end;let L=S.getContentName(t.content,h),M=v.pushAttributed(L,e);if(a=a.withContentNameScopesList(M),S.whileHasBackReferences&&(a=a.withEndRule(S.getWhileWithResolvedBackReferences(t.content,h))),!w&&b.hasSameRuleAs(a)){a=a.pop(),o.produce(a,l),c=!0;return}}else if(Ee(e,t,n,a,o,m.captures,h),o.produce(a,h[0].end),a=a.pop(),!w){a=a.safePop(),o.produce(a,l),c=!0;return}}h[0].end>r&&(r=h[0].end,n=!1)}}function Eo(e,t,n,r,a,o){let i=a.beginRuleCapturedEOL?0:-1,s=[];for(let l=a;l;l=l.pop()){let c=l.getRule(e);c instanceof Je&&s.push({rule:c,stack:l})}for(let l=s.pop();l;l=s.pop()){let{ruleScanner:c,findOptions:u}=Bo(l.rule,e,l.stack.endRule,n,r===i),p=c.findNextMatchSync(t,r,u);if(p){if(p.ruleId!==Yn){a=l.stack.pop();break}p.captureIndices&&p.captureIndices.length&&(o.produce(l.stack,p.captureIndices[0].start),Ee(e,t,n,l.stack,o,l.rule.whileCaptures,p.captureIndices),o.produce(l.stack,p.captureIndices[0].end),i=p.captureIndices[0].end,p.captureIndices[0].end>r&&(r=p.captureIndices[0].end,n=!1))}else{a=l.stack.pop();break}}return{stack:a,linePos:r,anchorPosition:i,isFirstLine:n}}function Ao(e,t,n,r,a,o){let i=Ro(e,t,n,r,a,o),s=e.getInjections();if(s.length===0)return i;let l=Io(s,e,t,n,r,a,o);if(!l)return i;if(!i)return l;let c=i.captureIndices[0].start,u=l.captureIndices[0].start;return u=s)&&(s=k,l=b.captureIndices,c=b.ruleId,u=h.priority,s===a))break}return l?{priorityMatch:u===-1,captureIndices:l,matchedRuleId:c}:null}function nr(e,t,n,r,a){if(er){let i=e.compile(t,n),s=rr(r,a);return{ruleScanner:i,findOptions:s}}return{ruleScanner:e.compileAG(t,n,r,a),findOptions:0}}function Bo(e,t,n,r,a){if(er){let i=e.compileWhile(t,n),s=rr(r,a);return{ruleScanner:i,findOptions:s}}return{ruleScanner:e.compileWhileAG(t,n,r,a),findOptions:0}}function rr(e,t){let n=0;return e||(n|=1),t||(n|=4),n}function Ee(e,t,n,r,a,o,i){if(o.length===0)return;let s=t.content,l=Math.min(o.length,i.length),c=[],u=i[0].end;for(let p=0;pu)break;for(;c.length>0&&c[c.length-1].endPos<=g.start;)a.produceFromScopes(c[c.length-1].scopes,c[c.length-1].endPos),c.pop();if(c.length>0?a.produceFromScopes(c[c.length-1].scopes,g.start):a.produce(r,g.start),d.retokenizeCapturedWithRuleId){let y=d.getName(s,i),w=r.contentNameScopesList.pushAttributed(y,e),m=d.getContentName(s,i),b=w.pushAttributed(m,e),k=r.push(d.retokenizeCapturedWithRuleId,g.start,-1,!1,null,w,b),v=e.createOnigString(s.substring(0,g.end));tr(e,v,n&&g.start===0,g.start,k,a,!1,0),Kn(v);continue}let h=d.getName(s,i);if(h!==null){let w=(c.length>0?c[c.length-1].scopes:r.contentNameScopesList).pushAttributed(h,e);c.push(new No(w,g.end))}}for(;c.length>0;)a.produceFromScopes(c[c.length-1].scopes,c[c.length-1].endPos),c.pop()}var No=class{scopes;endPos;constructor(e,t){this.scopes=e,this.endPos=t}};function To(e,t,n,r,a,o,i,s){return new Po(e,t,n,r,a,o,i,s)}function On(e,t,n,r,a){let o=Qe(t,Ze),i=Jn.getCompiledRuleId(n,r,a.repository);for(let s of o)e.push({debugSelector:t,matcher:s.matcher,ruleId:i,grammar:a,priority:s.priority})}function Ze(e,t){if(t.length{for(let a=n;an&&e.substr(0,n)===t&&e[n]==="."}var Po=class{constructor(e,t,n,r,a,o,i,s){if(this._rootScopeName=e,this.balancedBracketSelectors=o,this._onigLib=s,this._basicScopeAttributesProvider=new _o(n,r),this._rootId=-1,this._lastRuleId=0,this._ruleId2desc=[null],this._includedGrammars={},this._grammarRepository=i,this._grammar=Dn(t,null),this._injections=null,this._tokenTypeMatchers=[],a)for(let l of Object.keys(a)){let c=Qe(l,Ze);for(let u of c)this._tokenTypeMatchers.push({matcher:u.matcher,type:a[l]})}}_rootScopeName;balancedBracketSelectors;_onigLib;_rootId;_lastRuleId;_ruleId2desc;_includedGrammars;_grammarRepository;_grammar;_injections;_basicScopeAttributesProvider;_tokenTypeMatchers;get themeProvider(){return this._grammarRepository}dispose(){for(let e of this._ruleId2desc)e&&e.dispose()}createOnigScanner(e){return this._onigLib.createOnigScanner(e)}createOnigString(e){return this._onigLib.createOnigString(e)}getMetadataForScope(e){return this._basicScopeAttributesProvider.getBasicScopeAttributes(e)}_collectInjections(){let e={lookup:a=>a===this._rootScopeName?this._grammar:this.getExternalGrammar(a),injections:a=>this._grammarRepository.injections(a)},t=[],n=this._rootScopeName,r=e.lookup(n);if(r){let a=r.injections;if(a)for(let i in a)On(t,i,a[i],this,r);let o=this._grammarRepository.injections(n);o&&o.forEach(i=>{let s=this.getExternalGrammar(i);if(s){let l=s.injectionSelector;l&&On(t,l,s,this,s)}})}return t.sort((a,o)=>a.priority-o.priority),t}getInjections(){return this._injections===null&&(this._injections=this._collectInjections()),this._injections}registerRule(e){let t=++this._lastRuleId,n=e(t);return this._ruleId2desc[t]=n,n}getRule(e){return this._ruleId2desc[e]}getExternalGrammar(e,t){if(this._includedGrammars[e])return this._includedGrammars[e];if(this._grammarRepository){let n=this._grammarRepository.lookup(e);if(n)return this._includedGrammars[e]=Dn(n,t&&t.$base),this._includedGrammars[e]}}tokenizeLine(e,t,n=0){let r=this._tokenize(e,t,!1,n);return{tokens:r.lineTokens.getResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}tokenizeLine2(e,t,n=0){let r=this._tokenize(e,t,!0,n);return{tokens:r.lineTokens.getBinaryResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}_tokenize(e,t,n,r){this._rootId===-1&&(this._rootId=Jn.getCompiledRuleId(this._grammar.repository.$self,this,this._grammar.repository),this.getInjections());let a;if(!t||t===Ot.NULL){a=!0;let c=this._basicScopeAttributesProvider.getDefaultAttributes(),u=this.themeProvider.getDefaults(),p=re.set(0,c.languageId,c.tokenType,null,u.fontStyle,u.foregroundId,u.backgroundId),d=this.getRule(this._rootId).getName(null,null),g;d?g=Ae.createRootAndLookUpScopeName(d,p,this):g=Ae.createRoot("unknown",p),t=new Ot(null,this._rootId,-1,-1,!1,null,g,g)}else a=!1,t.reset();e=e+` +`;let o=this.createOnigString(e),i=o.content.length,s=new Mo(n,e,this._tokenTypeMatchers,this.balancedBracketSelectors),l=tr(this,o,a,0,t,s,!0,r);return Kn(o),{lineLength:i,lineTokens:s,ruleStack:l.stack,stoppedEarly:l.stoppedEarly}}};function Dn(e,t){return e=Ja(e),e.repository=e.repository||{},e.repository.$self={$vscodeTextmateLocation:e.$vscodeTextmateLocation,patterns:e.patterns,name:e.scopeName},e.repository.$base=t||e.repository.$self,e}var Ae=class z{constructor(t,n,r){this.parent=t,this.scopePath=n,this.tokenAttributes=r}parent;scopePath;tokenAttributes;static fromExtension(t,n){let r=t,a=t?.scopePath??null;for(let o of n)a=Tt.push(a,o.scopeNames),r=new z(r,a,o.encodedTokenAttributes);return r}static createRoot(t,n){return new z(null,new Tt(null,t),n)}static createRootAndLookUpScopeName(t,n,r){let a=r.getMetadataForScope(t),o=new Tt(null,t),i=r.themeProvider.themeMatch(o),s=z.mergeAttributes(n,a,i);return new z(null,o,s)}get scopeName(){return this.scopePath.scopeName}toString(){return this.getScopeNames().join(" ")}equals(t){return z.equals(this,t)}static equals(t,n){do{if(t===n||!t&&!n)return!0;if(!t||!n||t.scopeName!==n.scopeName||t.tokenAttributes!==n.tokenAttributes)return!1;t=t.parent,n=n.parent}while(!0)}static mergeAttributes(t,n,r){let a=-1,o=0,i=0;return r!==null&&(a=r.fontStyle,o=r.foregroundId,i=r.backgroundId),re.set(t,n.languageId,n.tokenType,null,a,o,i)}pushAttributed(t,n){if(t===null)return this;if(t.indexOf(" ")===-1)return z._pushAttributed(this,t,n);let r=t.split(/ /g),a=this;for(let o of r)a=z._pushAttributed(a,o,n);return a}static _pushAttributed(t,n,r){let a=r.getMetadataForScope(n),o=t.scopePath.push(n),i=r.themeProvider.themeMatch(o),s=z.mergeAttributes(t.tokenAttributes,a,i);return new z(t,o,s)}getScopeNames(){return this.scopePath.getSegments()}getExtensionIfDefined(t){let n=[],r=this;for(;r&&r!==t;)n.push({encodedTokenAttributes:r.tokenAttributes,scopeNames:r.scopePath.getExtensionIfDefined(r.parent?.scopePath??null)}),r=r.parent;return r===t?n.reverse():void 0}},Ot=class le{constructor(t,n,r,a,o,i,s,l){this.parent=t,this.ruleId=n,this.beginRuleCapturedEOL=o,this.endRule=i,this.nameScopesList=s,this.contentNameScopesList=l,this.depth=this.parent?this.parent.depth+1:1,this._enterPos=r,this._anchorPos=a}parent;ruleId;beginRuleCapturedEOL;endRule;nameScopesList;contentNameScopesList;_stackElementBrand=void 0;static NULL=new le(null,0,0,0,!1,null,null,null);_enterPos;_anchorPos;depth;equals(t){return t===null?!1:le._equals(this,t)}static _equals(t,n){return t===n?!0:this._structuralEquals(t,n)?Ae.equals(t.contentNameScopesList,n.contentNameScopesList):!1}static _structuralEquals(t,n){do{if(t===n||!t&&!n)return!0;if(!t||!n||t.depth!==n.depth||t.ruleId!==n.ruleId||t.endRule!==n.endRule)return!1;t=t.parent,n=n.parent}while(!0)}clone(){return this}static _reset(t){for(;t;)t._enterPos=-1,t._anchorPos=-1,t=t.parent}reset(){le._reset(this)}pop(){return this.parent}safePop(){return this.parent?this.parent:this}push(t,n,r,a,o,i,s){return new le(this,t,n,r,a,o,i,s)}getEnterPos(){return this._enterPos}getAnchorPos(){return this._anchorPos}getRule(t){return t.getRule(this.ruleId)}toString(){let t=[];return this._writeString(t,0),"["+t.join(",")+"]"}_writeString(t,n){return this.parent&&(n=this.parent._writeString(t,n)),t[n++]=`(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`,n}withContentNameScopesList(t){return this.contentNameScopesList===t?this:this.parent.push(this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,this.endRule,this.nameScopesList,t)}withEndRule(t){return this.endRule===t?this:new le(this.parent,this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,t,this.nameScopesList,this.contentNameScopesList)}hasSameRuleAs(t){let n=this;for(;n&&n._enterPos===t._enterPos;){if(n.ruleId===t.ruleId)return!0;n=n.parent}return!1}toStateStackFrame(){return{ruleId:this.ruleId,beginRuleCapturedEOL:this.beginRuleCapturedEOL,endRule:this.endRule,nameScopesList:this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList??null)??[],contentNameScopesList:this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)??[]}}static pushFrame(t,n){let r=Ae.fromExtension(t?.nameScopesList??null,n.nameScopesList);return new le(t,n.ruleId,n.enterPos??-1,n.anchorPos??-1,n.beginRuleCapturedEOL,n.endRule,r,Ae.fromExtension(r,n.contentNameScopesList))}},$o=class{balancedBracketScopes;unbalancedBracketScopes;allowAny=!1;constructor(e,t){this.balancedBracketScopes=e.flatMap(n=>n==="*"?(this.allowAny=!0,[]):Qe(n,Ze).map(r=>r.matcher)),this.unbalancedBracketScopes=t.flatMap(n=>Qe(n,Ze).map(r=>r.matcher))}get matchesAlways(){return this.allowAny&&this.unbalancedBracketScopes.length===0}get matchesNever(){return this.balancedBracketScopes.length===0&&!this.allowAny}match(e){for(let t of this.unbalancedBracketScopes)if(t(e))return!1;for(let t of this.balancedBracketScopes)if(t(e))return!0;return this.allowAny}},Mo=class{constructor(e,t,n,r){this.balancedBracketSelectors=r,this._emitBinaryTokens=e,this._tokenTypeOverrides=n,this._lineText=null,this._tokens=[],this._binaryTokens=[],this._lastTokenEndIndex=0}balancedBracketSelectors;_emitBinaryTokens;_lineText;_tokens;_binaryTokens;_lastTokenEndIndex;_tokenTypeOverrides;produce(e,t){this.produceFromScopes(e.contentNameScopesList,t)}produceFromScopes(e,t){if(this._lastTokenEndIndex>=t)return;if(this._emitBinaryTokens){let r=e?.tokenAttributes??0,a=!1;if(this.balancedBracketSelectors?.matchesAlways&&(a=!0),this._tokenTypeOverrides.length>0||this.balancedBracketSelectors&&!this.balancedBracketSelectors.matchesAlways&&!this.balancedBracketSelectors.matchesNever){let o=e?.getScopeNames()??[];for(let i of this._tokenTypeOverrides)i.matcher(o)&&(r=re.set(r,0,i.type,null,-1,0,0));this.balancedBracketSelectors&&(a=this.balancedBracketSelectors.match(o))}if(a&&(r=re.set(r,0,8,a,-1,0,0)),this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-1]===r){this._lastTokenEndIndex=t;return}this._binaryTokens.push(this._lastTokenEndIndex),this._binaryTokens.push(r),this._lastTokenEndIndex=t;return}let n=e?.getScopeNames()??[];this._tokens.push({startIndex:this._lastTokenEndIndex,endIndex:t,scopes:n}),this._lastTokenEndIndex=t}getResult(e,t){return this._tokens.length>0&&this._tokens[this._tokens.length-1].startIndex===t-1&&this._tokens.pop(),this._tokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._tokens[this._tokens.length-1].startIndex=0),this._tokens}getBinaryResult(e,t){this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-2]===t-1&&(this._binaryTokens.pop(),this._binaryTokens.pop()),this._binaryTokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._binaryTokens[this._binaryTokens.length-2]=0);let n=new Uint32Array(this._binaryTokens.length);for(let r=0,a=this._binaryTokens.length;r0;)o.Q.map(i=>this._loadSingleGrammar(i.scopeName)),o.processQueue();return this._grammarForScopeName(e,t,n,r,a)}_loadSingleGrammar(e){this._ensureGrammarCache.has(e)||(this._doLoadSingleGrammar(e),this._ensureGrammarCache.set(e,!0))}_doLoadSingleGrammar(e){let t=this._options.loadGrammar(e);if(t){let n=typeof this._options.getInjections=="function"?this._options.getInjections(e):void 0;this._syncRegistry.addGrammar(t,n)}}addGrammar(e,t=[],n=0,r=null){return this._syncRegistry.addGrammar(e,t),this._grammarForScopeName(e.scopeName,n,r)}_grammarForScopeName(e,t=0,n=null,r=null,a=null){return this._syncRegistry.grammarForScopeName(e,t,n,r,a)}},et=Ot.NULL;function Pe(e,t){let n=typeof e=="string"?{}:{...e.colorReplacements},r=typeof e=="string"?e:e.name;for(let[a,o]of Object.entries(t?.colorReplacements||{}))typeof o=="string"?n[a]=o:a===r&&Object.assign(n,o);return n}function X(e,t){return e&&(t?.[e?.toLowerCase()]||e)}function cr(e){return Array.isArray(e)?e:[e]}async function Ut(e){return Promise.resolve(typeof e=="function"?e():e).then(t=>t.default||t)}function $e(e){return!e||["plaintext","txt","text","plain"].includes(e)}function ur(e){return e==="ansi"||$e(e)}function Me(e){return e==="none"}function pr(e){return Me(e)}var Fo=/(\r?\n)/g;function we(e,t=!1){if(e.length===0)return[["",0]];let n=e.split(Fo),r=0,a=[];for(let o=0;o!l.name&&!l.scope):void 0;s?.settings?.foreground&&(r=s.settings.foreground),s?.settings?.background&&(n=s.settings.background),!r&&t?.colors?.["editor.foreground"]&&(r=t.colors["editor.foreground"]),!n&&t?.colors?.["editor.background"]&&(n=t.colors["editor.background"]),r||(r=t.type==="light"?or.light:or.dark),n||(n=t.type==="light"?ir.light:ir.dark),t.fg=r,t.bg=n}t.settings[0]&&t.settings[0].settings&&!t.settings[0].scope||t.settings.unshift({settings:{foreground:t.fg,background:t.bg}});let a=0,o=new Map;function i(s){if(o.has(s))return o.get(s);a+=1;let l=`#${a.toString(16).padStart(8,"0").toLowerCase()}`;return t.colorReplacements?.[`#${l}`]?i(s):(o.set(s,l),l)}t.settings=t.settings.map(s=>{let l=s.settings?.foreground&&!s.settings.foreground.startsWith("#"),c=s.settings?.background&&!s.settings.background.startsWith("#");if(!l&&!c)return s;let u={...s,settings:{...s.settings}};if(l){let p=i(s.settings.foreground);t.colorReplacements[p]=s.settings.foreground,u.settings.foreground=p}if(c){let p=i(s.settings.background);t.colorReplacements[p]=s.settings.background,u.settings.background=p}return u});for(let s of Object.keys(t.colors||{}))if((s==="editor.foreground"||s==="editor.background"||s.startsWith("terminal.ansi"))&&!t.colors[s]?.startsWith("#")){let l=i(t.colors[s]);t.colorReplacements[l]=t.colors[s],t.colors[s]=l}return Object.defineProperty(t,sr,{enumerable:!1,writable:!1,value:!0}),t}async function dr(e){return[...new Set((await Promise.all(e.filter(t=>!ur(t)).map(async t=>await Ut(t).then(n=>Array.isArray(n)?n:[n])))).flat())]}async function gr(e){return(await Promise.all(e.map(async t=>pr(t)?null:tt(await Ut(t))))).filter(t=>!!t)}function hr(e,t){if(!t)return e;if(t[e]){let n=new Set([e]);for(;t[e];){if(e=t[e],n.has(e))throw new E(`Circular alias \`${[...n].join(" -> ")} -> ${e}\``);n.add(e)}}return e}var Oo=class extends ar{_resolver;_themes;_langs;_alias;_resolvedThemes=new Map;_resolvedGrammars=new Map;_langMap=new Map;_langGraph=new Map;_textmateThemeCache=new WeakMap;_loadedThemesCache=null;_loadedLanguagesCache=null;constructor(e,t,n,r={}){super(e),this._resolver=e,this._themes=t,this._langs=n,this._alias=r,this._themes.map(a=>this.loadTheme(a)),this.loadLanguages(this._langs)}getTheme(e){return typeof e=="string"?this._resolvedThemes.get(e):this.loadTheme(e)}loadTheme(e){let t=tt(e);return t.name&&(this._resolvedThemes.set(t.name,t),this._loadedThemesCache=null),t}getLoadedThemes(){return this._loadedThemesCache||(this._loadedThemesCache=[...this._resolvedThemes.keys()]),this._loadedThemesCache}setTheme(e){let t=this._textmateThemeCache.get(e);t||(t=Re.createFromRawTheme(e),this._textmateThemeCache.set(e,t)),this._syncRegistry.setTheme(t)}getGrammar(e){return e=hr(e,this._alias),this._resolvedGrammars.get(e)}loadLanguage(e){if(this.getGrammar(e.name))return;let t=new Set([...this._langMap.values()].filter(a=>a.embeddedLangsLazy?.includes(e.name)));this._resolver.addLanguage(e);let n={balancedBracketSelectors:e.balancedBracketSelectors||["*"],unbalancedBracketSelectors:e.unbalancedBracketSelectors||[]};this._syncRegistry._rawGrammars.set(e.scopeName,e);let r=this.loadGrammarWithConfiguration(e.scopeName,1,n);if(r.name=e.name,this._resolvedGrammars.set(e.name,r),e.aliases&&e.aliases.forEach(a=>{this._alias[a]=e.name}),this._loadedLanguagesCache=null,t.size)for(let a of t)this._resolvedGrammars.delete(a.name),this._loadedLanguagesCache=null,this._syncRegistry?._injectionGrammars?.delete(a.scopeName),this._syncRegistry?._grammars?.delete(a.scopeName),this.loadLanguage(this._langMap.get(a.name))}dispose(){super.dispose(),this._resolvedThemes.clear(),this._resolvedGrammars.clear(),this._langMap.clear(),this._langGraph.clear(),this._loadedThemesCache=null}loadLanguages(e){for(let r of e)this.resolveEmbeddedLanguages(r);let t=[...this._langGraph.entries()],n=t.filter(([r,a])=>!a);if(n.length){let r=t.filter(([a,o])=>o?(o.embeddedLanguages||o.embeddedLangs)?.some(i=>n.map(([s])=>s).includes(i)):!1).filter(a=>!n.includes(a));throw new E(`Missing languages ${n.map(([a])=>`\`${a}\``).join(", ")}, required by ${r.map(([a])=>`\`${a}\``).join(", ")}`)}for(let[r,a]of t)this._resolver.addLanguage(a);for(let[r,a]of t)this.loadLanguage(a)}getLoadedLanguages(){return this._loadedLanguagesCache||(this._loadedLanguagesCache=[...new Set([...this._resolvedGrammars.keys(),...Object.keys(this._alias)])]),this._loadedLanguagesCache}resolveEmbeddedLanguages(e){this._langMap.set(e.name,e),this._langGraph.set(e.name,e);let t=e.embeddedLanguages??e.embeddedLangs;if(t)for(let n of t)this._langGraph.set(n,this._langMap.get(n))}},Do=class{_langs=new Map;_scopeToLang=new Map;_injections=new Map;_onigLib;constructor(e,t){this._onigLib={createOnigScanner:n=>e.createScanner(n),createOnigString:n=>e.createString(n)},t.forEach(n=>this.addLanguage(n))}get onigLib(){return this._onigLib}getLangRegistration(e){return this._langs.get(e)}loadGrammar(e){return this._scopeToLang.get(e)}addLanguage(e){this._langs.set(e.name,e),e.aliases&&e.aliases.forEach(t=>{this._langs.set(t,e)}),this._scopeToLang.set(e.scopeName,e),e.injectTo&&e.injectTo.forEach(t=>{this._injections.get(t)||this._injections.set(t,[]),this._injections.get(t).push(e.scopeName)})}getInjections(e){let t=e.split("."),n=[];for(let r=1;r<=t.length;r++){let a=t.slice(0,r).join(".");n=[...n,...this._injections.get(a)||[]]}return n}},Le=0;function qt(e){Le+=1,e.warnings!==!1&&Le>=10&&Le%10===0&&console.warn(`[Shiki] ${Le} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call \`highlighter.dispose()\` to release unused instances.`);let t=!1;if(!e.engine)throw new E("`engine` option is required for synchronous mode");let n=(e.langs||[]).flat(1),r=(e.themes||[]).flat(1).map(tt),a=new Oo(new Do(e.engine,n),r,n,e.langAlias),o;function i(b){return hr(b,e.langAlias)}function s(b){w();let k=a.getGrammar(typeof b=="string"?b:b.name);if(!k)throw new E(`Language \`${b}\` not found, you may need to load it first`);return k}function l(b){if(b==="none")return{bg:"",fg:"",name:"none",settings:[],type:"dark"};w();let k=a.getTheme(b);if(!k)throw new E(`Theme \`${b}\` not found, you may need to load it first`);return k}function c(b){w();let k=l(b);return o!==b&&(a.setTheme(k),o=b),{theme:k,colorMap:a.getColorMap()}}function u(){return w(),a.getLoadedThemes()}function p(){return w(),a.getLoadedLanguages()}function d(...b){w(),a.loadLanguages(b.flat(1))}async function g(...b){return d(await dr(b))}function h(...b){w();for(let k of b.flat(1))a.loadTheme(k)}async function y(...b){return w(),h(await gr(b))}function w(){if(t)throw new E("Shiki instance has been disposed")}function m(){t||(t=!0,a.dispose(),Le-=1)}return{setTheme:c,getTheme:l,getLanguage:s,getLoadedThemes:u,getLoadedLanguages:p,resolveLangAlias:i,loadLanguage:g,loadLanguageSync:d,loadTheme:y,loadThemeSync:h,dispose:m,[Symbol.dispose]:m}}async function jt(e){e.engine||console.warn("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");let[t,n,r]=await Promise.all([gr(e.themes||[]),dr(e.langs||[]),e.engine]);return qt({...e,themes:t,langs:n,engine:r})}var fr=new WeakMap;function Ge(e,t){fr.set(e,t)}function ke(e){return fr.get(e)}var nt=class mr{_stacks={};lang;get themes(){return Object.keys(this._stacks)}get theme(){return this.themes[0]}get _stack(){return this._stacks[this.theme]}static initial(t,n){return new mr(Object.fromEntries(cr(n).map(r=>[r,et])),t)}constructor(...t){if(t.length===2){let[n,r]=t;this.lang=r,this._stacks=n}else{let[n,r,a]=t;this.lang=r,this._stacks={[a]:n}}}getInternalStack(t=this.theme){return this._stacks[t]}getScopes(t=this.theme){return Uo(this._stacks[t])}toJSON(){return{lang:this.lang,theme:this.theme,themes:this.themes,scopes:this.getScopes()}}};function Uo(e){let t=[],n=new Set;function r(a){if(n.has(a))return;n.add(a);let o=a?.nameScopesList?.scopeName;o&&t.push(o),a.parent&&r(a.parent)}return r(e),t}function qo(e,t){if(!(e instanceof nt))throw new E("Invalid grammar state");return e.getInternalStack(t)}var jo=/,/,Ho=/ /;function Ht(e,t,n={}){let{theme:r=e.getLoadedThemes()[0]}=n;if($e(e.resolveLangAlias(n.lang||"text"))||Me(r))return we(t).map(s=>[{content:s[0],offset:s[1]}]);let{theme:a,colorMap:o}=e.setTheme(r),i=e.getLanguage(n.lang||"text");if(n.grammarState){if(n.grammarState.lang!==i.name)throw new E(`Grammar state language "${n.grammarState.lang}" does not match highlight language "${i.name}"`);if(!n.grammarState.themes.includes(a.name))throw new E(`Grammar state themes "${n.grammarState.themes}" do not contain highlight theme "${a.name}"`)}return yr(t,i,a,o,n)}function br(...e){if(e.length===2)return ke(e[1]);let[t,n,r={}]=e,{lang:a="text",theme:o=t.getLoadedThemes()[0]}=r;if($e(a)||Me(o))throw new E("Plain language does not have grammar state");if(a==="ansi")throw new E("ANSI language does not have grammar state");let{theme:i,colorMap:s}=t.setTheme(o),l=t.getLanguage(a);return new nt(Wt(n,l,i,s,r).stateStack,l.name,i.name)}function yr(e,t,n,r,a){let o=Wt(e,t,n,r,a),i=new nt(o.stateStack,t.name,n.name);return Ge(o.tokens,i),o.tokens}function Wt(e,t,n,r,a){let o=Pe(n,a),{tokenizeMaxLineLength:i=0,tokenizeTimeLimit:s=500,includeExplanation:l=!1}=a,c=we(e),u=a.grammarState?qo(a.grammarState,n.name)??et:a.grammarContextCode!=null?Wt(a.grammarContextCode,t,n,r,{...a,grammarState:void 0,grammarContextCode:void 0}).stateStack:et,p=[],d=[];for(let g=0,h=c.length;g0&&y.length>=i){p=[],d.push([{content:y,offset:w,color:"",fontStyle:0}]);continue}let m,b,k;l&&l!=="tokenType"&&(m=t.tokenizeLine(y,u,s),b=m.tokens,k=0);let v=t.tokenizeLine2(y,u,s),S=v.tokens.length/2;for(let L=0;LBt.trim());break;case"object":ye=V.scope;break;default:continue}Nn.push({settings:V,selectors:ye.map(Bt=>Bt.split(Ho))})}W.explanation=[];let Tn=0;for(;M+Tn({scopeName:t}))}function zo(e,t){let n=[];for(let r=0,a=t.length;r=0&&a>=0;)lr(e[r],n[a])&&(r-=1),a-=1;return r===-1}function Xo(e,t,n){let r=[];for(let{selectors:a,settings:o}of e)for(let i of a)if(Vo(i,t,n)){r.push(o);break}return r}function rt(e,t,n,r=Ht){let a=Object.entries(n.themes).filter(c=>c[1]).map(c=>({color:c[0],theme:c[1]})),o=a.map(c=>{let u=r(e,t,{...n,theme:c.theme});return{tokens:u,state:ke(u),theme:typeof c.theme=="string"?c.theme:c.theme.name}}),i=Ko(...o.map(c=>c.tokens)),s=i[0].map((c,u)=>c.map((p,d)=>{let g={content:p.content,variants:{},offset:p.offset};return"includeExplanation"in n&&n.includeExplanation&&(g.explanation=p.explanation),i.forEach((h,y)=>{let{content:w,explanation:m,offset:b,...k}=h[u][d];g.variants[a[y].color]=k}),g})),l=o[0].state?new nt(Object.fromEntries(o.map(c=>[c.theme,c.state?.getInternalStack(c.theme)])),o[0].state.lang):void 0;return l&&Ge(s,l),s}function Ko(...e){let t=e.map(()=>[]),n=e.length;for(let r=0;rl[r]),o=t.map(()=>[]);t.forEach((l,c)=>l.push(o[c]));let i=a.map(()=>0),s=a.map(l=>l[0]);for(;s.every(l=>l);){let l=Math.min(...s.map(c=>c.content.length));for(let c=0;cx,booleanish:()=>A,commaOrSpaceSeparated:()=>G,commaSeparated:()=>Q,number:()=>f,overloadedBoolean:()=>at,spaceSeparated:()=>_});var Qo=0,x=ce(),A=ce(),at=ce(),f=ce(),_=ce(),Q=ce(),G=ce();function ce(){return 2**++Qo}var Vt=Object.keys(Oe),ue=class extends T{constructor(t,n,r,a){let o=-1;if(super(t,n),kr(this,"space",a),typeof r=="number")for(;++o4&&n.slice(0,4)==="data"&&Jo.test(t)){if(t.charAt(4)==="-"){let o=t.slice(5).replace(vr,ei);r="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{let o=t.slice(4);if(!vr.test(o)){let i=o.replace(Yo,Zo);i.charAt(0)!=="-"&&(i="-"+i),t="data"+i}}a=ue}return new a(r,t)}function Zo(e){return"-"+e.toLowerCase()}function ei(e){return e.charAt(1).toUpperCase()}var st=zt([Xt,xr,Kt,Qt,Yt],"html"),lt=zt([Xt,Cr,Kt,Qt,Yt],"svg");var _r={}.hasOwnProperty;function Sr(e,t){let n=t||{};function r(a,...o){let i=r.invalid,s=r.handlers;if(a&&_r.call(a,e)){let l=String(a[e]);i=_r.call(s,l)?s[l]:r.unknown}if(i)return i.call(this,a,...o)}return r.handlers=n.handlers||{},r.invalid=n.invalid,r.unknown=n.unknown,r}var ti=/["&'<>`]/g,ni=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,ri=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,ai=/[|\\{}()[\]^$+*?.]/g,Er=new WeakMap;function Ar(e,t){if(e=e.replace(t.subset?oi(t.subset):ti,r),t.subset||t.escapeOnly)return e;return e.replace(ni,n).replace(ri,r);function n(a,o,i){return t.format((a.charCodeAt(0)-55296)*1024+a.charCodeAt(1)-56320+65536,i.charCodeAt(o+2),t)}function r(a,o,i){return t.format(a.charCodeAt(0),i.charCodeAt(o+1),t)}}function oi(e){let t=Er.get(e);return t||(t=ii(e),Er.set(e,t)),t}function ii(e){let t=[],n=-1;for(;++n",OElig:"\u0152",oelig:"\u0153",Scaron:"\u0160",scaron:"\u0161",Yuml:"\u0178",circ:"\u02C6",tilde:"\u02DC",ensp:"\u2002",emsp:"\u2003",thinsp:"\u2009",zwnj:"\u200C",zwj:"\u200D",lrm:"\u200E",rlm:"\u200F",ndash:"\u2013",mdash:"\u2014",lsquo:"\u2018",rsquo:"\u2019",sbquo:"\u201A",ldquo:"\u201C",rdquo:"\u201D",bdquo:"\u201E",dagger:"\u2020",Dagger:"\u2021",permil:"\u2030",lsaquo:"\u2039",rsaquo:"\u203A",euro:"\u20AC"};var Nr=["cent","copy","divide","gt","lt","not","para","times"];var Tr={}.hasOwnProperty,Zt={},ut;for(ut in ct)Tr.call(ct,ut)&&(Zt[ct[ut]]=ut);var ci=/[^\dA-Za-z]/;function Lr(e,t,n,r){let a=String.fromCharCode(e);if(Tr.call(Zt,a)){let o=Zt[a],i="&"+o;return n&&Br.includes(o)&&!Nr.includes(o)&&(!r||t&&t!==61&&ci.test(String.fromCharCode(t)))?i:i+";"}return""}function Pr(e,t,n){let r=Rr(e,t,n.omitOptionalSemicolons),a;if((n.useNamedReferences||n.useShortestReferences)&&(a=Lr(e,t,n.omitOptionalSemicolons,n.attribute)),(n.useShortestReferences||!a)&&n.useShortestReferences){let o=Ir(e,t,n.omitOptionalSemicolons);o.length|^->||--!>|"],di=["<",">"];function $r(e,t,n,r){return r.settings.bogusComments?"":"";function a(o){return Y(o,Object.assign({},r.settings.characterReferences,{subset:di}))}}function Mr(e,t,n,r){return""}function en(e,t){let n=String(e);if(typeof t!="string")throw new TypeError("Expected character");let r=0,a=n.indexOf(t);for(;a!==-1;)r++,a=n.indexOf(t,a+t.length);return r}function Gr(e,t){let n=t||{};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}function Fr(e){return e.join(" ").trim()}var gi=/[ \t\n\f\r]/g;function pe(e){return typeof e=="object"?e.type==="text"?Or(e.value):!1:Or(e)}function Or(e){return e.replace(gi,"")===""}var R=Dr(1),tn=Dr(-1),hi=[];function Dr(e){return t;function t(n,r,a){let o=n?n.children:hi,i=(r||0)+e,s=o[i];if(!a)for(;s&&pe(s);)i+=e,s=o[i];return s}}var fi={}.hasOwnProperty;function pt(e){return t;function t(n,r,a){return fi.call(e,n.tagName)&&e[n.tagName](n,r,a)}}var De=pt({body:bi,caption:nn,colgroup:nn,dd:xi,dt:ki,head:nn,html:mi,li:wi,optgroup:Ci,option:vi,p:yi,rp:Ur,rt:Ur,tbody:Si,td:qr,tfoot:Ei,th:qr,thead:_i,tr:Ai});function nn(e,t,n){let r=R(n,t,!0);return!r||r.type!=="comment"&&!(r.type==="text"&&pe(r.value.charAt(0)))}function mi(e,t,n){let r=R(n,t);return!r||r.type!=="comment"}function bi(e,t,n){let r=R(n,t);return!r||r.type!=="comment"}function yi(e,t,n){let r=R(n,t);return r?r.type==="element"&&(r.tagName==="address"||r.tagName==="article"||r.tagName==="aside"||r.tagName==="blockquote"||r.tagName==="details"||r.tagName==="div"||r.tagName==="dl"||r.tagName==="fieldset"||r.tagName==="figcaption"||r.tagName==="figure"||r.tagName==="footer"||r.tagName==="form"||r.tagName==="h1"||r.tagName==="h2"||r.tagName==="h3"||r.tagName==="h4"||r.tagName==="h5"||r.tagName==="h6"||r.tagName==="header"||r.tagName==="hgroup"||r.tagName==="hr"||r.tagName==="main"||r.tagName==="menu"||r.tagName==="nav"||r.tagName==="ol"||r.tagName==="p"||r.tagName==="pre"||r.tagName==="section"||r.tagName==="table"||r.tagName==="ul"):!n||!(n.type==="element"&&(n.tagName==="a"||n.tagName==="audio"||n.tagName==="del"||n.tagName==="ins"||n.tagName==="map"||n.tagName==="noscript"||n.tagName==="video"||n.tagName.includes("-")))}function wi(e,t,n){let r=R(n,t);return!r||r.type==="element"&&r.tagName==="li"}function ki(e,t,n){let r=R(n,t);return!!(r&&r.type==="element"&&(r.tagName==="dt"||r.tagName==="dd"))}function xi(e,t,n){let r=R(n,t);return!r||r.type==="element"&&(r.tagName==="dt"||r.tagName==="dd")}function Ur(e,t,n){let r=R(n,t);return!r||r.type==="element"&&(r.tagName==="rp"||r.tagName==="rt")}function Ci(e,t,n){let r=R(n,t);return!r||r.type==="element"&&r.tagName==="optgroup"}function vi(e,t,n){let r=R(n,t);return!r||r.type==="element"&&(r.tagName==="option"||r.tagName==="optgroup")}function _i(e,t,n){let r=R(n,t);return!!(r&&r.type==="element"&&(r.tagName==="tbody"||r.tagName==="tfoot"))}function Si(e,t,n){let r=R(n,t);return!r||r.type==="element"&&(r.tagName==="tbody"||r.tagName==="tfoot")}function Ei(e,t,n){return!R(n,t)}function Ai(e,t,n){let r=R(n,t);return!r||r.type==="element"&&r.tagName==="tr"}function qr(e,t,n){let r=R(n,t);return!r||r.type==="element"&&(r.tagName==="td"||r.tagName==="th")}var jr=pt({body:Bi,colgroup:Ni,head:Ii,html:Ri,tbody:Ti});function Ri(e){let t=R(e,-1);return!t||t.type!=="comment"}function Ii(e){let t=new Set;for(let r of e.children)if(r.type==="element"&&(r.tagName==="base"||r.tagName==="title")){if(t.has(r.tagName))return!1;t.add(r.tagName)}let n=e.children[0];return!n||n.type==="element"}function Bi(e){let t=R(e,-1,!0);return!t||t.type!=="comment"&&!(t.type==="text"&&pe(t.value.charAt(0)))&&!(t.type==="element"&&(t.tagName==="meta"||t.tagName==="link"||t.tagName==="script"||t.tagName==="style"||t.tagName==="template"))}function Ni(e,t,n){let r=tn(n,t);if(n&&r&&r.type==="element"&&r.tagName==="colgroup"&&De(r,n.children.indexOf(r),n))return!1;let a=R(e,-1,!0);return!!(a&&a.type==="element"&&a.tagName==="col")}function Ti(e,t,n){let r=tn(n,t);if(n&&r&&r.type==="element"&&(r.tagName==="thead"||r.tagName==="tbody")&&De(r,n.children.indexOf(r),n))return!1;let a=R(e,-1);return!!(a&&a.type==="element"&&a.tagName==="tr")}var dt={name:[[` +\f\r &/=>`.split(""),` +\f\r "&'/=>\``.split("")],[`\0 +\f\r "&'/<=>`.split(""),`\0 +\f\r "&'/<=>\``.split("")]],unquoted:[[` +\f\r &>`.split(""),`\0 +\f\r "&'<=>\``.split("")],[`\0 +\f\r "&'<=>\``.split(""),`\0 +\f\r "&'<=>\``.split("")]],single:[["&'".split(""),"\"&'`".split("")],["\0&'".split(""),"\0\"&'`".split("")]],double:[['"&'.split(""),"\"&'`".split("")],['\0"&'.split(""),"\0\"&'`".split("")]]},Li=new Set(["desc","foreignObject","title"]);function Hr(e,t,n,r){let{schema:a}=r,o=a.space==="svg"?!1:r.settings.omitOptionalTags,i=a.space==="svg"?r.settings.closeEmptyElements:r.settings.voids.includes(e.tagName.toLowerCase()),s=[];a.space==="html"&&e.tagName==="svg"&&(r.schema=lt);let l=Pi(r,e.properties);r.schema.space==="svg"&&Li.has(e.tagName)&&(r.schema=st);let c=r.all(a.space==="html"&&e.tagName==="template"?e.content:e);if(r.schema=a,c&&(i=!1),l||!o||!jr(e,t,n)){if(s.push("<",e.tagName,l?" "+l:""),i&&(a.space==="svg"||r.settings.closeSelfClosing)){let u=l.charAt(l.length-1);(!r.settings.tightSelfClosing||u==="/"||u&&u!=='"'&&u!=="'")&&s.push(" "),s.push("/")}s.push(">")}return s.push(c),!i&&(!o||!De(e,t,n))&&s.push(""),s.join("")}function Pi(e,t){let n=[],r=-1,a;if(t){for(a in t)if(t[a]!==null&&t[a]!==void 0){let o=$i(e,a,t[a]);o&&n.push(o)}}for(;++ren(n,e.alternative)&&(l=e.alternative),s=l+Y(n,Object.assign({},e.settings.characterReferences,{subset:(l==="'"?dt.single:dt.double)[a][o],attribute:!0}))+l}return i+(s&&"="+s)}var Mi=["<","&"];function gt(e,t,n,r){return n&&n.type==="element"&&(n.tagName==="script"||n.tagName==="style")?e.value:Y(e.value,Object.assign({},r.settings.characterReferences,{subset:Mi}))}function Wr(e,t,n,r){return r.settings.allowDangerousHtml?e.value:gt(e,t,n,r)}function zr(e,t,n,r){return r.all(e)}var Vr=Sr("type",{invalid:Gi,unknown:Fi,handlers:{comment:$r,doctype:Mr,element:Hr,raw:Wr,root:zr,text:gt}});function Gi(e){throw new Error("Expected node, not `"+e+"`")}function Fi(e){let t=e;throw new Error("Cannot compile unknown node `"+t.type+"`")}var Oi={},Di={},Ui=[];function rn(e,t){let n=t||Oi,r=n.quote||'"';if(r!=='"'&&r!=="'")throw new Error("Invalid quote `"+r+"`, expected `'` or `\"`");let a=r==='"'?"'":'"';return{one:qi,all:ji,settings:{omitOptionalTags:n.omitOptionalTags||!1,allowParseErrors:n.allowParseErrors||!1,allowDangerousCharacters:n.allowDangerousCharacters||!1,quoteSmart:n.quoteSmart||!1,preferUnquoted:n.preferUnquoted||!1,tightAttributes:n.tightAttributes||!1,upperDoctype:n.upperDoctype||!1,tightDoctype:n.tightDoctype||!1,bogusComments:n.bogusComments||!1,tightCommaSeparatedLists:n.tightCommaSeparatedLists||!1,tightSelfClosing:n.tightSelfClosing||!1,collapseEmptyAttributes:n.collapseEmptyAttributes||!1,allowDangerousHtml:n.allowDangerousHtml||!1,voids:n.voids||wr,characterReferences:n.characterReferences||Di,closeSelfClosing:n.closeSelfClosing||!1,closeEmptyElements:n.closeEmptyElements||!1},schema:n.space==="svg"?lt:st,quote:r,alternative:a}.one(Array.isArray(e)?{type:"root",children:e}:e,void 0,void 0)}function qi(e,t,n){return Vr(e,t,n,this)}function ji(e){let t=[],n=e&&e.children||Ui,r=-1;for(;++ra);function n(a){if(a===e.length)return{line:t.length-1,character:t.at(-1).length};let o=a,i=0;for(let s of t){if(on&&r.push({...e,content:e.content.slice(n,a),offset:e.offset+n}),n=a;return n>1);e[a]<=t?n=a+1:r=a}return n}function Xi(e,t){let n=[...t instanceof Set?t:new Set(t)].sort((r,a)=>r-a);return n.length?e.map(r=>r.flatMap(a=>{let o=a.offset+a.content.length,i=Vi(n,a.offset),s=i;for(;sht(e.variants[u])),s=new Set(i.flatMap(u=>Object.keys(u))),l={},c=(u,p)=>{let d=p==="color"?"":p==="background-color"?"-bg":`-${p}`;return n+t[u]+(p==="color"?"":d)};return i.forEach((u,p)=>{for(let d of s){let g=u[d]||"inherit";if(p===0&&r&&Wi.includes(d))if(r==="light-dark()"&&i.length>1){let h=t.findIndex(b=>b==="light"),y=t.findIndex(b=>b==="dark");if(h===-1||y===-1)throw new E('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');let w=i[h][d]||"inherit",m=i[y][d]||"inherit";l[d]=`light-dark(${w}, ${m})`,a==="css-vars"&&(l[c(p,d)]=g)}else l[d]=g;else a==="css-vars"&&(l[c(p,d)]=g)}}),o.htmlStyle=l,o}function ht(e){let t={};if(e.color&&(t.color=e.color),e.bgColor&&(t["background-color"]=e.bgColor),e.fontStyle){e.fontStyle&P.Italic&&(t["font-style"]="italic"),e.fontStyle&P.Bold&&(t["font-weight"]="bold");let n=[];e.fontStyle&P.Underline&&n.push("underline"),e.fontStyle&P.Strikethrough&&n.push("line-through"),n.length&&(t["text-decoration"]=n.join(" "))}return t}function on(e){return typeof e=="string"?e:Object.entries(e).map(([t,n])=>`${t}:${n}`).join(";")}function Qi(){let e=new WeakMap;function t(n){if(!e.has(n.meta)){let a=function(i){if(typeof i=="number"){if(i<0||i>n.source.length)throw new E(`Invalid decoration offset: ${i}. Code length: ${n.source.length}`);return{...r.indexToPos(i),offset:i}}else{let s=r.lines[i.line];if(s===void 0)throw new E(`Invalid decoration position ${JSON.stringify(i)}. Lines length: ${r.lines.length}`);let l=i.character;if(l<0&&(l=s.length+l),l<0||l>s.length)throw new E(`Invalid decoration position ${JSON.stringify(i)}. Line ${i.line} length: ${s.length}`);return{...i,character:l,offset:r.posToIndex(i.line,l)}}},r=Hi(n.source),o=(n.options.decorations||[]).map(i=>({...i,start:a(i.start),end:a(i.end)}));Yi(o),e.set(n.meta,{decorations:o,converter:r,source:n.source})}return e.get(n.meta)}return{name:"shiki:decorations",tokens(n){if(this.options.decorations?.length)return Xi(n,t(this).decorations.flatMap(r=>[r.start.offset,r.end.offset]))},code(n){if(!this.options.decorations?.length)return;let r=t(this),a=[...n.children].filter(u=>u.type==="element"&&u.tagName==="span");if(a.length!==r.converter.lines.length)throw new E(`Number of lines in code element (${a.length}) does not match the number of lines in the source (${r.converter.lines.length}). Failed to apply decorations.`);function o(u,p,d,g){let h=a[u],y="",w=-1,m=-1;if(p===0&&(w=0),d===0&&(m=0),d===Number.POSITIVE_INFINITY&&(m=h.children.length),w===-1||m===-1)for(let k=0;ky);return u.tagName=p.tagName||"span",u.properties={...u.properties,...g,class:u.properties.class},p.properties?.class&&Yr(u,p.properties.class),u=h(u,d)||u,u}let l=[],c=r.decorations.sort((u,p)=>p.start.offset-u.start.offset||u.end.offset-p.end.offset);for(let u of c){let{start:p,end:d}=u;if(p.line===d.line)o(p.line,p.character,d.character,u);else if(p.linei(g,u));o(d.line,0,d.character,u)}}l.forEach(u=>u())}}}function Yi(e){for(let t=0;tn.end.offset)throw new E(`Invalid decoration range: ${JSON.stringify(n.start)} - ${JSON.stringify(n.end)}`);for(let r=t+1;rNumber.parseInt(r));return n.length!==3||n.some(r=>Number.isNaN(r))?void 0:{type:"rgb",rgb:n}}else if(t==="5"){let n=e.shift();if(n)return{type:"table",index:Number(n)}}}function ts(e){let t=[];for(;e.length>0;){let n=e.shift();if(!n)continue;let r=Number.parseInt(n);if(!Number.isNaN(r))if(r===0)t.push({type:"resetAll"});else if(r<=9)an[r]&&t.push({type:"setDecoration",value:an[r]});else if(r<=29){let a=an[r-20];a&&(t.push({type:"resetDecoration",value:a}),a==="dim"&&t.push({type:"resetDecoration",value:"bold"}))}else if(r<=37)t.push({type:"setForegroundColor",value:{type:"named",name:de[r-30]}});else if(r===38){let a=Kr(e);a&&t.push({type:"setForegroundColor",value:a})}else if(r===39)t.push({type:"resetForegroundColor"});else if(r<=47)t.push({type:"setBackgroundColor",value:{type:"named",name:de[r-40]}});else if(r===48){let a=Kr(e);a&&t.push({type:"setBackgroundColor",value:a})}else r===49?t.push({type:"resetBackgroundColor"}):r===53?t.push({type:"setDecoration",value:"overline"}):r===55?t.push({type:"resetDecoration",value:"overline"}):r>=90&&r<=97?t.push({type:"setForegroundColor",value:{type:"named",name:de[r-90+8]}}):r>=100&&r<=107&&t.push({type:"setBackgroundColor",value:{type:"named",name:de[r-100+8]}})}return t}function ns(){let e=null,t=null,n=new Set;return{parse(r){let a=[],o=0;do{let i=es(r,o),s=i.sequence?r.substring(o,i.startPosition):r.substring(o);if(s.length>0&&a.push({value:s,foreground:e,background:t,decorations:new Set(n)}),i.sequence){let l=ts(i.sequence);for(let c of l)c.type==="resetAll"?(e=null,t=null,n.clear()):c.type==="resetForegroundColor"?e=null:c.type==="resetBackgroundColor"?t=null:c.type==="resetDecoration"&&n.delete(c.value);for(let c of l)c.type==="setForegroundColor"?e=c.value:c.type==="setBackgroundColor"?t=c.value:c.type==="setDecoration"&&n.add(c.value)}o=i.position}while(oMath.max(0,Math.min(l,255)).toString(16).padStart(2,"0")).join("")}`}let r;function a(){if(r)return r;r=[];for(let c=0;c{let l=`terminal.ansi${s[0].toUpperCase()}${s.substring(1)}`;return[s,e.colors?.[l]||ss[s]]}))),i=ns();return a.map(s=>i.parse(s[0]).map(l=>{let c,u;l.decorations.has("reverse")?(c=l.background?o.value(l.background):e.bg,u=l.foreground?o.value(l.foreground):e.fg):(c=l.foreground?o.value(l.foreground):e.fg,u=l.background?o.value(l.background):void 0),c=X(c,r),u=X(u,r),l.decorations.has("dim")&&(c=cs(c));let p=P.None;return l.decorations.has("bold")&&(p|=P.Bold),l.decorations.has("italic")&&(p|=P.Italic),l.decorations.has("underline")&&(p|=P.Underline),l.decorations.has("strikethrough")&&(p|=P.Strikethrough),{content:l.value,offset:s[1],color:c,bgColor:u,fontStyle:p}}))}function cs(e){let t=e.match(os);if(t){let r=t[1];if(r.length===8){let a=Math.round(Number.parseInt(r.slice(6,8),16)/2).toString(16).padStart(2,"0");return`#${r.slice(0,6)}${a}`}else{if(r.length===6)return`#${r}80`;if(r.length===4){let a=r[0],o=r[1],i=r[2],s=r[3];return`#${a}${a}${o}${o}${i}${i}${Math.round(Number.parseInt(`${s}${s}`,16)/2).toString(16).padStart(2,"0")}`}else if(r.length===3){let a=r[0],o=r[1],i=r[2];return`#${a}${a}${o}${o}${i}${i}80`}}}let n=e.match(is);return n?`var(${n[1]}-dim)`:e}function sn(e,t,n={}){let r=e.resolveLangAlias(n.lang||"text"),{theme:a=e.getLoadedThemes()[0]}=n;if(!$e(r)&&!Me(a)&&r==="ansi"){let{theme:o}=e.setTheme(a);return ls(o,t,n)}return Ht(e,t,n)}function mt(e,t,n){let r,a,o,i,s,l;if("themes"in n){let{defaultColor:c="light",cssVariablePrefix:u="--shiki-",colorsRendering:p="css-vars"}=n,d=Object.entries(n.themes).filter(m=>m[1]).map(m=>({color:m[0],theme:m[1]})).sort((m,b)=>m.color===c?-1:b.color===c?1:0);if(d.length===0)throw new E("`themes` option must not be empty");let g=rt(e,t,n,sn);if(l=ke(g),c&&c!=="light-dark()"&&!d.some(m=>m.color===c))throw new E(`\`themes\` option must contain the defaultColor key \`${c}\``);let h=d.map(m=>e.getTheme(m.theme)),y=d.map(m=>m.color);o=g.map(m=>m.map(b=>Ki(b,y,u,c,p))),l&&Ge(o,l);let w=d.map(m=>Pe(m.theme,n));a=Qr(d,h,w,u,c,"fg",p),r=Qr(d,h,w,u,c,"bg",p),i=`shiki-themes ${h.map(m=>m.name).join(" ")}`,s=c?void 0:[a,r].join(";")}else if("theme"in n){let c=Pe(n.theme,n);o=sn(e,t,n);let u=e.getTheme(n.theme);r=X(u.bg,c),a=X(u.fg,c),i=u.name,l=ke(o)}else throw new E("Invalid options, either `theme` or `themes` must be provided");return{tokens:o,fg:a,bg:r,themeName:i,rootStyle:s,grammarState:l}}function Qr(e,t,n,r,a,o,i){return e.map((s,l)=>{let c=X(t[l][o],n[l])||"inherit",u=`${r+s.color}${o==="bg"?"-bg":""}:${c}`;if(l===0&&a){if(a==="light-dark()"&&e.length>1){let p=e.findIndex(g=>g.color==="light"),d=e.findIndex(g=>g.color==="dark");if(p===-1||d===-1)throw new E('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');return`light-dark(${X(t[p][o],n[p])||"inherit"}, ${X(t[d][o],n[d])||"inherit"});${u}`}return c}return i==="css-vars"?u:null}).filter(s=>!!s).join(";")}var Zr=/^\s+$/,us=/^(\s*)(.*?)(\s*)$/;function bt(e,t,n,r={meta:{},options:n,codeToHast:(a,o)=>bt(e,a,o),codeToTokens:(a,o)=>mt(e,a,o)}){let a=t;for(let h of ft(n))a=h.preprocess?.call(r,a,n)||a;let{tokens:o,fg:i,bg:s,themeName:l,rootStyle:c,grammarState:u}=mt(e,a,n),{mergeWhitespaces:p=!0,mergeSameStyleTokens:d=!1}=n;p===!0?o=ds(o):p==="never"&&(o=gs(o)),d&&(o=hs(o));let g={...r,get source(){return a}};for(let h of ft(n))o=h.tokens?.call(g,o)||o;return ps(o,{...n,fg:i,bg:s,themeName:l,rootStyle:n.rootStyle===!1?!1:n.rootStyle??c},g,u)}function ps(e,t,n,r=ke(e)){let a=ft(t),o=[],i={type:"root",children:[]},{structure:s="classic",tabindex:l="0"}=t,c={class:`shiki ${t.themeName||""}`};t.rootStyle!==!1&&(t.rootStyle!=null?c.style=t.rootStyle:c.style=`background-color:${t.bg};color:${t.fg}`),l!==!1&&l!=null&&(c.tabindex=l.toString());for(let[y,w]of Object.entries(t.meta||{}))y.startsWith("_")||(c[y]=w);let u={type:"element",tagName:"pre",properties:c,children:[],data:t.data},p={type:"element",tagName:"code",properties:{},children:o},d=[],g={...n,structure:s,addClassToHast:Yr,get source(){return n.source},get tokens(){return e},get options(){return t},get root(){return i},get pre(){return u},get code(){return p},get lines(){return d}};if(e.forEach((y,w)=>{w&&(s==="inline"?i.children.push({type:"element",tagName:"br",properties:{},children:[]}):s==="classic"&&o.push({type:"text",value:` +`}));let m={type:"element",tagName:"span",properties:{class:"line"},children:[]},b=0;for(let k of y){let v={type:"element",tagName:"span",properties:{...k.htmlAttrs},children:[{type:"text",value:k.content}]},S=on(k.htmlStyle||ht(k));S&&(v.properties.style=S);for(let L of a)v=L?.span?.call(g,v,w+1,b,m,k)||v;s==="inline"?i.children.push(v):s==="classic"&&m.children.push(v),b+=k.content.length}if(s==="classic"){for(let k of a)m=k?.line?.call(g,m,w+1)||m;d.push(m),o.push(m)}else s==="inline"&&d.push(m)}),s==="classic"){for(let y of a)p=y?.code?.call(g,p)||p;u.children.push(p);for(let y of a)u=y?.pre?.call(g,u)||u;i.children.push(u)}else if(s==="inline"){let y=[],w={type:"element",tagName:"span",properties:{class:"line"},children:[]};for(let b of i.children)b.type==="element"&&b.tagName==="br"?(y.push(w),w={type:"element",tagName:"span",properties:{class:"line"},children:[]}):(b.type==="element"||b.type==="text")&&w.children.push(b);y.push(w);let m={type:"element",tagName:"code",properties:{},children:y};for(let b of a)m=b?.code?.call(g,m)||m;i.children=[];for(let b=0;b0&&i.children.push({type:"element",tagName:"br",properties:{},children:[]});let k=m.children[b];k.type==="element"&&i.children.push(...k.children)}}let h=i;for(let y of a)h=y?.root?.call(g,h)||h;return r&&Ge(h,r),h}function ds(e){return e.map(t=>{let n=[],r="",a;return t.forEach((o,i)=>{let s=!(o.fontStyle&&(o.fontStyle&P.Underline||o.fontStyle&P.Strikethrough));s&&Zr.test(o.content)&&t[i+1]?(a===void 0&&(a=o.offset),r+=o.content):r?(s?n.push({...o,offset:a,content:r+o.content}):n.push({content:r,offset:a},o),a=void 0,r=""):n.push(o)}),n})}function gs(e){return e.map(t=>t.flatMap(n=>{if(Zr.test(n.content))return n;let r=n.content.match(us);if(!r)return n;let[,a,o,i]=r;if(!a&&!i)return n;let s=[{...n,offset:n.offset+a.length,content:o}];return a&&s.unshift({content:a,offset:n.offset}),i&&s.push({content:i,offset:n.offset+a.length+o.length}),s}))}function hs(e){return e.map(t=>{let n=[];for(let r of t){if(n.length===0){n.push({...r});continue}let a=n.at(-1),o=on(a.htmlStyle||ht(a)),i=on(r.htmlStyle||ht(r)),s=a.fontStyle&&(a.fontStyle&P.Underline||a.fontStyle&P.Strikethrough),l=r.fontStyle&&(r.fontStyle&P.Underline||r.fontStyle&P.Strikethrough);!s&&!l&&o===i?a.content+=r.content:n.push({...r})}return n})}var fs=rn;function ms(e,t,n){let r={meta:{},options:n,codeToHast:(o,i)=>bt(e,o,i),codeToTokens:(o,i)=>mt(e,o,i)},a=fs(bt(e,t,n,r));for(let o of ft(n))a=o.postprocess?.call(r,a,n)||a;return a}async function ea(e){let t=await jt(e);return{getLastGrammarState:(...n)=>br(t,...n),codeToTokensBase:(n,r)=>sn(t,n,r),codeToTokensWithThemes:(n,r)=>rt(t,n,r),codeToTokens:(n,r)=>mt(t,n,r),codeToHast:(n,r)=>bt(t,n,r),codeToHtml:(n,r)=>ms(t,n,r),getBundledLanguages:()=>({}),getBundledThemes:()=>({}),...t,getInternalContext:()=>t}}var ta=class{patterns;options;regexps;constructor(e,t={}){this.patterns=e,this.options=t;let{forgiving:n=!1,cache:r,regexConstructor:a}=t;if(!a)throw new Error("Option `regexConstructor` is not provided");this.regexps=e.map(o=>{if(typeof o!="string")return o;let i=r?.get(o);if(i){if(i instanceof RegExp)return i;if(n)return null;throw i}try{let s=a(o);return r?.set(o,s),s}catch(s){if(r?.set(o,s),n)return null;throw s}})}findNextMatchSync(e,t,n){let r=typeof e=="string"?e:e.content,a=[];function o(i,s,l=0){return{index:i,captureIndices:s.indices.map(c=>c==null?{start:4294967295,end:4294967295,length:0}:{start:c[0]+l,end:c[1]+l,length:c[1]-c[0]})}}for(let i=0;is[1].index));for(let[s,l,c]of a)if(l.index===i)return o(s,l,c)}return null}};function ae(e){if([...e].length!==1)throw new Error(`Expected "${e}" to be a single code point`);return e.codePointAt(0)}function na(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}var Ue=new Set(["alnum","alpha","ascii","blank","cntrl","digit","graph","lower","print","punct","space","upper","word","xdigit"]),B=String.raw;function J(e,t){if(e==null)throw new Error(t??"Value expected");return e}var la=B`\[\^?`,ca=`c.? | C(?:-.?)?|${B`[pP]\{(?:\^?[-\x20_]*[A-Za-z][-\x20\w]*\})?`}|${B`x[89A-Fa-f]\p{AHex}(?:\\x[89A-Fa-f]\p{AHex})*`}|${B`u(?:\p{AHex}{4})? | x\{[^\}]*\}? | x\p{AHex}{0,2}`}|${B`o\{[^\}]*\}?`}|${B`\d{1,3}`}`,cn=/[?*+][?+]?|\{(?:\d+(?:,\d*)?|,\d+)\}\??/,yt=new RegExp(B` + \\ (?: + ${ca} + | [gk]<[^>]*>? + | [gk]'[^']*'? + | . + ) + | \( (?: + \? (?: + [:=!>({] + | <[=!] + | <[^>]*> + | '[^']*' + | ~\|? + | #(?:[^)\\]|\\.?)* + | [^:)]*[:)] + )? + | \*[^\)]*\)? + )? + | (?:${cn.source})+ + | ${la} + | . +`.replace(/\s+/g,""),"gsu"),ln=new RegExp(B` + \\ (?: + ${ca} + | . + ) + | \[:(?:\^?\p{Alpha}+|\^):\] + | ${la} + | && + | . +`.replace(/\s+/g,""),"gsu");function ua(e,t={}){let n={flags:"",...t,rules:{captureGroup:!1,singleline:!1,...t.rules}};if(typeof e!="string")throw new Error("String expected as pattern");let r=$s(n.flags),a=[r.extended],o={captureGroup:n.rules.captureGroup,getCurrentModX(){return a.at(-1)},numOpenGroups:0,popModX(){a.pop()},pushModX(p){a.push(p)},replaceCurrentModX(p){a[a.length-1]=p},singleline:n.rules.singleline},i=[],s;for(yt.lastIndex=0;s=yt.exec(e);){let p=bs(o,e,s[0],yt.lastIndex);p.tokens?i.push(...p.tokens):p.token&&i.push(p.token),p.lastIndex!==void 0&&(yt.lastIndex=p.lastIndex)}let l=[],c=0;i.filter(p=>p.type==="GroupOpen").forEach(p=>{p.kind==="capturing"?p.number=++c:p.raw==="("&&l.push(p)}),c||l.forEach((p,d)=>{p.kind="capturing",p.number=d+1});let u=c||l.length;return{tokens:i.map(p=>p.type==="EscapedNumber"?Gs(p,u):p).flat(),flags:r}}function bs(e,t,n,r){let[a,o]=n;if(n==="["||n==="[^"){let i=ys(t,n,r);return{tokens:i.tokens,lastIndex:i.lastIndex}}if(a==="\\"){if("AbBGyYzZ".includes(o))return{token:ra(n,n)};if(/^\\g[<']/.test(n)){if(!/^\\g(?:<[^>]+>|'[^']+')$/.test(n))throw new Error(`Invalid group name "${n}"`);return{token:Rs(n)}}if(/^\\k[<']/.test(n)){if(!/^\\k(?:<[^>]+>|'[^']+')$/.test(n))throw new Error(`Invalid group name "${n}"`);return{token:da(n)}}if(o==="K")return{token:ga("keep",n)};if(o==="N"||o==="R")return{token:ge("newline",n,{negate:o==="N"})};if(o==="O")return{token:ge("any",n)};if(o==="X")return{token:ge("text_segment",n)};let i=pa(n,{inCharClass:!1});return Array.isArray(i)?{tokens:i}:{token:i}}if(a==="("){if(o==="*")return{token:Ts(n)};if(n==="(?{")throw new Error(`Unsupported callout "${n}"`);if(n.startsWith("(?#")){if(t[r]!==")")throw new Error('Unclosed comment group "(?#"');return{lastIndex:r+1}}if(/^\(\?[-imx]+[:)]$/.test(n))return{token:Ns(n,e)};if(e.pushModX(e.getCurrentModX()),e.numOpenGroups++,n==="("&&!e.captureGroup||n==="(?:")return{token:xe("group",n)};if(n==="(?>")return{token:xe("atomic",n)};if(n==="(?="||n==="(?!"||n==="(?<="||n==="(?")||n.startsWith("(?'")&&n.endsWith("'"))return{token:xe("capturing",n,{...n!=="("&&{name:n.slice(3,-1)}})};if(n.startsWith("(?~")){if(n==="(?~|")throw new Error(`Unsupported absence function kind "${n}"`);return{token:xe("absence_repeater",n)}}throw n==="(?("?new Error(`Unsupported conditional "${n}"`):new Error(`Invalid or unsupported group option "${n}"`)}if(n===")"){if(e.popModX(),e.numOpenGroups--,e.numOpenGroups<0)throw new Error('Unmatched ")"');return{token:Ss(n)}}if(e.getCurrentModX()){if(n==="#"){let i=t.indexOf(` +`,r);return{lastIndex:i===-1?t.length:i}}if(/^\s$/.test(n)){let i=/\s+/y;return i.lastIndex=r,{lastIndex:i.exec(t)?i.lastIndex:r}}}if(n===".")return{token:ge("dot",n)};if(n==="^"||n==="$"){let i=e.singleline?{"^":B`\A`,$:B`\Z`}[n]:n;return{token:ra(i,n)}}return n==="|"?{token:ks(n)}:cn.test(n)?{tokens:Fs(n)}:{token:Z(ae(n),n)}}function ys(e,t,n){let r=[aa(t[1]==="^",t)],a=1,o;for(ln.lastIndex=n;o=ln.exec(e);){let i=o[0];if(i[0]==="["&&i[1]!==":")a++,r.push(aa(i[1]==="^",i));else if(i==="]"){if(r.at(-1).type==="CharacterClassOpen")r.push(Z(93,i));else if(a--,r.push(xs(i)),!a)break}else{let s=ws(i);Array.isArray(s)?r.push(...s):r.push(s)}}return{tokens:r,lastIndex:ln.lastIndex||e.length}}function ws(e){if(e[0]==="\\")return pa(e,{inCharClass:!0});if(e[0]==="["){let t=/\[:(?\^?)(?[a-z]+):\]/.exec(e);if(!t||!Ue.has(t.groups.name))throw new Error(`Invalid POSIX class "${e}"`);return ge("posix",e,{value:t.groups.name,negate:!!t.groups.negate})}return e==="-"?Cs(e):e==="&&"?vs(e):Z(ae(e),e)}function pa(e,{inCharClass:t}){let n=e[1];if(n==="c"||n==="C")return Bs(e);if("dDhHsSwW".includes(n))return Ls(e);if(e.startsWith(B`\o{`))throw new Error(`Incomplete, invalid, or unsupported octal code point "${e}"`);if(/^\\[pP]\{/.test(e)){if(e.length===3)throw new Error(`Incomplete or invalid Unicode property "${e}"`);return Ps(e)}if(/^\\x[89A-Fa-f]\p{AHex}/u.test(e))try{let r=e.split(/\\x/).slice(1).map(i=>parseInt(i,16)),a=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}).decode(new Uint8Array(r)),o=new TextEncoder;return[...a].map(i=>{let s=[...o.encode(i)].map(l=>`\\x${l.toString(16)}`).join("");return Z(ae(i),s)})}catch{throw new Error(`Multibyte code "${e}" incomplete or invalid in Oniguruma`)}if(n==="u"||n==="x")return Z(Ms(e),e);if(oa.has(n))return Z(oa.get(n),e);if(/\d/.test(n))return _s(t,e);if(e==="\\")throw new Error(B`Incomplete escape "\"`);if(n==="M")throw new Error(`Unsupported meta "${e}"`);if([...e].length===2)return Z(e.codePointAt(1),e);throw new Error(`Unexpected escape "${e}"`)}function ks(e){return{type:"Alternator",raw:e}}function ra(e,t){return{type:"Assertion",kind:e,raw:t}}function da(e){return{type:"Backreference",raw:e}}function Z(e,t){return{type:"Character",value:e,raw:t}}function xs(e){return{type:"CharacterClassClose",raw:e}}function Cs(e){return{type:"CharacterClassHyphen",raw:e}}function vs(e){return{type:"CharacterClassIntersector",raw:e}}function aa(e,t){return{type:"CharacterClassOpen",negate:e,raw:t}}function ge(e,t,n={}){return{type:"CharacterSet",kind:e,...n,raw:t}}function ga(e,t,n={}){return e==="keep"?{type:"Directive",kind:e,raw:t}:{type:"Directive",kind:e,flags:J(n.flags),raw:t}}function _s(e,t){return{type:"EscapedNumber",inCharClass:e,raw:t}}function Ss(e){return{type:"GroupClose",raw:e}}function xe(e,t,n={}){return{type:"GroupOpen",kind:e,...n,raw:t}}function Es(e,t,n,r){return{type:"NamedCallout",kind:e,tag:t,arguments:n,raw:r}}function As(e,t,n,r){return{type:"Quantifier",kind:e,min:t,max:n,raw:r}}function Rs(e){return{type:"Subroutine",raw:e}}var Is=new Set(["COUNT","CMP","ERROR","FAIL","MAX","MISMATCH","SKIP","TOTAL_COUNT"]),oa=new Map([["a",7],["b",8],["e",27],["f",12],["n",10],["r",13],["t",9],["v",11]]);function Bs(e){let t=e[1]==="c"?e[2]:e[3];if(!t||!/[A-Za-z]/.test(t))throw new Error(`Unsupported control character "${e}"`);return Z(ae(t.toUpperCase())-64,e)}function Ns(e,t){let{on:n,off:r}=/^\(\?(?[imx]*)(?:-(?[-imx]*))?/.exec(e).groups;r??="";let a=(t.getCurrentModX()||n.includes("x"))&&!r.includes("x"),o=sa(n),i=sa(r),s={};if(o&&(s.enable=o),i&&(s.disable=i),e.endsWith(")"))return t.replaceCurrentModX(a),ga("flags",e,{flags:s});if(e.endsWith(":"))return t.pushModX(a),t.numOpenGroups++,xe("group",e,{...(o||i)&&{flags:s}});throw new Error(`Unexpected flag modifier "${e}"`)}function Ts(e){let t=/\(\*(?[A-Za-z_]\w*)?(?:\[(?(?:[A-Za-z_]\w*)?)\])?(?:\{(?[^}]*)\})?\)/.exec(e);if(!t)throw new Error(`Incomplete or invalid named callout "${e}"`);let{name:n,tag:r,args:a}=t.groups;if(!n)throw new Error(`Invalid named callout "${e}"`);if(r==="")throw new Error(`Named callout tag with empty value not allowed "${e}"`);let o=a?a.split(",").filter(u=>u!=="").map(u=>/^[+-]?\d+$/.test(u)?+u:u):[],[i,s,l]=o,c=Is.has(n)?n.toLowerCase():"custom";switch(c){case"fail":case"mismatch":case"skip":if(o.length>0)throw new Error(`Named callout arguments not allowed "${o}"`);break;case"error":if(o.length>1)throw new Error(`Named callout allows only one argument "${o}"`);if(typeof i=="string")throw new Error(`Named callout argument must be a number "${i}"`);break;case"max":if(!o.length||o.length>2)throw new Error(`Named callout must have one or two arguments "${o}"`);if(typeof i=="string"&&!/^[A-Za-z_]\w*$/.test(i))throw new Error(`Named callout argument one must be a tag or number "${i}"`);if(o.length===2&&(typeof s=="number"||!/^[<>X]$/.test(s)))throw new Error(`Named callout optional argument two must be '<', '>', or 'X' "${s}"`);break;case"count":case"total_count":if(o.length>1)throw new Error(`Named callout allows only one argument "${o}"`);if(o.length===1&&(typeof i=="number"||!/^[<>X]$/.test(i)))throw new Error(`Named callout optional argument must be '<', '>', or 'X' "${i}"`);break;case"cmp":if(o.length!==3)throw new Error(`Named callout must have three arguments "${o}"`);if(typeof i=="string"&&!/^[A-Za-z_]\w*$/.test(i))throw new Error(`Named callout argument one must be a tag or number "${i}"`);if(typeof s=="number"||!/^(?:[<>!=]=|[<>])$/.test(s))throw new Error(`Named callout argument two must be '==', '!=', '>', '<', '>=', or '<=' "${s}"`);if(typeof l=="string"&&!/^[A-Za-z_]\w*$/.test(l))throw new Error(`Named callout argument three must be a tag or number "${l}"`);break;case"custom":throw new Error(`Undefined callout name "${n}"`);default:throw new Error(`Unexpected named callout kind "${c}"`)}return Es(c,r??null,a?.split(",")??null,e)}function ia(e){let t=null,n,r;if(e[0]==="{"){let{minStr:a,maxStr:o}=/^\{(?\d*)(?:,(?\d*))?/.exec(e).groups,i=1e5;if(+a>i||o&&+o>i)throw new Error("Quantifier value unsupported in Oniguruma");if(n=+a,r=o===void 0?+a:o===""?1/0:+o,n>r&&(t="possessive",[n,r]=[r,n]),e.endsWith("?")){if(t==="possessive")throw new Error('Unsupported possessive interval quantifier chain with "?"');t="lazy"}else t||(t="greedy")}else n=e[0]==="+"?1:0,r=e[0]==="?"?1:1/0,t=e[1]==="+"?"possessive":e[1]==="?"?"lazy":"greedy";return As(t,n,r,e)}function Ls(e){let t=e[1].toLowerCase();return ge({d:"digit",h:"hex",s:"space",w:"word"}[t],e,{negate:e[1]!==t})}function Ps(e){let{p:t,neg:n,value:r}=/^\\(?

[pP])\{(?\^?)(?[^}]+)/.exec(e).groups;return ge("property",e,{value:r,negate:t==="P"&&!n||t==="p"&&!!n})}function sa(e){let t={};return e.includes("i")&&(t.ignoreCase=!0),e.includes("m")&&(t.dotAll=!0),e.includes("x")&&(t.extended=!0),Object.keys(t).length?t:null}function $s(e){let t={ignoreCase:!1,dotAll:!1,extended:!1,digitIsAscii:!1,posixIsAscii:!1,spaceIsAscii:!1,wordIsAscii:!1,textSegmentMode:null};for(let n=0;n\p{AHex}+)/u.exec(e).groups.hex:e.slice(2);return parseInt(t,16)}function Gs(e,t){let{raw:n,inCharClass:r}=e,a=n.slice(1);if(!r&&(a!=="0"&&a.length===1||a[0]!=="0"&&+a<=t))return[da(n)];let o=[],i=a.match(/^[0-7]+|\d/g);for(let s=0;s127)throw new Error(B`Octal encoded byte above 177 unsupported "${n}"`)}else c=ae(l);o.push(Z(c,(s===0?"\\":"")+l))}return o}function Fs(e){let t=[],n=new RegExp(cn,"gy"),r;for(;r=n.exec(e);){let a=r[0];if(a[0]==="{"){let o=/^\{(?\d+),(?\d+)\}\??$/.exec(a);if(o){let{min:i,max:s}=o.groups;if(+i>+s&&a.endsWith("?")){n.lastIndex--,t.push(ia(a.slice(0,-1)));continue}}}t.push(ia(a))}return t}function wt(e,t){if(!Array.isArray(e.body))throw new Error("Expected node with body array");if(e.body.length!==1)return!1;let n=e.body[0];return!t||Object.keys(t).every(r=>t[r]===n[r])}function ha(e){return Os.has(e.type)}var Os=new Set(["AbsenceFunction","Backreference","CapturingGroup","Character","CharacterClass","CharacterSet","Group","Quantifier","Subroutine"]);function xt(e,t={}){let n={flags:"",normalizeUnknownPropertyNames:!1,skipBackrefValidation:!1,skipLookbehindValidation:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}},r=ua(e,{flags:n.flags,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline}}),a=(d,g)=>{let h=r.tokens[o.nextIndex];switch(o.parent=d,o.nextIndex++,h.type){case"Alternator":return ee();case"Assertion":return Ds(h);case"Backreference":return Us(h,o);case"Character":return Ce(h.value,{useLastValid:!!g.isCheckingRangeEnd});case"CharacterClassHyphen":return qs(h,o,g);case"CharacterClassOpen":return js(h,o,g);case"CharacterSet":return Hs(h,o);case"Directive":return Qs(h.kind,{flags:h.flags});case"GroupOpen":return Ws(h,o,g);case"NamedCallout":return Js(h.kind,h.tag,h.arguments);case"Quantifier":return zs(h,o);case"Subroutine":return Vs(h,o);default:throw new Error(`Unexpected token type "${h.type}"`)}},o={capturingGroups:[],hasNumberedRef:!1,namedGroupsByName:new Map,nextIndex:0,normalizeUnknownPropertyNames:n.normalizeUnknownPropertyNames,parent:null,skipBackrefValidation:n.skipBackrefValidation,skipLookbehindValidation:n.skipLookbehindValidation,skipPropertyNameValidation:n.skipPropertyNameValidation,subroutines:[],tokens:r.tokens,unicodePropertyMap:n.unicodePropertyMap,walk:a},i=el(Ys(r.flags)),s=i.body[0];for(;o.nextIndexl.length)throw new Error("Subroutine uses a group number that's not defined");d&&(l[d-1].isSubroutined=!0)}else if(u.has(d)){if(u.get(d).length>1)throw new Error(B`Subroutine uses a duplicate group name "\g<${d}>"`);u.get(d)[0].isSubroutined=!0}else throw new Error(B`Subroutine uses a group name that's not defined "\g<${d}>"`);return i}function Ds({kind:e}){return Ct(J({"^":"line_start",$:"line_end","\\A":"string_start","\\b":"word_boundary","\\B":"word_boundary","\\G":"search_start","\\y":"text_segment_boundary","\\Y":"text_segment_boundary","\\z":"string_end","\\Z":"string_end_newline"}[e],`Unexpected assertion kind "${e}"`),{negate:e===B`\B`||e===B`\Y`})}function Us({raw:e},t){let n=/^\\k[<']/.test(e),r=n?e.slice(3,-1):e.slice(1),a=(o,i=!1)=>{let s=t.capturingGroups.length,l=!1;if(o>s)if(t.skipBackrefValidation)l=!0;else throw new Error(`Not enough capturing groups defined to the left "${e}"`);return t.hasNumberedRef=!0,kt(i?s+1-o:o,{orphan:l})};if(n){let o=/^(?-?)0*(?[1-9]\d*)$/.exec(r);if(o)return a(+o.groups.num,!!o.groups.sign);if(/[-+]/.test(r))throw new Error(`Invalid backref name "${e}"`);if(!t.namedGroupsByName.has(r))throw new Error(`Group name not defined to the left "${e}"`);return kt(r)}return a(+r)}function qs(e,t,n){let{tokens:r,walk:a}=t,o=t.parent,i=o.body.at(-1),s=r[t.nextIndex];if(!n.isCheckingRangeEnd&&i&&i.type!=="CharacterClass"&&i.type!=="CharacterClassRange"&&s&&s.type!=="CharacterClassOpen"&&s.type!=="CharacterClassClose"&&s.type!=="CharacterClassIntersector"){let l=a(o,{...n,isCheckingRangeEnd:!0});if(i.type==="Character"&&l.type==="Character")return o.body.pop(),Ks(i,l);throw new Error("Invalid character class range")}return Ce(ae("-"))}function js({negate:e},t,n){let{tokens:r,walk:a}=t,o=[qe()],i=r[t.nextIndex],s=ba(i);for(;s.type!=="CharacterClassClose";){if(s.type==="CharacterClassIntersector")o.push(qe()),t.nextIndex++;else{let c=o.at(-1);c.body.push(a(c,n))}s=ba(r[t.nextIndex],i)}let l=qe({negate:e});return o.length===1?l.body=o[0].body:(l.kind="intersection",l.body=o.map(c=>c.body.length===1?c.body[0]:c)),t.nextIndex++,l}function Hs({kind:e,negate:t,value:n},r){let{normalizeUnknownPropertyNames:a,skipPropertyNameValidation:o,unicodePropertyMap:i}=r;if(e==="property"){let s=ve(n);if(Ue.has(s)&&!i?.has(s))e="posix",n=s;else return he(n,{negate:t,normalizeUnknownPropertyNames:a,skipPropertyNameValidation:o,unicodePropertyMap:i})}return e==="posix"?Zs(n,{negate:t}):vt(e,{negate:t})}function Ws(e,t,n){let{tokens:r,capturingGroups:a,namedGroupsByName:o,skipLookbehindValidation:i,walk:s}=t,l=tl(e),c=l.type==="AbsenceFunction",u=ma(l),p=u&&l.negate;if(l.type==="CapturingGroup"&&(a.push(l),l.name&&na(o,l.name,[]).push(l)),c&&n.isInAbsenceFunction)throw new Error("Nested absence function not supported by Oniguruma");let d=ya(r[t.nextIndex]);for(;d.type!=="GroupClose";){if(d.type==="Alternator")l.body.push(ee()),t.nextIndex++;else{let g=l.body.at(-1),h=s(g,{...n,isInAbsenceFunction:n.isInAbsenceFunction||c,isInLookbehind:n.isInLookbehind||u,isInNegLookbehind:n.isInNegLookbehind||p});if(g.body.push(h),(u||n.isInLookbehind)&&!i){let y="Lookbehind includes a pattern not allowed by Oniguruma";if(p||n.isInNegLookbehind){if(fa(h)||h.type==="CapturingGroup")throw new Error(y)}else if(fa(h)||ma(h)&&h.negate)throw new Error(y)}}d=ya(r[t.nextIndex])}return t.nextIndex++,l}function zs({kind:e,min:t,max:n},r){let a=r.parent,o=a.body.at(-1);if(!o||!ha(o))throw new Error("Quantifier requires a repeatable token");let i=pn(e,t,n,o);return a.body.pop(),i}function Vs({raw:e},t){let{capturingGroups:n,subroutines:r}=t,a=e.slice(3,-1),o=/^(?[-+]?)0*(?[1-9]\d*)$/.exec(a);if(o){let s=+o.groups.num,l=n.length;if(t.hasNumberedRef=!0,a={"":s,"+":l+s,"-":l+1-s}[o.groups.sign],a<1)throw new Error("Invalid subroutine number")}else a==="0"&&(a=0);let i=dn(a);return r.push(i),i}function Xs(e,t){if(e!=="repeater")throw new Error(`Unexpected absence function kind "${e}"`);return{type:"AbsenceFunction",kind:e,body:je(t?.body)}}function ee(e){return{type:"Alternative",body:wa(e?.body)}}function Ct(e,t){let n={type:"Assertion",kind:e};return(e==="word_boundary"||e==="text_segment_boundary")&&(n.negate=!!t?.negate),n}function kt(e,t){let n=!!t?.orphan;return{type:"Backreference",ref:e,...n&&{orphan:n}}}function un(e,t){let n={name:void 0,isSubroutined:!1,...t};if(n.name!==void 0&&!nl(n.name))throw new Error(`Group name "${n.name}" invalid in Oniguruma`);return{type:"CapturingGroup",number:e,...n.name&&{name:n.name},...n.isSubroutined&&{isSubroutined:n.isSubroutined},body:je(t?.body)}}function Ce(e,t){let n={useLastValid:!1,...t};if(e>1114111){let r=e.toString(16);if(n.useLastValid)e=1114111;else throw e>1310719?new Error(`Invalid code point out of range "\\x{${r}}"`):new Error(`Invalid code point out of range in JS "\\x{${r}}"`)}return{type:"Character",value:e}}function qe(e){let t={kind:"union",negate:!1,...e};return{type:"CharacterClass",kind:t.kind,negate:t.negate,body:wa(e?.body)}}function Ks(e,t){if(t.valuen)throw new Error("Invalid reversed quantifier range");return{type:"Quantifier",kind:e,min:t,max:n,body:r}}function el(e,t){return{type:"Regex",body:je(t?.body),flags:e}}function dn(e){return{type:"Subroutine",ref:e}}function he(e,t){let n={negate:!1,normalizeUnknownPropertyNames:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t},r=n.unicodePropertyMap?.get(ve(e));if(!r){if(n.normalizeUnknownPropertyNames)r=rl(e);else if(n.unicodePropertyMap&&!n.skipPropertyNameValidation)throw new Error(B`Invalid Unicode property "\p{${e}}"`)}return{type:"CharacterSet",kind:"property",value:r??e,negate:n.negate}}function tl({flags:e,kind:t,name:n,negate:r,number:a}){switch(t){case"absence_repeater":return Xs("repeater");case"atomic":return O({atomic:!0});case"capturing":return un(a,{name:n});case"group":return O({flags:e});case"lookahead":case"lookbehind":return oe({behind:t==="lookbehind",negate:r});default:throw new Error(`Unexpected group kind "${t}"`)}}function je(e){if(e===void 0)e=[ee()];else if(!Array.isArray(e)||!e.length||!e.every(t=>t.type==="Alternative"))throw new Error("Invalid body; expected array of one or more Alternative nodes");return e}function wa(e){if(e===void 0)e=[];else if(!Array.isArray(e)||!e.every(t=>!!t.type))throw new Error("Invalid body; expected array of nodes");return e}function fa(e){return e.type==="LookaroundAssertion"&&e.kind==="lookahead"}function ma(e){return e.type==="LookaroundAssertion"&&e.kind==="lookbehind"}function nl(e){return/^[\p{Alpha}\p{Pc}][^)]*$/u.test(e)}function rl(e){return e.trim().replace(/[- _]+/g,"_").replace(/[A-Z][a-z]+(?=[A-Z])/g,"$&_").replace(/[A-Za-z]+/g,t=>t[0].toUpperCase()+t.slice(1).toLowerCase())}function ve(e){return e.replace(/[- _]+/g,"").toLowerCase()}function ba(e,t){let n=t;return J(e,`Unclosed character class${n?.type==="Character"&&n.value===93&&n.raw==="]"?' (started with "]")':""}`)}function ya(e){return J(e,"Unclosed group")}function fe(e,t,n=null){function r(o,i){for(let s=0;sA-Za-z\-]|<[=!]|\(DEFINE\))`;function xa(e,t){for(let n=0;n=t&&e[n]++}function Ca(e,t,n,r){return e.slice(0,t)+r+e.slice(t+n.length)}var F=Object.freeze({DEFAULT:"DEFAULT",CHAR_CLASS:"CHAR_CLASS"});function He(e,t,n,r){let a=new RegExp(String.raw`${t}|(?<$skip>\[\^?|\\?.)`,"gsu"),o=[!1],i=0,s="";for(let l of e.matchAll(a)){let{0:c,groups:{$skip:u}}=l;if(!u&&(!r||r===F.DEFAULT==!i)){n instanceof Function?s+=n(l,{context:i?F.CHAR_CLASS:F.DEFAULT,negated:o[o.length-1]}):s+=n;continue}c[0]==="["?(i++,o.push(c[1]==="^")):c==="]"&&i&&(i--,o.pop()),s+=c}return s}function gn(e,t,n,r){He(e,t,n,r)}function al(e,t,n=0,r){if(!new RegExp(t,"su").test(e))return null;let a=new RegExp(`${t}|(?<$skip>\\\\?.)`,"gsu");a.lastIndex=n;let o=0,i;for(;i=a.exec(e);){let{0:s,groups:{$skip:l}}=i;if(!l&&(!r||r===F.DEFAULT==!o))return i;s==="["?o++:s==="]"&&o&&o--,a.lastIndex==i.index&&a.lastIndex++}return null}function We(e,t,n){return!!al(e,t,0,n)}function va(e,t){let n=/\\?./gsu;n.lastIndex=t;let r=e.length,a=0,o=1,i;for(;i=n.exec(e);){let[s]=i;if(s==="[")a++;else if(a)s==="]"&&a--;else if(s==="(")o++;else if(s===")"&&(o--,!o)){r=i.index;break}}return e.slice(t,r)}var _a=new RegExp(String.raw`(?${ka})|(?\((?:\?<[^>]+>)?)|\\?.`,"gsu");function fn(e,t){let n=t?.hiddenCaptures??[],r=t?.captureTransfers??new Map;if(!/\(\?>/.test(e))return{pattern:e,captureTransfers:r,hiddenCaptures:n};let a="(?>",o="(?:(?=(",i=[0],s=[],l=0,c=0,u=NaN,p;do{p=!1;let d=0,g=0,h=!1,y;for(_a.lastIndex=Number.isNaN(u)?0:u+o.length;y=_a.exec(e);){let{0:w,index:m,groups:{capturingStart:b,noncapturingStart:k}}=y;if(w==="[")d++;else if(d)w==="]"&&d--;else if(w===a&&!h)u=m,h=!0;else if(h&&k)g++;else if(b)h?g++:(l++,i.push(l+c));else if(w===")"&&h){if(!g){c++;let v=l+c;if(e=`${e.slice(0,u)}${o}${e.slice(u+a.length,m)}))<$$${v}>)${e.slice(m+1)}`,p=!0,s.push(v),xa(n,v),r.size){let S=new Map;r.forEach((L,M)=>{S.set(M>=v?M+1:M,L.map(H=>H>=v?H+1:H))}),r=S}break}g--}}}while(p);return n.push(...s),e=He(e,String.raw`\\(?[1-9]\d*)|<\$\$(?\d+)>`,({0:d,groups:{backrefNum:g,wrappedBackrefNum:h}})=>{if(g){let y=+g;if(y>i.length-1)throw new Error(`Backref "${d}" greater than number of captures`);return`\\${i[y]}`}return`\\${h}`},F.DEFAULT),{pattern:e,captureTransfers:r,hiddenCaptures:n}}var Sa=String.raw`(?:[?*+]|\{\d+(?:,\d*)?\})`,hn=new RegExp(String.raw` +\\(?: \d+ + | c[A-Za-z] + | [gk]<[^>]+> + | [pPu]\{[^\}]+\} + | u[A-Fa-f\d]{4} + | x[A-Fa-f\d]{2} + ) +| \((?: \? (?: [:=!>] + | <(?:[=!]|[^>]+>) + | [A-Za-z\-]+: + | \(DEFINE\) + ))? +| (?${Sa})(?[?+]?)(?[?*+\{]?) +| \\?. +`.replace(/\s+/g,""),"gsu");function mn(e){if(!new RegExp(`${Sa}\\+`).test(e))return{pattern:e};let t=[],n=null,r=null,a="",o=0,i;for(hn.lastIndex=0;i=hn.exec(e);){let{0:s,index:l,groups:{qBase:c,qMod:u,invalidQ:p}}=i;if(s==="[")o||(r=l),o++;else if(s==="]")o?o--:r=null;else if(!o)if(u==="+"&&a&&!a.startsWith("(")){if(p)throw new Error(`Invalid quantifier "${s}"`);let d=-1;if(/^\{\d+\}$/.test(c))e=Ca(e,l+c.length,u,"");else{if(a===")"||a==="]"){let g=a===")"?n:r;if(g===null)throw new Error(`Invalid unmatched "${a}"`);e=`${e.slice(0,g)}(?>${e.slice(g,l)}${c})${e.slice(l+s.length)}`}else e=`${e.slice(0,l-a.length)}(?>${a}${c})${e.slice(l+s.length)}`;d+=4}hn.lastIndex+=d}else s[0]==="("?t.push(l):s===")"&&(n=t.length?t.pop():null);a=s}return{pattern:e}}var q=String.raw,ol=q`\\g<(?[^>&]+)&R=(?[^>]+)>`,yn=q`\(\?R=(?[^\)]+)\)|${ol}`,St=q`\(\?<(?![=!])(?[^>]+)>`,Ba=q`${St}|(?\()(?!\?)`,me=new RegExp(q`${St}|${yn}|\(\?|\\?.`,"gsu"),bn="Cannot use multiple overlapping recursions";function Na(e,t){let{hiddenCaptures:n,mode:r}={hiddenCaptures:[],mode:"plugin",...t},a=t?.captureTransfers??new Map;if(!new RegExp(yn,"su").test(e))return{pattern:e,captureTransfers:a,hiddenCaptures:n};if(r==="plugin"&&We(e,q`\(\?\(DEFINE\)`,F.DEFAULT))throw new Error("DEFINE groups cannot be used with recursion");let o=[],i=We(e,q`\\[1-9]`,F.DEFAULT),s=new Map,l=[],c=!1,u=0,p=0,d;for(me.lastIndex=0;d=me.exec(e);){let{0:g,groups:{captureName:h,rDepth:y,gRNameOrNum:w,gRDepth:m}}=d;if(g==="[")u++;else if(u)g==="]"&&u--;else if(y){if(Ea(y),c)throw new Error(bn);if(i)throw new Error(`${r==="external"?"Backrefs":"Numbered backrefs"} cannot be used with global recursion`);let b=e.slice(0,d.index),k=e.slice(me.lastIndex);if(We(k,yn,F.DEFAULT))throw new Error(bn);let v=+y-1;e=Aa(b,k,v,!1,n,o,p),a=Ia(a,b,v,o.length,0,p);break}else if(w){Ea(m);let b=!1;for(let W of l)if(W.name===w||W.num===+w){if(b=!0,W.hasRecursedWithin)throw new Error(bn);break}if(!b)throw new Error(q`Recursive \g cannot be used outside the referenced group "${r==="external"?w:q`\g<${w}&R=${m}>`}"`);let k=s.get(w),v=va(e,k);if(i&&We(v,q`${St}|\((?!\?)`,F.DEFAULT))throw new Error(`${r==="external"?"Backrefs":"Numbered backrefs"} cannot be used with recursion of capturing groups`);let S=e.slice(k,d.index),L=v.slice(S.length+g.length),M=o.length,H=+m-1,be=Aa(S,L,H,!0,n,o,p);a=Ia(a,S,H,o.length-M,M,p);let Rt=e.slice(0,k),It=e.slice(k+v.length);e=`${Rt}${be}${It}`,me.lastIndex+=be.length-g.length-S.length-L.length,l.forEach(W=>W.hasRecursedWithin=!0),c=!0}else if(h)p++,s.set(String(p),me.lastIndex),s.set(h,me.lastIndex),l.push({num:p,name:h});else if(g[0]==="("){let b=g==="(";b&&(p++,s.set(String(p),me.lastIndex)),l.push(b?{num:p}:{})}else g===")"&&l.pop()}return n.push(...o),{pattern:e,captureTransfers:a,hiddenCaptures:n}}function Ea(e){let t=`Max depth must be integer between 2 and 100; used ${e}`;if(!/^[1-9]\d*$/.test(e))throw new Error(t);if(e=+e,e<2||e>100)throw new Error(t)}function Aa(e,t,n,r,a,o,i){let s=new Set;r&&gn(e+t,St,({groups:{captureName:c}})=>{s.add(c)},F.DEFAULT);let l=[n,r?s:null,a,o,i];return`${e}${Ra(`(?:${e}`,"forward",...l)}(?:)${Ra(`${t})`,"backward",...l)}${t}`}function Ra(e,t,n,r,a,o,i){let l=u=>t==="forward"?u+2:n-u+2-1,c="";for(let u=0;u[^>]+)>`,({0:d,groups:{captureName:g,unnamed:h,backref:y}})=>{if(y&&r&&!r.has(y))return d;let w=`_$${p}`;if(h||g){let m=i+o.length+1;return o.push(m),il(a,m),h?d:`(?<${g}${w}>`}return q`\k<${y}${w}>`},F.DEFAULT)}return c}function il(e,t){for(let n=0;n=t&&e[n]++}function Ia(e,t,n,r,a,o){if(e.size&&r){let i=0;gn(t,Ba,()=>i++,F.DEFAULT);let s=o-i+a,l=new Map;return e.forEach((c,u)=>{let p=(r-i*n)/n,d=i*n,g=u>s+i?u+r:u,h=[];for(let y of c)if(y<=s)h.push(y);else if(y>s+i+p)h.push(y+r);else if(y<=s+i)for(let w=0;w<=n;w++)h.push(y+i*w);else for(let w=0;w<=n;w++)h.push(y+d+p*w);l.set(g,h)}),l}return e}var N=String.fromCodePoint,C=String.raw,j={},At=globalThis.RegExp;j.flagGroups=(()=>{try{new At("(?i:)")}catch{return!1}return!0})();j.unicodeSets=(()=>{try{new At("[[]]","v")}catch{return!1}return!0})();j.bugFlagVLiteralHyphenIsRange=j.unicodeSets?(()=>{try{new At(C`[\d\-a]`,"v")}catch{return!0}return!1})():!1;j.bugNestedClassIgnoresNegation=j.unicodeSets&&new At("[[^a]]","v").test("a");function Et(e,{enable:t,disable:n}){return{dotAll:!n?.dotAll&&!!(t?.dotAll||e.dotAll),ignoreCase:!n?.ignoreCase&&!!(t?.ignoreCase||e.ignoreCase)}}function ze(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}function vn(e,t){return Ta[e]>=Ta[t]}function sl(e,t){if(e==null)throw new Error(t??"Value expected");return e}var Ta={ES2025:2025,ES2024:2024,ES2018:2018},ll={auto:"auto",ES2025:"ES2025",ES2024:"ES2024",ES2018:"ES2018"};function Ga(e={}){if({}.toString.call(e)!=="[object Object]")throw new Error("Unexpected options");if(e.target!==void 0&&!ll[e.target])throw new Error(`Unexpected target "${e.target}"`);let t={accuracy:"default",avoidSubclass:!1,flags:"",global:!1,hasIndices:!1,lazyCompileLength:1/0,target:"auto",verbose:!1,...e,rules:{allowOrphanBackrefs:!1,asciiWordBoundaries:!1,captureGroup:!1,recursionLimit:20,singleline:!1,...e.rules}};return t.target==="auto"&&(t.target=j.flagGroups?"ES2025":j.unicodeSets?"ES2024":"ES2018"),t}var cl="[ -\r ]",ul=new Set([N(304),N(305)]),te=C`[\p{L}\p{M}\p{N}\p{Pc}]`;function Fa(e){if(ul.has(e))return[e];let t=new Set,n=e.toLowerCase(),r=n.toUpperCase(),a=gl.get(n),o=pl.get(n),i=dl.get(n);return[...r].length===1&&t.add(r),i&&t.add(i),a&&t.add(a),t.add(n),o&&t.add(o),[...t]}var Sn=new Map(`C Other +Cc Control cntrl +Cf Format +Cn Unassigned +Co Private_Use +Cs Surrogate +L Letter +LC Cased_Letter +Ll Lowercase_Letter +Lm Modifier_Letter +Lo Other_Letter +Lt Titlecase_Letter +Lu Uppercase_Letter +M Mark Combining_Mark +Mc Spacing_Mark +Me Enclosing_Mark +Mn Nonspacing_Mark +N Number +Nd Decimal_Number digit +Nl Letter_Number +No Other_Number +P Punctuation punct +Pc Connector_Punctuation +Pd Dash_Punctuation +Pe Close_Punctuation +Pf Final_Punctuation +Pi Initial_Punctuation +Po Other_Punctuation +Ps Open_Punctuation +S Symbol +Sc Currency_Symbol +Sk Modifier_Symbol +Sm Math_Symbol +So Other_Symbol +Z Separator +Zl Line_Separator +Zp Paragraph_Separator +Zs Space_Separator +ASCII +ASCII_Hex_Digit AHex +Alphabetic Alpha +Any +Assigned +Bidi_Control Bidi_C +Bidi_Mirrored Bidi_M +Case_Ignorable CI +Cased +Changes_When_Casefolded CWCF +Changes_When_Casemapped CWCM +Changes_When_Lowercased CWL +Changes_When_NFKC_Casefolded CWKCF +Changes_When_Titlecased CWT +Changes_When_Uppercased CWU +Dash +Default_Ignorable_Code_Point DI +Deprecated Dep +Diacritic Dia +Emoji +Emoji_Component EComp +Emoji_Modifier EMod +Emoji_Modifier_Base EBase +Emoji_Presentation EPres +Extended_Pictographic ExtPict +Extender Ext +Grapheme_Base Gr_Base +Grapheme_Extend Gr_Ext +Hex_Digit Hex +IDS_Binary_Operator IDSB +IDS_Trinary_Operator IDST +ID_Continue IDC +ID_Start IDS +Ideographic Ideo +Join_Control Join_C +Logical_Order_Exception LOE +Lowercase Lower +Math +Noncharacter_Code_Point NChar +Pattern_Syntax Pat_Syn +Pattern_White_Space Pat_WS +Quotation_Mark QMark +Radical +Regional_Indicator RI +Sentence_Terminal STerm +Soft_Dotted SD +Terminal_Punctuation Term +Unified_Ideograph UIdeo +Uppercase Upper +Variation_Selector VS +White_Space space +XID_Continue XIDC +XID_Start XIDS`.split(/\s/).map(e=>[ve(e),e])),pl=new Map([["s",N(383)],[N(383),"s"]]),dl=new Map([[N(223),N(7838)],[N(107),N(8490)],[N(229),N(8491)],[N(969),N(8486)]]),gl=new Map([ie(453),ie(456),ie(459),ie(498),...wn(8072,8079),...wn(8088,8095),...wn(8104,8111),ie(8124),ie(8140),ie(8188)]),hl=new Map([["alnum",C`[\p{Alpha}\p{Nd}]`],["alpha",C`\p{Alpha}`],["ascii",C`\p{ASCII}`],["blank",C`[\p{Zs}\t]`],["cntrl",C`\p{Cc}`],["digit",C`\p{Nd}`],["graph",C`[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]`],["lower",C`\p{Lower}`],["print",C`[[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]\p{Zs}]`],["punct",C`[\p{P}\p{S}]`],["space",C`\p{space}`],["upper",C`\p{Upper}`],["word",C`[\p{Alpha}\p{M}\p{Nd}\p{Pc}]`],["xdigit",C`\p{AHex}`]]);function fl(e,t){let n=[];for(let r=e;r<=t;r++)n.push(r);return n}function ie(e){let t=N(e);return[t.toLowerCase(),t]}function wn(e,t){return fl(e,t).map(n=>ie(n))}var Oa=new Set(["Lower","Lowercase","Upper","Uppercase","Ll","Lowercase_Letter","Lt","Titlecase_Letter","Lu","Uppercase_Letter"]);function ml(e,t){let n={accuracy:"default",asciiWordBoundaries:!1,avoidSubclass:!1,bestEffortTarget:"ES2025",...t};Da(e);let r={accuracy:n.accuracy,asciiWordBoundaries:n.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,flagDirectivesByAlt:new Map,jsGroupNameMap:new Map,minTargetEs2024:vn(n.bestEffortTarget,"ES2024"),passedLookbehind:!1,strategy:null,subroutineRefMap:new Map,supportedGNodes:new Set,digitIsAscii:e.flags.digitIsAscii,spaceIsAscii:e.flags.spaceIsAscii,wordIsAscii:e.flags.wordIsAscii};fe(e,bl,r);let a={dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},o={currentFlags:a,prevFlags:null,globalFlags:a,groupOriginByCopy:new Map,groupsByName:new Map,multiplexCapturesToLeftByRef:new Map,openRefs:new Map,reffedNodesByReferencer:new Map,subroutineRefMap:r.subroutineRefMap};fe(e,yl,o);let i={groupsByName:o.groupsByName,highestOrphanBackref:0,numCapturesToLeft:0,reffedNodesByReferencer:o.reffedNodesByReferencer};return fe(e,wl,i),e._originMap=o.groupOriginByCopy,e._strategy=r.strategy,e}var bl={AbsenceFunction({node:e,parent:t,replaceWith:n}){let{body:r,kind:a}=e;if(a==="repeater"){let o=O();o.body[0].body.push(oe({negate:!0,body:r}),he("Any"));let i=O();i.body[0].body.push(pn("greedy",0,1/0,o)),n(I(i,t),{traverse:!0})}else throw new Error('Unsupported absence function "(?~|"')},Alternative:{enter({node:e,parent:t,key:n},{flagDirectivesByAlt:r}){let a=e.body.filter(o=>o.kind==="flags");for(let o=n+1;o\r\n|${a?C`\p{RGI_Emoji}`:d}|\P{M}\p{M}*)`,{skipPropertyNameValidation:!0}),t))}else if(l==="hex")n(se(he("AHex",{negate:c}),t));else if(l==="newline")n(I(ne(c?`[^ +]`:`(?>\r +?|[ +\v\f\x85\u2028\u2029])`),t));else if(l==="posix")if(!a&&(u==="graph"||u==="print")){if(r==="strict")throw new Error(`POSIX class "${u}" requires min target ES2024 or non-strict accuracy`);let p={graph:"!-~",print:" -~"}[u];c&&(p=`\0-${N(p.codePointAt(0)-1)}${N(p.codePointAt(2)+1)}-\u{10FFFF}`),n(I(ne(`[${p}]`),t))}else n(I(Cn(ne(hl.get(u)),c),t));else if(l==="property")Sn.has(ve(u))||(e.key="sc");else if(l==="space")n(se(he("space",{negate:c}),t));else if(l==="word")n(I(Cn(ne(te),c),t));else throw new Error(`Unexpected character set kind "${l}"`)},Directive({node:e,parent:t,root:n,remove:r,replaceWith:a,removeAllPrevSiblings:o,removeAllNextSiblings:i}){let{kind:s,flags:l}=e;if(s==="flags")if(!l.enable&&!l.disable)r();else{let c=O({flags:l});c.body[0].body=i(),a(I(c,t),{traverse:!0})}else if(s==="keep"){let c=n.body[0],p=n.body.length===1&&wt(c,{type:"Group"})&&c.body[0].body.length===1?c.body[0]:n;if(t.parent!==p||p.body.length>1)throw new Error(C`Uses "\K" in a way that's unsupported`);let d=oe({behind:!0});d.body[0].body=o(),a(I(d,t))}else throw new Error(`Unexpected directive kind "${s}"`)},Flags({node:e,parent:t}){if(e.posixIsAscii)throw new Error('Unsupported flag "P"');if(e.textSegmentMode==="word")throw new Error('Unsupported flag "y{w}"');["digitIsAscii","extended","posixIsAscii","spaceIsAscii","wordIsAscii","textSegmentMode"].forEach(n=>delete e[n]),Object.assign(e,{global:!1,hasIndices:!1,multiline:!1,sticky:e.sticky??!1}),t.options={disable:{x:!0,n:!0},force:{v:!0}}},Group({node:e}){if(!e.flags)return;let{enable:t,disable:n}=e.flags;t?.extended&&delete t.extended,n?.extended&&delete n.extended,t?.dotAll&&n?.dotAll&&delete t.dotAll,t?.ignoreCase&&n?.ignoreCase&&delete t.ignoreCase,t&&!Object.keys(t).length&&delete e.flags.enable,n&&!Object.keys(n).length&&delete e.flags.disable,!e.flags.enable&&!e.flags.disable&&delete e.flags},LookaroundAssertion({node:e},t){let{kind:n}=e;n==="lookbehind"&&(t.passedLookbehind=!0)},NamedCallout({node:e,parent:t,replaceWith:n}){let{kind:r}=e;if(r==="fail")n(I(oe({negate:!0}),t));else throw new Error(`Unsupported named callout "(*${r.toUpperCase()}"`)},Quantifier({node:e}){if(e.body.type==="Quantifier"){let t=O();t.body[0].body.push(e.body),e.body=I(t,e)}},Regex:{enter({node:e},{supportedGNodes:t}){let n=[],r=!1,a=!1;for(let o of e.body)if(o.body.length===1&&o.body[0].kind==="search_start")o.body.pop();else{let i=Ha(o.body);i?(r=!0,Array.isArray(i)?n.push(...i):n.push(i)):a=!0}r&&!a&&n.forEach(o=>t.add(o))},exit(e,{accuracy:t,passedLookbehind:n,strategy:r}){if(t==="strict"&&n&&r)throw new Error(C`Uses "\G" in a way that requires non-strict accuracy`)}},Subroutine({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n=="string"&&!xn(n)&&(n=kn(n,t),e.ref=n)}},yl={Backreference({node:e},{multiplexCapturesToLeftByRef:t,reffedNodesByReferencer:n}){let{orphan:r,ref:a}=e;r||n.set(e,[...t.get(a).map(({node:o})=>o)])},CapturingGroup:{enter({node:e,parent:t,replaceWith:n,skip:r},{groupOriginByCopy:a,groupsByName:o,multiplexCapturesToLeftByRef:i,openRefs:s,reffedNodesByReferencer:l}){let c=a.get(e);if(c&&s.has(e.number)){let p=se(La(e.number),t);l.set(p,s.get(e.number)),n(p);return}s.set(e.number,e),i.set(e.number,[]),e.name&&ze(i,e.name,[]);let u=i.get(e.name??e.number);for(let p=0;pd.type==="Group"&&!!d.flags)),p=u?Et(r.globalFlags,u):r.globalFlags;kl(p,r.currentFlags)||(c=O({flags:vl(p)}),c.body[0].body.push(l))}n(I(c,t),{traverse:!s})}},wl={Backreference({node:e,parent:t,replaceWith:n},r){if(e.orphan){r.highestOrphanBackref=Math.max(r.highestOrphanBackref,e.ref);return}let o=r.reffedNodesByReferencer.get(e).filter(i=>xl(i,e));if(!o.length)n(I(oe({negate:!0}),t));else if(o.length>1){let i=O({atomic:!0,body:o.reverse().map(s=>ee({body:[kt(s.number)]}))});n(I(i,t))}else e.ref=o[0].number},CapturingGroup({node:e},t){e.number=++t.numCapturesToLeft,e.name&&t.groupsByName.get(e.name).get(e).hasDuplicateNameToRemove&&delete e.name},Regex:{exit({node:e},t){let n=Math.max(t.highestOrphanBackref-t.numCapturesToLeft,0);for(let r=0;r{t.forEach(a=>{r.enable?.[a]&&(delete n.disable[a],n.enable[a]=!0),r.disable?.[a]&&(n.disable[a]=!0)})}),Object.keys(n.enable).length||delete n.enable,Object.keys(n.disable).length||delete n.disable,n.enable||n.disable?n:null}function vl({dotAll:e,ignoreCase:t}){let n={};return(e||t)&&(n.enable={},e&&(n.enable.dotAll=!0),t&&(n.enable.ignoreCase=!0)),(!e||!t)&&(n.disable={},!e&&(n.disable.dotAll=!0),!t&&(n.disable.ignoreCase=!0)),n}function ja(e){if(!e)throw new Error("Node expected");let{body:t}=e;return Array.isArray(t)?t:t?[t]:null}function Ha(e){let t=e.find(n=>n.kind==="search_start"||El(n,{negate:!1})||!_l(n));if(!t)return null;if(t.kind==="search_start")return t;if(t.type==="LookaroundAssertion")return t.body[0].body[0];if(t.type==="CapturingGroup"||t.type==="Group"){let n=[];for(let r of t.body){let a=Ha(r.body);if(!a)return null;Array.isArray(a)?n.push(...a):n.push(a)}return n}return null}function Wa(e,t){let n=ja(e)??[];for(let r of n)if(r===t||Wa(r,t))return!0;return!1}function _l({type:e}){return e==="Assertion"||e==="Directive"||e==="LookaroundAssertion"}function Sl(e){let t=["Character","CharacterClass","CharacterSet"];return t.includes(e.type)||e.type==="Quantifier"&&e.min&&t.includes(e.body.type)}function El(e,t){let n={negate:null,...t};return e.type==="LookaroundAssertion"&&(n.negate===null||e.negate===n.negate)&&e.body.length===1&&wt(e.body[0],{type:"Assertion",kind:"search_start"})}function xn(e){return/^[$_\p{IDS}][$\u200C\u200D\p{IDC}]*$/u.test(e)}function ne(e,t){let r=xt(e,{...t,unicodePropertyMap:Sn}).body;return r.length>1||r[0].body.length>1?O({body:r}):r[0].body[0]}function Cn(e,t){return e.negate=t,e}function se(e,t){return e.parent=t,e}function I(e,t){return Da(e),e.parent=t,e}function Al(e,t){let n=Ga(t),r=vn(n.target,"ES2024"),a=vn(n.target,"ES2025"),o=n.rules.recursionLimit;if(!Number.isInteger(o)||o<2||o>20)throw new Error("Invalid recursionLimit; use 2-20");let i=null,s=null;if(!a){let g=[e.flags.ignoreCase];fe(e,Rl,{getCurrentModI:()=>g.at(-1),popModI(){g.pop()},pushModI(h){g.push(h)},setHasCasedChar(){g.at(-1)?i=!0:s=!0}})}let l={dotAll:e.flags.dotAll,ignoreCase:!!((e.flags.ignoreCase||i)&&!s)},c=e,u={accuracy:n.accuracy,appliedGlobalFlags:l,captureMap:new Map,currentFlags:{dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},inCharClass:!1,lastNode:c,originMap:e._originMap,recursionLimit:o,useAppliedIgnoreCase:!!(!a&&i&&s),useFlagMods:a,useFlagV:r,verbose:n.verbose};function p(g){return u.lastNode=c,c=g,sl(Il[g.type],`Unexpected node type "${g.type}"`)(g,u,p)}let d={pattern:e.body.map(p).join("|"),flags:p(e.flags),options:{...e.options}};return r||(delete d.options.force.v,d.options.disable.v=!0,d.options.unicodeSetsPlugin=null),d._captureTransfers=new Map,d._hiddenCaptures=[],u.captureMap.forEach((g,h)=>{g.hidden&&d._hiddenCaptures.push(h),g.transferTo&&ze(d._captureTransfers,g.transferTo,[]).push(h)}),d}var Rl={"*":{enter({node:e},t){if($a(e)){let n=t.getCurrentModI();t.pushModI(e.flags?Et({ignoreCase:n},e.flags).ignoreCase:n)}},exit({node:e},t){$a(e)&&t.popModI()}},Backreference(e,t){t.setHasCasedChar()},Character({node:e},t){En(N(e.value))&&t.setHasCasedChar()},CharacterClassRange({node:e,skip:t},n){t(),za(e,{firstOnly:!0}).length&&n.setHasCasedChar()},CharacterSet({node:e},t){e.kind==="property"&&Oa.has(e.value)&&t.setHasCasedChar()}},Il={Alternative({body:e},t,n){return e.map(n).join("")},Assertion({kind:e,negate:t}){if(e==="string_end")return"$";if(e==="string_start")return"^";if(e==="word_boundary")return t?C`\B`:C`\b`;throw new Error(`Unexpected assertion kind "${e}"`)},Backreference({ref:e},t){if(typeof e!="number")throw new Error("Unexpected named backref in transformed AST");if(!t.useFlagMods&&t.accuracy==="strict"&&t.currentFlags.ignoreCase&&!t.captureMap.get(e).ignoreCase)throw new Error("Use of case-insensitive backref to case-sensitive group requires target ES2025 or non-strict accuracy");return"\\"+e},CapturingGroup(e,t,n){let{body:r,name:a,number:o}=e,i={ignoreCase:t.currentFlags.ignoreCase},s=t.originMap.get(e);return s&&(i.hidden=!0,o>s.number&&(i.transferTo=s.number)),t.captureMap.set(o,i),`(${a?`?<${a}>`:""}${r.map(n).join("|")})`},Character({value:e},t){let n=N(e),r=Se(e,{escDigit:t.lastNode.type==="Backreference",inCharClass:t.inCharClass,useFlagV:t.useFlagV});if(r!==n)return r;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&En(n)){let a=Fa(n);return t.inCharClass?a.join(""):a.length>1?`[${a.join("")}]`:a[0]}return n},CharacterClass(e,t,n){let{kind:r,negate:a,parent:o}=e,{body:i}=e;if(r==="intersection"&&!t.useFlagV)throw new Error("Use of character class intersection requires min target ES2024");j.bugFlagVLiteralHyphenIsRange&&t.useFlagV&&i.some(Ma)&&(i=[Ce(45),...i.filter(c=>!Ma(c))]);let s=()=>`[${a?"^":""}${i.map(n).join(r==="intersection"?"&&":"")}]`;if(!t.inCharClass){if((!t.useFlagV||j.bugNestedClassIgnoresNegation)&&!a){let u=i.filter(p=>p.type==="CharacterClass"&&p.kind==="union"&&p.negate);if(u.length){let p=O(),d=p.body[0];return p.parent=o,d.parent=p,i=i.filter(g=>!u.includes(g)),e.body=i,i.length?(e.parent=d,d.body.push(e)):p.body.pop(),u.forEach(g=>{let h=ee({body:[g]});g.parent=h,h.parent=p,p.body.push(h)}),n(p)}}t.inCharClass=!0;let c=s();return t.inCharClass=!1,c}let l=i[0];if(r==="union"&&!a&&l&&((!t.useFlagV||!t.verbose)&&o.kind==="union"&&!(j.bugFlagVLiteralHyphenIsRange&&t.useFlagV)||!t.verbose&&o.kind==="intersection"&&i.length===1&&l.type!=="CharacterClassRange"))return i.map(n).join("");if(!t.useFlagV&&o.type==="CharacterClass")throw new Error("Uses nested character class in a way that requires min target ES2024");return s()},CharacterClassRange(e,t){let n=e.min.value,r=e.max.value,a={escDigit:!1,inCharClass:!0,useFlagV:t.useFlagV},o=Se(n,a),i=Se(r,a),s=new Set;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase){let l=za(e);Pl(l).forEach(u=>{s.add(Array.isArray(u)?`${Se(u[0],a)}-${Se(u[1],a)}`:Se(u,a))})}return`${o}-${i}${[...s].join("")}`},CharacterSet({kind:e,negate:t,value:n,key:r},a){if(e==="dot")return a.currentFlags.dotAll?a.appliedGlobalFlags.dotAll||a.useFlagMods?".":"[^]":C`[^\n]`;if(e==="digit")return t?C`\D`:C`\d`;if(e==="property"){if(a.useAppliedIgnoreCase&&a.currentFlags.ignoreCase&&Oa.has(n))throw new Error(`Unicode property "${n}" can't be case-insensitive when other chars have specific case`);return`${t?C`\P`:C`\p`}{${r?`${r}=`:""}${n}}`}if(e==="word")return t?C`\W`:C`\w`;throw new Error(`Unexpected character set kind "${e}"`)},Flags(e,t){return(t.appliedGlobalFlags.ignoreCase?"i":"")+(e.dotAll?"s":"")+(e.sticky?"y":"")},Group({atomic:e,body:t,flags:n,parent:r},a,o){let i=a.currentFlags;n&&(a.currentFlags=Et(i,n));let s=t.map(o).join("|"),l=!a.verbose&&t.length===1&&r.type!=="Quantifier"&&!e&&(!a.useFlagMods||!n)?s:`(?${$l(e,n,a.useFlagMods)}${s})`;return a.currentFlags=i,l},LookaroundAssertion({body:e,kind:t,negate:n},r,a){return`(?${`${t==="lookahead"?"":"<"}${n?"!":"="}`}${e.map(a).join("|")})`},Quantifier(e,t,n){return n(e.body)+Ml(e)},Subroutine({isRecursive:e,ref:t},n){if(!e)throw new Error("Unexpected non-recursive subroutine in transformed AST");let r=n.recursionLimit;return t===0?`(?R=${r})`:C`\g<${t}&R=${r}>`}},Bl=new Set(["$","(",")","*","+",".","?","[","\\","]","^","{","|","}"]),Nl=new Set(["-","\\","]","^","["]),Tl=new Set(["(",")","-","/","[","\\","]","^","{","|","}","!","#","$","%","&","*","+",",",".",":",";","<","=",">","?","@","`","~"]),Pa=new Map([[9,C`\t`],[10,C`\n`],[11,C`\v`],[12,C`\f`],[13,C`\r`],[8232,C`\u2028`],[8233,C`\u2029`],[65279,C`\uFEFF`]]),Ll=/^\p{Cased}$/u;function En(e){return Ll.test(e)}function za(e,t){let n=!!t?.firstOnly,r=e.min.value,a=e.max.value,o=[];if(r<65&&(a===65535||a>=131071)||r===65536&&a>=131071)return o;for(let i=r;i<=a;i++){let s=N(i);if(!En(s))continue;let l=Fa(s).filter(c=>{let u=c.codePointAt(0);return ua});if(l.length&&(o.push(...l),n))break}return o}function Se(e,{escDigit:t,inCharClass:n,useFlagV:r}){if(Pa.has(e))return Pa.get(e);if(e<32||e>126&&e<160||e>262143||t&&Gl(e))return e>255?`\\u{${e.toString(16).toUpperCase()}}`:`\\x${e.toString(16).toUpperCase().padStart(2,"0")}`;let a=n?r?Tl:Nl:Bl,o=N(e);return(a.has(o)?"\\":"")+o}function Pl(e){let t=e.map(a=>a.codePointAt(0)).sort((a,o)=>a-o),n=[],r=null;for(let a=0;a";let r="";if(t&&n){let{enable:a,disable:o}=t;r=(a?.ignoreCase?"i":"")+(a?.dotAll?"s":"")+(o?"-":"")+(o?.ignoreCase?"i":"")+(o?.dotAll?"s":"")}return`${r}:`}function Ml({kind:e,max:t,min:n}){let r;return!n&&t===1?r="?":!n&&t===1/0?r="*":n===1&&t===1/0?r="+":n===t?r=`{${n}}`:r=`{${n},${t===1/0?"":t}}`,r+{greedy:"",lazy:"?",possessive:"+"}[e]}function $a({type:e}){return e==="CapturingGroup"||e==="Group"||e==="LookaroundAssertion"}function Gl(e){return e>47&&e<58}function Ma({type:e,value:t}){return e==="Character"&&t===45}var Fl=class _n extends RegExp{#t=new Map;#e=null;#r;#n=null;#a=null;rawOptions={};get source(){return this.#r||"(?:)"}constructor(t,n,r){let a=!!r?.lazyCompile;if(t instanceof RegExp){if(r)throw new Error("Cannot provide options when copying a regexp");let o=t;super(o,n),this.#r=o.source,o instanceof _n&&(this.#t=o.#t,this.#n=o.#n,this.#a=o.#a,this.rawOptions=o.rawOptions)}else{let o={hiddenCaptures:[],strategy:null,transfers:[],...r};super(a?"":t,n),this.#r=t,this.#t=Dl(o.hiddenCaptures,o.transfers),this.#a=o.strategy,this.rawOptions=r??{}}a||(this.#e=this)}exec(t){if(!this.#e){let{lazyCompile:a,...o}=this.rawOptions;this.#e=new _n(this.#r,this.flags,o)}let n=this.global||this.sticky,r=this.lastIndex;if(this.#a==="clip_search"&&n&&r){this.lastIndex=0;let a=this.#o(t.slice(r));return a&&(Ol(a,r,t,this.hasIndices),this.lastIndex+=r),a}return this.#o(t)}#o(t){this.#e.lastIndex=this.lastIndex;let n=super.exec.call(this.#e,t);if(this.lastIndex=this.#e.lastIndex,!n||!this.#t.size)return n;let r=[...n];n.length=1;let a;this.hasIndices&&(a=[...n.indices],n.indices.length=1);let o=[0];for(let i=1;i{let s=o[i];s&&(o[i]=[s[0]+t,s[1]+t])})}}function Dl(e,t){let n=new Map;for(let r of e)n.set(r,{hidden:!0});for(let[r,a]of t)for(let o of a)ze(n,o,{}).transferTo=r;return n}function Ul(e){let t=/(?\((?:\?<(?![=!])(?[^>]+)>|(?!\?)))|\\?./gsu,n=new Map,r=0,a=0,o;for(;o=t.exec(e);){let{0:i,groups:{capture:s,name:l}}=o;i==="["?r++:r?i==="]"&&r--:s&&(a++,l&&n.set(a,l))}return n}function Va(e,t){let n=ql(e,t);return n.options?new Fl(n.pattern,n.flags,n.options):new RegExp(n.pattern,n.flags)}function ql(e,t){let n=Ga(t),r=xt(e,{flags:n.flags,normalizeUnknownPropertyNames:!0,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline},skipBackrefValidation:n.rules.allowOrphanBackrefs,unicodePropertyMap:Sn}),a=ml(r,{accuracy:n.accuracy,asciiWordBoundaries:n.rules.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,bestEffortTarget:n.target}),o=Al(a,n),i=Na(o.pattern,{captureTransfers:o._captureTransfers,hiddenCaptures:o._hiddenCaptures,mode:"external"}),s=mn(i.pattern),l=fn(s.pattern,{captureTransfers:i.captureTransfers,hiddenCaptures:i.hiddenCaptures}),c={pattern:l.pattern,flags:`${n.hasIndices?"d":""}${n.global?"g":""}${o.flags}${o.options.disable.v?"u":"v"}`};if(n.avoidSubclass){if(n.lazyCompileLength!==1/0)throw new Error("Lazy compilation requires subclass")}else{let u=l.hiddenCaptures.sort((h,y)=>h-y),p=Array.from(l.captureTransfers),d=a._strategy,g=c.pattern.length>=n.lazyCompileLength;(u.length||p.length||d||g)&&(c.options={...u.length&&{hiddenCaptures:u},...p.length&&{transfers:p},...d&&{strategy:d},...g&&{lazyCompile:g}})}return c}function Xa(e,t){return Va(e,{global:!0,hasIndices:!0,lazyCompileLength:3e3,rules:{allowOrphanBackrefs:!0,asciiWordBoundaries:!0,captureGroup:!0,recursionLimit:5,singleline:!0},...t})}function An(e={}){let t={target:"auto",cache:new Map,...e};return t.regexConstructor||=n=>Xa(n,{target:t.target}),{createScanner(n){return new ta(n,t)},createString(n){return{content:n}}}}var jl=Object.freeze(JSON.parse(`{"displayName":"Python","name":"python","patterns":[{"include":"#statement"},{"include":"#expression"}],"repository":{"annotated-parameter":{"begin":"\\\\b([_[:alpha:]]\\\\w*)\\\\s*(:)","beginCaptures":{"1":{"name":"variable.parameter.function.language.python"},"2":{"name":"punctuation.separator.annotation.python"}},"end":"(,)|(?=\\\\))","endCaptures":{"1":{"name":"punctuation.separator.parameters.python"}},"patterns":[{"include":"#expression"},{"match":"=(?!=)","name":"keyword.operator.assignment.python"}]},"assignment-operator":{"match":"<<=|>>=|//=|\\\\*\\\\*=|\\\\+=|-=|/=|@=|\\\\*=|%=|~=|\\\\^=|&=|\\\\|=|=(?!=)","name":"keyword.operator.assignment.python"},"backticks":{"begin":"\`","end":"\`|(?))","name":"comment.typehint.punctuation.notation.python"},{"match":"([_[:alpha:]]\\\\w*)","name":"comment.typehint.variable.notation.python"}]},{"include":"#comments-base"}]},"comments-base":{"begin":"(#)","beginCaptures":{"1":{"name":"punctuation.definition.comment.python"}},"end":"$()","name":"comment.line.number-sign.python","patterns":[{"include":"#codetags"}]},"comments-string-double-three":{"begin":"(#)","beginCaptures":{"1":{"name":"punctuation.definition.comment.python"}},"end":"($|(?=\\"\\"\\"))","name":"comment.line.number-sign.python","patterns":[{"include":"#codetags"}]},"comments-string-single-three":{"begin":"(#)","beginCaptures":{"1":{"name":"punctuation.definition.comment.python"}},"end":"($|(?='''))","name":"comment.line.number-sign.python","patterns":[{"include":"#codetags"}]},"curly-braces":{"begin":"\\\\{","beginCaptures":{"0":{"name":"punctuation.definition.dict.begin.python"}},"end":"}","endCaptures":{"0":{"name":"punctuation.definition.dict.end.python"}},"patterns":[{"match":":","name":"punctuation.separator.dict.python"},{"include":"#expression"}]},"decorator":{"begin":"^\\\\s*((@))\\\\s*(?=[_[:alpha:]]\\\\w*)","beginCaptures":{"1":{"name":"entity.name.function.decorator.python"},"2":{"name":"punctuation.definition.decorator.python"}},"end":"(\\\\))(.*?)(?=\\\\s*(?:#|$))|(?=[\\\\n#])","endCaptures":{"1":{"name":"punctuation.definition.arguments.end.python"},"2":{"name":"invalid.illegal.decorator.python"}},"name":"meta.function.decorator.python","patterns":[{"include":"#decorator-name"},{"include":"#function-arguments"}]},"decorator-name":{"patterns":[{"include":"#builtin-callables"},{"include":"#illegal-object-name"},{"captures":{"2":{"name":"punctuation.separator.period.python"}},"match":"([_[:alpha:]]\\\\w*)|(\\\\.)","name":"entity.name.function.decorator.python"},{"include":"#line-continuation"},{"captures":{"1":{"name":"invalid.illegal.decorator.python"}},"match":"\\\\s*([^#(.\\\\\\\\_[:alpha:]\\\\s].*?)(?=#|$)","name":"invalid.illegal.decorator.python"}]},"docstring":{"patterns":[{"begin":"('''|\\"\\"\\")","beginCaptures":{"1":{"name":"punctuation.definition.string.begin.python"}},"end":"(\\\\1)","endCaptures":{"1":{"name":"punctuation.definition.string.end.python"}},"name":"string.quoted.docstring.multi.python","patterns":[{"include":"#docstring-prompt"},{"include":"#codetags"},{"include":"#docstring-guts-unicode"}]},{"begin":"([Rr])('''|\\"\\"\\")","beginCaptures":{"1":{"name":"storage.type.string.python"},"2":{"name":"punctuation.definition.string.begin.python"}},"end":"(\\\\2)","endCaptures":{"1":{"name":"punctuation.definition.string.end.python"}},"name":"string.quoted.docstring.raw.multi.python","patterns":[{"include":"#string-consume-escape"},{"include":"#docstring-prompt"},{"include":"#codetags"}]},{"begin":"([\\"'])","beginCaptures":{"1":{"name":"punctuation.definition.string.begin.python"}},"end":"(\\\\1)|(\\\\n)","endCaptures":{"1":{"name":"punctuation.definition.string.end.python"},"2":{"name":"invalid.illegal.newline.python"}},"name":"string.quoted.docstring.single.python","patterns":[{"include":"#codetags"},{"include":"#docstring-guts-unicode"}]},{"begin":"([Rr])([\\"'])","beginCaptures":{"1":{"name":"storage.type.string.python"},"2":{"name":"punctuation.definition.string.begin.python"}},"end":"(\\\\2)|(\\\\n)","endCaptures":{"1":{"name":"punctuation.definition.string.end.python"},"2":{"name":"invalid.illegal.newline.python"}},"name":"string.quoted.docstring.raw.single.python","patterns":[{"include":"#string-consume-escape"},{"include":"#codetags"}]}]},"docstring-guts-unicode":{"patterns":[{"include":"#escape-sequence-unicode"},{"include":"#escape-sequence"},{"include":"#string-line-continuation"}]},"docstring-prompt":{"captures":{"1":{"name":"keyword.control.flow.python"}},"match":"(?:^|\\\\G)\\\\s*((?:>>>|\\\\.\\\\.\\\\.)\\\\s)(?=\\\\s*\\\\S)"},"docstring-statement":{"begin":"^(?=\\\\s*[Rr]?('''|\\"\\"\\"|[\\"']))","end":"((?<=\\\\1)|^)(?!\\\\s*[Rr]?('''|\\"\\"\\"|[\\"']))","patterns":[{"include":"#docstring"}]},"double-one-regexp-character-set":{"patterns":[{"match":"\\\\[\\\\^?](?!.*?])"},{"begin":"(\\\\[)(\\\\^)?(])?","beginCaptures":{"1":{"name":"punctuation.character.set.begin.regexp constant.other.set.regexp"},"2":{"name":"keyword.operator.negation.regexp"},"3":{"name":"constant.character.set.regexp"}},"end":"(]|(?=\\"))|((?=(?)","beginCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.named.begin.regexp"},"2":{"name":"entity.name.tag.named.group.regexp"}},"end":"(\\\\)|(?=\\"))|((?=(?)","beginCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.named.begin.regexp"},"2":{"name":"entity.name.tag.named.group.regexp"}},"end":"(\\\\)|(?=\\"\\"\\"))","endCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.named.end.regexp"},"2":{"name":"invalid.illegal.newline.python"}},"name":"meta.named.regexp","patterns":[{"include":"#double-three-regexp-expression"},{"include":"#comments-string-double-three"}]},"double-three-regexp-parentheses":{"begin":"\\\\(","beginCaptures":{"0":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.begin.regexp"}},"end":"(\\\\)|(?=\\"\\"\\"))","endCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.end.regexp"},"2":{"name":"invalid.illegal.newline.python"}},"patterns":[{"include":"#double-three-regexp-expression"},{"include":"#comments-string-double-three"}]},"double-three-regexp-parentheses-non-capturing":{"begin":"\\\\(\\\\?:","beginCaptures":{"0":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.non-capturing.begin.regexp"}},"end":"(\\\\)|(?=\\"\\"\\"))","endCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.non-capturing.end.regexp"},"2":{"name":"invalid.illegal.newline.python"}},"patterns":[{"include":"#double-three-regexp-expression"},{"include":"#comments-string-double-three"}]},"ellipsis":{"match":"\\\\.\\\\.\\\\.","name":"constant.other.ellipsis.python"},"escape-sequence":{"match":"\\\\\\\\(x\\\\h{2}|[0-7]{1,3}|[\\"'\\\\\\\\abfnrtv])","name":"constant.character.escape.python"},"escape-sequence-unicode":{"patterns":[{"match":"\\\\\\\\(u\\\\h{4}|U\\\\h{8}|N\\\\{[\\\\w\\\\s]+?})","name":"constant.character.escape.python"}]},"expression":{"patterns":[{"include":"#expression-base"},{"include":"#member-access"},{"match":"\\\\b([_[:alpha:]]\\\\w*)\\\\b"}]},"expression-bare":{"patterns":[{"include":"#backticks"},{"include":"#illegal-anno"},{"include":"#literal"},{"include":"#regexp"},{"include":"#string"},{"include":"#lambda"},{"include":"#generator"},{"include":"#illegal-operator"},{"include":"#operator"},{"include":"#curly-braces"},{"include":"#item-access"},{"include":"#list"},{"include":"#odd-function-call"},{"include":"#round-braces"},{"include":"#function-call"},{"include":"#builtin-functions"},{"include":"#builtin-types"},{"include":"#builtin-exceptions"},{"include":"#magic-names"},{"include":"#special-names"},{"include":"#illegal-names"},{"include":"#special-variables"},{"include":"#ellipsis"},{"include":"#punctuation"},{"include":"#line-continuation"}]},"expression-base":{"patterns":[{"include":"#comments"},{"include":"#expression-bare"},{"include":"#line-continuation"}]},"f-expression":{"patterns":[{"include":"#expression-bare"},{"include":"#member-access"},{"match":"\\\\b([_[:alpha:]]\\\\w*)\\\\b"}]},"fregexp-base-expression":{"patterns":[{"include":"#fregexp-quantifier"},{"include":"#fstring-formatting-braces"},{"match":"\\\\{.*?}"},{"include":"#regexp-base-common"}]},"fregexp-quantifier":{"match":"\\\\{\\\\{(\\\\d+|\\\\d+,(\\\\d+)?|,\\\\d+)}}","name":"keyword.operator.quantifier.regexp"},"fstring-fnorm-quoted-multi-line":{"begin":"\\\\b([Ff])([BUbu])?('''|\\"\\"\\")","beginCaptures":{"1":{"name":"string.interpolated.python string.quoted.multi.python storage.type.string.python"},"2":{"name":"invalid.illegal.prefix.python"},"3":{"name":"punctuation.definition.string.begin.python string.interpolated.python string.quoted.multi.python"}},"end":"(\\\\3)","endCaptures":{"1":{"name":"punctuation.definition.string.end.python string.interpolated.python string.quoted.multi.python"},"2":{"name":"invalid.illegal.newline.python"}},"name":"meta.fstring.python","patterns":[{"include":"#fstring-guts"},{"include":"#fstring-illegal-multi-brace"},{"include":"#fstring-multi-brace"},{"include":"#fstring-multi-core"}]},"fstring-fnorm-quoted-single-line":{"begin":"\\\\b([Ff])([BUbu])?(([\\"']))","beginCaptures":{"1":{"name":"string.interpolated.python string.quoted.single.python storage.type.string.python"},"2":{"name":"invalid.illegal.prefix.python"},"3":{"name":"punctuation.definition.string.begin.python string.interpolated.python string.quoted.single.python"}},"end":"(\\\\3)|((?^]?[- +]?#?\\\\d*,?(\\\\.\\\\d+)?[%EFGXb-gnosx]?)(?=})"},{"include":"#fstring-terminator-multi-tail"}]},"fstring-terminator-multi-tail":{"begin":"(=?(?:![ars])?)(:)(?=.*?\\\\{)","beginCaptures":{"1":{"name":"storage.type.format.python"},"2":{"name":"storage.type.format.python"}},"end":"(?=})","patterns":[{"include":"#fstring-illegal-multi-brace"},{"include":"#fstring-multi-brace"},{"match":"([%EFGXb-gnosx])(?=})","name":"storage.type.format.python"},{"match":"(\\\\.\\\\d+)","name":"storage.type.format.python"},{"match":"(,)","name":"storage.type.format.python"},{"match":"(\\\\d+)","name":"storage.type.format.python"},{"match":"(#)","name":"storage.type.format.python"},{"match":"([- +])","name":"storage.type.format.python"},{"match":"([<=>^])","name":"storage.type.format.python"},{"match":"(\\\\w)","name":"storage.type.format.python"}]},"fstring-terminator-single":{"patterns":[{"match":"(=(![ars])?)(?=})","name":"storage.type.format.python"},{"match":"(=?![ars])(?=})","name":"storage.type.format.python"},{"captures":{"1":{"name":"storage.type.format.python"},"2":{"name":"storage.type.format.python"}},"match":"(=?(?:![ars])?)(:\\\\w?[<=>^]?[- +]?#?\\\\d*,?(\\\\.\\\\d+)?[%EFGXb-gnosx]?)(?=})"},{"include":"#fstring-terminator-single-tail"}]},"fstring-terminator-single-tail":{"begin":"(=?(?:![ars])?)(:)(?=.*?\\\\{)","beginCaptures":{"1":{"name":"storage.type.format.python"},"2":{"name":"storage.type.format.python"}},"end":"(?=})|(?=\\\\n)","patterns":[{"include":"#fstring-illegal-single-brace"},{"include":"#fstring-single-brace"},{"match":"([%EFGXb-gnosx])(?=})","name":"storage.type.format.python"},{"match":"(\\\\.\\\\d+)","name":"storage.type.format.python"},{"match":"(,)","name":"storage.type.format.python"},{"match":"(\\\\d+)","name":"storage.type.format.python"},{"match":"(#)","name":"storage.type.format.python"},{"match":"([- +])","name":"storage.type.format.python"},{"match":"([<=>^])","name":"storage.type.format.python"},{"match":"(\\\\w)","name":"storage.type.format.python"}]},"function-arguments":{"begin":"(\\\\()","beginCaptures":{"1":{"name":"punctuation.definition.arguments.begin.python"}},"contentName":"meta.function-call.arguments.python","end":"(?=\\\\))(?!\\\\)\\\\s*\\\\()","patterns":[{"match":"(,)","name":"punctuation.separator.arguments.python"},{"captures":{"1":{"name":"keyword.operator.unpacking.arguments.python"}},"match":"(?:(?<=[(,])|^)\\\\s*(\\\\*{1,2})"},{"include":"#lambda-incomplete"},{"include":"#illegal-names"},{"captures":{"1":{"name":"variable.parameter.function-call.python"},"2":{"name":"keyword.operator.assignment.python"}},"match":"\\\\b([_[:alpha:]]\\\\w*)\\\\s*(=)(?!=)"},{"match":"=(?!=)","name":"keyword.operator.assignment.python"},{"include":"#expression"},{"captures":{"1":{"name":"punctuation.definition.arguments.end.python"},"2":{"name":"punctuation.definition.arguments.begin.python"}},"match":"\\\\s*(\\\\))\\\\s*(\\\\()"}]},"function-call":{"begin":"\\\\b(?=([_[:alpha:]]\\\\w*)\\\\s*(\\\\())","end":"(\\\\))","endCaptures":{"1":{"name":"punctuation.definition.arguments.end.python"}},"name":"meta.function-call.python","patterns":[{"include":"#special-variables"},{"include":"#function-name"},{"include":"#function-arguments"}]},"function-declaration":{"begin":"\\\\s*(?:\\\\b(async)\\\\s+)?\\\\b(def)\\\\s+(?=[_[:alpha:]]\\\\p{word}*\\\\s*\\\\()","beginCaptures":{"1":{"name":"storage.type.function.async.python"},"2":{"name":"storage.type.function.python"}},"end":"(:|(?=[\\\\n\\"#']))","endCaptures":{"1":{"name":"punctuation.section.function.begin.python"}},"name":"meta.function.python","patterns":[{"include":"#function-def-name"},{"include":"#parameters"},{"include":"#line-continuation"},{"include":"#return-annotation"}]},"function-def-name":{"patterns":[{"include":"#illegal-object-name"},{"include":"#builtin-possible-callables"},{"match":"\\\\b([_[:alpha:]]\\\\w*)\\\\b","name":"entity.name.function.python"}]},"function-name":{"patterns":[{"include":"#builtin-possible-callables"},{"match":"\\\\b([_[:alpha:]]\\\\w*)\\\\b","name":"meta.function-call.generic.python"}]},"generator":{"begin":"\\\\bfor\\\\b","beginCaptures":{"0":{"name":"keyword.control.flow.python"}},"end":"\\\\bin\\\\b","endCaptures":{"0":{"name":"keyword.control.flow.python"}},"patterns":[{"include":"#expression"}]},"illegal-anno":{"match":"->","name":"invalid.illegal.annotation.python"},"illegal-names":{"captures":{"1":{"name":"keyword.control.flow.python"},"2":{"name":"keyword.control.import.python"}},"match":"\\\\b(?:(and|assert|async|await|break|class|continue|def|del|elif|else|except|finally|for|from|global|if|in|is|(?<=\\\\.)lambda|lambda(?=\\\\s*[.=])|nonlocal|not|or|pass|raise|return|try|while|with|yield)|(as|import))\\\\b"},"illegal-object-name":{"match":"\\\\b(True|False|None)\\\\b","name":"keyword.illegal.name.python"},"illegal-operator":{"patterns":[{"match":"&&|\\\\|\\\\||--|\\\\+\\\\+","name":"invalid.illegal.operator.python"},{"match":"[$?]","name":"invalid.illegal.operator.python"},{"match":"!\\\\b","name":"invalid.illegal.operator.python"}]},"import":{"patterns":[{"begin":"\\\\b(?>|[\\\\&^|~])|(\\\\*\\\\*|[-%*+]|//|[/@])|(!=|==|>=|<=|[<>])|(:=)"},"parameter-special":{"captures":{"1":{"name":"variable.parameter.function.language.python"},"2":{"name":"variable.parameter.function.language.special.self.python"},"3":{"name":"variable.parameter.function.language.special.cls.python"},"4":{"name":"punctuation.separator.parameters.python"}},"match":"\\\\b((self)|(cls))\\\\b\\\\s*(?:(,)|(?=\\\\)))"},"parameters":{"begin":"(\\\\()","beginCaptures":{"1":{"name":"punctuation.definition.parameters.begin.python"}},"end":"(\\\\))","endCaptures":{"1":{"name":"punctuation.definition.parameters.end.python"}},"name":"meta.function.parameters.python","patterns":[{"match":"/","name":"keyword.operator.positional.parameter.python"},{"match":"(\\\\*\\\\*?)","name":"keyword.operator.unpacking.parameter.python"},{"include":"#lambda-incomplete"},{"include":"#illegal-names"},{"include":"#illegal-object-name"},{"include":"#parameter-special"},{"captures":{"1":{"name":"variable.parameter.function.language.python"},"2":{"name":"punctuation.separator.parameters.python"}},"match":"([_[:alpha:]]\\\\w*)\\\\s*(?:(,)|(?=[\\\\n#)=]))"},{"include":"#comments"},{"include":"#loose-default"},{"include":"#annotated-parameter"}]},"punctuation":{"patterns":[{"match":":","name":"punctuation.separator.colon.python"},{"match":",","name":"punctuation.separator.element.python"}]},"regexp":{"patterns":[{"include":"#regexp-single-three-line"},{"include":"#regexp-double-three-line"},{"include":"#regexp-single-one-line"},{"include":"#regexp-double-one-line"}]},"regexp-backreference":{"captures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.backreference.named.begin.regexp"},"2":{"name":"entity.name.tag.named.backreference.regexp"},"3":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.backreference.named.end.regexp"}},"match":"(\\\\()(\\\\?P=\\\\w+(?:\\\\s+\\\\p{alnum}+)?)(\\\\))","name":"meta.backreference.named.regexp"},"regexp-backreference-number":{"captures":{"1":{"name":"entity.name.tag.backreference.regexp"}},"match":"(\\\\\\\\[1-9]\\\\d?)","name":"meta.backreference.regexp"},"regexp-base-common":{"patterns":[{"match":"\\\\.","name":"support.other.match.any.regexp"},{"match":"\\\\^","name":"support.other.match.begin.regexp"},{"match":"\\\\$","name":"support.other.match.end.regexp"},{"match":"[*+?]\\\\??","name":"keyword.operator.quantifier.regexp"},{"match":"\\\\|","name":"keyword.operator.disjunction.regexp"},{"include":"#regexp-escape-sequence"}]},"regexp-base-expression":{"patterns":[{"include":"#regexp-quantifier"},{"include":"#regexp-base-common"}]},"regexp-charecter-set-escapes":{"patterns":[{"match":"\\\\\\\\[\\\\\\\\abfnrtv]","name":"constant.character.escape.regexp"},{"include":"#regexp-escape-special"},{"match":"\\\\\\\\([0-7]{1,3})","name":"constant.character.escape.regexp"},{"include":"#regexp-escape-character"},{"include":"#regexp-escape-unicode"},{"include":"#regexp-escape-catchall"}]},"regexp-double-one-line":{"begin":"\\\\b(([Uu]r)|([Bb]r)|(r[Bb]?))(\\")","beginCaptures":{"2":{"name":"invalid.deprecated.prefix.python"},"3":{"name":"storage.type.string.python"},"4":{"name":"storage.type.string.python"},"5":{"name":"punctuation.definition.string.begin.python"}},"end":"(\\")|(?)","beginCaptures":{"1":{"name":"punctuation.separator.annotation.result.python"}},"end":"(?=:)","patterns":[{"include":"#expression"}]},"round-braces":{"begin":"\\\\(","beginCaptures":{"0":{"name":"punctuation.parenthesis.begin.python"}},"end":"\\\\)","endCaptures":{"0":{"name":"punctuation.parenthesis.end.python"}},"patterns":[{"include":"#expression"}]},"semicolon":{"patterns":[{"match":";$","name":"invalid.deprecated.semicolon.python"}]},"single-one-regexp-character-set":{"patterns":[{"match":"\\\\[\\\\^?](?!.*?])"},{"begin":"(\\\\[)(\\\\^)?(])?","beginCaptures":{"1":{"name":"punctuation.character.set.begin.regexp constant.other.set.regexp"},"2":{"name":"keyword.operator.negation.regexp"},"3":{"name":"constant.character.set.regexp"}},"end":"(]|(?='))|((?=(?)","beginCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.named.begin.regexp"},"2":{"name":"entity.name.tag.named.group.regexp"}},"end":"(\\\\)|(?='))|((?=(?)","beginCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.named.begin.regexp"},"2":{"name":"entity.name.tag.named.group.regexp"}},"end":"(\\\\)|(?='''))","endCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.named.end.regexp"},"2":{"name":"invalid.illegal.newline.python"}},"name":"meta.named.regexp","patterns":[{"include":"#single-three-regexp-expression"},{"include":"#comments-string-single-three"}]},"single-three-regexp-parentheses":{"begin":"\\\\(","beginCaptures":{"0":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.begin.regexp"}},"end":"(\\\\)|(?='''))","endCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.end.regexp"},"2":{"name":"invalid.illegal.newline.python"}},"patterns":[{"include":"#single-three-regexp-expression"},{"include":"#comments-string-single-three"}]},"single-three-regexp-parentheses-non-capturing":{"begin":"\\\\(\\\\?:","beginCaptures":{"0":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.non-capturing.begin.regexp"}},"end":"(\\\\)|(?='''))","endCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.non-capturing.end.regexp"},"2":{"name":"invalid.illegal.newline.python"}},"patterns":[{"include":"#single-three-regexp-expression"},{"include":"#comments-string-single-three"}]},"special-names":{"match":"\\\\b(_*\\\\p{upper}[_\\\\d]*\\\\p{upper})[[:upper:]\\\\d]*(_\\\\w*)?\\\\b","name":"constant.other.caps.python"},"special-variables":{"captures":{"1":{"name":"variable.language.special.self.python"},"2":{"name":"variable.language.special.cls.python"}},"match":"\\\\b(?^]?[- +]?#?\\\\d*,?(\\\\.\\\\d+)?[%EFGXb-gnosx]?)?})","name":"meta.format.brace.python"},{"captures":{"1":{"name":"constant.character.format.placeholder.other.python"},"3":{"name":"storage.type.format.python"},"4":{"name":"storage.type.format.python"}},"match":"(\\\\{\\\\w*(\\\\.[_[:alpha:]]\\\\w*|\\\\[[^]\\"']+])*(![ars])?(:)[^\\\\n\\"'{}]*(?:\\\\{[^\\\\n\\"'}]*?}[^\\\\n\\"'{}]*)*})","name":"meta.format.brace.python"}]},"string-consume-escape":{"match":"\\\\\\\\[\\\\n\\"'\\\\\\\\]"},"string-entity":{"patterns":[{"include":"#escape-sequence"},{"include":"#string-line-continuation"},{"include":"#string-formatting"}]},"string-formatting":{"captures":{"1":{"name":"constant.character.format.placeholder.other.python"}},"match":"(%(\\\\([\\\\w\\\\s]*\\\\))?[- #+0]*(\\\\d+|\\\\*)?(\\\\.(\\\\d+|\\\\*))?([Lhl])?[%EFGXa-giorsux])","name":"meta.format.percent.python"},"string-line-continuation":{"match":"\\\\\\\\$","name":"constant.language.python"},"string-multi-bad-brace1-formatting-raw":{"begin":"(?=\\\\{%(.*?(?!'''|\\"\\"\\"))%})","end":"(?='''|\\"\\"\\")","patterns":[{"include":"#string-consume-escape"}]},"string-multi-bad-brace1-formatting-unicode":{"begin":"(?=\\\\{%(.*?(?!'''|\\"\\"\\"))%})","end":"(?='''|\\"\\"\\")","patterns":[{"include":"#escape-sequence-unicode"},{"include":"#escape-sequence"},{"include":"#string-line-continuation"}]},"string-multi-bad-brace2-formatting-raw":{"begin":"(?!\\\\{\\\\{)(?=\\\\{(\\\\w*?(?!'''|\\"\\"\\")[^!.:\\\\[}\\\\w]).*?(?!'''|\\"\\"\\")})","end":"(?='''|\\"\\"\\")","patterns":[{"include":"#string-consume-escape"},{"include":"#string-formatting"}]},"string-multi-bad-brace2-formatting-unicode":{"begin":"(?!\\\\{\\\\{)(?=\\\\{(\\\\w*?(?!'''|\\"\\"\\")[^!.:\\\\[}\\\\w]).*?(?!'''|\\"\\"\\")})","end":"(?='''|\\"\\"\\")","patterns":[{"include":"#escape-sequence-unicode"},{"include":"#string-entity"}]},"string-quoted-multi-line":{"begin":"(?:\\\\b([Rr])(?=[Uu]))?([Uu])?('''|\\"\\"\\")","beginCaptures":{"1":{"name":"invalid.illegal.prefix.python"},"2":{"name":"storage.type.string.python"},"3":{"name":"punctuation.definition.string.begin.python"}},"end":"(\\\\3)","endCaptures":{"1":{"name":"punctuation.definition.string.end.python"},"2":{"name":"invalid.illegal.newline.python"}},"name":"string.quoted.multi.python","patterns":[{"include":"#string-multi-bad-brace1-formatting-unicode"},{"include":"#string-multi-bad-brace2-formatting-unicode"},{"include":"#string-unicode-guts"}]},"string-quoted-single-line":{"begin":"(?:\\\\b([Rr])(?=[Uu]))?([Uu])?(([\\"']))","beginCaptures":{"1":{"name":"invalid.illegal.prefix.python"},"2":{"name":"storage.type.string.python"},"3":{"name":"punctuation.definition.string.begin.python"}},"end":"(\\\\3)|((?{for(var n in t)Qa(e,n,{get:t[n],enumerable:!0})};var E=class extends Error{constructor(e){super(e),this.name="ShikiError"}};function Ja(e){return Dt(e)}function Dt(e){return Array.isArray(e)?Za(e):e instanceof RegExp?e:typeof e=="object"?eo(e):e}function Za(e){let t=[];for(let n=0,r=e.length;n{for(let r in n)e[r]=n[r]}),e}function qn(e){let t=~e.lastIndexOf("/")||~e.lastIndexOf("\\");return t===0?e:~t===e.length-1?qn(e.substring(0,e.length-1)):e.substr(~t+1)}var Nt=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,Ve=class{static hasCaptures(e){return e===null?!1:(Nt.lastIndex=0,Nt.test(e))}static replaceCaptures(e,t,n){return e.replace(Nt,(r,a,o,i)=>{let s=n[parseInt(a||o,10)];if(s){let l=t.substring(s.start,s.end);for(;l[0]===".";)l=l.substring(1);switch(i){case"downcase":return l.toLowerCase();case"upcase":return l.toUpperCase();default:return l}}else return r})}};function jn(e,t){return et?1:0}function Hn(e,t){if(e===null&&t===null)return 0;if(!e)return-1;if(!t)return 1;let n=e.length,r=t.length;if(n===r){for(let a=0;athis._root.match(e));getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(e){if(e===null)return this._defaults;let t=e.scopeName,r=this._cachedMatchRoot.get(t).find(a=>to(e.parent,a.parentScopes));return r?new Vn(r.fontStyle,r.foreground,r.background):null}},Tt=class Xe{constructor(t,n){this.parent=t,this.scopeName=n}parent;scopeName;static push(t,n){for(let r of n)t=new Xe(t,r);return t}static from(...t){let n=null;for(let r=0;r"){if(n===t.length-1)return!1;r=t[++n],a=!0}for(;e&&!no(e.scopeName,r);){if(a)return!1;e=e.parent}if(!e)return!1;e=e.parent}return!0}function no(e,t){return t===e||e.startsWith(t)&&e[t.length]==="."}var Vn=class{constructor(e,t,n){this.fontStyle=e,this.foregroundId=t,this.backgroundId=n}fontStyle;foregroundId;backgroundId};function ro(e){if(!e)return[];if(!e.settings||!Array.isArray(e.settings))return[];let t=e.settings,n=[],r=0;for(let a=0,o=t.length;a1&&(w=h.slice(0,h.length-1),w.reverse()),n[r++]=new ao(y,w,a,l,c,u)}}return n}var ao=class{constructor(e,t,n,r,a,o){this.scope=e,this.parentScopes=t,this.index=n,this.fontStyle=r,this.foreground=a,this.background=o}scope;parentScopes;index;fontStyle;foreground;background},P=(e=>(e[e.NotSet=-1]="NotSet",e[e.None=0]="None",e[e.Italic=1]="Italic",e[e.Bold=2]="Bold",e[e.Underline=4]="Underline",e[e.Strikethrough=8]="Strikethrough",e))(P||{});function oo(e,t){e.sort((l,c)=>{let u=jn(l.scope,c.scope);return u!==0||(u=Hn(l.parentScopes,c.parentScopes),u!==0)?u:l.index-c.index});let n=0,r="#000000",a="#ffffff";for(;e.length>=1&&e[0].scope==="";){let l=e.shift();l.fontStyle!==-1&&(n=l.fontStyle),l.foreground!==null&&(r=l.foreground),l.background!==null&&(a=l.background)}let o=new io(t),i=new Vn(n,o.getId(r),o.getId(a)),s=new lo(new Pt(0,null,-1,0,0),[]);for(let l=0,c=e.length;lt?console.log("how did this happen?"):this.scopeDepth=t,n!==-1&&(this.fontStyle=n),r!==0&&(this.foreground=r),a!==0&&(this.background=a)}},lo=class $t{constructor(t,n=[],r={}){this._mainRule=t,this._children=r,this._rulesWithParentScopes=n}_mainRule;_children;_rulesWithParentScopes;static _cmpBySpecificity(t,n){if(t.scopeDepth!==n.scopeDepth)return n.scopeDepth-t.scopeDepth;let r=0,a=0;for(;t.parentScopes[r]===">"&&r++,n.parentScopes[a]===">"&&a++,!(r>=t.parentScopes.length||a>=n.parentScopes.length);){let o=n.parentScopes[a].length-t.parentScopes[r].length;if(o!==0)return o;r++,a++}return n.parentScopes.length-t.parentScopes.length}match(t){if(t!==""){let r=t.indexOf("."),a,o;if(r===-1?(a=t,o=""):(a=t.substring(0,r),o=t.substring(r+1)),this._children.hasOwnProperty(a))return this._children[a].match(o)}let n=this._rulesWithParentScopes.concat(this._mainRule);return n.sort($t._cmpBySpecificity),n}insert(t,n,r,a,o,i){if(n===""){this._doInsertHere(t,r,a,o,i);return}let s=n.indexOf("."),l,c;s===-1?(l=n,c=""):(l=n.substring(0,s),c=n.substring(s+1));let u;this._children.hasOwnProperty(l)?u=this._children[l]:(u=new $t(this._mainRule.clone(),Pt.cloneArr(this._rulesWithParentScopes)),this._children[l]=u),u.insert(t+1,c,r,a,o,i)}_doInsertHere(t,n,r,a,o){if(n===null){this._mainRule.acceptOverwrite(t,r,a,o);return}for(let i=0,s=this._rulesWithParentScopes.length;i>>0}static getTokenType(t){return(t&768)>>>8}static containsBalancedBrackets(t){return(t&1024)!==0}static getFontStyle(t){return(t&30720)>>>11}static getForeground(t){return(t&16744448)>>>15}static getBackground(t){return(t&4278190080)>>>24}static set(t,n,r,a,o,i,s){let l=D.getLanguageId(t),c=D.getTokenType(t),u=D.containsBalancedBrackets(t)?1:0,p=D.getFontStyle(t),d=D.getForeground(t),g=D.getBackground(t);return n!==0&&(l=n),r!==8&&(c=r),a!==null&&(u=a?1:0),o!==-1&&(p=o),i!==0&&(d=i),s!==0&&(g=s),(l<<0|c<<8|u<<10|p<<11|d<<15|g<<24)>>>0}};function Qe(e,t){let n=[],r=co(e),a=r.next();for(;a!==null;){let l=0;if(a.length===2&&a.charAt(1)===":"){switch(a.charAt(0)){case"R":l=1;break;case"L":l=-1;break;default:console.log(`Unknown priority ${a} in scope selector`)}a=r.next()}let c=i();if(n.push({matcher:c,priority:l}),a!==",")break;a=r.next()}return n;function o(){if(a==="-"){a=r.next();let l=o();return c=>!!l&&!l(c)}if(a==="("){a=r.next();let l=s();return a===")"&&(a=r.next()),l}if(Pn(a)){let l=[];do l.push(a),a=r.next();while(Pn(a));return c=>t(l,c)}return null}function i(){let l=[],c=o();for(;c;)l.push(c),c=o();return u=>l.every(p=>p(u))}function s(){let l=[],c=i();for(;c&&(l.push(c),a==="|"||a===",");){do a=r.next();while(a==="|"||a===",");c=i()}return u=>l.some(p=>p(u))}}function Pn(e){return!!e&&!!e.match(/[\w\.:]+/)}function co(e){let t=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,n=t.exec(e);return{next:()=>{if(!n)return null;let r=n[0];return n=t.exec(e),r}}}function Kn(e){typeof e.dispose=="function"&&e.dispose()}var Ie=class{constructor(e){this.scopeName=e}scopeName;toKey(){return this.scopeName}},uo=class{constructor(e,t){this.scopeName=e,this.ruleName=t}scopeName;ruleName;toKey(){return`${this.scopeName}#${this.ruleName}`}},po=class{_references=[];_seenReferenceKeys=new Set;get references(){return this._references}visitedRule=new Set;add(e){let t=e.toKey();this._seenReferenceKeys.has(t)||(this._seenReferenceKeys.add(t),this._references.push(e))}},go=class{constructor(e,t){this.repo=e,this.initialScopeName=t,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new Ie(this.initialScopeName)]}repo;initialScopeName;seenFullScopeRequests=new Set;seenPartialScopeRequests=new Set;Q;processQueue(){let e=this.Q;this.Q=[];let t=new po;for(let n of e)ho(n,this.initialScopeName,this.repo,t);for(let n of t.references)if(n instanceof Ie){if(this.seenFullScopeRequests.has(n.scopeName))continue;this.seenFullScopeRequests.add(n.scopeName),this.Q.push(n)}else{if(this.seenFullScopeRequests.has(n.scopeName)||this.seenPartialScopeRequests.has(n.toKey()))continue;this.seenPartialScopeRequests.add(n.toKey()),this.Q.push(n)}}};function ho(e,t,n,r){let a=n.lookup(e.scopeName);if(!a){if(e.scopeName===t)throw new Error(`No grammar provided for <${t}>`);return}let o=n.lookup(t);e instanceof Ie?Ke({baseGrammar:o,selfGrammar:a},r):Mt(e.ruleName,{baseGrammar:o,selfGrammar:a,repository:a.repository},r);let i=n.injections(e.scopeName);if(i)for(let s of i)r.add(new Ie(s))}function Mt(e,t,n){if(t.repository&&t.repository[e]){let r=t.repository[e];Ye([r],t,n)}}function Ke(e,t){e.selfGrammar.patterns&&Array.isArray(e.selfGrammar.patterns)&&Ye(e.selfGrammar.patterns,{...e,repository:e.selfGrammar.repository},t),e.selfGrammar.injections&&Ye(Object.values(e.selfGrammar.injections),{...e,repository:e.selfGrammar.repository},t)}function Ye(e,t,n){for(let r of e){if(n.visitedRule.has(r))continue;n.visitedRule.add(r);let a=r.repository?Un({},t.repository,r.repository):t.repository;Array.isArray(r.patterns)&&Ye(r.patterns,{...t,repository:a},n);let o=r.include;if(!o)continue;let i=Qn(o);switch(i.kind){case 0:Ke({...t,selfGrammar:t.baseGrammar},n);break;case 1:Ke(t,n);break;case 2:Mt(i.ruleName,{...t,repository:a},n);break;case 3:case 4:let s=i.scopeName===t.selfGrammar.scopeName?t.selfGrammar:i.scopeName===t.baseGrammar.scopeName?t.baseGrammar:void 0;if(s){let l={baseGrammar:t.baseGrammar,selfGrammar:s,repository:a};i.kind===4?Mt(i.ruleName,l,n):Ke(l,n)}else i.kind===4?n.add(new uo(i.scopeName,i.ruleName)):n.add(new Ie(i.scopeName));break}}}var fo=class{kind=0},mo=class{kind=1},bo=class{constructor(e){this.ruleName=e}ruleName;kind=2},yo=class{constructor(e){this.scopeName=e}scopeName;kind=3},wo=class{constructor(e,t){this.scopeName=e,this.ruleName=t}scopeName;ruleName;kind=4};function Qn(e){if(e==="$base")return new fo;if(e==="$self")return new mo;let t=e.indexOf("#");if(t===-1)return new yo(e);if(t===0)return new bo(e.substring(1));{let n=e.substring(0,t),r=e.substring(t+1);return new wo(n,r)}}var ko=/\\(\d+)/,$n=/\\(\d+)/g,xo=-1,Yn=-2;var Te=class{$location;id;_nameIsCapturing;_name;_contentNameIsCapturing;_contentName;constructor(e,t,n,r){this.$location=e,this.id=t,this._name=n||null,this._nameIsCapturing=Ve.hasCaptures(this._name),this._contentName=r||null,this._contentNameIsCapturing=Ve.hasCaptures(this._contentName)}get debugName(){let e=this.$location?`${qn(this.$location.filename)}:${this.$location.line}`:"unknown";return`${this.constructor.name}#${this.id} @ ${e}`}getName(e,t){return!this._nameIsCapturing||this._name===null||e===null||t===null?this._name:Ve.replaceCaptures(this._name,e,t)}getContentName(e,t){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:Ve.replaceCaptures(this._contentName,e,t)}},Co=class extends Te{retokenizeCapturedWithRuleId;constructor(e,t,n,r,a){super(e,t,n,r),this.retokenizeCapturedWithRuleId=a}dispose(){}collectPatterns(e,t){throw new Error("Not supported!")}compile(e,t){throw new Error("Not supported!")}compileAG(e,t,n,r){throw new Error("Not supported!")}},vo=class extends Te{_match;captures;_cachedCompiledPatterns;constructor(e,t,n,r,a){super(e,t,n,null),this._match=new Be(r,this.id),this.captures=a,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(e,t){t.push(this._match)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new Ne,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},Mn=class extends Te{hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,a){super(e,t,n,r),this.patterns=a.patterns,this.hasMissingPatterns=a.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}collectPatterns(e,t){for(let n of this.patterns)e.getRule(n).collectPatterns(e,t)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new Ne,this.collectPatterns(e,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},Gt=class extends Te{_begin;beginCaptures;_end;endHasBackReferences;endCaptures;applyEndPatternLast;hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(e,t,n,r,a,o,i,s,l,c){super(e,t,n,r),this._begin=new Be(a,this.id),this.beginCaptures=o,this._end=new Be(i||"\uFFFF",-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=s,this.applyEndPatternLast=l||!1,this.patterns=c.patterns,this.hasMissingPatterns=c.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(e,t){return this._end.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e,t).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e,t).compileAG(e,n,r)}_getCachedCompiledPatterns(e,t){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new Ne;for(let n of this.patterns)e.getRule(n).collectPatterns(e,this._cachedCompiledPatterns);this.applyEndPatternLast?this._cachedCompiledPatterns.push(this._end.hasBackReferences?this._end.clone():this._end):this._cachedCompiledPatterns.unshift(this._end.hasBackReferences?this._end.clone():this._end)}return this._end.hasBackReferences&&(this.applyEndPatternLast?this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length()-1,t):this._cachedCompiledPatterns.setSource(0,t)),this._cachedCompiledPatterns}},Je=class extends Te{_begin;beginCaptures;whileCaptures;_while;whileHasBackReferences;hasMissingPatterns;patterns;_cachedCompiledPatterns;_cachedCompiledWhilePatterns;constructor(e,t,n,r,a,o,i,s,l){super(e,t,n,r),this._begin=new Be(a,this.id),this.beginCaptures=o,this.whileCaptures=s,this._while=new Be(i,Yn),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=l.patterns,this.hasMissingPatterns=l.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null),this._cachedCompiledWhilePatterns&&(this._cachedCompiledWhilePatterns.dispose(),this._cachedCompiledWhilePatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(e,t){return this._while.resolveBackReferences(e,t)}collectPatterns(e,t){t.push(this._begin)}compile(e,t){return this._getCachedCompiledPatterns(e).compile(e)}compileAG(e,t,n,r){return this._getCachedCompiledPatterns(e).compileAG(e,n,r)}_getCachedCompiledPatterns(e){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new Ne;for(let t of this.patterns)e.getRule(t).collectPatterns(e,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(e,t){return this._getCachedCompiledWhilePatterns(e,t).compile(e)}compileWhileAG(e,t,n,r){return this._getCachedCompiledWhilePatterns(e,t).compileAG(e,n,r)}_getCachedCompiledWhilePatterns(e,t){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new Ne,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,t||"\uFFFF"),this._cachedCompiledWhilePatterns}},Jn=class ${static createCaptureRule(t,n,r,a,o){return t.registerRule(i=>new Co(n,i,r,a,o))}static getCompiledRuleId(t,n,r){return t.id||n.registerRule(a=>{if(t.id=a,t.match)return new vo(t.$vscodeTextmateLocation,t.id,t.name,t.match,$._compileCaptures(t.captures,n,r));if(typeof t.begin>"u"){t.repository&&(r=Un({},r,t.repository));let o=t.patterns;return typeof o>"u"&&t.include&&(o=[{include:t.include}]),new Mn(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,$._compilePatterns(o,n,r))}return t.while?new Je(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,$._compileCaptures(t.beginCaptures||t.captures,n,r),t.while,$._compileCaptures(t.whileCaptures||t.captures,n,r),$._compilePatterns(t.patterns,n,r)):new Gt(t.$vscodeTextmateLocation,t.id,t.name,t.contentName,t.begin,$._compileCaptures(t.beginCaptures||t.captures,n,r),t.end,$._compileCaptures(t.endCaptures||t.captures,n,r),t.applyEndPatternLast,$._compilePatterns(t.patterns,n,r))}),t.id}static _compileCaptures(t,n,r){let a=[];if(t){let o=0;for(let i in t){if(i==="$vscodeTextmateLocation")continue;let s=parseInt(i,10);s>o&&(o=s)}for(let i=0;i<=o;i++)a[i]=null;for(let i in t){if(i==="$vscodeTextmateLocation")continue;let s=parseInt(i,10),l=0;t[i].patterns&&(l=$.getCompiledRuleId(t[i],n,r)),a[s]=$.createCaptureRule(n,t[i].$vscodeTextmateLocation,t[i].name,t[i].contentName,l)}}return a}static _compilePatterns(t,n,r){let a=[];if(t)for(let o=0,i=t.length;ot.substring(a.start,a.end));return $n.lastIndex=0,this.source.replace($n,(a,o)=>Wn(r[parseInt(o,10)]||""))}_buildAnchorCache(){if(typeof this.source!="string")throw new Error("This method should only be called if the source is a string");let t=[],n=[],r=[],a=[],o,i,s,l;for(o=0,i=this.source.length;on.source);this._cached=new Gn(e,t,this._items.map(n=>n.ruleId))}return this._cached}compileAG(e,t,n){return this._hasAnchors?t?n?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A1_G0):n?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(e,t,n)),this._anchorCache.A0_G0):this.compile(e)}_resolveAnchors(e,t,n){let r=this._items.map(a=>a.resolveAnchors(t,n));return new Gn(e,r,this._items.map(a=>a.ruleId))}},Gn=class{constructor(e,t,n){this.regExps=t,this.rules=n,this.scanner=e.createOnigScanner(t)}regExps;rules;scanner;dispose(){typeof this.scanner.dispose=="function"&&this.scanner.dispose()}toString(){let e=[];for(let t=0,n=this.rules.length;t{let n=this._scopeToLanguage(t),r=this._toStandardTokenType(t);return new Lt(n,r)});_scopeToLanguage(t){return this._embeddedLanguagesMatcher.match(t)||0}_toStandardTokenType(t){let n=t.match(Ft.STANDARD_TOKEN_TYPE_REGEXP);if(!n)return 8;switch(n[1]){case"comment":return 1;case"string":return 2;case"regex":return 3;case"meta.embedded":return 0}throw new Error("Unexpected match for standard token type!")}static STANDARD_TOKEN_TYPE_REGEXP=/\b(comment|string|regex|meta\.embedded)\b/},So=class{values;scopesRegExp;constructor(e){if(e.length===0)this.values=null,this.scopesRegExp=null;else{this.values=new Map(e);let t=e.map(([n,r])=>Wn(n));t.sort(),t.reverse(),this.scopesRegExp=new RegExp(`^((${t.join(")|(")}))($|\\.)`,"")}}match(e){if(!this.scopesRegExp)return;let t=e.match(this.scopesRegExp);if(t)return this.values.get(t[1])}},Vl={InDebugMode:typeof process<"u"&&!!process.env.VSCODE_TEXTMATE_DEBUG},er=!1,Fn=class{constructor(e,t){this.stack=e,this.stoppedEarly=t}stack;stoppedEarly};function tr(e,t,n,r,a,o,i,s){let l=t.content.length,c=!1,u=-1;if(i){let g=Eo(e,t,n,r,a,o);a=g.stack,r=g.linePos,n=g.isFirstLine,u=g.anchorPosition}let p=Date.now();for(;!c;){if(s!==0&&Date.now()-p>s)return new Fn(a,!0);d()}return new Fn(a,!1);function d(){let g=Ao(e,t,n,r,a,u);if(!g){o.produce(a,l),c=!0;return}let h=g.captureIndices,y=g.matchedRuleId,w=h&&h.length>0?h[0].end>r:!1;if(y===xo){let m=a.getRule(e);o.produce(a,h[0].start),a=a.withContentNameScopesList(a.nameScopesList),Ee(e,t,n,a,o,m.endCaptures,h),o.produce(a,h[0].end);let b=a;if(a=a.parent,u=b.getAnchorPos(),!w&&b.getEnterPos()===r){a=b,o.produce(a,l),c=!0;return}}else{let m=e.getRule(y);o.produce(a,h[0].start);let b=a,k=m.getName(t.content,h),v=a.contentNameScopesList.pushAttributed(k,e);if(a=a.push(y,r,u,h[0].end===l,null,v,v),m instanceof Gt){let S=m;Ee(e,t,n,a,o,S.beginCaptures,h),o.produce(a,h[0].end),u=h[0].end;let L=S.getContentName(t.content,h),M=v.pushAttributed(L,e);if(a=a.withContentNameScopesList(M),S.endHasBackReferences&&(a=a.withEndRule(S.getEndWithResolvedBackReferences(t.content,h))),!w&&b.hasSameRuleAs(a)){a=a.pop(),o.produce(a,l),c=!0;return}}else if(m instanceof Je){let S=m;Ee(e,t,n,a,o,S.beginCaptures,h),o.produce(a,h[0].end),u=h[0].end;let L=S.getContentName(t.content,h),M=v.pushAttributed(L,e);if(a=a.withContentNameScopesList(M),S.whileHasBackReferences&&(a=a.withEndRule(S.getWhileWithResolvedBackReferences(t.content,h))),!w&&b.hasSameRuleAs(a)){a=a.pop(),o.produce(a,l),c=!0;return}}else if(Ee(e,t,n,a,o,m.captures,h),o.produce(a,h[0].end),a=a.pop(),!w){a=a.safePop(),o.produce(a,l),c=!0;return}}h[0].end>r&&(r=h[0].end,n=!1)}}function Eo(e,t,n,r,a,o){let i=a.beginRuleCapturedEOL?0:-1,s=[];for(let l=a;l;l=l.pop()){let c=l.getRule(e);c instanceof Je&&s.push({rule:c,stack:l})}for(let l=s.pop();l;l=s.pop()){let{ruleScanner:c,findOptions:u}=Bo(l.rule,e,l.stack.endRule,n,r===i),p=c.findNextMatchSync(t,r,u);if(p){if(p.ruleId!==Yn){a=l.stack.pop();break}p.captureIndices&&p.captureIndices.length&&(o.produce(l.stack,p.captureIndices[0].start),Ee(e,t,n,l.stack,o,l.rule.whileCaptures,p.captureIndices),o.produce(l.stack,p.captureIndices[0].end),i=p.captureIndices[0].end,p.captureIndices[0].end>r&&(r=p.captureIndices[0].end,n=!1))}else{a=l.stack.pop();break}}return{stack:a,linePos:r,anchorPosition:i,isFirstLine:n}}function Ao(e,t,n,r,a,o){let i=Ro(e,t,n,r,a,o),s=e.getInjections();if(s.length===0)return i;let l=Io(s,e,t,n,r,a,o);if(!l)return i;if(!i)return l;let c=i.captureIndices[0].start,u=l.captureIndices[0].start;return u=s)&&(s=k,l=b.captureIndices,c=b.ruleId,u=h.priority,s===a))break}return l?{priorityMatch:u===-1,captureIndices:l,matchedRuleId:c}:null}function nr(e,t,n,r,a){if(er){let i=e.compile(t,n),s=rr(r,a);return{ruleScanner:i,findOptions:s}}return{ruleScanner:e.compileAG(t,n,r,a),findOptions:0}}function Bo(e,t,n,r,a){if(er){let i=e.compileWhile(t,n),s=rr(r,a);return{ruleScanner:i,findOptions:s}}return{ruleScanner:e.compileWhileAG(t,n,r,a),findOptions:0}}function rr(e,t){let n=0;return e||(n|=1),t||(n|=4),n}function Ee(e,t,n,r,a,o,i){if(o.length===0)return;let s=t.content,l=Math.min(o.length,i.length),c=[],u=i[0].end;for(let p=0;pu)break;for(;c.length>0&&c[c.length-1].endPos<=g.start;)a.produceFromScopes(c[c.length-1].scopes,c[c.length-1].endPos),c.pop();if(c.length>0?a.produceFromScopes(c[c.length-1].scopes,g.start):a.produce(r,g.start),d.retokenizeCapturedWithRuleId){let y=d.getName(s,i),w=r.contentNameScopesList.pushAttributed(y,e),m=d.getContentName(s,i),b=w.pushAttributed(m,e),k=r.push(d.retokenizeCapturedWithRuleId,g.start,-1,!1,null,w,b),v=e.createOnigString(s.substring(0,g.end));tr(e,v,n&&g.start===0,g.start,k,a,!1,0),Kn(v);continue}let h=d.getName(s,i);if(h!==null){let w=(c.length>0?c[c.length-1].scopes:r.contentNameScopesList).pushAttributed(h,e);c.push(new No(w,g.end))}}for(;c.length>0;)a.produceFromScopes(c[c.length-1].scopes,c[c.length-1].endPos),c.pop()}var No=class{scopes;endPos;constructor(e,t){this.scopes=e,this.endPos=t}};function To(e,t,n,r,a,o,i,s){return new Po(e,t,n,r,a,o,i,s)}function On(e,t,n,r,a){let o=Qe(t,Ze),i=Jn.getCompiledRuleId(n,r,a.repository);for(let s of o)e.push({debugSelector:t,matcher:s.matcher,ruleId:i,grammar:a,priority:s.priority})}function Ze(e,t){if(t.length{for(let a=n;an&&e.substr(0,n)===t&&e[n]==="."}var Po=class{constructor(e,t,n,r,a,o,i,s){if(this._rootScopeName=e,this.balancedBracketSelectors=o,this._onigLib=s,this._basicScopeAttributesProvider=new _o(n,r),this._rootId=-1,this._lastRuleId=0,this._ruleId2desc=[null],this._includedGrammars={},this._grammarRepository=i,this._grammar=Dn(t,null),this._injections=null,this._tokenTypeMatchers=[],a)for(let l of Object.keys(a)){let c=Qe(l,Ze);for(let u of c)this._tokenTypeMatchers.push({matcher:u.matcher,type:a[l]})}}_rootScopeName;balancedBracketSelectors;_onigLib;_rootId;_lastRuleId;_ruleId2desc;_includedGrammars;_grammarRepository;_grammar;_injections;_basicScopeAttributesProvider;_tokenTypeMatchers;get themeProvider(){return this._grammarRepository}dispose(){for(let e of this._ruleId2desc)e&&e.dispose()}createOnigScanner(e){return this._onigLib.createOnigScanner(e)}createOnigString(e){return this._onigLib.createOnigString(e)}getMetadataForScope(e){return this._basicScopeAttributesProvider.getBasicScopeAttributes(e)}_collectInjections(){let e={lookup:a=>a===this._rootScopeName?this._grammar:this.getExternalGrammar(a),injections:a=>this._grammarRepository.injections(a)},t=[],n=this._rootScopeName,r=e.lookup(n);if(r){let a=r.injections;if(a)for(let i in a)On(t,i,a[i],this,r);let o=this._grammarRepository.injections(n);o&&o.forEach(i=>{let s=this.getExternalGrammar(i);if(s){let l=s.injectionSelector;l&&On(t,l,s,this,s)}})}return t.sort((a,o)=>a.priority-o.priority),t}getInjections(){return this._injections===null&&(this._injections=this._collectInjections()),this._injections}registerRule(e){let t=++this._lastRuleId,n=e(t);return this._ruleId2desc[t]=n,n}getRule(e){return this._ruleId2desc[e]}getExternalGrammar(e,t){if(this._includedGrammars[e])return this._includedGrammars[e];if(this._grammarRepository){let n=this._grammarRepository.lookup(e);if(n)return this._includedGrammars[e]=Dn(n,t&&t.$base),this._includedGrammars[e]}}tokenizeLine(e,t,n=0){let r=this._tokenize(e,t,!1,n);return{tokens:r.lineTokens.getResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}tokenizeLine2(e,t,n=0){let r=this._tokenize(e,t,!0,n);return{tokens:r.lineTokens.getBinaryResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}_tokenize(e,t,n,r){this._rootId===-1&&(this._rootId=Jn.getCompiledRuleId(this._grammar.repository.$self,this,this._grammar.repository),this.getInjections());let a;if(!t||t===Ot.NULL){a=!0;let c=this._basicScopeAttributesProvider.getDefaultAttributes(),u=this.themeProvider.getDefaults(),p=re.set(0,c.languageId,c.tokenType,null,u.fontStyle,u.foregroundId,u.backgroundId),d=this.getRule(this._rootId).getName(null,null),g;d?g=Ae.createRootAndLookUpScopeName(d,p,this):g=Ae.createRoot("unknown",p),t=new Ot(null,this._rootId,-1,-1,!1,null,g,g)}else a=!1,t.reset();e=e+` +`;let o=this.createOnigString(e),i=o.content.length,s=new Mo(n,e,this._tokenTypeMatchers,this.balancedBracketSelectors),l=tr(this,o,a,0,t,s,!0,r);return Kn(o),{lineLength:i,lineTokens:s,ruleStack:l.stack,stoppedEarly:l.stoppedEarly}}};function Dn(e,t){return e=Ja(e),e.repository=e.repository||{},e.repository.$self={$vscodeTextmateLocation:e.$vscodeTextmateLocation,patterns:e.patterns,name:e.scopeName},e.repository.$base=t||e.repository.$self,e}var Ae=class z{constructor(t,n,r){this.parent=t,this.scopePath=n,this.tokenAttributes=r}parent;scopePath;tokenAttributes;static fromExtension(t,n){let r=t,a=t?.scopePath??null;for(let o of n)a=Tt.push(a,o.scopeNames),r=new z(r,a,o.encodedTokenAttributes);return r}static createRoot(t,n){return new z(null,new Tt(null,t),n)}static createRootAndLookUpScopeName(t,n,r){let a=r.getMetadataForScope(t),o=new Tt(null,t),i=r.themeProvider.themeMatch(o),s=z.mergeAttributes(n,a,i);return new z(null,o,s)}get scopeName(){return this.scopePath.scopeName}toString(){return this.getScopeNames().join(" ")}equals(t){return z.equals(this,t)}static equals(t,n){do{if(t===n||!t&&!n)return!0;if(!t||!n||t.scopeName!==n.scopeName||t.tokenAttributes!==n.tokenAttributes)return!1;t=t.parent,n=n.parent}while(!0)}static mergeAttributes(t,n,r){let a=-1,o=0,i=0;return r!==null&&(a=r.fontStyle,o=r.foregroundId,i=r.backgroundId),re.set(t,n.languageId,n.tokenType,null,a,o,i)}pushAttributed(t,n){if(t===null)return this;if(t.indexOf(" ")===-1)return z._pushAttributed(this,t,n);let r=t.split(/ /g),a=this;for(let o of r)a=z._pushAttributed(a,o,n);return a}static _pushAttributed(t,n,r){let a=r.getMetadataForScope(n),o=t.scopePath.push(n),i=r.themeProvider.themeMatch(o),s=z.mergeAttributes(t.tokenAttributes,a,i);return new z(t,o,s)}getScopeNames(){return this.scopePath.getSegments()}getExtensionIfDefined(t){let n=[],r=this;for(;r&&r!==t;)n.push({encodedTokenAttributes:r.tokenAttributes,scopeNames:r.scopePath.getExtensionIfDefined(r.parent?.scopePath??null)}),r=r.parent;return r===t?n.reverse():void 0}},Ot=class le{constructor(t,n,r,a,o,i,s,l){this.parent=t,this.ruleId=n,this.beginRuleCapturedEOL=o,this.endRule=i,this.nameScopesList=s,this.contentNameScopesList=l,this.depth=this.parent?this.parent.depth+1:1,this._enterPos=r,this._anchorPos=a}parent;ruleId;beginRuleCapturedEOL;endRule;nameScopesList;contentNameScopesList;_stackElementBrand=void 0;static NULL=new le(null,0,0,0,!1,null,null,null);_enterPos;_anchorPos;depth;equals(t){return t===null?!1:le._equals(this,t)}static _equals(t,n){return t===n?!0:this._structuralEquals(t,n)?Ae.equals(t.contentNameScopesList,n.contentNameScopesList):!1}static _structuralEquals(t,n){do{if(t===n||!t&&!n)return!0;if(!t||!n||t.depth!==n.depth||t.ruleId!==n.ruleId||t.endRule!==n.endRule)return!1;t=t.parent,n=n.parent}while(!0)}clone(){return this}static _reset(t){for(;t;)t._enterPos=-1,t._anchorPos=-1,t=t.parent}reset(){le._reset(this)}pop(){return this.parent}safePop(){return this.parent?this.parent:this}push(t,n,r,a,o,i,s){return new le(this,t,n,r,a,o,i,s)}getEnterPos(){return this._enterPos}getAnchorPos(){return this._anchorPos}getRule(t){return t.getRule(this.ruleId)}toString(){let t=[];return this._writeString(t,0),"["+t.join(",")+"]"}_writeString(t,n){return this.parent&&(n=this.parent._writeString(t,n)),t[n++]=`(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`,n}withContentNameScopesList(t){return this.contentNameScopesList===t?this:this.parent.push(this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,this.endRule,this.nameScopesList,t)}withEndRule(t){return this.endRule===t?this:new le(this.parent,this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,t,this.nameScopesList,this.contentNameScopesList)}hasSameRuleAs(t){let n=this;for(;n&&n._enterPos===t._enterPos;){if(n.ruleId===t.ruleId)return!0;n=n.parent}return!1}toStateStackFrame(){return{ruleId:this.ruleId,beginRuleCapturedEOL:this.beginRuleCapturedEOL,endRule:this.endRule,nameScopesList:this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList??null)??[],contentNameScopesList:this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)??[]}}static pushFrame(t,n){let r=Ae.fromExtension(t?.nameScopesList??null,n.nameScopesList);return new le(t,n.ruleId,n.enterPos??-1,n.anchorPos??-1,n.beginRuleCapturedEOL,n.endRule,r,Ae.fromExtension(r,n.contentNameScopesList))}},$o=class{balancedBracketScopes;unbalancedBracketScopes;allowAny=!1;constructor(e,t){this.balancedBracketScopes=e.flatMap(n=>n==="*"?(this.allowAny=!0,[]):Qe(n,Ze).map(r=>r.matcher)),this.unbalancedBracketScopes=t.flatMap(n=>Qe(n,Ze).map(r=>r.matcher))}get matchesAlways(){return this.allowAny&&this.unbalancedBracketScopes.length===0}get matchesNever(){return this.balancedBracketScopes.length===0&&!this.allowAny}match(e){for(let t of this.unbalancedBracketScopes)if(t(e))return!1;for(let t of this.balancedBracketScopes)if(t(e))return!0;return this.allowAny}},Mo=class{constructor(e,t,n,r){this.balancedBracketSelectors=r,this._emitBinaryTokens=e,this._tokenTypeOverrides=n,this._lineText=null,this._tokens=[],this._binaryTokens=[],this._lastTokenEndIndex=0}balancedBracketSelectors;_emitBinaryTokens;_lineText;_tokens;_binaryTokens;_lastTokenEndIndex;_tokenTypeOverrides;produce(e,t){this.produceFromScopes(e.contentNameScopesList,t)}produceFromScopes(e,t){if(this._lastTokenEndIndex>=t)return;if(this._emitBinaryTokens){let r=e?.tokenAttributes??0,a=!1;if(this.balancedBracketSelectors?.matchesAlways&&(a=!0),this._tokenTypeOverrides.length>0||this.balancedBracketSelectors&&!this.balancedBracketSelectors.matchesAlways&&!this.balancedBracketSelectors.matchesNever){let o=e?.getScopeNames()??[];for(let i of this._tokenTypeOverrides)i.matcher(o)&&(r=re.set(r,0,i.type,null,-1,0,0));this.balancedBracketSelectors&&(a=this.balancedBracketSelectors.match(o))}if(a&&(r=re.set(r,0,8,a,-1,0,0)),this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-1]===r){this._lastTokenEndIndex=t;return}this._binaryTokens.push(this._lastTokenEndIndex),this._binaryTokens.push(r),this._lastTokenEndIndex=t;return}let n=e?.getScopeNames()??[];this._tokens.push({startIndex:this._lastTokenEndIndex,endIndex:t,scopes:n}),this._lastTokenEndIndex=t}getResult(e,t){return this._tokens.length>0&&this._tokens[this._tokens.length-1].startIndex===t-1&&this._tokens.pop(),this._tokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._tokens[this._tokens.length-1].startIndex=0),this._tokens}getBinaryResult(e,t){this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-2]===t-1&&(this._binaryTokens.pop(),this._binaryTokens.pop()),this._binaryTokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(e,t),this._binaryTokens[this._binaryTokens.length-2]=0);let n=new Uint32Array(this._binaryTokens.length);for(let r=0,a=this._binaryTokens.length;r0;)o.Q.map(i=>this._loadSingleGrammar(i.scopeName)),o.processQueue();return this._grammarForScopeName(e,t,n,r,a)}_loadSingleGrammar(e){this._ensureGrammarCache.has(e)||(this._doLoadSingleGrammar(e),this._ensureGrammarCache.set(e,!0))}_doLoadSingleGrammar(e){let t=this._options.loadGrammar(e);if(t){let n=typeof this._options.getInjections=="function"?this._options.getInjections(e):void 0;this._syncRegistry.addGrammar(t,n)}}addGrammar(e,t=[],n=0,r=null){return this._syncRegistry.addGrammar(e,t),this._grammarForScopeName(e.scopeName,n,r)}_grammarForScopeName(e,t=0,n=null,r=null,a=null){return this._syncRegistry.grammarForScopeName(e,t,n,r,a)}},et=Ot.NULL;function Pe(e,t){let n=typeof e=="string"?{}:{...e.colorReplacements},r=typeof e=="string"?e:e.name;for(let[a,o]of Object.entries(t?.colorReplacements||{}))typeof o=="string"?n[a]=o:a===r&&Object.assign(n,o);return n}function X(e,t){return e&&(t?.[e?.toLowerCase()]||e)}function cr(e){return Array.isArray(e)?e:[e]}async function Ut(e){return Promise.resolve(typeof e=="function"?e():e).then(t=>t.default||t)}function $e(e){return!e||["plaintext","txt","text","plain"].includes(e)}function ur(e){return e==="ansi"||$e(e)}function Me(e){return e==="none"}function pr(e){return Me(e)}var Fo=/(\r?\n)/g;function we(e,t=!1){if(e.length===0)return[["",0]];let n=e.split(Fo),r=0,a=[];for(let o=0;o!l.name&&!l.scope):void 0;s?.settings?.foreground&&(r=s.settings.foreground),s?.settings?.background&&(n=s.settings.background),!r&&t?.colors?.["editor.foreground"]&&(r=t.colors["editor.foreground"]),!n&&t?.colors?.["editor.background"]&&(n=t.colors["editor.background"]),r||(r=t.type==="light"?or.light:or.dark),n||(n=t.type==="light"?ir.light:ir.dark),t.fg=r,t.bg=n}t.settings[0]&&t.settings[0].settings&&!t.settings[0].scope||t.settings.unshift({settings:{foreground:t.fg,background:t.bg}});let a=0,o=new Map;function i(s){if(o.has(s))return o.get(s);a+=1;let l=`#${a.toString(16).padStart(8,"0").toLowerCase()}`;return t.colorReplacements?.[`#${l}`]?i(s):(o.set(s,l),l)}t.settings=t.settings.map(s=>{let l=s.settings?.foreground&&!s.settings.foreground.startsWith("#"),c=s.settings?.background&&!s.settings.background.startsWith("#");if(!l&&!c)return s;let u={...s,settings:{...s.settings}};if(l){let p=i(s.settings.foreground);t.colorReplacements[p]=s.settings.foreground,u.settings.foreground=p}if(c){let p=i(s.settings.background);t.colorReplacements[p]=s.settings.background,u.settings.background=p}return u});for(let s of Object.keys(t.colors||{}))if((s==="editor.foreground"||s==="editor.background"||s.startsWith("terminal.ansi"))&&!t.colors[s]?.startsWith("#")){let l=i(t.colors[s]);t.colorReplacements[l]=t.colors[s],t.colors[s]=l}return Object.defineProperty(t,sr,{enumerable:!1,writable:!1,value:!0}),t}async function dr(e){return[...new Set((await Promise.all(e.filter(t=>!ur(t)).map(async t=>await Ut(t).then(n=>Array.isArray(n)?n:[n])))).flat())]}async function gr(e){return(await Promise.all(e.map(async t=>pr(t)?null:tt(await Ut(t))))).filter(t=>!!t)}function hr(e,t){if(!t)return e;if(t[e]){let n=new Set([e]);for(;t[e];){if(e=t[e],n.has(e))throw new E(`Circular alias \`${[...n].join(" -> ")} -> ${e}\``);n.add(e)}}return e}var Oo=class extends ar{_resolver;_themes;_langs;_alias;_resolvedThemes=new Map;_resolvedGrammars=new Map;_langMap=new Map;_langGraph=new Map;_textmateThemeCache=new WeakMap;_loadedThemesCache=null;_loadedLanguagesCache=null;constructor(e,t,n,r={}){super(e),this._resolver=e,this._themes=t,this._langs=n,this._alias=r,this._themes.map(a=>this.loadTheme(a)),this.loadLanguages(this._langs)}getTheme(e){return typeof e=="string"?this._resolvedThemes.get(e):this.loadTheme(e)}loadTheme(e){let t=tt(e);return t.name&&(this._resolvedThemes.set(t.name,t),this._loadedThemesCache=null),t}getLoadedThemes(){return this._loadedThemesCache||(this._loadedThemesCache=[...this._resolvedThemes.keys()]),this._loadedThemesCache}setTheme(e){let t=this._textmateThemeCache.get(e);t||(t=Re.createFromRawTheme(e),this._textmateThemeCache.set(e,t)),this._syncRegistry.setTheme(t)}getGrammar(e){return e=hr(e,this._alias),this._resolvedGrammars.get(e)}loadLanguage(e){if(this.getGrammar(e.name))return;let t=new Set([...this._langMap.values()].filter(a=>a.embeddedLangsLazy?.includes(e.name)));this._resolver.addLanguage(e);let n={balancedBracketSelectors:e.balancedBracketSelectors||["*"],unbalancedBracketSelectors:e.unbalancedBracketSelectors||[]};this._syncRegistry._rawGrammars.set(e.scopeName,e);let r=this.loadGrammarWithConfiguration(e.scopeName,1,n);if(r.name=e.name,this._resolvedGrammars.set(e.name,r),e.aliases&&e.aliases.forEach(a=>{this._alias[a]=e.name}),this._loadedLanguagesCache=null,t.size)for(let a of t)this._resolvedGrammars.delete(a.name),this._loadedLanguagesCache=null,this._syncRegistry?._injectionGrammars?.delete(a.scopeName),this._syncRegistry?._grammars?.delete(a.scopeName),this.loadLanguage(this._langMap.get(a.name))}dispose(){super.dispose(),this._resolvedThemes.clear(),this._resolvedGrammars.clear(),this._langMap.clear(),this._langGraph.clear(),this._loadedThemesCache=null}loadLanguages(e){for(let r of e)this.resolveEmbeddedLanguages(r);let t=[...this._langGraph.entries()],n=t.filter(([r,a])=>!a);if(n.length){let r=t.filter(([a,o])=>o?(o.embeddedLanguages||o.embeddedLangs)?.some(i=>n.map(([s])=>s).includes(i)):!1).filter(a=>!n.includes(a));throw new E(`Missing languages ${n.map(([a])=>`\`${a}\``).join(", ")}, required by ${r.map(([a])=>`\`${a}\``).join(", ")}`)}for(let[r,a]of t)this._resolver.addLanguage(a);for(let[r,a]of t)this.loadLanguage(a)}getLoadedLanguages(){return this._loadedLanguagesCache||(this._loadedLanguagesCache=[...new Set([...this._resolvedGrammars.keys(),...Object.keys(this._alias)])]),this._loadedLanguagesCache}resolveEmbeddedLanguages(e){this._langMap.set(e.name,e),this._langGraph.set(e.name,e);let t=e.embeddedLanguages??e.embeddedLangs;if(t)for(let n of t)this._langGraph.set(n,this._langMap.get(n))}},Do=class{_langs=new Map;_scopeToLang=new Map;_injections=new Map;_onigLib;constructor(e,t){this._onigLib={createOnigScanner:n=>e.createScanner(n),createOnigString:n=>e.createString(n)},t.forEach(n=>this.addLanguage(n))}get onigLib(){return this._onigLib}getLangRegistration(e){return this._langs.get(e)}loadGrammar(e){return this._scopeToLang.get(e)}addLanguage(e){this._langs.set(e.name,e),e.aliases&&e.aliases.forEach(t=>{this._langs.set(t,e)}),this._scopeToLang.set(e.scopeName,e),e.injectTo&&e.injectTo.forEach(t=>{this._injections.get(t)||this._injections.set(t,[]),this._injections.get(t).push(e.scopeName)})}getInjections(e){let t=e.split("."),n=[];for(let r=1;r<=t.length;r++){let a=t.slice(0,r).join(".");n=[...n,...this._injections.get(a)||[]]}return n}},Le=0;function qt(e){Le+=1,e.warnings!==!1&&Le>=10&&Le%10===0&&console.warn(`[Shiki] ${Le} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call \`highlighter.dispose()\` to release unused instances.`);let t=!1;if(!e.engine)throw new E("`engine` option is required for synchronous mode");let n=(e.langs||[]).flat(1),r=(e.themes||[]).flat(1).map(tt),a=new Oo(new Do(e.engine,n),r,n,e.langAlias),o;function i(b){return hr(b,e.langAlias)}function s(b){w();let k=a.getGrammar(typeof b=="string"?b:b.name);if(!k)throw new E(`Language \`${b}\` not found, you may need to load it first`);return k}function l(b){if(b==="none")return{bg:"",fg:"",name:"none",settings:[],type:"dark"};w();let k=a.getTheme(b);if(!k)throw new E(`Theme \`${b}\` not found, you may need to load it first`);return k}function c(b){w();let k=l(b);return o!==b&&(a.setTheme(k),o=b),{theme:k,colorMap:a.getColorMap()}}function u(){return w(),a.getLoadedThemes()}function p(){return w(),a.getLoadedLanguages()}function d(...b){w(),a.loadLanguages(b.flat(1))}async function g(...b){return d(await dr(b))}function h(...b){w();for(let k of b.flat(1))a.loadTheme(k)}async function y(...b){return w(),h(await gr(b))}function w(){if(t)throw new E("Shiki instance has been disposed")}function m(){t||(t=!0,a.dispose(),Le-=1)}return{setTheme:c,getTheme:l,getLanguage:s,getLoadedThemes:u,getLoadedLanguages:p,resolveLangAlias:i,loadLanguage:g,loadLanguageSync:d,loadTheme:y,loadThemeSync:h,dispose:m,[Symbol.dispose]:m}}async function jt(e){e.engine||console.warn("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");let[t,n,r]=await Promise.all([gr(e.themes||[]),dr(e.langs||[]),e.engine]);return qt({...e,themes:t,langs:n,engine:r})}var fr=new WeakMap;function Ge(e,t){fr.set(e,t)}function ke(e){return fr.get(e)}var nt=class mr{_stacks={};lang;get themes(){return Object.keys(this._stacks)}get theme(){return this.themes[0]}get _stack(){return this._stacks[this.theme]}static initial(t,n){return new mr(Object.fromEntries(cr(n).map(r=>[r,et])),t)}constructor(...t){if(t.length===2){let[n,r]=t;this.lang=r,this._stacks=n}else{let[n,r,a]=t;this.lang=r,this._stacks={[a]:n}}}getInternalStack(t=this.theme){return this._stacks[t]}getScopes(t=this.theme){return Uo(this._stacks[t])}toJSON(){return{lang:this.lang,theme:this.theme,themes:this.themes,scopes:this.getScopes()}}};function Uo(e){let t=[],n=new Set;function r(a){if(n.has(a))return;n.add(a);let o=a?.nameScopesList?.scopeName;o&&t.push(o),a.parent&&r(a.parent)}return r(e),t}function qo(e,t){if(!(e instanceof nt))throw new E("Invalid grammar state");return e.getInternalStack(t)}var jo=/,/,Ho=/ /;function Ht(e,t,n={}){let{theme:r=e.getLoadedThemes()[0]}=n;if($e(e.resolveLangAlias(n.lang||"text"))||Me(r))return we(t).map(s=>[{content:s[0],offset:s[1]}]);let{theme:a,colorMap:o}=e.setTheme(r),i=e.getLanguage(n.lang||"text");if(n.grammarState){if(n.grammarState.lang!==i.name)throw new E(`Grammar state language "${n.grammarState.lang}" does not match highlight language "${i.name}"`);if(!n.grammarState.themes.includes(a.name))throw new E(`Grammar state themes "${n.grammarState.themes}" do not contain highlight theme "${a.name}"`)}return yr(t,i,a,o,n)}function br(...e){if(e.length===2)return ke(e[1]);let[t,n,r={}]=e,{lang:a="text",theme:o=t.getLoadedThemes()[0]}=r;if($e(a)||Me(o))throw new E("Plain language does not have grammar state");if(a==="ansi")throw new E("ANSI language does not have grammar state");let{theme:i,colorMap:s}=t.setTheme(o),l=t.getLanguage(a);return new nt(Wt(n,l,i,s,r).stateStack,l.name,i.name)}function yr(e,t,n,r,a){let o=Wt(e,t,n,r,a),i=new nt(o.stateStack,t.name,n.name);return Ge(o.tokens,i),o.tokens}function Wt(e,t,n,r,a){let o=Pe(n,a),{tokenizeMaxLineLength:i=0,tokenizeTimeLimit:s=500,includeExplanation:l=!1}=a,c=we(e),u=a.grammarState?qo(a.grammarState,n.name)??et:a.grammarContextCode!=null?Wt(a.grammarContextCode,t,n,r,{...a,grammarState:void 0,grammarContextCode:void 0}).stateStack:et,p=[],d=[];for(let g=0,h=c.length;g0&&y.length>=i){p=[],d.push([{content:y,offset:w,color:"",fontStyle:0}]);continue}let m,b,k;l&&l!=="tokenType"&&(m=t.tokenizeLine(y,u,s),b=m.tokens,k=0);let v=t.tokenizeLine2(y,u,s),S=v.tokens.length/2;for(let L=0;LBt.trim());break;case"object":ye=V.scope;break;default:continue}Nn.push({settings:V,selectors:ye.map(Bt=>Bt.split(Ho))})}W.explanation=[];let Tn=0;for(;M+Tn({scopeName:t}))}function zo(e,t){let n=[];for(let r=0,a=t.length;r=0&&a>=0;)lr(e[r],n[a])&&(r-=1),a-=1;return r===-1}function Xo(e,t,n){let r=[];for(let{selectors:a,settings:o}of e)for(let i of a)if(Vo(i,t,n)){r.push(o);break}return r}function rt(e,t,n,r=Ht){let a=Object.entries(n.themes).filter(c=>c[1]).map(c=>({color:c[0],theme:c[1]})),o=a.map(c=>{let u=r(e,t,{...n,theme:c.theme});return{tokens:u,state:ke(u),theme:typeof c.theme=="string"?c.theme:c.theme.name}}),i=Ko(...o.map(c=>c.tokens)),s=i[0].map((c,u)=>c.map((p,d)=>{let g={content:p.content,variants:{},offset:p.offset};return"includeExplanation"in n&&n.includeExplanation&&(g.explanation=p.explanation),i.forEach((h,y)=>{let{content:w,explanation:m,offset:b,...k}=h[u][d];g.variants[a[y].color]=k}),g})),l=o[0].state?new nt(Object.fromEntries(o.map(c=>[c.theme,c.state?.getInternalStack(c.theme)])),o[0].state.lang):void 0;return l&&Ge(s,l),s}function Ko(...e){let t=e.map(()=>[]),n=e.length;for(let r=0;rl[r]),o=t.map(()=>[]);t.forEach((l,c)=>l.push(o[c]));let i=a.map(()=>0),s=a.map(l=>l[0]);for(;s.every(l=>l);){let l=Math.min(...s.map(c=>c.content.length));for(let c=0;cx,booleanish:()=>A,commaOrSpaceSeparated:()=>G,commaSeparated:()=>Q,number:()=>f,overloadedBoolean:()=>at,spaceSeparated:()=>_});var Qo=0,x=ce(),A=ce(),at=ce(),f=ce(),_=ce(),Q=ce(),G=ce();function ce(){return 2**++Qo}var Vt=Object.keys(Oe),ue=class extends T{constructor(t,n,r,a){let o=-1;if(super(t,n),kr(this,"space",a),typeof r=="number")for(;++o4&&n.slice(0,4)==="data"&&Jo.test(t)){if(t.charAt(4)==="-"){let o=t.slice(5).replace(vr,ei);r="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{let o=t.slice(4);if(!vr.test(o)){let i=o.replace(Yo,Zo);i.charAt(0)!=="-"&&(i="-"+i),t="data"+i}}a=ue}return new a(r,t)}function Zo(e){return"-"+e.toLowerCase()}function ei(e){return e.charAt(1).toUpperCase()}var st=zt([Xt,xr,Kt,Qt,Yt],"html"),lt=zt([Xt,Cr,Kt,Qt,Yt],"svg");var _r={}.hasOwnProperty;function Sr(e,t){let n=t||{};function r(a,...o){let i=r.invalid,s=r.handlers;if(a&&_r.call(a,e)){let l=String(a[e]);i=_r.call(s,l)?s[l]:r.unknown}if(i)return i.call(this,a,...o)}return r.handlers=n.handlers||{},r.invalid=n.invalid,r.unknown=n.unknown,r}var ti=/["&'<>`]/g,ni=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,ri=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,ai=/[|\\{}()[\]^$+*?.]/g,Er=new WeakMap;function Ar(e,t){if(e=e.replace(t.subset?oi(t.subset):ti,r),t.subset||t.escapeOnly)return e;return e.replace(ni,n).replace(ri,r);function n(a,o,i){return t.format((a.charCodeAt(0)-55296)*1024+a.charCodeAt(1)-56320+65536,i.charCodeAt(o+2),t)}function r(a,o,i){return t.format(a.charCodeAt(0),i.charCodeAt(o+1),t)}}function oi(e){let t=Er.get(e);return t||(t=ii(e),Er.set(e,t)),t}function ii(e){let t=[],n=-1;for(;++n",OElig:"\u0152",oelig:"\u0153",Scaron:"\u0160",scaron:"\u0161",Yuml:"\u0178",circ:"\u02C6",tilde:"\u02DC",ensp:"\u2002",emsp:"\u2003",thinsp:"\u2009",zwnj:"\u200C",zwj:"\u200D",lrm:"\u200E",rlm:"\u200F",ndash:"\u2013",mdash:"\u2014",lsquo:"\u2018",rsquo:"\u2019",sbquo:"\u201A",ldquo:"\u201C",rdquo:"\u201D",bdquo:"\u201E",dagger:"\u2020",Dagger:"\u2021",permil:"\u2030",lsaquo:"\u2039",rsaquo:"\u203A",euro:"\u20AC"};var Nr=["cent","copy","divide","gt","lt","not","para","times"];var Tr={}.hasOwnProperty,Zt={},ut;for(ut in ct)Tr.call(ct,ut)&&(Zt[ct[ut]]=ut);var ci=/[^\dA-Za-z]/;function Lr(e,t,n,r){let a=String.fromCharCode(e);if(Tr.call(Zt,a)){let o=Zt[a],i="&"+o;return n&&Br.includes(o)&&!Nr.includes(o)&&(!r||t&&t!==61&&ci.test(String.fromCharCode(t)))?i:i+";"}return""}function Pr(e,t,n){let r=Rr(e,t,n.omitOptionalSemicolons),a;if((n.useNamedReferences||n.useShortestReferences)&&(a=Lr(e,t,n.omitOptionalSemicolons,n.attribute)),(n.useShortestReferences||!a)&&n.useShortestReferences){let o=Ir(e,t,n.omitOptionalSemicolons);o.length|^->||--!>|"],di=["<",">"];function $r(e,t,n,r){return r.settings.bogusComments?"":"";function a(o){return Y(o,Object.assign({},r.settings.characterReferences,{subset:di}))}}function Mr(e,t,n,r){return""}function en(e,t){let n=String(e);if(typeof t!="string")throw new TypeError("Expected character");let r=0,a=n.indexOf(t);for(;a!==-1;)r++,a=n.indexOf(t,a+t.length);return r}function Gr(e,t){let n=t||{};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}function Fr(e){return e.join(" ").trim()}var gi=/[ \t\n\f\r]/g;function pe(e){return typeof e=="object"?e.type==="text"?Or(e.value):!1:Or(e)}function Or(e){return e.replace(gi,"")===""}var R=Dr(1),tn=Dr(-1),hi=[];function Dr(e){return t;function t(n,r,a){let o=n?n.children:hi,i=(r||0)+e,s=o[i];if(!a)for(;s&&pe(s);)i+=e,s=o[i];return s}}var fi={}.hasOwnProperty;function pt(e){return t;function t(n,r,a){return fi.call(e,n.tagName)&&e[n.tagName](n,r,a)}}var De=pt({body:bi,caption:nn,colgroup:nn,dd:xi,dt:ki,head:nn,html:mi,li:wi,optgroup:Ci,option:vi,p:yi,rp:Ur,rt:Ur,tbody:Si,td:qr,tfoot:Ei,th:qr,thead:_i,tr:Ai});function nn(e,t,n){let r=R(n,t,!0);return!r||r.type!=="comment"&&!(r.type==="text"&&pe(r.value.charAt(0)))}function mi(e,t,n){let r=R(n,t);return!r||r.type!=="comment"}function bi(e,t,n){let r=R(n,t);return!r||r.type!=="comment"}function yi(e,t,n){let r=R(n,t);return r?r.type==="element"&&(r.tagName==="address"||r.tagName==="article"||r.tagName==="aside"||r.tagName==="blockquote"||r.tagName==="details"||r.tagName==="div"||r.tagName==="dl"||r.tagName==="fieldset"||r.tagName==="figcaption"||r.tagName==="figure"||r.tagName==="footer"||r.tagName==="form"||r.tagName==="h1"||r.tagName==="h2"||r.tagName==="h3"||r.tagName==="h4"||r.tagName==="h5"||r.tagName==="h6"||r.tagName==="header"||r.tagName==="hgroup"||r.tagName==="hr"||r.tagName==="main"||r.tagName==="menu"||r.tagName==="nav"||r.tagName==="ol"||r.tagName==="p"||r.tagName==="pre"||r.tagName==="section"||r.tagName==="table"||r.tagName==="ul"):!n||!(n.type==="element"&&(n.tagName==="a"||n.tagName==="audio"||n.tagName==="del"||n.tagName==="ins"||n.tagName==="map"||n.tagName==="noscript"||n.tagName==="video"||n.tagName.includes("-")))}function wi(e,t,n){let r=R(n,t);return!r||r.type==="element"&&r.tagName==="li"}function ki(e,t,n){let r=R(n,t);return!!(r&&r.type==="element"&&(r.tagName==="dt"||r.tagName==="dd"))}function xi(e,t,n){let r=R(n,t);return!r||r.type==="element"&&(r.tagName==="dt"||r.tagName==="dd")}function Ur(e,t,n){let r=R(n,t);return!r||r.type==="element"&&(r.tagName==="rp"||r.tagName==="rt")}function Ci(e,t,n){let r=R(n,t);return!r||r.type==="element"&&r.tagName==="optgroup"}function vi(e,t,n){let r=R(n,t);return!r||r.type==="element"&&(r.tagName==="option"||r.tagName==="optgroup")}function _i(e,t,n){let r=R(n,t);return!!(r&&r.type==="element"&&(r.tagName==="tbody"||r.tagName==="tfoot"))}function Si(e,t,n){let r=R(n,t);return!r||r.type==="element"&&(r.tagName==="tbody"||r.tagName==="tfoot")}function Ei(e,t,n){return!R(n,t)}function Ai(e,t,n){let r=R(n,t);return!r||r.type==="element"&&r.tagName==="tr"}function qr(e,t,n){let r=R(n,t);return!r||r.type==="element"&&(r.tagName==="td"||r.tagName==="th")}var jr=pt({body:Bi,colgroup:Ni,head:Ii,html:Ri,tbody:Ti});function Ri(e){let t=R(e,-1);return!t||t.type!=="comment"}function Ii(e){let t=new Set;for(let r of e.children)if(r.type==="element"&&(r.tagName==="base"||r.tagName==="title")){if(t.has(r.tagName))return!1;t.add(r.tagName)}let n=e.children[0];return!n||n.type==="element"}function Bi(e){let t=R(e,-1,!0);return!t||t.type!=="comment"&&!(t.type==="text"&&pe(t.value.charAt(0)))&&!(t.type==="element"&&(t.tagName==="meta"||t.tagName==="link"||t.tagName==="script"||t.tagName==="style"||t.tagName==="template"))}function Ni(e,t,n){let r=tn(n,t);if(n&&r&&r.type==="element"&&r.tagName==="colgroup"&&De(r,n.children.indexOf(r),n))return!1;let a=R(e,-1,!0);return!!(a&&a.type==="element"&&a.tagName==="col")}function Ti(e,t,n){let r=tn(n,t);if(n&&r&&r.type==="element"&&(r.tagName==="thead"||r.tagName==="tbody")&&De(r,n.children.indexOf(r),n))return!1;let a=R(e,-1);return!!(a&&a.type==="element"&&a.tagName==="tr")}var dt={name:[[` +\f\r &/=>`.split(""),` +\f\r "&'/=>\``.split("")],[`\0 +\f\r "&'/<=>`.split(""),`\0 +\f\r "&'/<=>\``.split("")]],unquoted:[[` +\f\r &>`.split(""),`\0 +\f\r "&'<=>\``.split("")],[`\0 +\f\r "&'<=>\``.split(""),`\0 +\f\r "&'<=>\``.split("")]],single:[["&'".split(""),"\"&'`".split("")],["\0&'".split(""),"\0\"&'`".split("")]],double:[['"&'.split(""),"\"&'`".split("")],['\0"&'.split(""),"\0\"&'`".split("")]]},Li=new Set(["desc","foreignObject","title"]);function Hr(e,t,n,r){let{schema:a}=r,o=a.space==="svg"?!1:r.settings.omitOptionalTags,i=a.space==="svg"?r.settings.closeEmptyElements:r.settings.voids.includes(e.tagName.toLowerCase()),s=[];a.space==="html"&&e.tagName==="svg"&&(r.schema=lt);let l=Pi(r,e.properties);r.schema.space==="svg"&&Li.has(e.tagName)&&(r.schema=st);let c=r.all(a.space==="html"&&e.tagName==="template"?e.content:e);if(r.schema=a,c&&(i=!1),l||!o||!jr(e,t,n)){if(s.push("<",e.tagName,l?" "+l:""),i&&(a.space==="svg"||r.settings.closeSelfClosing)){let u=l.charAt(l.length-1);(!r.settings.tightSelfClosing||u==="/"||u&&u!=='"'&&u!=="'")&&s.push(" "),s.push("/")}s.push(">")}return s.push(c),!i&&(!o||!De(e,t,n))&&s.push(""),s.join("")}function Pi(e,t){let n=[],r=-1,a;if(t){for(a in t)if(t[a]!==null&&t[a]!==void 0){let o=$i(e,a,t[a]);o&&n.push(o)}}for(;++ren(n,e.alternative)&&(l=e.alternative),s=l+Y(n,Object.assign({},e.settings.characterReferences,{subset:(l==="'"?dt.single:dt.double)[a][o],attribute:!0}))+l}return i+(s&&"="+s)}var Mi=["<","&"];function gt(e,t,n,r){return n&&n.type==="element"&&(n.tagName==="script"||n.tagName==="style")?e.value:Y(e.value,Object.assign({},r.settings.characterReferences,{subset:Mi}))}function Wr(e,t,n,r){return r.settings.allowDangerousHtml?e.value:gt(e,t,n,r)}function zr(e,t,n,r){return r.all(e)}var Vr=Sr("type",{invalid:Gi,unknown:Fi,handlers:{comment:$r,doctype:Mr,element:Hr,raw:Wr,root:zr,text:gt}});function Gi(e){throw new Error("Expected node, not `"+e+"`")}function Fi(e){let t=e;throw new Error("Cannot compile unknown node `"+t.type+"`")}var Oi={},Di={},Ui=[];function rn(e,t){let n=t||Oi,r=n.quote||'"';if(r!=='"'&&r!=="'")throw new Error("Invalid quote `"+r+"`, expected `'` or `\"`");let a=r==='"'?"'":'"';return{one:qi,all:ji,settings:{omitOptionalTags:n.omitOptionalTags||!1,allowParseErrors:n.allowParseErrors||!1,allowDangerousCharacters:n.allowDangerousCharacters||!1,quoteSmart:n.quoteSmart||!1,preferUnquoted:n.preferUnquoted||!1,tightAttributes:n.tightAttributes||!1,upperDoctype:n.upperDoctype||!1,tightDoctype:n.tightDoctype||!1,bogusComments:n.bogusComments||!1,tightCommaSeparatedLists:n.tightCommaSeparatedLists||!1,tightSelfClosing:n.tightSelfClosing||!1,collapseEmptyAttributes:n.collapseEmptyAttributes||!1,allowDangerousHtml:n.allowDangerousHtml||!1,voids:n.voids||wr,characterReferences:n.characterReferences||Di,closeSelfClosing:n.closeSelfClosing||!1,closeEmptyElements:n.closeEmptyElements||!1},schema:n.space==="svg"?lt:st,quote:r,alternative:a}.one(Array.isArray(e)?{type:"root",children:e}:e,void 0,void 0)}function qi(e,t,n){return Vr(e,t,n,this)}function ji(e){let t=[],n=e&&e.children||Ui,r=-1;for(;++ra);function n(a){if(a===e.length)return{line:t.length-1,character:t.at(-1).length};let o=a,i=0;for(let s of t){if(on&&r.push({...e,content:e.content.slice(n,a),offset:e.offset+n}),n=a;return n>1);e[a]<=t?n=a+1:r=a}return n}function Xi(e,t){let n=[...t instanceof Set?t:new Set(t)].sort((r,a)=>r-a);return n.length?e.map(r=>r.flatMap(a=>{let o=a.offset+a.content.length,i=Vi(n,a.offset),s=i;for(;sht(e.variants[u])),s=new Set(i.flatMap(u=>Object.keys(u))),l={},c=(u,p)=>{let d=p==="color"?"":p==="background-color"?"-bg":`-${p}`;return n+t[u]+(p==="color"?"":d)};return i.forEach((u,p)=>{for(let d of s){let g=u[d]||"inherit";if(p===0&&r&&Wi.includes(d))if(r==="light-dark()"&&i.length>1){let h=t.findIndex(b=>b==="light"),y=t.findIndex(b=>b==="dark");if(h===-1||y===-1)throw new E('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');let w=i[h][d]||"inherit",m=i[y][d]||"inherit";l[d]=`light-dark(${w}, ${m})`,a==="css-vars"&&(l[c(p,d)]=g)}else l[d]=g;else a==="css-vars"&&(l[c(p,d)]=g)}}),o.htmlStyle=l,o}function ht(e){let t={};if(e.color&&(t.color=e.color),e.bgColor&&(t["background-color"]=e.bgColor),e.fontStyle){e.fontStyle&P.Italic&&(t["font-style"]="italic"),e.fontStyle&P.Bold&&(t["font-weight"]="bold");let n=[];e.fontStyle&P.Underline&&n.push("underline"),e.fontStyle&P.Strikethrough&&n.push("line-through"),n.length&&(t["text-decoration"]=n.join(" "))}return t}function on(e){return typeof e=="string"?e:Object.entries(e).map(([t,n])=>`${t}:${n}`).join(";")}function Qi(){let e=new WeakMap;function t(n){if(!e.has(n.meta)){let a=function(i){if(typeof i=="number"){if(i<0||i>n.source.length)throw new E(`Invalid decoration offset: ${i}. Code length: ${n.source.length}`);return{...r.indexToPos(i),offset:i}}else{let s=r.lines[i.line];if(s===void 0)throw new E(`Invalid decoration position ${JSON.stringify(i)}. Lines length: ${r.lines.length}`);let l=i.character;if(l<0&&(l=s.length+l),l<0||l>s.length)throw new E(`Invalid decoration position ${JSON.stringify(i)}. Line ${i.line} length: ${s.length}`);return{...i,character:l,offset:r.posToIndex(i.line,l)}}},r=Hi(n.source),o=(n.options.decorations||[]).map(i=>({...i,start:a(i.start),end:a(i.end)}));Yi(o),e.set(n.meta,{decorations:o,converter:r,source:n.source})}return e.get(n.meta)}return{name:"shiki:decorations",tokens(n){if(this.options.decorations?.length)return Xi(n,t(this).decorations.flatMap(r=>[r.start.offset,r.end.offset]))},code(n){if(!this.options.decorations?.length)return;let r=t(this),a=[...n.children].filter(u=>u.type==="element"&&u.tagName==="span");if(a.length!==r.converter.lines.length)throw new E(`Number of lines in code element (${a.length}) does not match the number of lines in the source (${r.converter.lines.length}). Failed to apply decorations.`);function o(u,p,d,g){let h=a[u],y="",w=-1,m=-1;if(p===0&&(w=0),d===0&&(m=0),d===Number.POSITIVE_INFINITY&&(m=h.children.length),w===-1||m===-1)for(let k=0;ky);return u.tagName=p.tagName||"span",u.properties={...u.properties,...g,class:u.properties.class},p.properties?.class&&Yr(u,p.properties.class),u=h(u,d)||u,u}let l=[],c=r.decorations.sort((u,p)=>p.start.offset-u.start.offset||u.end.offset-p.end.offset);for(let u of c){let{start:p,end:d}=u;if(p.line===d.line)o(p.line,p.character,d.character,u);else if(p.linei(g,u));o(d.line,0,d.character,u)}}l.forEach(u=>u())}}}function Yi(e){for(let t=0;tn.end.offset)throw new E(`Invalid decoration range: ${JSON.stringify(n.start)} - ${JSON.stringify(n.end)}`);for(let r=t+1;rNumber.parseInt(r));return n.length!==3||n.some(r=>Number.isNaN(r))?void 0:{type:"rgb",rgb:n}}else if(t==="5"){let n=e.shift();if(n)return{type:"table",index:Number(n)}}}function ts(e){let t=[];for(;e.length>0;){let n=e.shift();if(!n)continue;let r=Number.parseInt(n);if(!Number.isNaN(r))if(r===0)t.push({type:"resetAll"});else if(r<=9)an[r]&&t.push({type:"setDecoration",value:an[r]});else if(r<=29){let a=an[r-20];a&&(t.push({type:"resetDecoration",value:a}),a==="dim"&&t.push({type:"resetDecoration",value:"bold"}))}else if(r<=37)t.push({type:"setForegroundColor",value:{type:"named",name:de[r-30]}});else if(r===38){let a=Kr(e);a&&t.push({type:"setForegroundColor",value:a})}else if(r===39)t.push({type:"resetForegroundColor"});else if(r<=47)t.push({type:"setBackgroundColor",value:{type:"named",name:de[r-40]}});else if(r===48){let a=Kr(e);a&&t.push({type:"setBackgroundColor",value:a})}else r===49?t.push({type:"resetBackgroundColor"}):r===53?t.push({type:"setDecoration",value:"overline"}):r===55?t.push({type:"resetDecoration",value:"overline"}):r>=90&&r<=97?t.push({type:"setForegroundColor",value:{type:"named",name:de[r-90+8]}}):r>=100&&r<=107&&t.push({type:"setBackgroundColor",value:{type:"named",name:de[r-100+8]}})}return t}function ns(){let e=null,t=null,n=new Set;return{parse(r){let a=[],o=0;do{let i=es(r,o),s=i.sequence?r.substring(o,i.startPosition):r.substring(o);if(s.length>0&&a.push({value:s,foreground:e,background:t,decorations:new Set(n)}),i.sequence){let l=ts(i.sequence);for(let c of l)c.type==="resetAll"?(e=null,t=null,n.clear()):c.type==="resetForegroundColor"?e=null:c.type==="resetBackgroundColor"?t=null:c.type==="resetDecoration"&&n.delete(c.value);for(let c of l)c.type==="setForegroundColor"?e=c.value:c.type==="setBackgroundColor"?t=c.value:c.type==="setDecoration"&&n.add(c.value)}o=i.position}while(oMath.max(0,Math.min(l,255)).toString(16).padStart(2,"0")).join("")}`}let r;function a(){if(r)return r;r=[];for(let c=0;c{let l=`terminal.ansi${s[0].toUpperCase()}${s.substring(1)}`;return[s,e.colors?.[l]||ss[s]]}))),i=ns();return a.map(s=>i.parse(s[0]).map(l=>{let c,u;l.decorations.has("reverse")?(c=l.background?o.value(l.background):e.bg,u=l.foreground?o.value(l.foreground):e.fg):(c=l.foreground?o.value(l.foreground):e.fg,u=l.background?o.value(l.background):void 0),c=X(c,r),u=X(u,r),l.decorations.has("dim")&&(c=cs(c));let p=P.None;return l.decorations.has("bold")&&(p|=P.Bold),l.decorations.has("italic")&&(p|=P.Italic),l.decorations.has("underline")&&(p|=P.Underline),l.decorations.has("strikethrough")&&(p|=P.Strikethrough),{content:l.value,offset:s[1],color:c,bgColor:u,fontStyle:p}}))}function cs(e){let t=e.match(os);if(t){let r=t[1];if(r.length===8){let a=Math.round(Number.parseInt(r.slice(6,8),16)/2).toString(16).padStart(2,"0");return`#${r.slice(0,6)}${a}`}else{if(r.length===6)return`#${r}80`;if(r.length===4){let a=r[0],o=r[1],i=r[2],s=r[3];return`#${a}${a}${o}${o}${i}${i}${Math.round(Number.parseInt(`${s}${s}`,16)/2).toString(16).padStart(2,"0")}`}else if(r.length===3){let a=r[0],o=r[1],i=r[2];return`#${a}${a}${o}${o}${i}${i}80`}}}let n=e.match(is);return n?`var(${n[1]}-dim)`:e}function sn(e,t,n={}){let r=e.resolveLangAlias(n.lang||"text"),{theme:a=e.getLoadedThemes()[0]}=n;if(!$e(r)&&!Me(a)&&r==="ansi"){let{theme:o}=e.setTheme(a);return ls(o,t,n)}return Ht(e,t,n)}function mt(e,t,n){let r,a,o,i,s,l;if("themes"in n){let{defaultColor:c="light",cssVariablePrefix:u="--shiki-",colorsRendering:p="css-vars"}=n,d=Object.entries(n.themes).filter(m=>m[1]).map(m=>({color:m[0],theme:m[1]})).sort((m,b)=>m.color===c?-1:b.color===c?1:0);if(d.length===0)throw new E("`themes` option must not be empty");let g=rt(e,t,n,sn);if(l=ke(g),c&&c!=="light-dark()"&&!d.some(m=>m.color===c))throw new E(`\`themes\` option must contain the defaultColor key \`${c}\``);let h=d.map(m=>e.getTheme(m.theme)),y=d.map(m=>m.color);o=g.map(m=>m.map(b=>Ki(b,y,u,c,p))),l&&Ge(o,l);let w=d.map(m=>Pe(m.theme,n));a=Qr(d,h,w,u,c,"fg",p),r=Qr(d,h,w,u,c,"bg",p),i=`shiki-themes ${h.map(m=>m.name).join(" ")}`,s=c?void 0:[a,r].join(";")}else if("theme"in n){let c=Pe(n.theme,n);o=sn(e,t,n);let u=e.getTheme(n.theme);r=X(u.bg,c),a=X(u.fg,c),i=u.name,l=ke(o)}else throw new E("Invalid options, either `theme` or `themes` must be provided");return{tokens:o,fg:a,bg:r,themeName:i,rootStyle:s,grammarState:l}}function Qr(e,t,n,r,a,o,i){return e.map((s,l)=>{let c=X(t[l][o],n[l])||"inherit",u=`${r+s.color}${o==="bg"?"-bg":""}:${c}`;if(l===0&&a){if(a==="light-dark()"&&e.length>1){let p=e.findIndex(g=>g.color==="light"),d=e.findIndex(g=>g.color==="dark");if(p===-1||d===-1)throw new E('When using `defaultColor: "light-dark()"`, you must provide both `light` and `dark` themes');return`light-dark(${X(t[p][o],n[p])||"inherit"}, ${X(t[d][o],n[d])||"inherit"});${u}`}return c}return i==="css-vars"?u:null}).filter(s=>!!s).join(";")}var Zr=/^\s+$/,us=/^(\s*)(.*?)(\s*)$/;function bt(e,t,n,r={meta:{},options:n,codeToHast:(a,o)=>bt(e,a,o),codeToTokens:(a,o)=>mt(e,a,o)}){let a=t;for(let h of ft(n))a=h.preprocess?.call(r,a,n)||a;let{tokens:o,fg:i,bg:s,themeName:l,rootStyle:c,grammarState:u}=mt(e,a,n),{mergeWhitespaces:p=!0,mergeSameStyleTokens:d=!1}=n;p===!0?o=ds(o):p==="never"&&(o=gs(o)),d&&(o=hs(o));let g={...r,get source(){return a}};for(let h of ft(n))o=h.tokens?.call(g,o)||o;return ps(o,{...n,fg:i,bg:s,themeName:l,rootStyle:n.rootStyle===!1?!1:n.rootStyle??c},g,u)}function ps(e,t,n,r=ke(e)){let a=ft(t),o=[],i={type:"root",children:[]},{structure:s="classic",tabindex:l="0"}=t,c={class:`shiki ${t.themeName||""}`};t.rootStyle!==!1&&(t.rootStyle!=null?c.style=t.rootStyle:c.style=`background-color:${t.bg};color:${t.fg}`),l!==!1&&l!=null&&(c.tabindex=l.toString());for(let[y,w]of Object.entries(t.meta||{}))y.startsWith("_")||(c[y]=w);let u={type:"element",tagName:"pre",properties:c,children:[],data:t.data},p={type:"element",tagName:"code",properties:{},children:o},d=[],g={...n,structure:s,addClassToHast:Yr,get source(){return n.source},get tokens(){return e},get options(){return t},get root(){return i},get pre(){return u},get code(){return p},get lines(){return d}};if(e.forEach((y,w)=>{w&&(s==="inline"?i.children.push({type:"element",tagName:"br",properties:{},children:[]}):s==="classic"&&o.push({type:"text",value:` +`}));let m={type:"element",tagName:"span",properties:{class:"line"},children:[]},b=0;for(let k of y){let v={type:"element",tagName:"span",properties:{...k.htmlAttrs},children:[{type:"text",value:k.content}]},S=on(k.htmlStyle||ht(k));S&&(v.properties.style=S);for(let L of a)v=L?.span?.call(g,v,w+1,b,m,k)||v;s==="inline"?i.children.push(v):s==="classic"&&m.children.push(v),b+=k.content.length}if(s==="classic"){for(let k of a)m=k?.line?.call(g,m,w+1)||m;d.push(m),o.push(m)}else s==="inline"&&d.push(m)}),s==="classic"){for(let y of a)p=y?.code?.call(g,p)||p;u.children.push(p);for(let y of a)u=y?.pre?.call(g,u)||u;i.children.push(u)}else if(s==="inline"){let y=[],w={type:"element",tagName:"span",properties:{class:"line"},children:[]};for(let b of i.children)b.type==="element"&&b.tagName==="br"?(y.push(w),w={type:"element",tagName:"span",properties:{class:"line"},children:[]}):(b.type==="element"||b.type==="text")&&w.children.push(b);y.push(w);let m={type:"element",tagName:"code",properties:{},children:y};for(let b of a)m=b?.code?.call(g,m)||m;i.children=[];for(let b=0;b0&&i.children.push({type:"element",tagName:"br",properties:{},children:[]});let k=m.children[b];k.type==="element"&&i.children.push(...k.children)}}let h=i;for(let y of a)h=y?.root?.call(g,h)||h;return r&&Ge(h,r),h}function ds(e){return e.map(t=>{let n=[],r="",a;return t.forEach((o,i)=>{let s=!(o.fontStyle&&(o.fontStyle&P.Underline||o.fontStyle&P.Strikethrough));s&&Zr.test(o.content)&&t[i+1]?(a===void 0&&(a=o.offset),r+=o.content):r?(s?n.push({...o,offset:a,content:r+o.content}):n.push({content:r,offset:a},o),a=void 0,r=""):n.push(o)}),n})}function gs(e){return e.map(t=>t.flatMap(n=>{if(Zr.test(n.content))return n;let r=n.content.match(us);if(!r)return n;let[,a,o,i]=r;if(!a&&!i)return n;let s=[{...n,offset:n.offset+a.length,content:o}];return a&&s.unshift({content:a,offset:n.offset}),i&&s.push({content:i,offset:n.offset+a.length+o.length}),s}))}function hs(e){return e.map(t=>{let n=[];for(let r of t){if(n.length===0){n.push({...r});continue}let a=n.at(-1),o=on(a.htmlStyle||ht(a)),i=on(r.htmlStyle||ht(r)),s=a.fontStyle&&(a.fontStyle&P.Underline||a.fontStyle&P.Strikethrough),l=r.fontStyle&&(r.fontStyle&P.Underline||r.fontStyle&P.Strikethrough);!s&&!l&&o===i?a.content+=r.content:n.push({...r})}return n})}var fs=rn;function ms(e,t,n){let r={meta:{},options:n,codeToHast:(o,i)=>bt(e,o,i),codeToTokens:(o,i)=>mt(e,o,i)},a=fs(bt(e,t,n,r));for(let o of ft(n))a=o.postprocess?.call(r,a,n)||a;return a}async function ea(e){let t=await jt(e);return{getLastGrammarState:(...n)=>br(t,...n),codeToTokensBase:(n,r)=>sn(t,n,r),codeToTokensWithThemes:(n,r)=>rt(t,n,r),codeToTokens:(n,r)=>mt(t,n,r),codeToHast:(n,r)=>bt(t,n,r),codeToHtml:(n,r)=>ms(t,n,r),getBundledLanguages:()=>({}),getBundledThemes:()=>({}),...t,getInternalContext:()=>t}}var ta=class{patterns;options;regexps;constructor(e,t={}){this.patterns=e,this.options=t;let{forgiving:n=!1,cache:r,regexConstructor:a}=t;if(!a)throw new Error("Option `regexConstructor` is not provided");this.regexps=e.map(o=>{if(typeof o!="string")return o;let i=r?.get(o);if(i){if(i instanceof RegExp)return i;if(n)return null;throw i}try{let s=a(o);return r?.set(o,s),s}catch(s){if(r?.set(o,s),n)return null;throw s}})}findNextMatchSync(e,t,n){let r=typeof e=="string"?e:e.content,a=[];function o(i,s,l=0){return{index:i,captureIndices:s.indices.map(c=>c==null?{start:4294967295,end:4294967295,length:0}:{start:c[0]+l,end:c[1]+l,length:c[1]-c[0]})}}for(let i=0;is[1].index));for(let[s,l,c]of a)if(l.index===i)return o(s,l,c)}return null}};function ae(e){if([...e].length!==1)throw new Error(`Expected "${e}" to be a single code point`);return e.codePointAt(0)}function na(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}var Ue=new Set(["alnum","alpha","ascii","blank","cntrl","digit","graph","lower","print","punct","space","upper","word","xdigit"]),B=String.raw;function J(e,t){if(e==null)throw new Error(t??"Value expected");return e}var la=B`\[\^?`,ca=`c.? | C(?:-.?)?|${B`[pP]\{(?:\^?[-\x20_]*[A-Za-z][-\x20\w]*\})?`}|${B`x[89A-Fa-f]\p{AHex}(?:\\x[89A-Fa-f]\p{AHex})*`}|${B`u(?:\p{AHex}{4})? | x\{[^\}]*\}? | x\p{AHex}{0,2}`}|${B`o\{[^\}]*\}?`}|${B`\d{1,3}`}`,cn=/[?*+][?+]?|\{(?:\d+(?:,\d*)?|,\d+)\}\??/,yt=new RegExp(B` + \\ (?: + ${ca} + | [gk]<[^>]*>? + | [gk]'[^']*'? + | . + ) + | \( (?: + \? (?: + [:=!>({] + | <[=!] + | <[^>]*> + | '[^']*' + | ~\|? + | #(?:[^)\\]|\\.?)* + | [^:)]*[:)] + )? + | \*[^\)]*\)? + )? + | (?:${cn.source})+ + | ${la} + | . +`.replace(/\s+/g,""),"gsu"),ln=new RegExp(B` + \\ (?: + ${ca} + | . + ) + | \[:(?:\^?\p{Alpha}+|\^):\] + | ${la} + | && + | . +`.replace(/\s+/g,""),"gsu");function ua(e,t={}){let n={flags:"",...t,rules:{captureGroup:!1,singleline:!1,...t.rules}};if(typeof e!="string")throw new Error("String expected as pattern");let r=$s(n.flags),a=[r.extended],o={captureGroup:n.rules.captureGroup,getCurrentModX(){return a.at(-1)},numOpenGroups:0,popModX(){a.pop()},pushModX(p){a.push(p)},replaceCurrentModX(p){a[a.length-1]=p},singleline:n.rules.singleline},i=[],s;for(yt.lastIndex=0;s=yt.exec(e);){let p=bs(o,e,s[0],yt.lastIndex);p.tokens?i.push(...p.tokens):p.token&&i.push(p.token),p.lastIndex!==void 0&&(yt.lastIndex=p.lastIndex)}let l=[],c=0;i.filter(p=>p.type==="GroupOpen").forEach(p=>{p.kind==="capturing"?p.number=++c:p.raw==="("&&l.push(p)}),c||l.forEach((p,d)=>{p.kind="capturing",p.number=d+1});let u=c||l.length;return{tokens:i.map(p=>p.type==="EscapedNumber"?Gs(p,u):p).flat(),flags:r}}function bs(e,t,n,r){let[a,o]=n;if(n==="["||n==="[^"){let i=ys(t,n,r);return{tokens:i.tokens,lastIndex:i.lastIndex}}if(a==="\\"){if("AbBGyYzZ".includes(o))return{token:ra(n,n)};if(/^\\g[<']/.test(n)){if(!/^\\g(?:<[^>]+>|'[^']+')$/.test(n))throw new Error(`Invalid group name "${n}"`);return{token:Rs(n)}}if(/^\\k[<']/.test(n)){if(!/^\\k(?:<[^>]+>|'[^']+')$/.test(n))throw new Error(`Invalid group name "${n}"`);return{token:da(n)}}if(o==="K")return{token:ga("keep",n)};if(o==="N"||o==="R")return{token:ge("newline",n,{negate:o==="N"})};if(o==="O")return{token:ge("any",n)};if(o==="X")return{token:ge("text_segment",n)};let i=pa(n,{inCharClass:!1});return Array.isArray(i)?{tokens:i}:{token:i}}if(a==="("){if(o==="*")return{token:Ts(n)};if(n==="(?{")throw new Error(`Unsupported callout "${n}"`);if(n.startsWith("(?#")){if(t[r]!==")")throw new Error('Unclosed comment group "(?#"');return{lastIndex:r+1}}if(/^\(\?[-imx]+[:)]$/.test(n))return{token:Ns(n,e)};if(e.pushModX(e.getCurrentModX()),e.numOpenGroups++,n==="("&&!e.captureGroup||n==="(?:")return{token:xe("group",n)};if(n==="(?>")return{token:xe("atomic",n)};if(n==="(?="||n==="(?!"||n==="(?<="||n==="(?")||n.startsWith("(?'")&&n.endsWith("'"))return{token:xe("capturing",n,{...n!=="("&&{name:n.slice(3,-1)}})};if(n.startsWith("(?~")){if(n==="(?~|")throw new Error(`Unsupported absence function kind "${n}"`);return{token:xe("absence_repeater",n)}}throw n==="(?("?new Error(`Unsupported conditional "${n}"`):new Error(`Invalid or unsupported group option "${n}"`)}if(n===")"){if(e.popModX(),e.numOpenGroups--,e.numOpenGroups<0)throw new Error('Unmatched ")"');return{token:Ss(n)}}if(e.getCurrentModX()){if(n==="#"){let i=t.indexOf(` +`,r);return{lastIndex:i===-1?t.length:i}}if(/^\s$/.test(n)){let i=/\s+/y;return i.lastIndex=r,{lastIndex:i.exec(t)?i.lastIndex:r}}}if(n===".")return{token:ge("dot",n)};if(n==="^"||n==="$"){let i=e.singleline?{"^":B`\A`,$:B`\Z`}[n]:n;return{token:ra(i,n)}}return n==="|"?{token:ks(n)}:cn.test(n)?{tokens:Fs(n)}:{token:Z(ae(n),n)}}function ys(e,t,n){let r=[aa(t[1]==="^",t)],a=1,o;for(ln.lastIndex=n;o=ln.exec(e);){let i=o[0];if(i[0]==="["&&i[1]!==":")a++,r.push(aa(i[1]==="^",i));else if(i==="]"){if(r.at(-1).type==="CharacterClassOpen")r.push(Z(93,i));else if(a--,r.push(xs(i)),!a)break}else{let s=ws(i);Array.isArray(s)?r.push(...s):r.push(s)}}return{tokens:r,lastIndex:ln.lastIndex||e.length}}function ws(e){if(e[0]==="\\")return pa(e,{inCharClass:!0});if(e[0]==="["){let t=/\[:(?\^?)(?[a-z]+):\]/.exec(e);if(!t||!Ue.has(t.groups.name))throw new Error(`Invalid POSIX class "${e}"`);return ge("posix",e,{value:t.groups.name,negate:!!t.groups.negate})}return e==="-"?Cs(e):e==="&&"?vs(e):Z(ae(e),e)}function pa(e,{inCharClass:t}){let n=e[1];if(n==="c"||n==="C")return Bs(e);if("dDhHsSwW".includes(n))return Ls(e);if(e.startsWith(B`\o{`))throw new Error(`Incomplete, invalid, or unsupported octal code point "${e}"`);if(/^\\[pP]\{/.test(e)){if(e.length===3)throw new Error(`Incomplete or invalid Unicode property "${e}"`);return Ps(e)}if(/^\\x[89A-Fa-f]\p{AHex}/u.test(e))try{let r=e.split(/\\x/).slice(1).map(i=>parseInt(i,16)),a=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}).decode(new Uint8Array(r)),o=new TextEncoder;return[...a].map(i=>{let s=[...o.encode(i)].map(l=>`\\x${l.toString(16)}`).join("");return Z(ae(i),s)})}catch{throw new Error(`Multibyte code "${e}" incomplete or invalid in Oniguruma`)}if(n==="u"||n==="x")return Z(Ms(e),e);if(oa.has(n))return Z(oa.get(n),e);if(/\d/.test(n))return _s(t,e);if(e==="\\")throw new Error(B`Incomplete escape "\"`);if(n==="M")throw new Error(`Unsupported meta "${e}"`);if([...e].length===2)return Z(e.codePointAt(1),e);throw new Error(`Unexpected escape "${e}"`)}function ks(e){return{type:"Alternator",raw:e}}function ra(e,t){return{type:"Assertion",kind:e,raw:t}}function da(e){return{type:"Backreference",raw:e}}function Z(e,t){return{type:"Character",value:e,raw:t}}function xs(e){return{type:"CharacterClassClose",raw:e}}function Cs(e){return{type:"CharacterClassHyphen",raw:e}}function vs(e){return{type:"CharacterClassIntersector",raw:e}}function aa(e,t){return{type:"CharacterClassOpen",negate:e,raw:t}}function ge(e,t,n={}){return{type:"CharacterSet",kind:e,...n,raw:t}}function ga(e,t,n={}){return e==="keep"?{type:"Directive",kind:e,raw:t}:{type:"Directive",kind:e,flags:J(n.flags),raw:t}}function _s(e,t){return{type:"EscapedNumber",inCharClass:e,raw:t}}function Ss(e){return{type:"GroupClose",raw:e}}function xe(e,t,n={}){return{type:"GroupOpen",kind:e,...n,raw:t}}function Es(e,t,n,r){return{type:"NamedCallout",kind:e,tag:t,arguments:n,raw:r}}function As(e,t,n,r){return{type:"Quantifier",kind:e,min:t,max:n,raw:r}}function Rs(e){return{type:"Subroutine",raw:e}}var Is=new Set(["COUNT","CMP","ERROR","FAIL","MAX","MISMATCH","SKIP","TOTAL_COUNT"]),oa=new Map([["a",7],["b",8],["e",27],["f",12],["n",10],["r",13],["t",9],["v",11]]);function Bs(e){let t=e[1]==="c"?e[2]:e[3];if(!t||!/[A-Za-z]/.test(t))throw new Error(`Unsupported control character "${e}"`);return Z(ae(t.toUpperCase())-64,e)}function Ns(e,t){let{on:n,off:r}=/^\(\?(?[imx]*)(?:-(?[-imx]*))?/.exec(e).groups;r??="";let a=(t.getCurrentModX()||n.includes("x"))&&!r.includes("x"),o=sa(n),i=sa(r),s={};if(o&&(s.enable=o),i&&(s.disable=i),e.endsWith(")"))return t.replaceCurrentModX(a),ga("flags",e,{flags:s});if(e.endsWith(":"))return t.pushModX(a),t.numOpenGroups++,xe("group",e,{...(o||i)&&{flags:s}});throw new Error(`Unexpected flag modifier "${e}"`)}function Ts(e){let t=/\(\*(?[A-Za-z_]\w*)?(?:\[(?(?:[A-Za-z_]\w*)?)\])?(?:\{(?[^}]*)\})?\)/.exec(e);if(!t)throw new Error(`Incomplete or invalid named callout "${e}"`);let{name:n,tag:r,args:a}=t.groups;if(!n)throw new Error(`Invalid named callout "${e}"`);if(r==="")throw new Error(`Named callout tag with empty value not allowed "${e}"`);let o=a?a.split(",").filter(u=>u!=="").map(u=>/^[+-]?\d+$/.test(u)?+u:u):[],[i,s,l]=o,c=Is.has(n)?n.toLowerCase():"custom";switch(c){case"fail":case"mismatch":case"skip":if(o.length>0)throw new Error(`Named callout arguments not allowed "${o}"`);break;case"error":if(o.length>1)throw new Error(`Named callout allows only one argument "${o}"`);if(typeof i=="string")throw new Error(`Named callout argument must be a number "${i}"`);break;case"max":if(!o.length||o.length>2)throw new Error(`Named callout must have one or two arguments "${o}"`);if(typeof i=="string"&&!/^[A-Za-z_]\w*$/.test(i))throw new Error(`Named callout argument one must be a tag or number "${i}"`);if(o.length===2&&(typeof s=="number"||!/^[<>X]$/.test(s)))throw new Error(`Named callout optional argument two must be '<', '>', or 'X' "${s}"`);break;case"count":case"total_count":if(o.length>1)throw new Error(`Named callout allows only one argument "${o}"`);if(o.length===1&&(typeof i=="number"||!/^[<>X]$/.test(i)))throw new Error(`Named callout optional argument must be '<', '>', or 'X' "${i}"`);break;case"cmp":if(o.length!==3)throw new Error(`Named callout must have three arguments "${o}"`);if(typeof i=="string"&&!/^[A-Za-z_]\w*$/.test(i))throw new Error(`Named callout argument one must be a tag or number "${i}"`);if(typeof s=="number"||!/^(?:[<>!=]=|[<>])$/.test(s))throw new Error(`Named callout argument two must be '==', '!=', '>', '<', '>=', or '<=' "${s}"`);if(typeof l=="string"&&!/^[A-Za-z_]\w*$/.test(l))throw new Error(`Named callout argument three must be a tag or number "${l}"`);break;case"custom":throw new Error(`Undefined callout name "${n}"`);default:throw new Error(`Unexpected named callout kind "${c}"`)}return Es(c,r??null,a?.split(",")??null,e)}function ia(e){let t=null,n,r;if(e[0]==="{"){let{minStr:a,maxStr:o}=/^\{(?\d*)(?:,(?\d*))?/.exec(e).groups,i=1e5;if(+a>i||o&&+o>i)throw new Error("Quantifier value unsupported in Oniguruma");if(n=+a,r=o===void 0?+a:o===""?1/0:+o,n>r&&(t="possessive",[n,r]=[r,n]),e.endsWith("?")){if(t==="possessive")throw new Error('Unsupported possessive interval quantifier chain with "?"');t="lazy"}else t||(t="greedy")}else n=e[0]==="+"?1:0,r=e[0]==="?"?1:1/0,t=e[1]==="+"?"possessive":e[1]==="?"?"lazy":"greedy";return As(t,n,r,e)}function Ls(e){let t=e[1].toLowerCase();return ge({d:"digit",h:"hex",s:"space",w:"word"}[t],e,{negate:e[1]!==t})}function Ps(e){let{p:t,neg:n,value:r}=/^\\(?

[pP])\{(?\^?)(?[^}]+)/.exec(e).groups;return ge("property",e,{value:r,negate:t==="P"&&!n||t==="p"&&!!n})}function sa(e){let t={};return e.includes("i")&&(t.ignoreCase=!0),e.includes("m")&&(t.dotAll=!0),e.includes("x")&&(t.extended=!0),Object.keys(t).length?t:null}function $s(e){let t={ignoreCase:!1,dotAll:!1,extended:!1,digitIsAscii:!1,posixIsAscii:!1,spaceIsAscii:!1,wordIsAscii:!1,textSegmentMode:null};for(let n=0;n\p{AHex}+)/u.exec(e).groups.hex:e.slice(2);return parseInt(t,16)}function Gs(e,t){let{raw:n,inCharClass:r}=e,a=n.slice(1);if(!r&&(a!=="0"&&a.length===1||a[0]!=="0"&&+a<=t))return[da(n)];let o=[],i=a.match(/^[0-7]+|\d/g);for(let s=0;s127)throw new Error(B`Octal encoded byte above 177 unsupported "${n}"`)}else c=ae(l);o.push(Z(c,(s===0?"\\":"")+l))}return o}function Fs(e){let t=[],n=new RegExp(cn,"gy"),r;for(;r=n.exec(e);){let a=r[0];if(a[0]==="{"){let o=/^\{(?\d+),(?\d+)\}\??$/.exec(a);if(o){let{min:i,max:s}=o.groups;if(+i>+s&&a.endsWith("?")){n.lastIndex--,t.push(ia(a.slice(0,-1)));continue}}}t.push(ia(a))}return t}function wt(e,t){if(!Array.isArray(e.body))throw new Error("Expected node with body array");if(e.body.length!==1)return!1;let n=e.body[0];return!t||Object.keys(t).every(r=>t[r]===n[r])}function ha(e){return Os.has(e.type)}var Os=new Set(["AbsenceFunction","Backreference","CapturingGroup","Character","CharacterClass","CharacterSet","Group","Quantifier","Subroutine"]);function xt(e,t={}){let n={flags:"",normalizeUnknownPropertyNames:!1,skipBackrefValidation:!1,skipLookbehindValidation:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t,rules:{captureGroup:!1,singleline:!1,...t.rules}},r=ua(e,{flags:n.flags,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline}}),a=(d,g)=>{let h=r.tokens[o.nextIndex];switch(o.parent=d,o.nextIndex++,h.type){case"Alternator":return ee();case"Assertion":return Ds(h);case"Backreference":return Us(h,o);case"Character":return Ce(h.value,{useLastValid:!!g.isCheckingRangeEnd});case"CharacterClassHyphen":return qs(h,o,g);case"CharacterClassOpen":return js(h,o,g);case"CharacterSet":return Hs(h,o);case"Directive":return Qs(h.kind,{flags:h.flags});case"GroupOpen":return Ws(h,o,g);case"NamedCallout":return Js(h.kind,h.tag,h.arguments);case"Quantifier":return zs(h,o);case"Subroutine":return Vs(h,o);default:throw new Error(`Unexpected token type "${h.type}"`)}},o={capturingGroups:[],hasNumberedRef:!1,namedGroupsByName:new Map,nextIndex:0,normalizeUnknownPropertyNames:n.normalizeUnknownPropertyNames,parent:null,skipBackrefValidation:n.skipBackrefValidation,skipLookbehindValidation:n.skipLookbehindValidation,skipPropertyNameValidation:n.skipPropertyNameValidation,subroutines:[],tokens:r.tokens,unicodePropertyMap:n.unicodePropertyMap,walk:a},i=el(Ys(r.flags)),s=i.body[0];for(;o.nextIndexl.length)throw new Error("Subroutine uses a group number that's not defined");d&&(l[d-1].isSubroutined=!0)}else if(u.has(d)){if(u.get(d).length>1)throw new Error(B`Subroutine uses a duplicate group name "\g<${d}>"`);u.get(d)[0].isSubroutined=!0}else throw new Error(B`Subroutine uses a group name that's not defined "\g<${d}>"`);return i}function Ds({kind:e}){return Ct(J({"^":"line_start",$:"line_end","\\A":"string_start","\\b":"word_boundary","\\B":"word_boundary","\\G":"search_start","\\y":"text_segment_boundary","\\Y":"text_segment_boundary","\\z":"string_end","\\Z":"string_end_newline"}[e],`Unexpected assertion kind "${e}"`),{negate:e===B`\B`||e===B`\Y`})}function Us({raw:e},t){let n=/^\\k[<']/.test(e),r=n?e.slice(3,-1):e.slice(1),a=(o,i=!1)=>{let s=t.capturingGroups.length,l=!1;if(o>s)if(t.skipBackrefValidation)l=!0;else throw new Error(`Not enough capturing groups defined to the left "${e}"`);return t.hasNumberedRef=!0,kt(i?s+1-o:o,{orphan:l})};if(n){let o=/^(?-?)0*(?[1-9]\d*)$/.exec(r);if(o)return a(+o.groups.num,!!o.groups.sign);if(/[-+]/.test(r))throw new Error(`Invalid backref name "${e}"`);if(!t.namedGroupsByName.has(r))throw new Error(`Group name not defined to the left "${e}"`);return kt(r)}return a(+r)}function qs(e,t,n){let{tokens:r,walk:a}=t,o=t.parent,i=o.body.at(-1),s=r[t.nextIndex];if(!n.isCheckingRangeEnd&&i&&i.type!=="CharacterClass"&&i.type!=="CharacterClassRange"&&s&&s.type!=="CharacterClassOpen"&&s.type!=="CharacterClassClose"&&s.type!=="CharacterClassIntersector"){let l=a(o,{...n,isCheckingRangeEnd:!0});if(i.type==="Character"&&l.type==="Character")return o.body.pop(),Ks(i,l);throw new Error("Invalid character class range")}return Ce(ae("-"))}function js({negate:e},t,n){let{tokens:r,walk:a}=t,o=[qe()],i=r[t.nextIndex],s=ba(i);for(;s.type!=="CharacterClassClose";){if(s.type==="CharacterClassIntersector")o.push(qe()),t.nextIndex++;else{let c=o.at(-1);c.body.push(a(c,n))}s=ba(r[t.nextIndex],i)}let l=qe({negate:e});return o.length===1?l.body=o[0].body:(l.kind="intersection",l.body=o.map(c=>c.body.length===1?c.body[0]:c)),t.nextIndex++,l}function Hs({kind:e,negate:t,value:n},r){let{normalizeUnknownPropertyNames:a,skipPropertyNameValidation:o,unicodePropertyMap:i}=r;if(e==="property"){let s=ve(n);if(Ue.has(s)&&!i?.has(s))e="posix",n=s;else return he(n,{negate:t,normalizeUnknownPropertyNames:a,skipPropertyNameValidation:o,unicodePropertyMap:i})}return e==="posix"?Zs(n,{negate:t}):vt(e,{negate:t})}function Ws(e,t,n){let{tokens:r,capturingGroups:a,namedGroupsByName:o,skipLookbehindValidation:i,walk:s}=t,l=tl(e),c=l.type==="AbsenceFunction",u=ma(l),p=u&&l.negate;if(l.type==="CapturingGroup"&&(a.push(l),l.name&&na(o,l.name,[]).push(l)),c&&n.isInAbsenceFunction)throw new Error("Nested absence function not supported by Oniguruma");let d=ya(r[t.nextIndex]);for(;d.type!=="GroupClose";){if(d.type==="Alternator")l.body.push(ee()),t.nextIndex++;else{let g=l.body.at(-1),h=s(g,{...n,isInAbsenceFunction:n.isInAbsenceFunction||c,isInLookbehind:n.isInLookbehind||u,isInNegLookbehind:n.isInNegLookbehind||p});if(g.body.push(h),(u||n.isInLookbehind)&&!i){let y="Lookbehind includes a pattern not allowed by Oniguruma";if(p||n.isInNegLookbehind){if(fa(h)||h.type==="CapturingGroup")throw new Error(y)}else if(fa(h)||ma(h)&&h.negate)throw new Error(y)}}d=ya(r[t.nextIndex])}return t.nextIndex++,l}function zs({kind:e,min:t,max:n},r){let a=r.parent,o=a.body.at(-1);if(!o||!ha(o))throw new Error("Quantifier requires a repeatable token");let i=pn(e,t,n,o);return a.body.pop(),i}function Vs({raw:e},t){let{capturingGroups:n,subroutines:r}=t,a=e.slice(3,-1),o=/^(?[-+]?)0*(?[1-9]\d*)$/.exec(a);if(o){let s=+o.groups.num,l=n.length;if(t.hasNumberedRef=!0,a={"":s,"+":l+s,"-":l+1-s}[o.groups.sign],a<1)throw new Error("Invalid subroutine number")}else a==="0"&&(a=0);let i=dn(a);return r.push(i),i}function Xs(e,t){if(e!=="repeater")throw new Error(`Unexpected absence function kind "${e}"`);return{type:"AbsenceFunction",kind:e,body:je(t?.body)}}function ee(e){return{type:"Alternative",body:wa(e?.body)}}function Ct(e,t){let n={type:"Assertion",kind:e};return(e==="word_boundary"||e==="text_segment_boundary")&&(n.negate=!!t?.negate),n}function kt(e,t){let n=!!t?.orphan;return{type:"Backreference",ref:e,...n&&{orphan:n}}}function un(e,t){let n={name:void 0,isSubroutined:!1,...t};if(n.name!==void 0&&!nl(n.name))throw new Error(`Group name "${n.name}" invalid in Oniguruma`);return{type:"CapturingGroup",number:e,...n.name&&{name:n.name},...n.isSubroutined&&{isSubroutined:n.isSubroutined},body:je(t?.body)}}function Ce(e,t){let n={useLastValid:!1,...t};if(e>1114111){let r=e.toString(16);if(n.useLastValid)e=1114111;else throw e>1310719?new Error(`Invalid code point out of range "\\x{${r}}"`):new Error(`Invalid code point out of range in JS "\\x{${r}}"`)}return{type:"Character",value:e}}function qe(e){let t={kind:"union",negate:!1,...e};return{type:"CharacterClass",kind:t.kind,negate:t.negate,body:wa(e?.body)}}function Ks(e,t){if(t.valuen)throw new Error("Invalid reversed quantifier range");return{type:"Quantifier",kind:e,min:t,max:n,body:r}}function el(e,t){return{type:"Regex",body:je(t?.body),flags:e}}function dn(e){return{type:"Subroutine",ref:e}}function he(e,t){let n={negate:!1,normalizeUnknownPropertyNames:!1,skipPropertyNameValidation:!1,unicodePropertyMap:null,...t},r=n.unicodePropertyMap?.get(ve(e));if(!r){if(n.normalizeUnknownPropertyNames)r=rl(e);else if(n.unicodePropertyMap&&!n.skipPropertyNameValidation)throw new Error(B`Invalid Unicode property "\p{${e}}"`)}return{type:"CharacterSet",kind:"property",value:r??e,negate:n.negate}}function tl({flags:e,kind:t,name:n,negate:r,number:a}){switch(t){case"absence_repeater":return Xs("repeater");case"atomic":return O({atomic:!0});case"capturing":return un(a,{name:n});case"group":return O({flags:e});case"lookahead":case"lookbehind":return oe({behind:t==="lookbehind",negate:r});default:throw new Error(`Unexpected group kind "${t}"`)}}function je(e){if(e===void 0)e=[ee()];else if(!Array.isArray(e)||!e.length||!e.every(t=>t.type==="Alternative"))throw new Error("Invalid body; expected array of one or more Alternative nodes");return e}function wa(e){if(e===void 0)e=[];else if(!Array.isArray(e)||!e.every(t=>!!t.type))throw new Error("Invalid body; expected array of nodes");return e}function fa(e){return e.type==="LookaroundAssertion"&&e.kind==="lookahead"}function ma(e){return e.type==="LookaroundAssertion"&&e.kind==="lookbehind"}function nl(e){return/^[\p{Alpha}\p{Pc}][^)]*$/u.test(e)}function rl(e){return e.trim().replace(/[- _]+/g,"_").replace(/[A-Z][a-z]+(?=[A-Z])/g,"$&_").replace(/[A-Za-z]+/g,t=>t[0].toUpperCase()+t.slice(1).toLowerCase())}function ve(e){return e.replace(/[- _]+/g,"").toLowerCase()}function ba(e,t){let n=t;return J(e,`Unclosed character class${n?.type==="Character"&&n.value===93&&n.raw==="]"?' (started with "]")':""}`)}function ya(e){return J(e,"Unclosed group")}function fe(e,t,n=null){function r(o,i){for(let s=0;sA-Za-z\-]|<[=!]|\(DEFINE\))`;function xa(e,t){for(let n=0;n=t&&e[n]++}function Ca(e,t,n,r){return e.slice(0,t)+r+e.slice(t+n.length)}var F=Object.freeze({DEFAULT:"DEFAULT",CHAR_CLASS:"CHAR_CLASS"});function He(e,t,n,r){let a=new RegExp(String.raw`${t}|(?<$skip>\[\^?|\\?.)`,"gsu"),o=[!1],i=0,s="";for(let l of e.matchAll(a)){let{0:c,groups:{$skip:u}}=l;if(!u&&(!r||r===F.DEFAULT==!i)){n instanceof Function?s+=n(l,{context:i?F.CHAR_CLASS:F.DEFAULT,negated:o[o.length-1]}):s+=n;continue}c[0]==="["?(i++,o.push(c[1]==="^")):c==="]"&&i&&(i--,o.pop()),s+=c}return s}function gn(e,t,n,r){He(e,t,n,r)}function al(e,t,n=0,r){if(!new RegExp(t,"su").test(e))return null;let a=new RegExp(`${t}|(?<$skip>\\\\?.)`,"gsu");a.lastIndex=n;let o=0,i;for(;i=a.exec(e);){let{0:s,groups:{$skip:l}}=i;if(!l&&(!r||r===F.DEFAULT==!o))return i;s==="["?o++:s==="]"&&o&&o--,a.lastIndex==i.index&&a.lastIndex++}return null}function We(e,t,n){return!!al(e,t,0,n)}function va(e,t){let n=/\\?./gsu;n.lastIndex=t;let r=e.length,a=0,o=1,i;for(;i=n.exec(e);){let[s]=i;if(s==="[")a++;else if(a)s==="]"&&a--;else if(s==="(")o++;else if(s===")"&&(o--,!o)){r=i.index;break}}return e.slice(t,r)}var _a=new RegExp(String.raw`(?${ka})|(?\((?:\?<[^>]+>)?)|\\?.`,"gsu");function fn(e,t){let n=t?.hiddenCaptures??[],r=t?.captureTransfers??new Map;if(!/\(\?>/.test(e))return{pattern:e,captureTransfers:r,hiddenCaptures:n};let a="(?>",o="(?:(?=(",i=[0],s=[],l=0,c=0,u=NaN,p;do{p=!1;let d=0,g=0,h=!1,y;for(_a.lastIndex=Number.isNaN(u)?0:u+o.length;y=_a.exec(e);){let{0:w,index:m,groups:{capturingStart:b,noncapturingStart:k}}=y;if(w==="[")d++;else if(d)w==="]"&&d--;else if(w===a&&!h)u=m,h=!0;else if(h&&k)g++;else if(b)h?g++:(l++,i.push(l+c));else if(w===")"&&h){if(!g){c++;let v=l+c;if(e=`${e.slice(0,u)}${o}${e.slice(u+a.length,m)}))<$$${v}>)${e.slice(m+1)}`,p=!0,s.push(v),xa(n,v),r.size){let S=new Map;r.forEach((L,M)=>{S.set(M>=v?M+1:M,L.map(H=>H>=v?H+1:H))}),r=S}break}g--}}}while(p);return n.push(...s),e=He(e,String.raw`\\(?[1-9]\d*)|<\$\$(?\d+)>`,({0:d,groups:{backrefNum:g,wrappedBackrefNum:h}})=>{if(g){let y=+g;if(y>i.length-1)throw new Error(`Backref "${d}" greater than number of captures`);return`\\${i[y]}`}return`\\${h}`},F.DEFAULT),{pattern:e,captureTransfers:r,hiddenCaptures:n}}var Sa=String.raw`(?:[?*+]|\{\d+(?:,\d*)?\})`,hn=new RegExp(String.raw` +\\(?: \d+ + | c[A-Za-z] + | [gk]<[^>]+> + | [pPu]\{[^\}]+\} + | u[A-Fa-f\d]{4} + | x[A-Fa-f\d]{2} + ) +| \((?: \? (?: [:=!>] + | <(?:[=!]|[^>]+>) + | [A-Za-z\-]+: + | \(DEFINE\) + ))? +| (?${Sa})(?[?+]?)(?[?*+\{]?) +| \\?. +`.replace(/\s+/g,""),"gsu");function mn(e){if(!new RegExp(`${Sa}\\+`).test(e))return{pattern:e};let t=[],n=null,r=null,a="",o=0,i;for(hn.lastIndex=0;i=hn.exec(e);){let{0:s,index:l,groups:{qBase:c,qMod:u,invalidQ:p}}=i;if(s==="[")o||(r=l),o++;else if(s==="]")o?o--:r=null;else if(!o)if(u==="+"&&a&&!a.startsWith("(")){if(p)throw new Error(`Invalid quantifier "${s}"`);let d=-1;if(/^\{\d+\}$/.test(c))e=Ca(e,l+c.length,u,"");else{if(a===")"||a==="]"){let g=a===")"?n:r;if(g===null)throw new Error(`Invalid unmatched "${a}"`);e=`${e.slice(0,g)}(?>${e.slice(g,l)}${c})${e.slice(l+s.length)}`}else e=`${e.slice(0,l-a.length)}(?>${a}${c})${e.slice(l+s.length)}`;d+=4}hn.lastIndex+=d}else s[0]==="("?t.push(l):s===")"&&(n=t.length?t.pop():null);a=s}return{pattern:e}}var q=String.raw,ol=q`\\g<(?[^>&]+)&R=(?[^>]+)>`,yn=q`\(\?R=(?[^\)]+)\)|${ol}`,St=q`\(\?<(?![=!])(?[^>]+)>`,Ba=q`${St}|(?\()(?!\?)`,me=new RegExp(q`${St}|${yn}|\(\?|\\?.`,"gsu"),bn="Cannot use multiple overlapping recursions";function Na(e,t){let{hiddenCaptures:n,mode:r}={hiddenCaptures:[],mode:"plugin",...t},a=t?.captureTransfers??new Map;if(!new RegExp(yn,"su").test(e))return{pattern:e,captureTransfers:a,hiddenCaptures:n};if(r==="plugin"&&We(e,q`\(\?\(DEFINE\)`,F.DEFAULT))throw new Error("DEFINE groups cannot be used with recursion");let o=[],i=We(e,q`\\[1-9]`,F.DEFAULT),s=new Map,l=[],c=!1,u=0,p=0,d;for(me.lastIndex=0;d=me.exec(e);){let{0:g,groups:{captureName:h,rDepth:y,gRNameOrNum:w,gRDepth:m}}=d;if(g==="[")u++;else if(u)g==="]"&&u--;else if(y){if(Ea(y),c)throw new Error(bn);if(i)throw new Error(`${r==="external"?"Backrefs":"Numbered backrefs"} cannot be used with global recursion`);let b=e.slice(0,d.index),k=e.slice(me.lastIndex);if(We(k,yn,F.DEFAULT))throw new Error(bn);let v=+y-1;e=Aa(b,k,v,!1,n,o,p),a=Ia(a,b,v,o.length,0,p);break}else if(w){Ea(m);let b=!1;for(let W of l)if(W.name===w||W.num===+w){if(b=!0,W.hasRecursedWithin)throw new Error(bn);break}if(!b)throw new Error(q`Recursive \g cannot be used outside the referenced group "${r==="external"?w:q`\g<${w}&R=${m}>`}"`);let k=s.get(w),v=va(e,k);if(i&&We(v,q`${St}|\((?!\?)`,F.DEFAULT))throw new Error(`${r==="external"?"Backrefs":"Numbered backrefs"} cannot be used with recursion of capturing groups`);let S=e.slice(k,d.index),L=v.slice(S.length+g.length),M=o.length,H=+m-1,be=Aa(S,L,H,!0,n,o,p);a=Ia(a,S,H,o.length-M,M,p);let Rt=e.slice(0,k),It=e.slice(k+v.length);e=`${Rt}${be}${It}`,me.lastIndex+=be.length-g.length-S.length-L.length,l.forEach(W=>W.hasRecursedWithin=!0),c=!0}else if(h)p++,s.set(String(p),me.lastIndex),s.set(h,me.lastIndex),l.push({num:p,name:h});else if(g[0]==="("){let b=g==="(";b&&(p++,s.set(String(p),me.lastIndex)),l.push(b?{num:p}:{})}else g===")"&&l.pop()}return n.push(...o),{pattern:e,captureTransfers:a,hiddenCaptures:n}}function Ea(e){let t=`Max depth must be integer between 2 and 100; used ${e}`;if(!/^[1-9]\d*$/.test(e))throw new Error(t);if(e=+e,e<2||e>100)throw new Error(t)}function Aa(e,t,n,r,a,o,i){let s=new Set;r&&gn(e+t,St,({groups:{captureName:c}})=>{s.add(c)},F.DEFAULT);let l=[n,r?s:null,a,o,i];return`${e}${Ra(`(?:${e}`,"forward",...l)}(?:)${Ra(`${t})`,"backward",...l)}${t}`}function Ra(e,t,n,r,a,o,i){let l=u=>t==="forward"?u+2:n-u+2-1,c="";for(let u=0;u[^>]+)>`,({0:d,groups:{captureName:g,unnamed:h,backref:y}})=>{if(y&&r&&!r.has(y))return d;let w=`_$${p}`;if(h||g){let m=i+o.length+1;return o.push(m),il(a,m),h?d:`(?<${g}${w}>`}return q`\k<${y}${w}>`},F.DEFAULT)}return c}function il(e,t){for(let n=0;n=t&&e[n]++}function Ia(e,t,n,r,a,o){if(e.size&&r){let i=0;gn(t,Ba,()=>i++,F.DEFAULT);let s=o-i+a,l=new Map;return e.forEach((c,u)=>{let p=(r-i*n)/n,d=i*n,g=u>s+i?u+r:u,h=[];for(let y of c)if(y<=s)h.push(y);else if(y>s+i+p)h.push(y+r);else if(y<=s+i)for(let w=0;w<=n;w++)h.push(y+i*w);else for(let w=0;w<=n;w++)h.push(y+d+p*w);l.set(g,h)}),l}return e}var N=String.fromCodePoint,C=String.raw,j={},At=globalThis.RegExp;j.flagGroups=(()=>{try{new At("(?i:)")}catch{return!1}return!0})();j.unicodeSets=(()=>{try{new At("[[]]","v")}catch{return!1}return!0})();j.bugFlagVLiteralHyphenIsRange=j.unicodeSets?(()=>{try{new At(C`[\d\-a]`,"v")}catch{return!0}return!1})():!1;j.bugNestedClassIgnoresNegation=j.unicodeSets&&new At("[[^a]]","v").test("a");function Et(e,{enable:t,disable:n}){return{dotAll:!n?.dotAll&&!!(t?.dotAll||e.dotAll),ignoreCase:!n?.ignoreCase&&!!(t?.ignoreCase||e.ignoreCase)}}function ze(e,t,n){return e.has(t)||e.set(t,n),e.get(t)}function vn(e,t){return Ta[e]>=Ta[t]}function sl(e,t){if(e==null)throw new Error(t??"Value expected");return e}var Ta={ES2025:2025,ES2024:2024,ES2018:2018},ll={auto:"auto",ES2025:"ES2025",ES2024:"ES2024",ES2018:"ES2018"};function Ga(e={}){if({}.toString.call(e)!=="[object Object]")throw new Error("Unexpected options");if(e.target!==void 0&&!ll[e.target])throw new Error(`Unexpected target "${e.target}"`);let t={accuracy:"default",avoidSubclass:!1,flags:"",global:!1,hasIndices:!1,lazyCompileLength:1/0,target:"auto",verbose:!1,...e,rules:{allowOrphanBackrefs:!1,asciiWordBoundaries:!1,captureGroup:!1,recursionLimit:20,singleline:!1,...e.rules}};return t.target==="auto"&&(t.target=j.flagGroups?"ES2025":j.unicodeSets?"ES2024":"ES2018"),t}var cl="[ -\r ]",ul=new Set([N(304),N(305)]),te=C`[\p{L}\p{M}\p{N}\p{Pc}]`;function Fa(e){if(ul.has(e))return[e];let t=new Set,n=e.toLowerCase(),r=n.toUpperCase(),a=gl.get(n),o=pl.get(n),i=dl.get(n);return[...r].length===1&&t.add(r),i&&t.add(i),a&&t.add(a),t.add(n),o&&t.add(o),[...t]}var Sn=new Map(`C Other +Cc Control cntrl +Cf Format +Cn Unassigned +Co Private_Use +Cs Surrogate +L Letter +LC Cased_Letter +Ll Lowercase_Letter +Lm Modifier_Letter +Lo Other_Letter +Lt Titlecase_Letter +Lu Uppercase_Letter +M Mark Combining_Mark +Mc Spacing_Mark +Me Enclosing_Mark +Mn Nonspacing_Mark +N Number +Nd Decimal_Number digit +Nl Letter_Number +No Other_Number +P Punctuation punct +Pc Connector_Punctuation +Pd Dash_Punctuation +Pe Close_Punctuation +Pf Final_Punctuation +Pi Initial_Punctuation +Po Other_Punctuation +Ps Open_Punctuation +S Symbol +Sc Currency_Symbol +Sk Modifier_Symbol +Sm Math_Symbol +So Other_Symbol +Z Separator +Zl Line_Separator +Zp Paragraph_Separator +Zs Space_Separator +ASCII +ASCII_Hex_Digit AHex +Alphabetic Alpha +Any +Assigned +Bidi_Control Bidi_C +Bidi_Mirrored Bidi_M +Case_Ignorable CI +Cased +Changes_When_Casefolded CWCF +Changes_When_Casemapped CWCM +Changes_When_Lowercased CWL +Changes_When_NFKC_Casefolded CWKCF +Changes_When_Titlecased CWT +Changes_When_Uppercased CWU +Dash +Default_Ignorable_Code_Point DI +Deprecated Dep +Diacritic Dia +Emoji +Emoji_Component EComp +Emoji_Modifier EMod +Emoji_Modifier_Base EBase +Emoji_Presentation EPres +Extended_Pictographic ExtPict +Extender Ext +Grapheme_Base Gr_Base +Grapheme_Extend Gr_Ext +Hex_Digit Hex +IDS_Binary_Operator IDSB +IDS_Trinary_Operator IDST +ID_Continue IDC +ID_Start IDS +Ideographic Ideo +Join_Control Join_C +Logical_Order_Exception LOE +Lowercase Lower +Math +Noncharacter_Code_Point NChar +Pattern_Syntax Pat_Syn +Pattern_White_Space Pat_WS +Quotation_Mark QMark +Radical +Regional_Indicator RI +Sentence_Terminal STerm +Soft_Dotted SD +Terminal_Punctuation Term +Unified_Ideograph UIdeo +Uppercase Upper +Variation_Selector VS +White_Space space +XID_Continue XIDC +XID_Start XIDS`.split(/\s/).map(e=>[ve(e),e])),pl=new Map([["s",N(383)],[N(383),"s"]]),dl=new Map([[N(223),N(7838)],[N(107),N(8490)],[N(229),N(8491)],[N(969),N(8486)]]),gl=new Map([ie(453),ie(456),ie(459),ie(498),...wn(8072,8079),...wn(8088,8095),...wn(8104,8111),ie(8124),ie(8140),ie(8188)]),hl=new Map([["alnum",C`[\p{Alpha}\p{Nd}]`],["alpha",C`\p{Alpha}`],["ascii",C`\p{ASCII}`],["blank",C`[\p{Zs}\t]`],["cntrl",C`\p{Cc}`],["digit",C`\p{Nd}`],["graph",C`[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]`],["lower",C`\p{Lower}`],["print",C`[[\P{space}&&\P{Cc}&&\P{Cn}&&\P{Cs}]\p{Zs}]`],["punct",C`[\p{P}\p{S}]`],["space",C`\p{space}`],["upper",C`\p{Upper}`],["word",C`[\p{Alpha}\p{M}\p{Nd}\p{Pc}]`],["xdigit",C`\p{AHex}`]]);function fl(e,t){let n=[];for(let r=e;r<=t;r++)n.push(r);return n}function ie(e){let t=N(e);return[t.toLowerCase(),t]}function wn(e,t){return fl(e,t).map(n=>ie(n))}var Oa=new Set(["Lower","Lowercase","Upper","Uppercase","Ll","Lowercase_Letter","Lt","Titlecase_Letter","Lu","Uppercase_Letter"]);function ml(e,t){let n={accuracy:"default",asciiWordBoundaries:!1,avoidSubclass:!1,bestEffortTarget:"ES2025",...t};Da(e);let r={accuracy:n.accuracy,asciiWordBoundaries:n.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,flagDirectivesByAlt:new Map,jsGroupNameMap:new Map,minTargetEs2024:vn(n.bestEffortTarget,"ES2024"),passedLookbehind:!1,strategy:null,subroutineRefMap:new Map,supportedGNodes:new Set,digitIsAscii:e.flags.digitIsAscii,spaceIsAscii:e.flags.spaceIsAscii,wordIsAscii:e.flags.wordIsAscii};fe(e,bl,r);let a={dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},o={currentFlags:a,prevFlags:null,globalFlags:a,groupOriginByCopy:new Map,groupsByName:new Map,multiplexCapturesToLeftByRef:new Map,openRefs:new Map,reffedNodesByReferencer:new Map,subroutineRefMap:r.subroutineRefMap};fe(e,yl,o);let i={groupsByName:o.groupsByName,highestOrphanBackref:0,numCapturesToLeft:0,reffedNodesByReferencer:o.reffedNodesByReferencer};return fe(e,wl,i),e._originMap=o.groupOriginByCopy,e._strategy=r.strategy,e}var bl={AbsenceFunction({node:e,parent:t,replaceWith:n}){let{body:r,kind:a}=e;if(a==="repeater"){let o=O();o.body[0].body.push(oe({negate:!0,body:r}),he("Any"));let i=O();i.body[0].body.push(pn("greedy",0,1/0,o)),n(I(i,t),{traverse:!0})}else throw new Error('Unsupported absence function "(?~|"')},Alternative:{enter({node:e,parent:t,key:n},{flagDirectivesByAlt:r}){let a=e.body.filter(o=>o.kind==="flags");for(let o=n+1;o\r\n|${a?C`\p{RGI_Emoji}`:d}|\P{M}\p{M}*)`,{skipPropertyNameValidation:!0}),t))}else if(l==="hex")n(se(he("AHex",{negate:c}),t));else if(l==="newline")n(I(ne(c?`[^ +]`:`(?>\r +?|[ +\v\f\x85\u2028\u2029])`),t));else if(l==="posix")if(!a&&(u==="graph"||u==="print")){if(r==="strict")throw new Error(`POSIX class "${u}" requires min target ES2024 or non-strict accuracy`);let p={graph:"!-~",print:" -~"}[u];c&&(p=`\0-${N(p.codePointAt(0)-1)}${N(p.codePointAt(2)+1)}-\u{10FFFF}`),n(I(ne(`[${p}]`),t))}else n(I(Cn(ne(hl.get(u)),c),t));else if(l==="property")Sn.has(ve(u))||(e.key="sc");else if(l==="space")n(se(he("space",{negate:c}),t));else if(l==="word")n(I(Cn(ne(te),c),t));else throw new Error(`Unexpected character set kind "${l}"`)},Directive({node:e,parent:t,root:n,remove:r,replaceWith:a,removeAllPrevSiblings:o,removeAllNextSiblings:i}){let{kind:s,flags:l}=e;if(s==="flags")if(!l.enable&&!l.disable)r();else{let c=O({flags:l});c.body[0].body=i(),a(I(c,t),{traverse:!0})}else if(s==="keep"){let c=n.body[0],p=n.body.length===1&&wt(c,{type:"Group"})&&c.body[0].body.length===1?c.body[0]:n;if(t.parent!==p||p.body.length>1)throw new Error(C`Uses "\K" in a way that's unsupported`);let d=oe({behind:!0});d.body[0].body=o(),a(I(d,t))}else throw new Error(`Unexpected directive kind "${s}"`)},Flags({node:e,parent:t}){if(e.posixIsAscii)throw new Error('Unsupported flag "P"');if(e.textSegmentMode==="word")throw new Error('Unsupported flag "y{w}"');["digitIsAscii","extended","posixIsAscii","spaceIsAscii","wordIsAscii","textSegmentMode"].forEach(n=>delete e[n]),Object.assign(e,{global:!1,hasIndices:!1,multiline:!1,sticky:e.sticky??!1}),t.options={disable:{x:!0,n:!0},force:{v:!0}}},Group({node:e}){if(!e.flags)return;let{enable:t,disable:n}=e.flags;t?.extended&&delete t.extended,n?.extended&&delete n.extended,t?.dotAll&&n?.dotAll&&delete t.dotAll,t?.ignoreCase&&n?.ignoreCase&&delete t.ignoreCase,t&&!Object.keys(t).length&&delete e.flags.enable,n&&!Object.keys(n).length&&delete e.flags.disable,!e.flags.enable&&!e.flags.disable&&delete e.flags},LookaroundAssertion({node:e},t){let{kind:n}=e;n==="lookbehind"&&(t.passedLookbehind=!0)},NamedCallout({node:e,parent:t,replaceWith:n}){let{kind:r}=e;if(r==="fail")n(I(oe({negate:!0}),t));else throw new Error(`Unsupported named callout "(*${r.toUpperCase()}"`)},Quantifier({node:e}){if(e.body.type==="Quantifier"){let t=O();t.body[0].body.push(e.body),e.body=I(t,e)}},Regex:{enter({node:e},{supportedGNodes:t}){let n=[],r=!1,a=!1;for(let o of e.body)if(o.body.length===1&&o.body[0].kind==="search_start")o.body.pop();else{let i=Ha(o.body);i?(r=!0,Array.isArray(i)?n.push(...i):n.push(i)):a=!0}r&&!a&&n.forEach(o=>t.add(o))},exit(e,{accuracy:t,passedLookbehind:n,strategy:r}){if(t==="strict"&&n&&r)throw new Error(C`Uses "\G" in a way that requires non-strict accuracy`)}},Subroutine({node:e},{jsGroupNameMap:t}){let{ref:n}=e;typeof n=="string"&&!xn(n)&&(n=kn(n,t),e.ref=n)}},yl={Backreference({node:e},{multiplexCapturesToLeftByRef:t,reffedNodesByReferencer:n}){let{orphan:r,ref:a}=e;r||n.set(e,[...t.get(a).map(({node:o})=>o)])},CapturingGroup:{enter({node:e,parent:t,replaceWith:n,skip:r},{groupOriginByCopy:a,groupsByName:o,multiplexCapturesToLeftByRef:i,openRefs:s,reffedNodesByReferencer:l}){let c=a.get(e);if(c&&s.has(e.number)){let p=se(La(e.number),t);l.set(p,s.get(e.number)),n(p);return}s.set(e.number,e),i.set(e.number,[]),e.name&&ze(i,e.name,[]);let u=i.get(e.name??e.number);for(let p=0;pd.type==="Group"&&!!d.flags)),p=u?Et(r.globalFlags,u):r.globalFlags;kl(p,r.currentFlags)||(c=O({flags:vl(p)}),c.body[0].body.push(l))}n(I(c,t),{traverse:!s})}},wl={Backreference({node:e,parent:t,replaceWith:n},r){if(e.orphan){r.highestOrphanBackref=Math.max(r.highestOrphanBackref,e.ref);return}let o=r.reffedNodesByReferencer.get(e).filter(i=>xl(i,e));if(!o.length)n(I(oe({negate:!0}),t));else if(o.length>1){let i=O({atomic:!0,body:o.reverse().map(s=>ee({body:[kt(s.number)]}))});n(I(i,t))}else e.ref=o[0].number},CapturingGroup({node:e},t){e.number=++t.numCapturesToLeft,e.name&&t.groupsByName.get(e.name).get(e).hasDuplicateNameToRemove&&delete e.name},Regex:{exit({node:e},t){let n=Math.max(t.highestOrphanBackref-t.numCapturesToLeft,0);for(let r=0;r{t.forEach(a=>{r.enable?.[a]&&(delete n.disable[a],n.enable[a]=!0),r.disable?.[a]&&(n.disable[a]=!0)})}),Object.keys(n.enable).length||delete n.enable,Object.keys(n.disable).length||delete n.disable,n.enable||n.disable?n:null}function vl({dotAll:e,ignoreCase:t}){let n={};return(e||t)&&(n.enable={},e&&(n.enable.dotAll=!0),t&&(n.enable.ignoreCase=!0)),(!e||!t)&&(n.disable={},!e&&(n.disable.dotAll=!0),!t&&(n.disable.ignoreCase=!0)),n}function ja(e){if(!e)throw new Error("Node expected");let{body:t}=e;return Array.isArray(t)?t:t?[t]:null}function Ha(e){let t=e.find(n=>n.kind==="search_start"||El(n,{negate:!1})||!_l(n));if(!t)return null;if(t.kind==="search_start")return t;if(t.type==="LookaroundAssertion")return t.body[0].body[0];if(t.type==="CapturingGroup"||t.type==="Group"){let n=[];for(let r of t.body){let a=Ha(r.body);if(!a)return null;Array.isArray(a)?n.push(...a):n.push(a)}return n}return null}function Wa(e,t){let n=ja(e)??[];for(let r of n)if(r===t||Wa(r,t))return!0;return!1}function _l({type:e}){return e==="Assertion"||e==="Directive"||e==="LookaroundAssertion"}function Sl(e){let t=["Character","CharacterClass","CharacterSet"];return t.includes(e.type)||e.type==="Quantifier"&&e.min&&t.includes(e.body.type)}function El(e,t){let n={negate:null,...t};return e.type==="LookaroundAssertion"&&(n.negate===null||e.negate===n.negate)&&e.body.length===1&&wt(e.body[0],{type:"Assertion",kind:"search_start"})}function xn(e){return/^[$_\p{IDS}][$\u200C\u200D\p{IDC}]*$/u.test(e)}function ne(e,t){let r=xt(e,{...t,unicodePropertyMap:Sn}).body;return r.length>1||r[0].body.length>1?O({body:r}):r[0].body[0]}function Cn(e,t){return e.negate=t,e}function se(e,t){return e.parent=t,e}function I(e,t){return Da(e),e.parent=t,e}function Al(e,t){let n=Ga(t),r=vn(n.target,"ES2024"),a=vn(n.target,"ES2025"),o=n.rules.recursionLimit;if(!Number.isInteger(o)||o<2||o>20)throw new Error("Invalid recursionLimit; use 2-20");let i=null,s=null;if(!a){let g=[e.flags.ignoreCase];fe(e,Rl,{getCurrentModI:()=>g.at(-1),popModI(){g.pop()},pushModI(h){g.push(h)},setHasCasedChar(){g.at(-1)?i=!0:s=!0}})}let l={dotAll:e.flags.dotAll,ignoreCase:!!((e.flags.ignoreCase||i)&&!s)},c=e,u={accuracy:n.accuracy,appliedGlobalFlags:l,captureMap:new Map,currentFlags:{dotAll:e.flags.dotAll,ignoreCase:e.flags.ignoreCase},inCharClass:!1,lastNode:c,originMap:e._originMap,recursionLimit:o,useAppliedIgnoreCase:!!(!a&&i&&s),useFlagMods:a,useFlagV:r,verbose:n.verbose};function p(g){return u.lastNode=c,c=g,sl(Il[g.type],`Unexpected node type "${g.type}"`)(g,u,p)}let d={pattern:e.body.map(p).join("|"),flags:p(e.flags),options:{...e.options}};return r||(delete d.options.force.v,d.options.disable.v=!0,d.options.unicodeSetsPlugin=null),d._captureTransfers=new Map,d._hiddenCaptures=[],u.captureMap.forEach((g,h)=>{g.hidden&&d._hiddenCaptures.push(h),g.transferTo&&ze(d._captureTransfers,g.transferTo,[]).push(h)}),d}var Rl={"*":{enter({node:e},t){if($a(e)){let n=t.getCurrentModI();t.pushModI(e.flags?Et({ignoreCase:n},e.flags).ignoreCase:n)}},exit({node:e},t){$a(e)&&t.popModI()}},Backreference(e,t){t.setHasCasedChar()},Character({node:e},t){En(N(e.value))&&t.setHasCasedChar()},CharacterClassRange({node:e,skip:t},n){t(),za(e,{firstOnly:!0}).length&&n.setHasCasedChar()},CharacterSet({node:e},t){e.kind==="property"&&Oa.has(e.value)&&t.setHasCasedChar()}},Il={Alternative({body:e},t,n){return e.map(n).join("")},Assertion({kind:e,negate:t}){if(e==="string_end")return"$";if(e==="string_start")return"^";if(e==="word_boundary")return t?C`\B`:C`\b`;throw new Error(`Unexpected assertion kind "${e}"`)},Backreference({ref:e},t){if(typeof e!="number")throw new Error("Unexpected named backref in transformed AST");if(!t.useFlagMods&&t.accuracy==="strict"&&t.currentFlags.ignoreCase&&!t.captureMap.get(e).ignoreCase)throw new Error("Use of case-insensitive backref to case-sensitive group requires target ES2025 or non-strict accuracy");return"\\"+e},CapturingGroup(e,t,n){let{body:r,name:a,number:o}=e,i={ignoreCase:t.currentFlags.ignoreCase},s=t.originMap.get(e);return s&&(i.hidden=!0,o>s.number&&(i.transferTo=s.number)),t.captureMap.set(o,i),`(${a?`?<${a}>`:""}${r.map(n).join("|")})`},Character({value:e},t){let n=N(e),r=Se(e,{escDigit:t.lastNode.type==="Backreference",inCharClass:t.inCharClass,useFlagV:t.useFlagV});if(r!==n)return r;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase&&En(n)){let a=Fa(n);return t.inCharClass?a.join(""):a.length>1?`[${a.join("")}]`:a[0]}return n},CharacterClass(e,t,n){let{kind:r,negate:a,parent:o}=e,{body:i}=e;if(r==="intersection"&&!t.useFlagV)throw new Error("Use of character class intersection requires min target ES2024");j.bugFlagVLiteralHyphenIsRange&&t.useFlagV&&i.some(Ma)&&(i=[Ce(45),...i.filter(c=>!Ma(c))]);let s=()=>`[${a?"^":""}${i.map(n).join(r==="intersection"?"&&":"")}]`;if(!t.inCharClass){if((!t.useFlagV||j.bugNestedClassIgnoresNegation)&&!a){let u=i.filter(p=>p.type==="CharacterClass"&&p.kind==="union"&&p.negate);if(u.length){let p=O(),d=p.body[0];return p.parent=o,d.parent=p,i=i.filter(g=>!u.includes(g)),e.body=i,i.length?(e.parent=d,d.body.push(e)):p.body.pop(),u.forEach(g=>{let h=ee({body:[g]});g.parent=h,h.parent=p,p.body.push(h)}),n(p)}}t.inCharClass=!0;let c=s();return t.inCharClass=!1,c}let l=i[0];if(r==="union"&&!a&&l&&((!t.useFlagV||!t.verbose)&&o.kind==="union"&&!(j.bugFlagVLiteralHyphenIsRange&&t.useFlagV)||!t.verbose&&o.kind==="intersection"&&i.length===1&&l.type!=="CharacterClassRange"))return i.map(n).join("");if(!t.useFlagV&&o.type==="CharacterClass")throw new Error("Uses nested character class in a way that requires min target ES2024");return s()},CharacterClassRange(e,t){let n=e.min.value,r=e.max.value,a={escDigit:!1,inCharClass:!0,useFlagV:t.useFlagV},o=Se(n,a),i=Se(r,a),s=new Set;if(t.useAppliedIgnoreCase&&t.currentFlags.ignoreCase){let l=za(e);Pl(l).forEach(u=>{s.add(Array.isArray(u)?`${Se(u[0],a)}-${Se(u[1],a)}`:Se(u,a))})}return`${o}-${i}${[...s].join("")}`},CharacterSet({kind:e,negate:t,value:n,key:r},a){if(e==="dot")return a.currentFlags.dotAll?a.appliedGlobalFlags.dotAll||a.useFlagMods?".":"[^]":C`[^\n]`;if(e==="digit")return t?C`\D`:C`\d`;if(e==="property"){if(a.useAppliedIgnoreCase&&a.currentFlags.ignoreCase&&Oa.has(n))throw new Error(`Unicode property "${n}" can't be case-insensitive when other chars have specific case`);return`${t?C`\P`:C`\p`}{${r?`${r}=`:""}${n}}`}if(e==="word")return t?C`\W`:C`\w`;throw new Error(`Unexpected character set kind "${e}"`)},Flags(e,t){return(t.appliedGlobalFlags.ignoreCase?"i":"")+(e.dotAll?"s":"")+(e.sticky?"y":"")},Group({atomic:e,body:t,flags:n,parent:r},a,o){let i=a.currentFlags;n&&(a.currentFlags=Et(i,n));let s=t.map(o).join("|"),l=!a.verbose&&t.length===1&&r.type!=="Quantifier"&&!e&&(!a.useFlagMods||!n)?s:`(?${$l(e,n,a.useFlagMods)}${s})`;return a.currentFlags=i,l},LookaroundAssertion({body:e,kind:t,negate:n},r,a){return`(?${`${t==="lookahead"?"":"<"}${n?"!":"="}`}${e.map(a).join("|")})`},Quantifier(e,t,n){return n(e.body)+Ml(e)},Subroutine({isRecursive:e,ref:t},n){if(!e)throw new Error("Unexpected non-recursive subroutine in transformed AST");let r=n.recursionLimit;return t===0?`(?R=${r})`:C`\g<${t}&R=${r}>`}},Bl=new Set(["$","(",")","*","+",".","?","[","\\","]","^","{","|","}"]),Nl=new Set(["-","\\","]","^","["]),Tl=new Set(["(",")","-","/","[","\\","]","^","{","|","}","!","#","$","%","&","*","+",",",".",":",";","<","=",">","?","@","`","~"]),Pa=new Map([[9,C`\t`],[10,C`\n`],[11,C`\v`],[12,C`\f`],[13,C`\r`],[8232,C`\u2028`],[8233,C`\u2029`],[65279,C`\uFEFF`]]),Ll=/^\p{Cased}$/u;function En(e){return Ll.test(e)}function za(e,t){let n=!!t?.firstOnly,r=e.min.value,a=e.max.value,o=[];if(r<65&&(a===65535||a>=131071)||r===65536&&a>=131071)return o;for(let i=r;i<=a;i++){let s=N(i);if(!En(s))continue;let l=Fa(s).filter(c=>{let u=c.codePointAt(0);return ua});if(l.length&&(o.push(...l),n))break}return o}function Se(e,{escDigit:t,inCharClass:n,useFlagV:r}){if(Pa.has(e))return Pa.get(e);if(e<32||e>126&&e<160||e>262143||t&&Gl(e))return e>255?`\\u{${e.toString(16).toUpperCase()}}`:`\\x${e.toString(16).toUpperCase().padStart(2,"0")}`;let a=n?r?Tl:Nl:Bl,o=N(e);return(a.has(o)?"\\":"")+o}function Pl(e){let t=e.map(a=>a.codePointAt(0)).sort((a,o)=>a-o),n=[],r=null;for(let a=0;a";let r="";if(t&&n){let{enable:a,disable:o}=t;r=(a?.ignoreCase?"i":"")+(a?.dotAll?"s":"")+(o?"-":"")+(o?.ignoreCase?"i":"")+(o?.dotAll?"s":"")}return`${r}:`}function Ml({kind:e,max:t,min:n}){let r;return!n&&t===1?r="?":!n&&t===1/0?r="*":n===1&&t===1/0?r="+":n===t?r=`{${n}}`:r=`{${n},${t===1/0?"":t}}`,r+{greedy:"",lazy:"?",possessive:"+"}[e]}function $a({type:e}){return e==="CapturingGroup"||e==="Group"||e==="LookaroundAssertion"}function Gl(e){return e>47&&e<58}function Ma({type:e,value:t}){return e==="Character"&&t===45}var Fl=class _n extends RegExp{#t=new Map;#e=null;#r;#n=null;#a=null;rawOptions={};get source(){return this.#r||"(?:)"}constructor(t,n,r){let a=!!r?.lazyCompile;if(t instanceof RegExp){if(r)throw new Error("Cannot provide options when copying a regexp");let o=t;super(o,n),this.#r=o.source,o instanceof _n&&(this.#t=o.#t,this.#n=o.#n,this.#a=o.#a,this.rawOptions=o.rawOptions)}else{let o={hiddenCaptures:[],strategy:null,transfers:[],...r};super(a?"":t,n),this.#r=t,this.#t=Dl(o.hiddenCaptures,o.transfers),this.#a=o.strategy,this.rawOptions=r??{}}a||(this.#e=this)}exec(t){if(!this.#e){let{lazyCompile:a,...o}=this.rawOptions;this.#e=new _n(this.#r,this.flags,o)}let n=this.global||this.sticky,r=this.lastIndex;if(this.#a==="clip_search"&&n&&r){this.lastIndex=0;let a=this.#o(t.slice(r));return a&&(Ol(a,r,t,this.hasIndices),this.lastIndex+=r),a}return this.#o(t)}#o(t){this.#e.lastIndex=this.lastIndex;let n=super.exec.call(this.#e,t);if(this.lastIndex=this.#e.lastIndex,!n||!this.#t.size)return n;let r=[...n];n.length=1;let a;this.hasIndices&&(a=[...n.indices],n.indices.length=1);let o=[0];for(let i=1;i{let s=o[i];s&&(o[i]=[s[0]+t,s[1]+t])})}}function Dl(e,t){let n=new Map;for(let r of e)n.set(r,{hidden:!0});for(let[r,a]of t)for(let o of a)ze(n,o,{}).transferTo=r;return n}function Ul(e){let t=/(?\((?:\?<(?![=!])(?[^>]+)>|(?!\?)))|\\?./gsu,n=new Map,r=0,a=0,o;for(;o=t.exec(e);){let{0:i,groups:{capture:s,name:l}}=o;i==="["?r++:r?i==="]"&&r--:s&&(a++,l&&n.set(a,l))}return n}function Va(e,t){let n=ql(e,t);return n.options?new Fl(n.pattern,n.flags,n.options):new RegExp(n.pattern,n.flags)}function ql(e,t){let n=Ga(t),r=xt(e,{flags:n.flags,normalizeUnknownPropertyNames:!0,rules:{captureGroup:n.rules.captureGroup,singleline:n.rules.singleline},skipBackrefValidation:n.rules.allowOrphanBackrefs,unicodePropertyMap:Sn}),a=ml(r,{accuracy:n.accuracy,asciiWordBoundaries:n.rules.asciiWordBoundaries,avoidSubclass:n.avoidSubclass,bestEffortTarget:n.target}),o=Al(a,n),i=Na(o.pattern,{captureTransfers:o._captureTransfers,hiddenCaptures:o._hiddenCaptures,mode:"external"}),s=mn(i.pattern),l=fn(s.pattern,{captureTransfers:i.captureTransfers,hiddenCaptures:i.hiddenCaptures}),c={pattern:l.pattern,flags:`${n.hasIndices?"d":""}${n.global?"g":""}${o.flags}${o.options.disable.v?"u":"v"}`};if(n.avoidSubclass){if(n.lazyCompileLength!==1/0)throw new Error("Lazy compilation requires subclass")}else{let u=l.hiddenCaptures.sort((h,y)=>h-y),p=Array.from(l.captureTransfers),d=a._strategy,g=c.pattern.length>=n.lazyCompileLength;(u.length||p.length||d||g)&&(c.options={...u.length&&{hiddenCaptures:u},...p.length&&{transfers:p},...d&&{strategy:d},...g&&{lazyCompile:g}})}return c}function Xa(e,t){return Va(e,{global:!0,hasIndices:!0,lazyCompileLength:3e3,rules:{allowOrphanBackrefs:!0,asciiWordBoundaries:!0,captureGroup:!0,recursionLimit:5,singleline:!0},...t})}function An(e={}){let t={target:"auto",cache:new Map,...e};return t.regexConstructor||=n=>Xa(n,{target:t.target}),{createScanner(n){return new ta(n,t)},createString(n){return{content:n}}}}var jl=Object.freeze(JSON.parse(`{"displayName":"Python","name":"python","patterns":[{"include":"#statement"},{"include":"#expression"}],"repository":{"annotated-parameter":{"begin":"\\\\b([_[:alpha:]]\\\\w*)\\\\s*(:)","beginCaptures":{"1":{"name":"variable.parameter.function.language.python"},"2":{"name":"punctuation.separator.annotation.python"}},"end":"(,)|(?=\\\\))","endCaptures":{"1":{"name":"punctuation.separator.parameters.python"}},"patterns":[{"include":"#expression"},{"match":"=(?!=)","name":"keyword.operator.assignment.python"}]},"assignment-operator":{"match":"<<=|>>=|//=|\\\\*\\\\*=|\\\\+=|-=|/=|@=|\\\\*=|%=|~=|\\\\^=|&=|\\\\|=|=(?!=)","name":"keyword.operator.assignment.python"},"backticks":{"begin":"\`","end":"\`|(?))","name":"comment.typehint.punctuation.notation.python"},{"match":"([_[:alpha:]]\\\\w*)","name":"comment.typehint.variable.notation.python"}]},{"include":"#comments-base"}]},"comments-base":{"begin":"(#)","beginCaptures":{"1":{"name":"punctuation.definition.comment.python"}},"end":"$()","name":"comment.line.number-sign.python","patterns":[{"include":"#codetags"}]},"comments-string-double-three":{"begin":"(#)","beginCaptures":{"1":{"name":"punctuation.definition.comment.python"}},"end":"($|(?=\\"\\"\\"))","name":"comment.line.number-sign.python","patterns":[{"include":"#codetags"}]},"comments-string-single-three":{"begin":"(#)","beginCaptures":{"1":{"name":"punctuation.definition.comment.python"}},"end":"($|(?='''))","name":"comment.line.number-sign.python","patterns":[{"include":"#codetags"}]},"curly-braces":{"begin":"\\\\{","beginCaptures":{"0":{"name":"punctuation.definition.dict.begin.python"}},"end":"}","endCaptures":{"0":{"name":"punctuation.definition.dict.end.python"}},"patterns":[{"match":":","name":"punctuation.separator.dict.python"},{"include":"#expression"}]},"decorator":{"begin":"^\\\\s*((@))\\\\s*(?=[_[:alpha:]]\\\\w*)","beginCaptures":{"1":{"name":"entity.name.function.decorator.python"},"2":{"name":"punctuation.definition.decorator.python"}},"end":"(\\\\))(.*?)(?=\\\\s*(?:#|$))|(?=[\\\\n#])","endCaptures":{"1":{"name":"punctuation.definition.arguments.end.python"},"2":{"name":"invalid.illegal.decorator.python"}},"name":"meta.function.decorator.python","patterns":[{"include":"#decorator-name"},{"include":"#function-arguments"}]},"decorator-name":{"patterns":[{"include":"#builtin-callables"},{"include":"#illegal-object-name"},{"captures":{"2":{"name":"punctuation.separator.period.python"}},"match":"([_[:alpha:]]\\\\w*)|(\\\\.)","name":"entity.name.function.decorator.python"},{"include":"#line-continuation"},{"captures":{"1":{"name":"invalid.illegal.decorator.python"}},"match":"\\\\s*([^#(.\\\\\\\\_[:alpha:]\\\\s].*?)(?=#|$)","name":"invalid.illegal.decorator.python"}]},"docstring":{"patterns":[{"begin":"('''|\\"\\"\\")","beginCaptures":{"1":{"name":"punctuation.definition.string.begin.python"}},"end":"(\\\\1)","endCaptures":{"1":{"name":"punctuation.definition.string.end.python"}},"name":"string.quoted.docstring.multi.python","patterns":[{"include":"#docstring-prompt"},{"include":"#codetags"},{"include":"#docstring-guts-unicode"}]},{"begin":"([Rr])('''|\\"\\"\\")","beginCaptures":{"1":{"name":"storage.type.string.python"},"2":{"name":"punctuation.definition.string.begin.python"}},"end":"(\\\\2)","endCaptures":{"1":{"name":"punctuation.definition.string.end.python"}},"name":"string.quoted.docstring.raw.multi.python","patterns":[{"include":"#string-consume-escape"},{"include":"#docstring-prompt"},{"include":"#codetags"}]},{"begin":"([\\"'])","beginCaptures":{"1":{"name":"punctuation.definition.string.begin.python"}},"end":"(\\\\1)|(\\\\n)","endCaptures":{"1":{"name":"punctuation.definition.string.end.python"},"2":{"name":"invalid.illegal.newline.python"}},"name":"string.quoted.docstring.single.python","patterns":[{"include":"#codetags"},{"include":"#docstring-guts-unicode"}]},{"begin":"([Rr])([\\"'])","beginCaptures":{"1":{"name":"storage.type.string.python"},"2":{"name":"punctuation.definition.string.begin.python"}},"end":"(\\\\2)|(\\\\n)","endCaptures":{"1":{"name":"punctuation.definition.string.end.python"},"2":{"name":"invalid.illegal.newline.python"}},"name":"string.quoted.docstring.raw.single.python","patterns":[{"include":"#string-consume-escape"},{"include":"#codetags"}]}]},"docstring-guts-unicode":{"patterns":[{"include":"#escape-sequence-unicode"},{"include":"#escape-sequence"},{"include":"#string-line-continuation"}]},"docstring-prompt":{"captures":{"1":{"name":"keyword.control.flow.python"}},"match":"(?:^|\\\\G)\\\\s*((?:>>>|\\\\.\\\\.\\\\.)\\\\s)(?=\\\\s*\\\\S)"},"docstring-statement":{"begin":"^(?=\\\\s*[Rr]?('''|\\"\\"\\"|[\\"']))","end":"((?<=\\\\1)|^)(?!\\\\s*[Rr]?('''|\\"\\"\\"|[\\"']))","patterns":[{"include":"#docstring"}]},"double-one-regexp-character-set":{"patterns":[{"match":"\\\\[\\\\^?](?!.*?])"},{"begin":"(\\\\[)(\\\\^)?(])?","beginCaptures":{"1":{"name":"punctuation.character.set.begin.regexp constant.other.set.regexp"},"2":{"name":"keyword.operator.negation.regexp"},"3":{"name":"constant.character.set.regexp"}},"end":"(]|(?=\\"))|((?=(?)","beginCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.named.begin.regexp"},"2":{"name":"entity.name.tag.named.group.regexp"}},"end":"(\\\\)|(?=\\"))|((?=(?)","beginCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.named.begin.regexp"},"2":{"name":"entity.name.tag.named.group.regexp"}},"end":"(\\\\)|(?=\\"\\"\\"))","endCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.named.end.regexp"},"2":{"name":"invalid.illegal.newline.python"}},"name":"meta.named.regexp","patterns":[{"include":"#double-three-regexp-expression"},{"include":"#comments-string-double-three"}]},"double-three-regexp-parentheses":{"begin":"\\\\(","beginCaptures":{"0":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.begin.regexp"}},"end":"(\\\\)|(?=\\"\\"\\"))","endCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.end.regexp"},"2":{"name":"invalid.illegal.newline.python"}},"patterns":[{"include":"#double-three-regexp-expression"},{"include":"#comments-string-double-three"}]},"double-three-regexp-parentheses-non-capturing":{"begin":"\\\\(\\\\?:","beginCaptures":{"0":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.non-capturing.begin.regexp"}},"end":"(\\\\)|(?=\\"\\"\\"))","endCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.non-capturing.end.regexp"},"2":{"name":"invalid.illegal.newline.python"}},"patterns":[{"include":"#double-three-regexp-expression"},{"include":"#comments-string-double-three"}]},"ellipsis":{"match":"\\\\.\\\\.\\\\.","name":"constant.other.ellipsis.python"},"escape-sequence":{"match":"\\\\\\\\(x\\\\h{2}|[0-7]{1,3}|[\\"'\\\\\\\\abfnrtv])","name":"constant.character.escape.python"},"escape-sequence-unicode":{"patterns":[{"match":"\\\\\\\\(u\\\\h{4}|U\\\\h{8}|N\\\\{[\\\\w\\\\s]+?})","name":"constant.character.escape.python"}]},"expression":{"patterns":[{"include":"#expression-base"},{"include":"#member-access"},{"match":"\\\\b([_[:alpha:]]\\\\w*)\\\\b"}]},"expression-bare":{"patterns":[{"include":"#backticks"},{"include":"#illegal-anno"},{"include":"#literal"},{"include":"#regexp"},{"include":"#string"},{"include":"#lambda"},{"include":"#generator"},{"include":"#illegal-operator"},{"include":"#operator"},{"include":"#curly-braces"},{"include":"#item-access"},{"include":"#list"},{"include":"#odd-function-call"},{"include":"#round-braces"},{"include":"#function-call"},{"include":"#builtin-functions"},{"include":"#builtin-types"},{"include":"#builtin-exceptions"},{"include":"#magic-names"},{"include":"#special-names"},{"include":"#illegal-names"},{"include":"#special-variables"},{"include":"#ellipsis"},{"include":"#punctuation"},{"include":"#line-continuation"}]},"expression-base":{"patterns":[{"include":"#comments"},{"include":"#expression-bare"},{"include":"#line-continuation"}]},"f-expression":{"patterns":[{"include":"#expression-bare"},{"include":"#member-access"},{"match":"\\\\b([_[:alpha:]]\\\\w*)\\\\b"}]},"fregexp-base-expression":{"patterns":[{"include":"#fregexp-quantifier"},{"include":"#fstring-formatting-braces"},{"match":"\\\\{.*?}"},{"include":"#regexp-base-common"}]},"fregexp-quantifier":{"match":"\\\\{\\\\{(\\\\d+|\\\\d+,(\\\\d+)?|,\\\\d+)}}","name":"keyword.operator.quantifier.regexp"},"fstring-fnorm-quoted-multi-line":{"begin":"\\\\b([Ff])([BUbu])?('''|\\"\\"\\")","beginCaptures":{"1":{"name":"string.interpolated.python string.quoted.multi.python storage.type.string.python"},"2":{"name":"invalid.illegal.prefix.python"},"3":{"name":"punctuation.definition.string.begin.python string.interpolated.python string.quoted.multi.python"}},"end":"(\\\\3)","endCaptures":{"1":{"name":"punctuation.definition.string.end.python string.interpolated.python string.quoted.multi.python"},"2":{"name":"invalid.illegal.newline.python"}},"name":"meta.fstring.python","patterns":[{"include":"#fstring-guts"},{"include":"#fstring-illegal-multi-brace"},{"include":"#fstring-multi-brace"},{"include":"#fstring-multi-core"}]},"fstring-fnorm-quoted-single-line":{"begin":"\\\\b([Ff])([BUbu])?(([\\"']))","beginCaptures":{"1":{"name":"string.interpolated.python string.quoted.single.python storage.type.string.python"},"2":{"name":"invalid.illegal.prefix.python"},"3":{"name":"punctuation.definition.string.begin.python string.interpolated.python string.quoted.single.python"}},"end":"(\\\\3)|((?^]?[- +]?#?\\\\d*,?(\\\\.\\\\d+)?[%EFGXb-gnosx]?)(?=})"},{"include":"#fstring-terminator-multi-tail"}]},"fstring-terminator-multi-tail":{"begin":"(=?(?:![ars])?)(:)(?=.*?\\\\{)","beginCaptures":{"1":{"name":"storage.type.format.python"},"2":{"name":"storage.type.format.python"}},"end":"(?=})","patterns":[{"include":"#fstring-illegal-multi-brace"},{"include":"#fstring-multi-brace"},{"match":"([%EFGXb-gnosx])(?=})","name":"storage.type.format.python"},{"match":"(\\\\.\\\\d+)","name":"storage.type.format.python"},{"match":"(,)","name":"storage.type.format.python"},{"match":"(\\\\d+)","name":"storage.type.format.python"},{"match":"(#)","name":"storage.type.format.python"},{"match":"([- +])","name":"storage.type.format.python"},{"match":"([<=>^])","name":"storage.type.format.python"},{"match":"(\\\\w)","name":"storage.type.format.python"}]},"fstring-terminator-single":{"patterns":[{"match":"(=(![ars])?)(?=})","name":"storage.type.format.python"},{"match":"(=?![ars])(?=})","name":"storage.type.format.python"},{"captures":{"1":{"name":"storage.type.format.python"},"2":{"name":"storage.type.format.python"}},"match":"(=?(?:![ars])?)(:\\\\w?[<=>^]?[- +]?#?\\\\d*,?(\\\\.\\\\d+)?[%EFGXb-gnosx]?)(?=})"},{"include":"#fstring-terminator-single-tail"}]},"fstring-terminator-single-tail":{"begin":"(=?(?:![ars])?)(:)(?=.*?\\\\{)","beginCaptures":{"1":{"name":"storage.type.format.python"},"2":{"name":"storage.type.format.python"}},"end":"(?=})|(?=\\\\n)","patterns":[{"include":"#fstring-illegal-single-brace"},{"include":"#fstring-single-brace"},{"match":"([%EFGXb-gnosx])(?=})","name":"storage.type.format.python"},{"match":"(\\\\.\\\\d+)","name":"storage.type.format.python"},{"match":"(,)","name":"storage.type.format.python"},{"match":"(\\\\d+)","name":"storage.type.format.python"},{"match":"(#)","name":"storage.type.format.python"},{"match":"([- +])","name":"storage.type.format.python"},{"match":"([<=>^])","name":"storage.type.format.python"},{"match":"(\\\\w)","name":"storage.type.format.python"}]},"function-arguments":{"begin":"(\\\\()","beginCaptures":{"1":{"name":"punctuation.definition.arguments.begin.python"}},"contentName":"meta.function-call.arguments.python","end":"(?=\\\\))(?!\\\\)\\\\s*\\\\()","patterns":[{"match":"(,)","name":"punctuation.separator.arguments.python"},{"captures":{"1":{"name":"keyword.operator.unpacking.arguments.python"}},"match":"(?:(?<=[(,])|^)\\\\s*(\\\\*{1,2})"},{"include":"#lambda-incomplete"},{"include":"#illegal-names"},{"captures":{"1":{"name":"variable.parameter.function-call.python"},"2":{"name":"keyword.operator.assignment.python"}},"match":"\\\\b([_[:alpha:]]\\\\w*)\\\\s*(=)(?!=)"},{"match":"=(?!=)","name":"keyword.operator.assignment.python"},{"include":"#expression"},{"captures":{"1":{"name":"punctuation.definition.arguments.end.python"},"2":{"name":"punctuation.definition.arguments.begin.python"}},"match":"\\\\s*(\\\\))\\\\s*(\\\\()"}]},"function-call":{"begin":"\\\\b(?=([_[:alpha:]]\\\\w*)\\\\s*(\\\\())","end":"(\\\\))","endCaptures":{"1":{"name":"punctuation.definition.arguments.end.python"}},"name":"meta.function-call.python","patterns":[{"include":"#special-variables"},{"include":"#function-name"},{"include":"#function-arguments"}]},"function-declaration":{"begin":"\\\\s*(?:\\\\b(async)\\\\s+)?\\\\b(def)\\\\s+(?=[_[:alpha:]]\\\\p{word}*\\\\s*\\\\()","beginCaptures":{"1":{"name":"storage.type.function.async.python"},"2":{"name":"storage.type.function.python"}},"end":"(:|(?=[\\\\n\\"#']))","endCaptures":{"1":{"name":"punctuation.section.function.begin.python"}},"name":"meta.function.python","patterns":[{"include":"#function-def-name"},{"include":"#parameters"},{"include":"#line-continuation"},{"include":"#return-annotation"}]},"function-def-name":{"patterns":[{"include":"#illegal-object-name"},{"include":"#builtin-possible-callables"},{"match":"\\\\b([_[:alpha:]]\\\\w*)\\\\b","name":"entity.name.function.python"}]},"function-name":{"patterns":[{"include":"#builtin-possible-callables"},{"match":"\\\\b([_[:alpha:]]\\\\w*)\\\\b","name":"meta.function-call.generic.python"}]},"generator":{"begin":"\\\\bfor\\\\b","beginCaptures":{"0":{"name":"keyword.control.flow.python"}},"end":"\\\\bin\\\\b","endCaptures":{"0":{"name":"keyword.control.flow.python"}},"patterns":[{"include":"#expression"}]},"illegal-anno":{"match":"->","name":"invalid.illegal.annotation.python"},"illegal-names":{"captures":{"1":{"name":"keyword.control.flow.python"},"2":{"name":"keyword.control.import.python"}},"match":"\\\\b(?:(and|assert|async|await|break|class|continue|def|del|elif|else|except|finally|for|from|global|if|in|is|(?<=\\\\.)lambda|lambda(?=\\\\s*[.=])|nonlocal|not|or|pass|raise|return|try|while|with|yield)|(as|import))\\\\b"},"illegal-object-name":{"match":"\\\\b(True|False|None)\\\\b","name":"keyword.illegal.name.python"},"illegal-operator":{"patterns":[{"match":"&&|\\\\|\\\\||--|\\\\+\\\\+","name":"invalid.illegal.operator.python"},{"match":"[$?]","name":"invalid.illegal.operator.python"},{"match":"!\\\\b","name":"invalid.illegal.operator.python"}]},"import":{"patterns":[{"begin":"\\\\b(?>|[\\\\&^|~])|(\\\\*\\\\*|[-%*+]|//|[/@])|(!=|==|>=|<=|[<>])|(:=)"},"parameter-special":{"captures":{"1":{"name":"variable.parameter.function.language.python"},"2":{"name":"variable.parameter.function.language.special.self.python"},"3":{"name":"variable.parameter.function.language.special.cls.python"},"4":{"name":"punctuation.separator.parameters.python"}},"match":"\\\\b((self)|(cls))\\\\b\\\\s*(?:(,)|(?=\\\\)))"},"parameters":{"begin":"(\\\\()","beginCaptures":{"1":{"name":"punctuation.definition.parameters.begin.python"}},"end":"(\\\\))","endCaptures":{"1":{"name":"punctuation.definition.parameters.end.python"}},"name":"meta.function.parameters.python","patterns":[{"match":"/","name":"keyword.operator.positional.parameter.python"},{"match":"(\\\\*\\\\*?)","name":"keyword.operator.unpacking.parameter.python"},{"include":"#lambda-incomplete"},{"include":"#illegal-names"},{"include":"#illegal-object-name"},{"include":"#parameter-special"},{"captures":{"1":{"name":"variable.parameter.function.language.python"},"2":{"name":"punctuation.separator.parameters.python"}},"match":"([_[:alpha:]]\\\\w*)\\\\s*(?:(,)|(?=[\\\\n#)=]))"},{"include":"#comments"},{"include":"#loose-default"},{"include":"#annotated-parameter"}]},"punctuation":{"patterns":[{"match":":","name":"punctuation.separator.colon.python"},{"match":",","name":"punctuation.separator.element.python"}]},"regexp":{"patterns":[{"include":"#regexp-single-three-line"},{"include":"#regexp-double-three-line"},{"include":"#regexp-single-one-line"},{"include":"#regexp-double-one-line"}]},"regexp-backreference":{"captures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.backreference.named.begin.regexp"},"2":{"name":"entity.name.tag.named.backreference.regexp"},"3":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.backreference.named.end.regexp"}},"match":"(\\\\()(\\\\?P=\\\\w+(?:\\\\s+\\\\p{alnum}+)?)(\\\\))","name":"meta.backreference.named.regexp"},"regexp-backreference-number":{"captures":{"1":{"name":"entity.name.tag.backreference.regexp"}},"match":"(\\\\\\\\[1-9]\\\\d?)","name":"meta.backreference.regexp"},"regexp-base-common":{"patterns":[{"match":"\\\\.","name":"support.other.match.any.regexp"},{"match":"\\\\^","name":"support.other.match.begin.regexp"},{"match":"\\\\$","name":"support.other.match.end.regexp"},{"match":"[*+?]\\\\??","name":"keyword.operator.quantifier.regexp"},{"match":"\\\\|","name":"keyword.operator.disjunction.regexp"},{"include":"#regexp-escape-sequence"}]},"regexp-base-expression":{"patterns":[{"include":"#regexp-quantifier"},{"include":"#regexp-base-common"}]},"regexp-charecter-set-escapes":{"patterns":[{"match":"\\\\\\\\[\\\\\\\\abfnrtv]","name":"constant.character.escape.regexp"},{"include":"#regexp-escape-special"},{"match":"\\\\\\\\([0-7]{1,3})","name":"constant.character.escape.regexp"},{"include":"#regexp-escape-character"},{"include":"#regexp-escape-unicode"},{"include":"#regexp-escape-catchall"}]},"regexp-double-one-line":{"begin":"\\\\b(([Uu]r)|([Bb]r)|(r[Bb]?))(\\")","beginCaptures":{"2":{"name":"invalid.deprecated.prefix.python"},"3":{"name":"storage.type.string.python"},"4":{"name":"storage.type.string.python"},"5":{"name":"punctuation.definition.string.begin.python"}},"end":"(\\")|(?)","beginCaptures":{"1":{"name":"punctuation.separator.annotation.result.python"}},"end":"(?=:)","patterns":[{"include":"#expression"}]},"round-braces":{"begin":"\\\\(","beginCaptures":{"0":{"name":"punctuation.parenthesis.begin.python"}},"end":"\\\\)","endCaptures":{"0":{"name":"punctuation.parenthesis.end.python"}},"patterns":[{"include":"#expression"}]},"semicolon":{"patterns":[{"match":";$","name":"invalid.deprecated.semicolon.python"}]},"single-one-regexp-character-set":{"patterns":[{"match":"\\\\[\\\\^?](?!.*?])"},{"begin":"(\\\\[)(\\\\^)?(])?","beginCaptures":{"1":{"name":"punctuation.character.set.begin.regexp constant.other.set.regexp"},"2":{"name":"keyword.operator.negation.regexp"},"3":{"name":"constant.character.set.regexp"}},"end":"(]|(?='))|((?=(?)","beginCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.named.begin.regexp"},"2":{"name":"entity.name.tag.named.group.regexp"}},"end":"(\\\\)|(?='))|((?=(?)","beginCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.named.begin.regexp"},"2":{"name":"entity.name.tag.named.group.regexp"}},"end":"(\\\\)|(?='''))","endCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.named.end.regexp"},"2":{"name":"invalid.illegal.newline.python"}},"name":"meta.named.regexp","patterns":[{"include":"#single-three-regexp-expression"},{"include":"#comments-string-single-three"}]},"single-three-regexp-parentheses":{"begin":"\\\\(","beginCaptures":{"0":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.begin.regexp"}},"end":"(\\\\)|(?='''))","endCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.end.regexp"},"2":{"name":"invalid.illegal.newline.python"}},"patterns":[{"include":"#single-three-regexp-expression"},{"include":"#comments-string-single-three"}]},"single-three-regexp-parentheses-non-capturing":{"begin":"\\\\(\\\\?:","beginCaptures":{"0":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.non-capturing.begin.regexp"}},"end":"(\\\\)|(?='''))","endCaptures":{"1":{"name":"support.other.parenthesis.regexp punctuation.parenthesis.non-capturing.end.regexp"},"2":{"name":"invalid.illegal.newline.python"}},"patterns":[{"include":"#single-three-regexp-expression"},{"include":"#comments-string-single-three"}]},"special-names":{"match":"\\\\b(_*\\\\p{upper}[_\\\\d]*\\\\p{upper})[[:upper:]\\\\d]*(_\\\\w*)?\\\\b","name":"constant.other.caps.python"},"special-variables":{"captures":{"1":{"name":"variable.language.special.self.python"},"2":{"name":"variable.language.special.cls.python"}},"match":"\\\\b(?^]?[- +]?#?\\\\d*,?(\\\\.\\\\d+)?[%EFGXb-gnosx]?)?})","name":"meta.format.brace.python"},{"captures":{"1":{"name":"constant.character.format.placeholder.other.python"},"3":{"name":"storage.type.format.python"},"4":{"name":"storage.type.format.python"}},"match":"(\\\\{\\\\w*(\\\\.[_[:alpha:]]\\\\w*|\\\\[[^]\\"']+])*(![ars])?(:)[^\\\\n\\"'{}]*(?:\\\\{[^\\\\n\\"'}]*?}[^\\\\n\\"'{}]*)*})","name":"meta.format.brace.python"}]},"string-consume-escape":{"match":"\\\\\\\\[\\\\n\\"'\\\\\\\\]"},"string-entity":{"patterns":[{"include":"#escape-sequence"},{"include":"#string-line-continuation"},{"include":"#string-formatting"}]},"string-formatting":{"captures":{"1":{"name":"constant.character.format.placeholder.other.python"}},"match":"(%(\\\\([\\\\w\\\\s]*\\\\))?[- #+0]*(\\\\d+|\\\\*)?(\\\\.(\\\\d+|\\\\*))?([Lhl])?[%EFGXa-giorsux])","name":"meta.format.percent.python"},"string-line-continuation":{"match":"\\\\\\\\$","name":"constant.language.python"},"string-multi-bad-brace1-formatting-raw":{"begin":"(?=\\\\{%(.*?(?!'''|\\"\\"\\"))%})","end":"(?='''|\\"\\"\\")","patterns":[{"include":"#string-consume-escape"}]},"string-multi-bad-brace1-formatting-unicode":{"begin":"(?=\\\\{%(.*?(?!'''|\\"\\"\\"))%})","end":"(?='''|\\"\\"\\")","patterns":[{"include":"#escape-sequence-unicode"},{"include":"#escape-sequence"},{"include":"#string-line-continuation"}]},"string-multi-bad-brace2-formatting-raw":{"begin":"(?!\\\\{\\\\{)(?=\\\\{(\\\\w*?(?!'''|\\"\\"\\")[^!.:\\\\[}\\\\w]).*?(?!'''|\\"\\"\\")})","end":"(?='''|\\"\\"\\")","patterns":[{"include":"#string-consume-escape"},{"include":"#string-formatting"}]},"string-multi-bad-brace2-formatting-unicode":{"begin":"(?!\\\\{\\\\{)(?=\\\\{(\\\\w*?(?!'''|\\"\\"\\")[^!.:\\\\[}\\\\w]).*?(?!'''|\\"\\"\\")})","end":"(?='''|\\"\\"\\")","patterns":[{"include":"#escape-sequence-unicode"},{"include":"#string-entity"}]},"string-quoted-multi-line":{"begin":"(?:\\\\b([Rr])(?=[Uu]))?([Uu])?('''|\\"\\"\\")","beginCaptures":{"1":{"name":"invalid.illegal.prefix.python"},"2":{"name":"storage.type.string.python"},"3":{"name":"punctuation.definition.string.begin.python"}},"end":"(\\\\3)","endCaptures":{"1":{"name":"punctuation.definition.string.end.python"},"2":{"name":"invalid.illegal.newline.python"}},"name":"string.quoted.multi.python","patterns":[{"include":"#string-multi-bad-brace1-formatting-unicode"},{"include":"#string-multi-bad-brace2-formatting-unicode"},{"include":"#string-unicode-guts"}]},"string-quoted-single-line":{"begin":"(?:\\\\b([Rr])(?=[Uu]))?([Uu])?(([\\"']))","beginCaptures":{"1":{"name":"invalid.illegal.prefix.python"},"2":{"name":"storage.type.string.python"},"3":{"name":"punctuation.definition.string.begin.python"}},"end":"(\\\\3)|((?Journey-figures gestalt

Every journey section's figure on one page so the set can be reasoned about as a whole. Score against the rubric; redesign anything below the 8.5 gate before shipping to /journeys/<slug>.

-

Runtime

This journey builds the smallest coherent model of Python at runtime: programs run statements, names refer to objects, objects have types, and operations ask those objects to do work.

Start with executable evidence.

Examples are evidence loops: source, a run step, and visible output stay together.

Separate value, identity, and absence.

Runtime objects answer separate questions: equal value, same identity, or the singleton that marks absence.

Read expressions as object operations.

Expression syntax enters the data model; object methods produce the result.

Control Flow

This journey follows how a Python program chooses which path runs, names facts at decision points, and exits early when the remaining work no longer applies.

Choose between paths.

Facts flow into one decision point; exactly one branch owns the next step.

Name and shape decisions.

Name a fact when a condition needs it; match shape when the data structure is the decision.

Stop as soon as the answer is known.

Early exits draw a boundary: once the answer is found, the tail stays unread.

Iteration

This journey follows repeated work from ordinary loops to the iterator protocol: consume values, stop deliberately, and produce lazy streams only when they help.

Choose the right loop shape.

Choose the loop from its stopping rule: exhaustion, condition, or sentinel marker.

See the protocol behind `for`.

for is surface syntax; iter() creates an iterator and next() pulls values until StopIteration.

Compose lazy value streams.

Lazy pipelines run from the consumer's pull: next() requests one value through each stage.

Shapes

This journey teaches the core Python habit of choosing a data shape, transforming it directly, and making the result visible.

Pick the container that matches the question.

Each container answers a different question: ordered, fixed, lookup, unique.

Move between shapes deliberately.

Most everyday code reshapes data: one input, one transform, one new value.

Cross text and data boundaries.

Programs receive text and produce structured data; parsing makes the boundary explicit.

Interfaces

This journey shows how Python grows from simple functions to callable APIs, object interfaces, protocols, and metaclasses.

Start with functions as named behavior.

A function is the first abstraction boundary: arguments in, body, return value out.

Use functions as values.

Functions are first-class values. A second name binds to the same function object.

Bundle behavior with state.

Classes group fields and methods so data and behavior move together behind one interface.

Types

This journey maps Python's runtime object model to optional static annotations so learners know what types can and cannot promise.

Keep runtime and static analysis separate.

Runtime values run the program; static tools inspect separate annotations and report before execution.

Describe realistic data shapes.

Real data contracts combine fields, variants, and expected absence instead of one scalar type.

Scale annotations for reusable libraries.

Reusable APIs carry caller contracts through the library boundary with generics, parameters, and overloads.

Reliability

This journey follows the boundaries where programs fail, clean up, split into modules, communicate with the outside world, and run concurrent work.

Make failure explicit.

Different failure shapes need explicit signals: assertions, recovery, chained causes, or warnings.

Control resource and module boundaries.

Reliable programs name their boundaries: resources clean up, modules import, environments constrain runtime.

Handle operations that outlive one expression.

Async, threaded, test, and logging work cross an operation boundary before evidence comes back.
+

Runtime

This journey builds the smallest coherent model of Python at runtime: programs run statements, names refer to objects, objects have types, and operations ask those objects to do work.

Start with executable evidence.

Examples are evidence loops: source, a run step, and visible output stay together.

Separate value, identity, and absence.

Runtime objects answer separate questions: equal value, same identity, or the singleton that marks absence.

Read expressions as object operations.

Expression syntax enters the data model; object methods produce the result.

Control Flow

This journey follows how a Python program chooses which path runs, names facts at decision points, and exits early when the remaining work no longer applies.

Choose between paths.

Facts flow into one decision point; exactly one branch owns the next step.

Name and shape decisions.

Name a fact when a condition needs it; match shape when the data structure is the decision.

Stop as soon as the answer is known.

Early exits draw a boundary: once the answer is found, the tail stays unread.

Iteration

This journey follows repeated work from ordinary loops to the iterator protocol: consume values, stop deliberately, and produce lazy streams only when they help.

Choose the right loop shape.

Choose the loop from its stopping rule: exhaustion, condition, or sentinel marker.

See the protocol behind `for`.

for is surface syntax; iter() creates an iterator and next() pulls values until StopIteration.

Compose lazy value streams.

Lazy pipelines run from the consumer's pull: next() requests one value through each stage.

Shapes

This journey teaches the core Python habit of choosing a data shape, transforming it directly, and making the result visible.

Pick the container that matches the question.

Each container answers a different question: ordered, fixed, lookup, unique.

Move between shapes deliberately.

Most everyday code reshapes data: one input, one transform, one new value.

Cross text and data boundaries.

Programs receive text and produce structured data; parsing makes the boundary explicit.

Interfaces

This journey shows how Python grows from simple functions to callable APIs, object interfaces, protocols, and metaclasses.

Start with functions as named behavior.

A function is the first abstraction boundary: arguments in, body, return value out.

Use functions as values.

Functions are first-class values. A second name binds to the same function object.

Bundle behavior with state.

Classes group fields and methods so data and behavior move together behind one interface.

Types

This journey maps Python's runtime object model to optional static annotations so learners know what types can and cannot promise.

Keep runtime and static analysis separate.

Runtime values run the program; static tools inspect separate annotations and report before execution.

Describe realistic data shapes.

Real data contracts combine fields, variants, and expected absence instead of one scalar type.

Scale annotations for reusable libraries.

Reusable APIs carry caller contracts through the library boundary with generics, parameters, and overloads.

Reliability

This journey follows the boundaries where programs fail, clean up, split into modules, communicate with the outside world, and run concurrent work.

Make failure explicit.

Different failure shapes need explicit signals: assertions, recovery, chained causes, or warnings.

Control resource and module boundaries.

Reliable programs name their boundaries: resources clean up, modules import, environments constrain runtime.

Handle operations that outlive one expression.

Async, threaded, test, and logging work cross an operation boundary before evidence comes back.
diff --git a/public/prototyping/layout-banner-pair.html b/public/prototyping/layout-banner-pair.html index 4efcb2b..c522be5 100644 --- a/public/prototyping/layout-banner-pair.html +++ b/public/prototyping/layout-banner-pair.html @@ -61,7 +61,7 @@

Mutability

second.append("workers") print(first) print(second)

Output

['python', 'workers']
-['python', 'workers']
Two names share one mutable list — appending through one name changes the object visible through both.
By contrast, a tuple is frozen — its contents cannot change in place, so aliasing carries no mutation hazard.

Immutable objects do not change in place. String methods such as upper() return a new string, leaving the original string unchanged.

Source

text = "python"
+['python', 'workers']
Two names share one mutable list — appending through one name changes the object visible through both.
By contrast, a tuple is frozen — its contents cannot change in place, so aliasing carries no mutation hazard.

Immutable objects do not change in place. String methods such as upper() return a new string, leaving the original string unchanged.

Source

text = "python"
 upper_text = text.upper()
 print(text)
 print(upper_text)

Output

python
diff --git a/public/prototyping/layout-banner-single.html b/public/prototyping/layout-banner-single.html
index 991e3d0..5c8335a 100644
--- a/public/prototyping/layout-banner-single.html
+++ b/public/prototyping/layout-banner-single.html
@@ -61,7 +61,7 @@ 

Mutability

second.append("workers") print(first) print(second)

Output

['python', 'workers']
-['python', 'workers']
Two names share one mutable list — appending through one name changes the object visible through both.

Immutable objects do not change in place. String methods such as upper() return a new string, leaving the original string unchanged.

Source

text = "python"
+['python', 'workers']
Two names share one mutable list — appending through one name changes the object visible through both.

Immutable objects do not change in place. String methods such as upper() return a new string, leaving the original string unchanged.

Source

text = "python"
 upper_text = text.upper()
 print(text)
 print(upper_text)

Output

python
diff --git a/public/prototyping/layout-banner-trio.html b/public/prototyping/layout-banner-trio.html
index f232969..7e5d032 100644
--- a/public/prototyping/layout-banner-trio.html
+++ b/public/prototyping/layout-banner-trio.html
@@ -56,7 +56,7 @@
     

Mutability

Some objects change in place, while others return new values.

-
Two names share one mutable list — appending through one name changes the object visible through both.

Mutable objects can change in place. first and second point to the same list, so appending through one name changes the object seen through both names.

Source

first = ["python"]
+  
Two names share one mutable list — appending through one name changes the object visible through both.

Mutable objects can change in place. first and second point to the same list, so appending through one name changes the object seen through both names.

Source

first = ["python"]
 second = first
 second.append("workers")
 print(first)
@@ -65,11 +65,11 @@ 

Mutability

upper_text = text.upper() print(text) print(upper_text)

Output

python
-PYTHON
Mutable: change visible through any alias.
Immutable: aliases share a frozen value.

Some APIs make the boundary explicit. sorted() returns a new list, while methods such as append() and list.sort() mutate an existing list.

Source

numbers = [3, 1, 2]
+PYTHON
Mutable: change visible through any alias.
Immutable: aliases share a frozen value.

Some APIs make the boundary explicit. sorted() returns a new list, while methods such as append() and list.sort() mutate an existing list.

Source

numbers = [3, 1, 2]
 ordered = sorted(numbers)
 print(ordered)
 print(numbers)

Output

[1, 2, 3]
-[3, 1, 2]
When in doubt, reach for the immutable shape.
+[3, 1, 2]
When in doubt, reach for the immutable shape.

Notes

  • Lists and dictionaries are mutable; strings and tuples are immutable.
  • Aliasing is useful, but copy mutable containers when independent changes are needed.
  • Pay attention to whether an operation mutates in place or returns a new value.
diff --git a/public/prototyping/marginalia-gestalt.html b/public/prototyping/marginalia-gestalt.html index e8896e7..0329d61 100644 --- a/public/prototyping/marginalia-gestalt.html +++ b/public/prototyping/marginalia-gestalt.html @@ -68,805 +68,812 @@

Examples

Basics · 01

Hello World

- +

Every Python program starts as source and produces text on standard output. The smallest mental model.

9.0 · program → output, smallest mechanism

Basics · 02

Values

- +

text names a str object, and type(text) is str: the type carries upper() and the rest of the behaviour, not the name.

9.0 · text → str binding plus the type() hop to where upper() lives; earns-place 0.75 since the cell prints type(text), one-move 0.75; 1.5/0.75/0.75/1/1 · 1/1/1 · 1/0.5

Basics · 03

Literals

- +

Each Python type has its own literal spellings; ints accept decimal, hex, and binary; strings accept either quote.

8.5 · literal spellings per type; a reference table, kept until a mechanism figure replaces it

Basics · 04

Numbers

- +

Ints have unbounded precision; floats use IEEE doubles whose representable values thin out near the extremes.

9.0 · int unbounded vs float thinning, both registers

Basics · 05

Booleans

- +

`a and b` returns True only when both are True; otherwise it returns the first falsy value.

9.0 · 2×2 truth table

Basics · 06

Operators

- +

An expression like `(2 + 3) * 4` parses as a tree; operator precedence and parentheses determine its shape.

9.0 · expression tree mechanism

Basics · 07

None

- +

`None` is a single object: every name that points at None points at the same object.

9.0 · three names converging on one None

Basics · 08

Variables

- +

A name is a label that points at an object. Assignment binds the label; the object exists independently.

9.5 · the canonical name → object picture

Basics · 09

Constants

- +

UPPER_CASE is a naming convention, not a language constraint; the binding behaves like any other variable.

9.0 · name binding with the cell's own MAX_RETRIES → 3; earns-place 0.5, the prose already says it is an ordinary binding; 1.5/0.5/1/1/1 · 1/1/1 · 1/0.5

Basics · 10

Truthiness

- +

bool(x) is True except for a small fixed set: 0, 0.0, "", [], {}, None, False.

9.0 · bool(x) with the falsy set as a strip

Data Model · 11

Equality and Identity

- +

Two names can share one object (`is` and `==` both true) or hold two equal-but-distinct objects (only `==` true).

9.0 · shared vs separate object, side-by-side

Data Model · 12

Mutability

- +

Two names share one mutable list — appending through one name changes the object visible through both.

9.5 · three-state small multiple of aliased mutation

Data Model · 12

Mutability

- +

By contrast, a tuple is frozen — its contents cannot change in place, so aliasing carries no mutation hazard.

9.5 · three-state small multiple of aliased mutation

Basics · 13

Object Lifecycle

- +

Names keep the same object reachable; deleting one name matters only when it removes the last reference.

9.0 · names keep object reachable until last reference disappears

Text · 14

Strings

- +

Strings are sequences of Unicode codepoints. UTF-8 encoding turns them into bytes; `é` takes two bytes, `c` takes one.

9.0 · codepoints + bytes registers

Text · 15

Bytes and Bytearray

- +

Both objects hold the same two bytes as integers; b"py" cannot change, while packet[0] = ord("P") rewrites the first slot of the bytearray in place.

9.5 · the example's two bytes as integer slots, packet[0] rewritten in place, anchored to the mutating cell; 1.5/0.75/1/1/1 · 1/1/1 · 1/0.5

Text · 16

String Formatting

- +

The format spec is a railroad of optional stations in a fixed order; this cell's 05.1f visits zero-pad, width, precision and type and bypasses the rest.

9.0 · railroad tracing the cell's 05.1f; one-move 0.75, restraint 0.75 and fit 0.75: still the densest figure in the set at the banner ceiling; 1.5/1/0.75/1/1 · 1/1/0.75 · 0.75/0.5

Control Flow · 17

Conditionals

- +

A predicate sorts a value into one of several branches; if/elif/else is the explicit spelling.

9.0 · predicate forks value to branch

Control Flow · 18

-

Guard Clauses

- -

Early returns handle the exceptional cases first so the main work is the body of the function, not its tail.

-

9.0 · early returns, main body at the tail

-
-
-

Control Flow · 19

-

Assignment Expressions

- -

The walrus binds a name during the surrounding expression; one expression, two outputs.

-

9.0 · walrus binds while comparing

-
-
-

Control Flow · 20

For Loops

- +

Each call to next() advances the caret one cell along the iterable — the same shape behind range(), strings, and any sequence.

9.0 · 4-row caret advance

-

Control Flow · 21

+

Control Flow · 19

Break and Continue

- +

break exits the loop; continue skips to the next iteration. Both interrupt the natural fall-through.

9.0 · early exit at first match

-

Control Flow · 22

+

Control Flow · 20

Loop Else

- +

The loop's else branch runs only when the loop falls through naturally; break skips it.

9.0 · fell-through vs broke, two outcomes

-

Iteration · 23

+

Iteration · 21

Iterating over Iterables

- +

`for` desugars to iter()+next(): one iter() call, then next() until StopIteration ends the loop.

9.0 · iter() exposes the iterator

-

Iteration · 24

+

Iteration · 22

Iterators

- +

iter() exposes the iterator behind for; next() pulls one value at a time until exhausted.

9.0 · three-state machine

-

Iteration · 25

+

Iteration · 23

Iterator vs Iterable

- +

An iterable knows how to produce an iterator (via iter()); the iterator knows how to produce values (via next()).

9.0 · the protocol exposed

-

Iteration · 25

+

Iteration · 23

Iterator vs Iterable

- +

The iterator's caret only moves forward — after the first `list(stream)` drains it, nothing is left for the second.

9.0 · the protocol exposed

-

Iteration · 26

-

Sentinel Iteration

- -

iter(read_chunk, "") keeps calling read_chunk and yields "py" and "thon"; the empty string is the sentinel, so it stops the loop and is never yielded.

-

9.0 · the cell's read_chunk and chunks; the empty string ghosted as the sentinel; earns-place 0.75, the output already omits it; 1.5/0.75/1/1/1 · 1/1/1 · 1/0.5

-
-
-

Control Flow · 27

+

Control Flow · 24

Match Statements

- +

match dispatches by pattern shape; the value flows down the patterns and the first match wins.

9.0 · dispatch ladder; first match wins

-

Control Flow · 28

+

Control Flow · 25

Advanced Match Patterns

- +

Capture, alternative, guard, and class patterns each name a different way a value can match a case.

9.0 · four pattern variants

-

Control Flow · 29

+

Control Flow · 26

While Loops

- +

`while` repeats the body while the test stays true; the back-edge returns control to the test before each pass.

9.0 · back-edge mechanism plus the three stopping rules

-

Control Flow · 29

+

Control Flow · 26

While Loops

- +

Each loop shape has its own stopping rule: `for` ends when the iterable is exhausted, `while` when the condition turns false, sentinel iteration when the marker value appears.

9.0 · back-edge mechanism plus the three stopping rules

-

Collections · 30

+

Control Flow · 27

+

Assignment Expressions

+ +

The walrus binds a name during the surrounding expression; one expression, two outputs.

+

9.0 · walrus binds while comparing

+
+
+

Iteration · 28

+

Sentinel Iteration

+ +

iter(queue.popleft, "") keeps calling queue.popleft and yields "py" and "thon"; the empty string is the sentinel, so it stops the loop and is never yielded.

+

9.0 · the cell's queue.popleft call and queued chunks; the empty string ghosted as the sentinel; earns-place 0.75, the output already omits it; 1.5/0.75/1/1/1 · 1/1/1 · 1/0.5

+
+
+

Collections · 29

Lists

- +

Lists are mutable sequences. `.append` extends the same list object — no new list is created.

9.0 · cells with append mechanism

-

Collections · 31

+

Collections · 30

Tuples

- +

Tuples are ordered, immutable sequences; positions matter, contents do not change once constructed.

9.0 · frozen sequence with struck-through .append

-

Collections · 31

+

Collections · 30

Tuples

- +

A list is the other intent: a variable number of similar items, growing in place with `.append`.

9.0 · frozen sequence with struck-through .append

-

Collections · 32

+

Collections · 31

Unpacking

- +

Left-side names bind to right-side positions; `*rest` gathers the middle into a list.

9.0 · binding-line mechanism with *rest

-

Collections · 33

+

Collections · 32

Dictionaries

- +

hash(key) picks the slot: "year" lands in an empty one, and profile["name"] goes straight to its slot without scanning the other entries.

9.0 · the cell's own keys hashed to slots, the insert of "year" accented; earns-place 0.75, one-move 0.75 since insert and lookup share the caption; 1.5/0.75/0.75/1/1 · 1/1/1 · 1/0.5

-

Collections · 34

+

Collections · 33

Sets

- +

Sets are hash buckets without values; `x in s` averages O(1) regardless of size.

9.0 · hash buckets without values

-

Collections · 35

+

Collections · 34

Slices

- +

Slice indices sit between cells; [:3] and [3:] partition the sequence at index 3, never overlapping or losing an item.

9.0 · ruler with bracket overlay

-

Collections · 36

+

Collections · 35

Comprehensions

- +

A comprehension is a compact spelling of the equivalent for-loop with append, made into one expression.

9.0 · comprehension over equivalent for-loop

-

Collections · 37

+

Collections · 36

Comprehension Patterns

- +

Nested clauses compose left to right; the comprehension is still equivalent to a for-loop with append.

9.0 · nested clauses compose

-

Collections · 38

+

Collections · 37

Sorting

- +

Python's sort is stable: items with equal keys keep their original order, so chained sorts compose predictably.

9.0 · stability ribbons preserved across keys

-

Collections · 39

+

Collections · 38

Collections Module

- +

Four specialised containers for shapes the built-in types don't cover well: deque, Counter, defaultdict, namedtuple.

8.5 · deque / Counter / defaultdict / namedtuple; a catalogue, kept until the page is split

-

Collections · 40

+

Collections · 39

Copying Collections

- +

Without copy() two names share the same object; mutating through one is visible through the other.

9.5 · same picture as mutability, perfect match

-

Functions · 41

+

Functions · 40

Functions

- +

A function takes inputs, evaluates a body, and returns a value: `greet('Ada')` produces `'Hello, Ada'`.

9.0 · specific call: greet('Ada') → 'Hello, Ada'

-

Functions · 42

+

Control Flow · 41

+

Guard Clauses

+ +

Early returns handle the exceptional cases first so the main work is the body of the function, not its tail.

+

9.0 · early returns, main body at the tail

+
+
+

Errors · 42

+

Exceptions

+ +

try, except, else, and finally as parallel lanes; a single coral path traces what actually runs.

+

9.0 · try/except/else/finally lanes with traced path

+
+
+

Functions · 43

Keyword-only Arguments

- +

A bare `*` divides positional or keyword arguments from keyword-only ones; callers must pass `c` and `d` by name.

9.0 · signature with explicit `*` separator

-

Functions · 43

+

Functions · 44

Positional-only Parameters

- +

A bare `/` divides positional-only arguments from positional-or-keyword ones; callers cannot name `a` or `b`.

9.0 · signature with explicit `/` separator

-

Functions · 43

+

Functions · 44

Positional-only Parameters

- +

In the same signature, the bare `*` works the other way: parameters after it, such as `clamp`, must be named at the call site.

9.0 · signature with explicit `/` separator

-

Functions · 44

+

Functions · 45

Args and Kwargs

- +

*args captures the extra positionals as a tuple; **kwargs captures the extra keywords as a dict.

9.0 · *args tuple, **kwargs dict regions

-

Functions · 45

+

Functions · 46

Multiple Return Values

- +

A function returning multiple values really returns one tuple; the caller unpacks it into named bindings.

9.0 · function returns tuple; caller unpacks

-

Functions · 46

+

Functions · 47

Closures

- +

make_multiplier(2) has returned, but the function object double names still points into that frame's cell, so the captured factor outlives the call.

9.5 · environment diagram: ghosted returned frame, heap function object, one live __closure__ reference; 1.5/1/0.75/1/1 · 1/1/1 · 1/0.5

-

Functions · 47

+

Functions · 48

Partial Functions

- +

`functools.partial(f, 1)` pre-fills `a=1`, returning a thinner callable `g(b, c)` that only needs the rest.

9.0 · f → partial(f, 1) → g

-

Functions · 48

+

Functions · 49

Global and Nonlocal

- +

Name lookup walks LEGB — local, enclosing, global, built-in — outward, returning the first binding it finds.

9.0 · LEGB nested rings

-

Functions · 49

+

Functions · 50

Recursion

- +

At the leaf with value 4, three frames of total are stacked, each waiting on the one below; unwinding returns 4, then 3 + 4 = 7, then 1 + 2 + 7 = 10.

9.0 · the example's own tree at its deepest frame, return values unwinding; earns-place 0.75, the cell's output already gives 10; 1.5/0.75/1/1/1 · 1/1/1 · 1/0.5

-

Functions · 50

+

Functions · 51

Lambdas

- +

A lambda is a function literal: parameters before the colon, a single expression after, no statement body.

9.0 · function literal: params / expression

-

Iteration · 51

+

Iteration · 52

Generators

- +

The cell's two next() calls on countdown(3), one timeline each: every call resumes the body to the next yield gate, and the local n survives the pause.

9.5 · the cell's two next() ribbons on countdown(3), local n shown surviving; earns-place 0.75, the prose says the same; 1.5/0.75/1/1/1 · 1/1/1 · 1/0.5

-

Iteration · 52

+

Iteration · 53

Yield From

- +

`yield from inner` delegates iteration to an inner generator; its yields surface here unchanged.

9.0 · stitched ribbons; delegation

-

Iteration · 53

+

Iteration · 54

Generator Expressions

- +

A generator expression composes filter and map lazily; values flow only when next() pulls them.

9.0 · lazy filter→map pipeline

-

Iteration · 54

+

Iteration · 55

Itertools

- +

chain stitches two iterables into one stream without materialising either: values arrive lazily.

9.0 · chain joins two iterables into one stream

-

Functions · 55

+

Functions · 56

Decorators

- +

@dec rebinds the name to wrapper(f₀); the original function survives only in the wrapper's closure cell.

9.0 · before/after rebinding through cell

-

Classes · 56

+

Classes · 57

Classes

- +

Every Python value sits on the instance → class → type triangle; the metaclass is the type of the class.

9.0 · instance/class/type triangle

-

Classes · 57

+

Classes · 58

Inheritance and Super

- +

Multiple inheritance forms a graph; C3 linearisation flattens it into the MRO Python uses for attribute lookup.

9.0 · MRO chain with diamond ghost

-

Classes · 58

+

Classes · 59

Classmethods and Staticmethods

- +

Three method kinds, three first-argument conventions: classmethod gets the class, staticmethod gets nothing, instance gets self.

9.0 · three method kinds, three first-arg conventions

-

Classes · 59

+

Classes · 60

Dataclasses

- +

Field declarations become the generated __init__ signature: declaration is the constructor.

9.0 · fields → generated __init__ signature

-

Classes · 60

+

Classes · 61

Properties

- +

When x is a property, attribute access routes through fget/fset instead of touching __dict__.

9.0 · obj.x routes through fget instead of __dict__

-

Data Model · 61

+

Data Model · 62

Special Methods

- +

Operators are method calls. `a + b` dispatches to `a.__add__(b)`; the data model exposes the syntax.

9.0 · syntax → method dispatch

-

Data Model · 62

+

Data Model · 63

Truth and Size

- +

bool(x) calls __bool__ first; if absent, __len__() != 0; if neither, defaults to True.

9.0 · __bool__ → __len__ → True fallback chain

-

Data Model · 63

+

Data Model · 64

Container Protocols

- +

Container syntax routes to narrow protocol methods: assignment to __setitem__, membership to __contains__, lookup to __getitem__.

9.0 · syntax routes to __setitem__, __contains__, __getitem__

-

Data Model · 64

+

Data Model · 65

Callable Objects

- +

Defining __call__ makes any object callable; functions are just one shape that satisfies this protocol.

9.0 · __call__ makes any object callable

-

Data Model · 65

+

Data Model · 66

Operator Overloading

- +

Defining `__add__` on a class lets `+` dispatch into the class's own behavior.

9.0 · dispatch arrow

-

Data Model · 66

+

Data Model · 67

Attribute Access

- +

obj.x checks instance __dict__, then class __dict__, then __getattr__; the first hit wins.

9.0 · instance __dict__ → class __dict__ → __getattr__

-

Data Model · 67

+

Data Model · 68

Bound and Unbound Methods

- +

Accessing a method via an instance binds self; accessing it via the class returns the underlying function.

9.0 · instance.method bound vs Class.method unbound

-

Data Model · 68

+

Data Model · 69

Descriptors

- +

Attribute access on an instance routes through the descriptor's __get__/__set__/__delete__ when the attribute is a descriptor.

9.0 · get/set/delete protocol routed through descriptor

-

Classes · 69

+

Classes · 70

Metaclasses

- +

A metaclass is the type of a class, just as a class is the type of its instances; type is the default metaclass.

9.0 · extended triangle to metaclass

-

Classes · 69

+

Classes · 70

Metaclasses

- +

The class makes instances — the same triangle one level down, with type as the default apex.

9.0 · extended triangle to metaclass

-

Data Model · 70

+

Data Model · 71

Context Managers

- +

A context manager pairs setup with reliable cleanup; the raise path still routes through __exit__.

9.0 · enter / body / exit bowtie

-

Data Model · 71

+

Data Model · 72

Delete Statements

- +

`del x` removes the name; the object survives if any other reference holds it, otherwise gets collected.

9.0 · name erased; object survives if referenced

-
-

Errors · 72

-

Exceptions

- -

try, except, else, and finally as parallel lanes; a single coral path traces what actually runs.

-

9.0 · try/except/else/finally lanes with traced path

-

Errors · 73

Assertions

- +

assert tests a condition; True passes silently, False raises AssertionError with the optional message.

9.0 · True passes, False raises

Errors · 74

Exception Chaining

- +

`raise X from Y` sets `__cause__` (explicit); raising during except sets `__context__` (implicit).

9.0 · __cause__ vs __context__ distinguished

Errors · 75

Exception Groups

- +

except* peels matched leaves out of an ExceptionGroup; survivors regroup and propagate.

9.0 · except* peels matching leaves

Errors · 76

Warnings

- +

A warning is a soft signal: the message is reported, but execution continues unless filters elevate it.

9.0 · soft signal; execution continues

Modules · 77

Modules

- +

An import walks sys.path entry by entry; the first directory containing the module wins.

9.0 · sys.path resolution; first hit wins

Modules · 78

Import Aliases

- +

`import x as y` binds the name y to the same module object x would have.

9.0 · two names bind to the same module

Modules · 79

Packages

- +

A directory with __init__.py becomes an importable package; submodules and subpackages nest beneath it.

9.0 · __init__.py + nested submodules

Modules · 80

Virtual Environments

- +

A venv carries its own interpreter and site-packages, isolating a project's dependencies from the system.

9.0 · project / venv boundary

Types · 81

Type Hints

- +

Annotations describe expected types for tools; the runtime accepts any object regardless.

9.0 · ghost annotations over runtime values

Types · 82

Runtime Type Checks

- +

isinstance and issubclass ask the runtime; the answer is a bool, not a static type refinement.

9.0 · isinstance returns bool

Types · 83

Union and Optional Types

- +

`int | str | None` says one slot may hold any of three shapes — including expected absence.

9.0 · type fork to several shapes

Types · 84

Type Aliases

- +

A type alias names a complex annotation once so call sites read as the domain meaning, not the type composition.

9.0 · complex annotation collapses to a name

Types · 85

TypedDict

- +

TypedDict gives each key a typed value, so `obj['x']` is checked against the declared shape.

9.0 · keys with declared value types

Classes · 86

Structured Data Shapes

- +

The same record can be a mutable dataclass, an immutable NamedTuple, or a runtime dict described by TypedDict.

9.0 · dataclass vs NamedTuple vs TypedDict runtime trade-offs

Types · 87

Literal and Final

- +

Literal narrows a slot to a fixed set of constant values; Final says the binding will not change.

9.0 · slot narrows to a fixed set

Types · 88

Callable Types

- +

A Callable annotation describes the callback slot: this argument list must produce this return type.

9.0 · callback slot shows argument list and return type

Types · 89

Generics and TypeVar

- +

A generic preserves the input type through the call: the same T flows in and out of fn[T].

9.0 · the same T flows in and out

Types · 90

ParamSpec

- +

ParamSpec preserves the wrapped function's signature through a decorator, parameter for parameter.

9.0 · P preserved through decorator

Types · 91

Overloads

- +

@overload declares static call signatures for double(int) and double(str); one runtime implementation handles both.

9.0 · static overload signatures contrasted with one runtime body

Types · 92

Casts and Any

- +

cast(T, x) tells the type checker to treat x as T; the runtime is unaffected.

9.0 · Any → cast(T, x) → T, runtime unchanged

Types · 93

NewType

- +

NewType creates a distinct static identity backed by the same runtime type — UserId is int with a name.

9.0 · same runtime, distinct static identity

Types · 94

Protocols

- +

An object satisfies a protocol structurally — by having the required methods — not by inheriting it.

9.0 · structural duck check

Classes · 95

Abstract Base Classes

- +

An ABC sits on the same triangle as concrete classes; subclasses inherit the abstract methods they must implement.

9.0 · same triangle as concrete classes

Types · 96

Enums

- +

An enum names a fixed set of symbolic values; no new members appear at runtime.

9.0 · closed set of symbolic values

Text · 97

Regular Expressions

- +

findall returns only what the parentheses capture: `([A-Za-z]+)` takes the name and `(\d+)` the score, one (name, score) pair per record.

9.0 · the cell's pattern with both capture groups dropped onto Ada: 10; one-move 0.75 and restraint 0.75 for two rows plus two drops; 1.5/1/0.75/1/1 · 1/1/0.75 · 1/0.5

Standard Library · 98

Number Parsing

- +

int() turns text into a typed number; malformed input raises ValueError instead of guessing.

9.0 · int() success path vs ValueError

Errors · 99

Custom Exceptions

- +

Subclassing an existing exception gains a domain name without changing semantics.

9.0 · subclass chain to a domain name

Standard Library · 100

+

Files and pathlib

+ +

Each `Path` names one place in the directory tree; `/` steps down one level per name.

+

9.0 · the page's own tree with the two paths the cells build; containment hairlines, dashed path-to-place links, no accent

+
+
+

Standard Library · 101

JSON

- +

Six type pairs bridge the JSON text boundary; each json value maps to one Python type.

9.0 · two-column type mapping

-

Standard Library · 101

+

Standard Library · 102

Logging

- +

The handler's level is a gate: debug is below INFO and never reaches stdout, while info and warning pass through unchanged.

9.5 · the cell's three records crossing the handler's INFO gate, debug dropped; earns-place 0.75 since the output already shows the drop; 1.5/0.75/1/1/1 · 1/1/1 · 1/0.5

-

Standard Library · 102

+

Standard Library · 103

Testing

- +

arrange-act-assert: set up the state, perform the behavior under test, compare the result to expectations.

9.0 · arrange-act-assert three-row pattern

-

Standard Library · 103

+

Standard Library · 104

Subprocesses

- +

subprocess.run spawns a child process and captures its stdout, stderr, and exit code as portable evidence.

9.0 · spawn → child → captured output

-

Standard Library · 104

+

Standard Library · 105

Threads and Processes

- +

Threads share memory but the GIL serialises Python bytecode; processes run in parallel with isolated memory.

9.0 · thread GIL sharing contrasted with process isolation

-

Standard Library · 105

+

Standard Library · 106

Networking

- +

Text crosses the socket as bytes — `encode` marks the python → wire boundary, `decode` brings the bytes back to a Python `str`.

9.0 · text ↔ bytes across the socket boundary

-

Standard Library · 106

+

Standard Library · 107

Dates and Times

- +

An aware datetime carries a UTC offset; one instant in time reads differently on two clocks.

9.0 · one instant, two clock offsets

-

Standard Library · 107

+

Standard Library · 108

CSV Data

- +

CSV files are rows of records; each line has the same columns in the same order.

9.0 · rows × columns; same shape per line

-

Async · 108

+

Async · 109

Async Await

- +

On await, the coroutine yields to the loop; the loop runs other work and resumes when the awaitable is ready.

9.0 · loop/coro swimlane with await handoffs

-

Async · 109

+

Async · 110

Async Iteration and Context

- +

async iteration and async with both rest on the same loop-vs-coroutine handoff as await.

9.0 · loop/coro lanes with await yields

diff --git a/public/prototyping/production-figures-gestalt.html b/public/prototyping/production-figures-gestalt.html index 0badca8..765cbf6 100644 --- a/public/prototyping/production-figures-gestalt.html +++ b/public/prototyping/production-figures-gestalt.html @@ -44,15 +44,15 @@ -
Prototype · All 125 figures currently registered in src/marginalia.py FIGURES; each card names where it renders. · all prototypes
+
Prototype · All 126 figures currently registered in src/marginalia.py FIGURES; each card names where it renders. · all prototypes
-

Production figure registry · 125 figures

+

Production figure registry · 126 figures

Production figures gestalt

Every figure currently registered in src/marginalia.py FIGURES. Each card names the figure, where it renders today (an example attachment, a journey section, or "not yet attached"), and the intrinsic viewBox dimensions. Use this page beside the example-figure rubric to triage which figures are shipping, which are journey-only, and which are sitting in the registry waiting for an example attachment.

-

value-type-lookup

attached to /examples/values · viewBox 280×80

v2 scores: values 9.0

logging-threshold

attached to /examples/logging · viewBox 266×130

v2 scores: logging 9.5

literal-forms

attached to /examples/literals · viewBox 252×132

v2 scores: literals 8.5

collections-containers

attached to /examples/collections-module · viewBox 284×92

v2 scores: collections-module 8.5

aliasing-mutation

attached to /examples/mutability, copying-collections · viewBox 220×175

v2 scores: mutability 9.5 · copying-collections 9.5

tuple-no-mutation

attached to /examples/mutability · viewBox 220×185

v2 scores: mutability 9.5

iterator-unroll

attached to /examples/for-loops, iterator-vs-iterable · viewBox 220×130

v2 scores: for-loops 9.0 · iterator-vs-iterable 9.0

scope-rings

attached to /examples/scope-global-nonlocal · viewBox 216×116

v2 scores: scope-global-nonlocal 9.0

closure-cell

attached to /examples/closures · viewBox 280×116

v2 scores: closures 9.5

slice-ruler

attached to /examples/slices · viewBox 232×120

v2 scores: slices 9.0

branch-fork

attached to /examples/conditionals · viewBox 232×100

v2 scores: conditionals 9.0

loop-repetition

attached to /examples/while-loops · viewBox 260×100

v2 scores: while-loops 9.0

while-backedge

attached to /examples/while-loops · viewBox 252×80

v2 scores: while-loops 9.0

iter-protocol

attached to /examples/iterators, iterator-vs-iterable, iterating-over-iterables · viewBox 304×70

v2 scores: iterators 9.0 · iterator-vs-iterable 9.0 · iterating-over-iterables 9.0

program-output

attached to /examples/hello-world · viewBox 240×80

v2 scores: hello-world 9.0

identity-and-equality

attached to /examples/equality-and-identity · viewBox 304×96

v2 scores: equality-and-identity 9.0

operator-dispatch

attached to /examples/special-methods, operator-overloading · viewBox 260×70

v2 scores: special-methods 9.0 · operator-overloading 9.0

runtime-evidence-loop

attached to a journey section · viewBox 306×96

runtime-object-axes

attached to a journey section · viewBox 214×104

runtime-expression-model

attached to a journey section · viewBox 344×96

container-questions

attached to a journey section · viewBox 280×88

reshape-pipeline

attached to a journey section · viewBox 204×80

text-data-boundary

attached to a journey section · viewBox 172×70

function-signature

attached to a journey section · viewBox 310×82

function-as-value

attached to a journey section · viewBox 200×66

class-with-state

attached to a journey section · viewBox 152×108

annotation-ghost

attached to /examples/type-hints · viewBox 220×52

v2 scores: type-hints 9.0

union-types

attached to /examples/union-and-optional-types · viewBox 166×80

v2 scores: union-and-optional-types 9.0

generic-preservation

attached to /examples/generics-and-typevar · viewBox 250×70

v2 scores: generics-and-typevar 9.0

type-runtime-static-split

attached to a journey section · viewBox 224×126

type-shape-catalog

attached to a journey section · viewBox 290×108

type-library-contract

attached to a journey section · viewBox 364×104

exception-lanes

attached to /examples/exceptions · viewBox 320×100

v2 scores: exceptions 9.0

context-bowtie

attached to /examples/context-managers · viewBox 244×76

v2 scores: context-managers 9.0

async-swimlane

attached to /examples/async-await, async-iteration-and-context · viewBox 280×84

v2 scores: async-await 9.0 · async-iteration-and-context 9.0

reliability-signal-map

attached to a journey section · viewBox 270×128

reliability-boundary-map

attached to a journey section · viewBox 286×110

reliability-operation-boundary

attached to a journey section · viewBox 354×104

naming-decisions

attached to /examples/assignment-expressions · viewBox 330×98

v2 scores: assignment-expressions 9.0

early-exit

attached to /examples/break-and-continue · viewBox 144×116

v2 scores: break-and-continue 9.0

lazy-stream

attached to /examples/generator-expressions · viewBox 300×56

v2 scores: generator-expressions 9.0

control-decision-map

attached to a journey section · viewBox 244×104

control-fact-shape

attached to a journey section · viewBox 286×104

control-stop-boundary

attached to a journey section · viewBox 210×104

iteration-loop-selector

attached to a journey section · viewBox 276×104

iteration-protocol-map

attached to a journey section · viewBox 306×132

iteration-lazy-pull

attached to a journey section · viewBox 360×112

variables-bind

attached to /examples/variables · viewBox 170×44

v2 scores: variables 9.5

constants-bind

attached to /examples/constants · viewBox 194×44

v2 scores: constants 9.0

call-stack

attached to /examples/recursion · viewBox 292×80

v2 scores: recursion 9.0

decorator-rebind

attached to /examples/decorators · viewBox 232×110

v2 scores: decorators 9.0

mro-chain

attached to /examples/inheritance-and-super · viewBox 200×152

v2 scores: inheritance-and-super 9.0

dataclass-fields

attached to /examples/dataclasses · viewBox 312×76

v2 scores: dataclasses 9.0

class-triangle

attached to /examples/classes, abstract-base-classes, metaclasses · viewBox 274×60

v2 scores: classes 9.0 · abstract-base-classes 9.0 · metaclasses 9.0

exception-cause-context

attached to /examples/exception-chaining · viewBox 282×70

v2 scores: exception-chaining 9.0

unpacking-bind

attached to /examples/unpacking · viewBox 152×80

v2 scores: unpacking 9.0

comprehension-equivalence

attached to /examples/comprehensions, comprehension-patterns · viewBox 280×76

v2 scores: comprehensions 9.0 · comprehension-patterns 9.0

list-append

attached to /examples/lists, tuples · viewBox 220×36

v2 scores: lists 9.0 · tuples 9.0

dict-buckets

attached to /examples/dicts · viewBox 288×92

v2 scores: dicts 9.0

number-lines

attached to /examples/numbers · viewBox 260×78

v2 scores: numbers 9.0

expression-tree

attached to /examples/operators · viewBox 220×92

v2 scores: operators 9.0

none-singleton

attached to /examples/none · viewBox 240×84

v2 scores: none 9.0

codepoints-bytes

attached to /examples/strings · viewBox 200×84

v2 scores: strings 9.0

sort-stability

attached to /examples/sorting · viewBox 270×100

v2 scores: sorting 9.0

kw-only-separator

attached to /examples/keyword-only-arguments, positional-only-parameters · viewBox 200×56

v2 scores: keyword-only-arguments 9.0 · positional-only-parameters 9.0

positional-only-separator

attached to /examples/positional-only-parameters · viewBox 200×56

v2 scores: positional-only-parameters 9.0

generator-resume

attached to /examples/generators · viewBox 318×72

v2 scores: generators 9.5

truth-and-size

attached to /examples/truth-and-size · viewBox 232×70

v2 scores: truth-and-size 9.0

descriptor-protocol

attached to /examples/descriptors · viewBox 222×76

v2 scores: descriptors 9.0

bound-unbound

attached to /examples/bound-and-unbound-methods · viewBox 296×56

v2 scores: bound-and-unbound-methods 9.0

method-kinds

attached to /examples/classmethods-and-staticmethods · viewBox 272×70

v2 scores: classmethods-and-staticmethods 9.0

callable-objects

attached to /examples/callable-objects · viewBox 220×44

v2 scores: callable-objects 9.0

attribute-lookup

attached to /examples/attribute-access · viewBox 242×70

v2 scores: attribute-access 9.0

guard-clauses

attached to /examples/guard-clauses · viewBox 264×104

v2 scores: guard-clauses 9.0

bytes-vs-bytearray

attached to /examples/bytes-and-bytearray · viewBox 200×90

v2 scores: bytes-and-bytearray 9.5

sentinel-iteration

attached to /examples/sentinel-iteration · viewBox 330×70

v2 scores: sentinel-iteration 9.0

partial-functions

attached to /examples/partial-functions · viewBox 334×36

v2 scores: partial-functions 9.0

args-kwargs

attached to /examples/args-and-kwargs · viewBox 280×68

v2 scores: args-and-kwargs 9.0

multiple-return

attached to /examples/multiple-return-values · viewBox 180×120

v2 scores: multiple-return-values 9.0

lambda-expression

attached to /examples/lambdas · viewBox 170×76

v2 scores: lambdas 9.0

property-fork

attached to /examples/properties · viewBox 232×72

v2 scores: properties 9.0

metaclass-triangle

attached to /examples/metaclasses · viewBox 300×60

v2 scores: metaclasses 9.0

sys-path-resolution

attached to /examples/modules · viewBox 258×100

v2 scores: modules 9.0

import-alias

attached to /examples/import-aliases · viewBox 212×56

v2 scores: import-aliases 9.0

protocol-check

attached to /examples/protocols · viewBox 220×78

v2 scores: protocols 9.0

enum-members

attached to /examples/enums · viewBox 280×60

v2 scores: enums 9.0

datetime-instant

attached to /examples/datetime · viewBox 280×88

v2 scores: datetime 9.0

json-python-mapping

attached to /examples/json · viewBox 220×116

v2 scores: json 9.0

regex-groups

attached to /examples/regular-expressions · viewBox 140×96

v2 scores: regular-expressions 9.0

number-parse

attached to /examples/number-parsing · viewBox 204×64

v2 scores: number-parsing 9.0

format-spec

attached to /examples/string-formatting · viewBox 372×82

v2 scores: string-formatting 9.0

truthy-check

attached to /examples/truthiness · viewBox 240×70

v2 scores: truthiness 9.0

boolean-truth-table

attached to /examples/booleans · viewBox 132×64

v2 scores: booleans 9.0

set-buckets

attached to /examples/sets · viewBox 156×90

v2 scores: sets 9.0

tuple-frozen

attached to /examples/tuples · viewBox 280×48

v2 scores: tuples 9.0

yield-delegation

attached to /examples/yield-from · viewBox 240×84

v2 scores: yield-from 9.0

itertools-chain

attached to /examples/itertools · viewBox 246×82

v2 scores: itertools 9.0

assertion-check

attached to /examples/assertions · viewBox 304×76

v2 scores: assertions 9.0

custom-exception-chain

attached to /examples/custom-exceptions · viewBox 220×90

v2 scores: custom-exceptions 9.0

exception-group-peel

attached to /examples/exception-groups · viewBox 240×50

v2 scores: exception-groups 9.0

delete-name-erased

attached to /examples/delete-statements · viewBox 200×84

v2 scores: delete-statements 9.0

package-tree

attached to /examples/packages · viewBox 240×76

v2 scores: packages 9.0

venv-boundary

attached to /examples/virtual-environments · viewBox 274×76

v2 scores: virtual-environments 9.0

subprocess-spawn

attached to /examples/subprocesses · viewBox 324×60

v2 scores: subprocesses 9.0

aaa-pattern

attached to /examples/testing · viewBox 250×80

v2 scores: testing 9.0

socket-byte-boundary

attached to /examples/networking · viewBox 364×46

v2 scores: networking 9.0

gil-lanes

attached to /examples/threads-and-processes · viewBox 300×138

v2 scores: threads-and-processes 9.0

cast-escape

attached to /examples/casts-and-any · viewBox 184×56

v2 scores: casts-and-any 9.0

newtype-phantom

attached to /examples/newtype · viewBox 96×92

v2 scores: newtype 9.0

overload-signatures

attached to /examples/overloads · viewBox 304×64

v2 scores: overloads 9.0

paramspec-preserve

attached to /examples/paramspec · viewBox 294×60

v2 scores: paramspec 9.0

literal-constrained

attached to /examples/literal-and-final · viewBox 144×76

v2 scores: literal-and-final 9.0

callable-type

attached to /examples/callable-types · viewBox 352×42

v2 scores: callable-types 9.0

isinstance-check

attached to /examples/runtime-type-checks · viewBox 232×76

v2 scores: runtime-type-checks 9.0

container-methods

attached to /examples/container-protocols · viewBox 272×82

v2 scores: container-protocols 9.0

typed-dict-shape

attached to /examples/typed-dicts · viewBox 200×92

v2 scores: typed-dicts 9.0

structured-shapes

attached to /examples/structured-data-shapes · viewBox 266×82

v2 scores: structured-data-shapes 9.0

csv-records

attached to /examples/csv-data · viewBox 212×96

v2 scores: csv-data 9.0

warning-signal

attached to /examples/warnings · viewBox 292×80

v2 scores: warnings 9.0

object-lifecycle

attached to /examples/object-lifecycle · viewBox 366×80

v2 scores: object-lifecycle 9.0

type-alias-name

attached to /examples/type-aliases · viewBox 240×104

v2 scores: type-aliases 9.0

match-dispatch-ladder

attached to /examples/match-statements · viewBox 260×130

v2 scores: match-statements 9.0

match-pattern-variants

attached to /examples/advanced-match-patterns · viewBox 272×96

v2 scores: advanced-match-patterns 9.0

loop-else-gate

attached to /examples/loop-else · viewBox 312×76

v2 scores: loop-else 9.0

function-with-body

attached to /examples/functions · viewBox 334×68

v2 scores: functions 9.0

+

value-type-lookup

attached to /examples/values · viewBox 280×80

v2 scores: values 9.0

logging-threshold

attached to /examples/logging · viewBox 266×130

v2 scores: logging 9.5

literal-forms

attached to /examples/literals · viewBox 252×132

v2 scores: literals 8.5

collections-containers

attached to /examples/collections-module · viewBox 284×92

v2 scores: collections-module 8.5

aliasing-mutation

attached to /examples/mutability, copying-collections · viewBox 220×175

v2 scores: mutability 9.5 · copying-collections 9.5

tuple-no-mutation

attached to /examples/mutability · viewBox 220×185

v2 scores: mutability 9.5

iterator-unroll

attached to /examples/for-loops, iterator-vs-iterable · viewBox 220×130

v2 scores: for-loops 9.0 · iterator-vs-iterable 9.0

scope-rings

attached to /examples/scope-global-nonlocal · viewBox 216×116

v2 scores: scope-global-nonlocal 9.0

closure-cell

attached to /examples/closures · viewBox 280×116

v2 scores: closures 9.5

slice-ruler

attached to /examples/slices · viewBox 232×120

v2 scores: slices 9.0

branch-fork

attached to /examples/conditionals · viewBox 232×100

v2 scores: conditionals 9.0

loop-repetition

attached to /examples/while-loops · viewBox 260×100

v2 scores: while-loops 9.0

while-backedge

attached to /examples/while-loops · viewBox 252×80

v2 scores: while-loops 9.0

iter-protocol

attached to /examples/iterators, iterator-vs-iterable, iterating-over-iterables · viewBox 304×70

v2 scores: iterators 9.0 · iterator-vs-iterable 9.0 · iterating-over-iterables 9.0

program-output

attached to /examples/hello-world · viewBox 240×80

v2 scores: hello-world 9.0

identity-and-equality

attached to /examples/equality-and-identity · viewBox 304×96

v2 scores: equality-and-identity 9.0

operator-dispatch

attached to /examples/special-methods, operator-overloading · viewBox 260×70

v2 scores: special-methods 9.0 · operator-overloading 9.0

runtime-evidence-loop

attached to a journey section · viewBox 306×96

runtime-object-axes

attached to a journey section · viewBox 214×104

runtime-expression-model

attached to a journey section · viewBox 344×96

container-questions

attached to a journey section · viewBox 280×88

reshape-pipeline

attached to a journey section · viewBox 204×80

text-data-boundary

attached to a journey section · viewBox 172×70

function-signature

attached to a journey section · viewBox 310×82

function-as-value

attached to a journey section · viewBox 200×66

class-with-state

attached to a journey section · viewBox 152×108

annotation-ghost

attached to /examples/type-hints · viewBox 220×52

v2 scores: type-hints 9.0

union-types

attached to /examples/union-and-optional-types · viewBox 166×80

v2 scores: union-and-optional-types 9.0

generic-preservation

attached to /examples/generics-and-typevar · viewBox 250×70

v2 scores: generics-and-typevar 9.0

type-runtime-static-split

attached to a journey section · viewBox 224×126

type-shape-catalog

attached to a journey section · viewBox 290×108

type-library-contract

attached to a journey section · viewBox 364×104

exception-lanes

attached to /examples/exceptions · viewBox 320×100

v2 scores: exceptions 9.0

context-bowtie

attached to /examples/context-managers · viewBox 244×76

v2 scores: context-managers 9.0

async-swimlane

attached to /examples/async-await, async-iteration-and-context · viewBox 280×84

v2 scores: async-await 9.0 · async-iteration-and-context 9.0

reliability-signal-map

attached to a journey section · viewBox 270×128

reliability-boundary-map

attached to a journey section · viewBox 286×110

reliability-operation-boundary

attached to a journey section · viewBox 354×104

naming-decisions

attached to /examples/assignment-expressions · viewBox 330×98

v2 scores: assignment-expressions 9.0

early-exit

attached to /examples/break-and-continue · viewBox 144×116

v2 scores: break-and-continue 9.0

lazy-stream

attached to /examples/generator-expressions · viewBox 300×56

v2 scores: generator-expressions 9.0

control-decision-map

attached to a journey section · viewBox 244×104

control-fact-shape

attached to a journey section · viewBox 286×104

control-stop-boundary

attached to a journey section · viewBox 210×104

iteration-loop-selector

attached to a journey section · viewBox 276×104

iteration-protocol-map

attached to a journey section · viewBox 306×132

iteration-lazy-pull

attached to a journey section · viewBox 360×112

variables-bind

attached to /examples/variables · viewBox 170×44

v2 scores: variables 9.5

constants-bind

attached to /examples/constants · viewBox 194×44

v2 scores: constants 9.0

call-stack

attached to /examples/recursion · viewBox 292×80

v2 scores: recursion 9.0

decorator-rebind

attached to /examples/decorators · viewBox 232×110

v2 scores: decorators 9.0

mro-chain

attached to /examples/inheritance-and-super · viewBox 200×152

v2 scores: inheritance-and-super 9.0

dataclass-fields

attached to /examples/dataclasses · viewBox 312×76

v2 scores: dataclasses 9.0

class-triangle

attached to /examples/classes, abstract-base-classes, metaclasses · viewBox 274×60

v2 scores: classes 9.0 · abstract-base-classes 9.0 · metaclasses 9.0

exception-cause-context

attached to /examples/exception-chaining · viewBox 282×70

v2 scores: exception-chaining 9.0

unpacking-bind

attached to /examples/unpacking · viewBox 152×80

v2 scores: unpacking 9.0

comprehension-equivalence

attached to /examples/comprehensions, comprehension-patterns · viewBox 280×76

v2 scores: comprehensions 9.0 · comprehension-patterns 9.0

list-append

attached to /examples/lists, tuples · viewBox 220×36

v2 scores: lists 9.0 · tuples 9.0

dict-buckets

attached to /examples/dicts · viewBox 288×92

v2 scores: dicts 9.0

number-lines

attached to /examples/numbers · viewBox 260×78

v2 scores: numbers 9.0

expression-tree

attached to /examples/operators · viewBox 220×92

v2 scores: operators 9.0

none-singleton

attached to /examples/none · viewBox 240×84

v2 scores: none 9.0

codepoints-bytes

attached to /examples/strings · viewBox 200×84

v2 scores: strings 9.0

sort-stability

attached to /examples/sorting · viewBox 270×100

v2 scores: sorting 9.0

kw-only-separator

attached to /examples/keyword-only-arguments, positional-only-parameters · viewBox 200×56

v2 scores: keyword-only-arguments 9.0 · positional-only-parameters 9.0

positional-only-separator

attached to /examples/positional-only-parameters · viewBox 200×56

v2 scores: positional-only-parameters 9.0

generator-resume

attached to /examples/generators · viewBox 318×72

v2 scores: generators 9.5

truth-and-size

attached to /examples/truth-and-size · viewBox 232×70

v2 scores: truth-and-size 9.0

descriptor-protocol

attached to /examples/descriptors · viewBox 222×76

v2 scores: descriptors 9.0

bound-unbound

attached to /examples/bound-and-unbound-methods · viewBox 296×56

v2 scores: bound-and-unbound-methods 9.0

method-kinds

attached to /examples/classmethods-and-staticmethods · viewBox 272×70

v2 scores: classmethods-and-staticmethods 9.0

callable-objects

attached to /examples/callable-objects · viewBox 220×44

v2 scores: callable-objects 9.0

attribute-lookup

attached to /examples/attribute-access · viewBox 242×70

v2 scores: attribute-access 9.0

guard-clauses

attached to /examples/guard-clauses · viewBox 264×104

v2 scores: guard-clauses 9.0

bytes-vs-bytearray

attached to /examples/bytes-and-bytearray · viewBox 200×90

v2 scores: bytes-and-bytearray 9.5

sentinel-iteration

attached to /examples/sentinel-iteration · viewBox 354×70

v2 scores: sentinel-iteration 9.0

partial-functions

attached to /examples/partial-functions · viewBox 334×36

v2 scores: partial-functions 9.0

args-kwargs

attached to /examples/args-and-kwargs · viewBox 280×68

v2 scores: args-and-kwargs 9.0

multiple-return

attached to /examples/multiple-return-values · viewBox 180×120

v2 scores: multiple-return-values 9.0

lambda-expression

attached to /examples/lambdas · viewBox 170×76

v2 scores: lambdas 9.0

property-fork

attached to /examples/properties · viewBox 232×72

v2 scores: properties 9.0

metaclass-triangle

attached to /examples/metaclasses · viewBox 300×60

v2 scores: metaclasses 9.0

sys-path-resolution

attached to /examples/modules · viewBox 258×100

v2 scores: modules 9.0

import-alias

attached to /examples/import-aliases · viewBox 212×56

v2 scores: import-aliases 9.0

protocol-check

attached to /examples/protocols · viewBox 220×78

v2 scores: protocols 9.0

enum-members

attached to /examples/enums · viewBox 280×60

v2 scores: enums 9.0

datetime-instant

attached to /examples/datetime · viewBox 280×88

v2 scores: datetime 9.0

json-python-mapping

attached to /examples/json · viewBox 220×116

v2 scores: json 9.0

path-tree

attached to /examples/files-and-pathlib · viewBox 290×100

v2 scores: files-and-pathlib 9.0

regex-groups

attached to /examples/regular-expressions · viewBox 140×96

v2 scores: regular-expressions 9.0

number-parse

attached to /examples/number-parsing · viewBox 204×64

v2 scores: number-parsing 9.0

format-spec

attached to /examples/string-formatting · viewBox 372×82

v2 scores: string-formatting 9.0

truthy-check

attached to /examples/truthiness · viewBox 240×70

v2 scores: truthiness 9.0

boolean-truth-table

attached to /examples/booleans · viewBox 132×64

v2 scores: booleans 9.0

set-buckets

attached to /examples/sets · viewBox 156×90

v2 scores: sets 9.0

tuple-frozen

attached to /examples/tuples · viewBox 280×48

v2 scores: tuples 9.0

yield-delegation

attached to /examples/yield-from · viewBox 240×84

v2 scores: yield-from 9.0

itertools-chain

attached to /examples/itertools · viewBox 246×82

v2 scores: itertools 9.0

assertion-check

attached to /examples/assertions · viewBox 304×76

v2 scores: assertions 9.0

custom-exception-chain

attached to /examples/custom-exceptions · viewBox 220×90

v2 scores: custom-exceptions 9.0

exception-group-peel

attached to /examples/exception-groups · viewBox 240×50

v2 scores: exception-groups 9.0

delete-name-erased

attached to /examples/delete-statements · viewBox 200×84

v2 scores: delete-statements 9.0

package-tree

attached to /examples/packages · viewBox 240×76

v2 scores: packages 9.0

venv-boundary

attached to /examples/virtual-environments · viewBox 274×76

v2 scores: virtual-environments 9.0

subprocess-spawn

attached to /examples/subprocesses · viewBox 324×60

v2 scores: subprocesses 9.0

aaa-pattern

attached to /examples/testing · viewBox 250×80

v2 scores: testing 9.0

socket-byte-boundary

attached to /examples/networking · viewBox 364×46

v2 scores: networking 9.0

gil-lanes

attached to /examples/threads-and-processes · viewBox 300×138

v2 scores: threads-and-processes 9.0

cast-escape

attached to /examples/casts-and-any · viewBox 184×56

v2 scores: casts-and-any 9.0

newtype-phantom

attached to /examples/newtype · viewBox 96×92

v2 scores: newtype 9.0

overload-signatures

attached to /examples/overloads · viewBox 304×64

v2 scores: overloads 9.0

paramspec-preserve

attached to /examples/paramspec · viewBox 294×60

v2 scores: paramspec 9.0

literal-constrained

attached to /examples/literal-and-final · viewBox 144×76

v2 scores: literal-and-final 9.0

callable-type

attached to /examples/callable-types · viewBox 352×42

v2 scores: callable-types 9.0

isinstance-check

attached to /examples/runtime-type-checks · viewBox 232×76

v2 scores: runtime-type-checks 9.0

container-methods

attached to /examples/container-protocols · viewBox 272×82

v2 scores: container-protocols 9.0

typed-dict-shape

attached to /examples/typed-dicts · viewBox 200×92

v2 scores: typed-dicts 9.0

structured-shapes

attached to /examples/structured-data-shapes · viewBox 266×82

v2 scores: structured-data-shapes 9.0

csv-records

attached to /examples/csv-data · viewBox 212×96

v2 scores: csv-data 9.0

warning-signal

attached to /examples/warnings · viewBox 292×80

v2 scores: warnings 9.0

object-lifecycle

attached to /examples/object-lifecycle · viewBox 366×80

v2 scores: object-lifecycle 9.0

type-alias-name

attached to /examples/type-aliases · viewBox 240×104

v2 scores: type-aliases 9.0

match-dispatch-ladder

attached to /examples/match-statements · viewBox 260×130

v2 scores: match-statements 9.0

match-pattern-variants

attached to /examples/advanced-match-patterns · viewBox 272×96

v2 scores: advanced-match-patterns 9.0

loop-else-gate

attached to /examples/loop-else · viewBox 312×76

v2 scores: loop-else 9.0

function-with-body

attached to /examples/functions · viewBox 334×68

v2 scores: functions 9.0

diff --git a/public/runner.05ddb60aa9e7.js b/public/runner.36d32891c1eb.js similarity index 99% rename from public/runner.05ddb60aa9e7.js rename to public/runner.36d32891c1eb.js index cdff252..d83271d 100644 --- a/public/runner.05ddb60aa9e7.js +++ b/public/runner.36d32891c1eb.js @@ -215,7 +215,7 @@ function initializeRunner() { // would otherwise loop through solves and Siteverify calls unbounded. if (turnstileToken) throw new Error(responseErrorMessage(response, html)); outputPanel.querySelector('code').textContent = challengeRequired.textContent - || 'Verification required before running edited code…'; + || 'Verification required before running code…'; const token = await requestTurnstileToken(signal); if (runId !== latestRunId) return; return submitRun(runId, signal, token); diff --git a/public/runner.js b/public/runner.js index cdff252..d83271d 100644 --- a/public/runner.js +++ b/public/runner.js @@ -215,7 +215,7 @@ function initializeRunner() { // would otherwise loop through solves and Siteverify calls unbounded. if (turnstileToken) throw new Error(responseErrorMessage(response, html)); outputPanel.querySelector('code').textContent = challengeRequired.textContent - || 'Verification required before running edited code…'; + || 'Verification required before running code…'; const token = await requestTurnstileToken(signal); if (runId !== latestRunId) return; return submitRun(runId, signal, token); diff --git a/public/search-index.332712b2e502.json b/public/search-index.332712b2e502.json deleted file mode 100644 index 263003e..0000000 --- a/public/search-index.332712b2e502.json +++ /dev/null @@ -1 +0,0 @@ -[{"slug":"hello-world","title":"Hello World","section":"Basics","summary":"The first Python program prints a line of text.","text":"hello world `print()` writes text followed by a newline. strings can be delimited with single or double quotes."},{"slug":"values","title":"Values","section":"Basics","summary":"Python programs evaluate expressions into objects such as text, numbers, booleans, and None.","text":"values values are objects; names point to them and operations usually create new values. use `is none` for the absence marker, not `== none`. this overview introduces boundaries that later pages explain in detail."},{"slug":"literals","title":"Literals","section":"Basics","summary":"Literals write values directly in Python source code.","text":"literals literals are good for small local values; constants are better for repeated values with meaning. `{}` is an empty dictionary. use `set()` for an empty set. bytes literals are binary data; string literals are unicode text. `...` evaluates to the `ellipsis` object."},{"slug":"numbers","title":"Numbers","section":"Basics","summary":"Python numbers include integers, floats, and complex values.","text":"numbers python's `int` has arbitrary precision; it grows as large as memory allows. python's `float` is approximate double-precision floating point. use `/` for true division and `//` for floor division. use `math.isclose` instead of `==` for floating-point comparison; reach for `decimal.decimal` when exact decimal precision is the domain requirement."},{"slug":"booleans","title":"Booleans","section":"Basics","summary":"Booleans represent truth values and combine with logical operators.","text":"booleans boolean constants are `true` and `false`, with capital letters. `and` and `or` short-circuit: python does not evaluate the right side if the left side already determines the result. prefer truthiness for containers and explicit comparisons when the exact boolean condition matters. `bool` subclasses `int`; `isinstance(true, int)` is `true`. exclude booleans explicitly when only \"real\" integers should pass."},{"slug":"operators","title":"Operators","section":"Basics","summary":"Operators combine, compare, and test values in expressions.","text":"operators use the clearest operator for the question: arithmetic, comparison, boolean logic, membership, identity, or bitwise manipulation. `and` and `or` short-circuit, so the right side may not run. operators have precedence; use parentheses when grouping would otherwise be hard to read. custom operator behavior should make an object feel more natural, not more clever."},{"slug":"none","title":"None","section":"Basics","summary":"None represents expected absence, distinct from missing keys and errors.","text":"none use `is none` rather than `== none`; `none` is a singleton identity value. use `none` for expected absence that callers can test. use dictionary defaults for missing mapping keys and exceptions for invalid operations."},{"slug":"variables","title":"Variables","section":"Basics","summary":"Names are bound to values with assignment.","text":"variables python variables are names bound to objects, not boxes with fixed types. rebinding a name is normal. use augmented assignment for counters and accumulators."},{"slug":"constants","title":"Constants","section":"Basics","summary":"Python uses naming conventions and optional types for values that should not change.","text":"constants python constants are a convention, not a runtime lock. use all-caps names for fixed module-level configuration. add `final` when static tooling should flag accidental rebinding."},{"slug":"truthiness","title":"Truthiness","section":"Basics","summary":"Python conditions use truthiness, not only explicit booleans.","text":"truthiness empty containers and zero-like numbers are false in conditions. use explicit comparisons when they communicate intent better than truthiness."},{"slug":"equality-and-identity","title":"Equality and Identity","section":"Data Model","summary":"== compares values, while is compares object identity.","text":"equality and identity use `==` for ordinary value comparisons. use `is` primarily for identity checks against singletons such as `none`. equal mutable containers can still be independent objects. never use `is` to compare numbers; cpython's small-integer cache makes the result an implementation detail."},{"slug":"mutability","title":"Mutability","section":"Data Model","summary":"Some objects change in place, while others return new values.","text":"mutability lists and dictionaries are mutable; strings and tuples are immutable. aliasing is useful, but copy mutable containers when independent changes are needed. pay attention to whether an operation mutates in place or returns a new value."},{"slug":"object-lifecycle","title":"Object Lifecycle","section":"Basics","summary":"Names keep objects reachable until the last reference goes away.","text":"object lifecycle assignment binds names to objects; it does not copy the object. `del name` removes one reference, not necessarily the object itself. python reclaims unreachable objects automatically, so lifetime bugs usually come from keeping references longer than intended."},{"slug":"strings","title":"Strings","section":"Text","summary":"Strings are immutable Unicode text sequences.","text":"strings use `str` for text and `bytes` for binary data. `len(text)` counts unicode code points; `len(text.encode(\"utf-8\"))` counts encoded bytes. ascii text is a useful baseline because each ascii code point is one utf-8 byte. string methods return new strings because strings are immutable. user-visible “characters” can be more subtle than code points; combining marks and emoji sequences may need specialized text handling."},{"slug":"bytes-and-bytearray","title":"Bytes and Bytearray","section":"Text","summary":"bytes and bytearray store binary data, not Unicode text.","text":"bytes and bytearray encode text when an external boundary needs bytes. decode bytes when you want text again. indexing `bytes` returns integers from 0 to 255. use `bytearray` when binary data must be changed in place."},{"slug":"string-formatting","title":"String Formatting","section":"Text","summary":"f-strings turn values into readable text at the point of use.","text":"string formatting use `f\"...\"` strings for most new formatting code. expressions inside braces are evaluated before formatting. format specifications after `:` control alignment, width, padding, and precision."},{"slug":"conditionals","title":"Conditionals","section":"Control Flow","summary":"if, elif, and else choose which block runs.","text":"conditionals python has no mandatory parentheses around conditions; the colon and indentation define the block. comparison operators such as `<` and `==` can be chained, as in `0 < value < 10`. keep branch bodies short; move larger work into functions so the decision remains easy to scan."},{"slug":"guard-clauses","title":"Guard Clauses","section":"Control Flow","summary":"Guard clauses handle boundary cases early so the main path stays flat.","text":"guard clauses guard clauses are a readability pattern, not a separate python feature. they work best when the early cases are true boundaries. for exceptional failures, raise an exception instead of returning a sentinel string."},{"slug":"assignment-expressions","title":"Assignment Expressions","section":"Control Flow","summary":"The walrus operator assigns a value inside an expression.","text":"assignment expressions `name := expression` assigns and evaluates to the assigned value. use it to avoid computing the same value twice. prefer a normal assignment when the expression becomes hard to scan."},{"slug":"for-loops","title":"For Loops","section":"Control Flow","summary":"for iterates over values produced by an iterable.","text":"for loops a `for` loop consumes an iterable until it is exhausted. reach for `while` when the stopping condition must be rechecked manually. `iter()` and `next()` expose the protocol that `for` uses internally."},{"slug":"break-and-continue","title":"Break and Continue","section":"Control Flow","summary":"break exits a loop early, while continue skips to the next iteration.","text":"break and continue `continue` skips to the next loop iteration. `break` exits the nearest enclosing loop immediately. prefer plain `if`/`else` when the loop does not need early skip or early stop behavior."},{"slug":"loop-else","title":"Loop Else","section":"Control Flow","summary":"A loop else block runs only when the loop did not end with break.","text":"loop else loop `else` runs when the loop was not ended by `break`. it is best for search loops with a clear found/not-found split. it works with both `for` and `while` loops."},{"slug":"iterating-over-iterables","title":"Iterating over Iterables","section":"Iteration","summary":"for loops consume values from any iterable object.","text":"iterating over iterables a `for` loop consumes values from an iterable. different producers can feed the same loop protocol. prefer `enumerate()` over `range(len(...))` when you need an index."},{"slug":"iterators","title":"Iterators","section":"Iteration","summary":"iter and next expose the protocol behind for loops.","text":"iterators iterables produce iterators; iterators produce values. `next()` consumes one value from an iterator. many iterators are one-pass even when the original collection is reusable."},{"slug":"iterator-vs-iterable","title":"Iterator vs Iterable","section":"Iteration","summary":"Iterables produce fresh iterators; iterators are one-pass.","text":"iterator vs iterable an iterable produces an iterator each time `iter()` is called on it; an iterator produces values until it is exhausted. `iter(iterable)` returns a fresh iterator; `iter(iterator)` returns the same iterator. functions that traverse their input more than once must accept an iterable or materialize the input at the boundary."},{"slug":"sentinel-iteration","title":"Sentinel Iteration","section":"Iteration","summary":"iter(callable, sentinel) repeats calls until a marker value appears.","text":"sentinel iteration the callable passed to `iter(callable, sentinel)` must take no arguments. the sentinel stops iteration and is not yielded. when the loop needs richer branching, an explicit `while` loop may be clearer."},{"slug":"match-statements","title":"Match Statements","section":"Control Flow","summary":"match selects cases using structural pattern matching.","text":"match statements `match` compares structure, not just equality. patterns can bind names such as `x` and `y` while matching. mapping patterns match when the named keys are present; extra keys in the subject are ignored rather than failing the case. put the catch-all `_` case last, because cases are tried from top to bottom."},{"slug":"advanced-match-patterns","title":"Advanced Match Patterns","section":"Control Flow","summary":"match patterns can destructure sequences, combine alternatives, and add guards.","text":"advanced match patterns use `case _` as a wildcard fallback. guards refine a pattern after the structure matches. or patterns and star patterns keep shape-based branches compact."},{"slug":"while-loops","title":"While Loops","section":"Control Flow","summary":"while repeats until changing state makes a condition false.","text":"while loops use `while` when changing state decides whether the loop continues. update loop state inside the body so the condition can become false. prefer `for` when you already have a collection, range, iterator, or generator to consume."},{"slug":"lists","title":"Lists","section":"Collections","summary":"Lists are ordered, mutable collections.","text":"lists lists are mutable sequences: methods such as `append()` change the list in place. negative indexes count from the end. `sorted()` returns a new list; `list.sort()` sorts the existing list in place."},{"slug":"tuples","title":"Tuples","section":"Collections","summary":"Tuples group a fixed number of positional values.","text":"tuples tuples are immutable sequences with fixed length. use tuples for small records where position has meaning. use lists for variable-length collections of similar items. reach for a dataclass or `namedtuple` when fields deserve names everywhere they're used."},{"slug":"unpacking","title":"Unpacking","section":"Collections","summary":"Unpacking binds names from sequences and mappings concisely.","text":"unpacking starred unpacking collects the remaining values into a list. dictionary unpacking with ** is common when calling functions with structured data. prefer indexing when you need one position; prefer unpacking when naming several positions makes the shape clearer."},{"slug":"dicts","title":"Dictionaries","section":"Collections","summary":"Dictionaries map keys to values for records, lookup, and structured data.","text":"dicts dictionaries preserve insertion order in modern python. use `get()` when a missing key has a reasonable default. use direct indexing when a missing key should be treated as an error. snapshot keys with `list(d.keys())` before deleting items in a loop; adding or removing keys during iteration raises `runtimeerror`."},{"slug":"sets","title":"Sets","section":"Collections","summary":"Sets store unique values and make membership checks explicit.","text":"sets use sets when uniqueness and membership are the main operations. prefer lists when order or repeated values are part of the meaning. sets are unordered, so sort them when examples need deterministic display."},{"slug":"slices","title":"Slices","section":"Collections","summary":"Slices copy meaningful ranges from ordered sequences.","text":"slices slice stop indexes are excluded, so adjacent ranges compose cleanly. omitted bounds mean the beginning or end of the sequence. a negative step walks backward; `[::-1]` is a common reversed-copy idiom."},{"slug":"comprehensions","title":"Comprehensions","section":"Collections","summary":"Comprehensions build collections by mapping and filtering iterables.","text":"comprehensions the left side says what to produce; the `for` clause says where values come from. use an `if` clause for simple filters. list, dict, and set comprehensions build concrete collections immediately. switch to a loop when the transformation needs multiple steps or explanations."},{"slug":"comprehension-patterns","title":"Comprehension Patterns","section":"Collections","summary":"Comprehensions can use multiple for clauses and filters when the shape stays clear.","text":"comprehension patterns read comprehension clauses from left to right. multiple `for` clauses act like nested loops. prefer an explicit loop when the comprehension stops being obvious."},{"slug":"sorting","title":"Sorting","section":"Collections","summary":"sorted returns a new ordered list and key functions choose the sort value.","text":"sorting `sorted()` makes a new list; `list.sort()` mutates an existing list. `key=` should return the value python compares for each item. python's sort is stable, so equal keys keep their original relative order."},{"slug":"collections-module","title":"Collections Module","section":"Collections","summary":"collections provides specialized containers for common data shapes.","text":"collections module `counter` counts, `defaultdict` groups, `deque` queues, and `namedtuple` names record fields. prefer the built-in containers until a specialized shape makes the code clearer. for new structured records with defaults and methods, consider `dataclasses` instead of `namedtuple`."},{"slug":"copying-collections","title":"Copying Collections","section":"Collections","summary":"Copies can duplicate the outer container while nested objects may still be shared.","text":"copying collections assignment aliases; it does not copy. shallow copies duplicate the outer container only. deep copies are useful for nested independence, but they can be expensive and surprising for objects with external resources."},{"slug":"functions","title":"Functions","section":"Functions","summary":"Use def to name reusable behavior and return results.","text":"functions use `return` for values the caller should receive. defaults keep common calls concise. keyword arguments make options readable at the call site. never use a mutable value as a default argument; use `none` and build the container inside the function body."},{"slug":"keyword-only-arguments","title":"Keyword-only Arguments","section":"Functions","summary":"Use * to require selected function arguments to be named.","text":"keyword only arguments put `*` before options that callers should name. keyword-only flags avoid mysterious positional `true` and `false` arguments. defaults work normally for keyword-only parameters."},{"slug":"positional-only-parameters","title":"Positional-only Parameters","section":"Functions","summary":"Use / to mark parameters that callers must pass by position.","text":"positional only parameters `/` marks parameters before it as positional-only. `*` marks parameters after it as keyword-only. use these markers when the call shape is part of the api design."},{"slug":"args-and-kwargs","title":"Args and Kwargs","section":"Functions","summary":"*args collects extra positional arguments and **kwargs collects named ones.","text":"args and kwargs use these tools when a function naturally accepts a flexible shape. prefer explicit parameters when the accepted arguments are known and fixed. `*args` is a tuple; `**kwargs` is a dictionary."},{"slug":"multiple-return-values","title":"Multiple Return Values","section":"Functions","summary":"Python returns multiple values by returning a tuple and unpacking it.","text":"multiple return values a comma creates a tuple; `return a, b` returns one tuple containing two values. unpacking at the call site gives each returned position a meaningful name. use a class-like record when the result has many fields."},{"slug":"closures","title":"Closures","section":"Functions","summary":"Inner functions can remember values from an enclosing scope.","text":"closures a closure keeps access to names from the scope where the inner function was created. each call to the outer function can create a separate remembered environment. closures are useful for callbacks, small factories, and decorators. closures bind names, not values; capture loop variables with `lambda x=x: ...` to freeze them at definition time."},{"slug":"partial-functions","title":"Partial Functions","section":"Functions","summary":"functools.partial pre-fills arguments to make a more specific callable.","text":"partial functions `partial` adapts a callable by pre-filling arguments. the resulting object can be passed anywhere a callable with the remaining parameters is expected. use a regular function when the adapter needs more logic than argument binding."},{"slug":"scope-global-nonlocal","title":"Global and Nonlocal","section":"Functions","summary":"global and nonlocal choose which outer binding assignment should update.","text":"scope global nonlocal assignment inside a function is local unless declared otherwise. prefer `nonlocal` for closure state and avoid `global` unless module state is truly intended. passing values and returning results is usually easier to test than rebinding outer names."},{"slug":"recursion","title":"Recursion","section":"Functions","summary":"Recursive functions solve nested problems by calling themselves on smaller pieces.","text":"recursion every recursive function needs a base case that stops the calls. recursion fits nested data better than flat repetition. python limits recursion depth, so loops are often better for very deep or simple repetition."},{"slug":"lambdas","title":"Lambdas","section":"Functions","summary":"lambda creates small anonymous function expressions.","text":"lambdas lambdas are expressions, not statements. prefer `def` for multi-step or reused behavior. lambdas are common as `key=` functions because the behavior is local to one call."},{"slug":"generators","title":"Generators","section":"Iteration","summary":"yield creates an iterator that produces values on demand.","text":"generators generator functions are a concise way to create custom iterators; every generator is an iterator. `yield` defers work and streams values; `return` produces the whole result up front. a generator is consumed as you iterate over it. prefer a list when you need to reuse stored results; prefer a generator when values can be streamed once."},{"slug":"yield-from","title":"Yield From","section":"Iteration","summary":"yield from delegates part of a generator to another iterable.","text":"yield from `yield from iterable` yields each value from that iterable. it keeps generator pipelines compact. use a plain `yield` when producing one value directly."},{"slug":"generator-expressions","title":"Generator Expressions","section":"Iteration","summary":"Generator expressions use comprehension-like syntax to stream values lazily.","text":"generator expressions list, dict, and set comprehensions build concrete collections. generator expressions produce one-pass iterators. use generator expressions when the consumer can process values one at a time."},{"slug":"itertools","title":"Itertools","section":"Iteration","summary":"itertools composes lazy iterator streams.","text":"itertools `itertools` composes producer and transformer streams. iterator pipelines avoid building intermediate lists. use `islice()` to take a finite piece from an infinite iterator. convert to a list only when you need concrete results."},{"slug":"decorators","title":"Decorators","section":"Functions","summary":"Decorators wrap or register functions using @ syntax.","text":"decorators `@decorator` is shorthand for assigning `func = decorator(func)`. decorators can wrap, replace, or register functions. use `functools.wraps` in production wrappers that should preserve metadata."},{"slug":"classes","title":"Classes","section":"Classes","summary":"Classes bundle data and behavior into new object types.","text":"classes `self` is the instance the method is operating on. `__init__` initializes each new object. class attributes are shared across instances; instance attributes belong to one object. put mutable defaults in `__init__`, not on the class body. use classes when behavior belongs with state; use dictionaries for looser structured data."},{"slug":"inheritance-and-super","title":"Inheritance and Super","section":"Classes","summary":"Inheritance reuses behavior, and super delegates to a parent implementation.","text":"inheritance and super inheritance models an “is a specialized kind of” relationship. `super()` calls the next implementation in the method resolution order. prefer composition when an object only needs to use another object."},{"slug":"classmethods-and-staticmethods","title":"Classmethods and Staticmethods","section":"Classes","summary":"Three method shapes: instance, class, and static — each receives a different first argument.","text":"classmethods and staticmethods instance methods need an instance; classmethods and staticmethods can be called on the class. use `@classmethod` for alternate constructors and class-level operations that respect subclassing. use `@staticmethod` only when a function is truly independent of instance and class state but still belongs in the class's namespace. a free function is often the right answer when neither decorator applies."},{"slug":"dataclasses","title":"Dataclasses","section":"Classes","summary":"dataclass generates common class methods for data containers.","text":"dataclasses type annotations define dataclass fields. dataclasses generate methods but remain normal python classes. use `field()` for advanced defaults such as per-instance lists or dictionaries."},{"slug":"properties","title":"Properties","section":"Classes","summary":"@property keeps attribute syntax while adding computation or validation.","text":"properties properties let apis start simple and grow validation or computation later. callers access a property like an attribute, not like a method. use methods instead when work is expensive or action-like."},{"slug":"special-methods","title":"Special Methods","section":"Data Model","summary":"Special methods connect your objects to Python syntax and built-ins.","text":"special methods dunder methods are looked up by python's data model protocols. `__repr__` is the developer-facing form; `__str__` is the user-facing form. `print()` falls back to `__repr__` when `__str__` is missing. defining `__eq__` removes the default `__hash__`; restore it when the type should be hashable. container protocols (`__contains__`, `__getitem__`, `__setitem__`, `__bool__`) make instances behave like built-in containers. `__call__` makes instances callable; `__enter__`/`__exit__` make them context managers. implement the smallest protocol that makes your object feel native."},{"slug":"truth-and-size","title":"Truth and Size","section":"Data Model","summary":"__bool__ and __len__ decide how objects behave in truth tests and len().","text":"truth and size prefer `__len__` for sized containers. prefer `__bool__` when truth has domain meaning. keep truth tests unsurprising; surprising falsy objects make conditionals harder to read."},{"slug":"container-protocols","title":"Container Protocols","section":"Data Model","summary":"Container methods connect objects to indexing, membership, and item assignment.","text":"container protocols implement the narrowest container protocol your object needs. use `keyerror` and `indexerror` consistently with built-in containers. if a plain `dict` or `list` is enough, prefer it over a custom container."},{"slug":"callable-objects","title":"Callable Objects","section":"Data Model","summary":"__call__ lets an instance behave like a function while keeping state.","text":"callable objects `callable(obj)` checks whether an object can be called. callable objects are good for named, stateful behavior. prefer plain functions when no instance state is needed."},{"slug":"operator-overloading","title":"Operator Overloading","section":"Data Model","summary":"Operator methods let objects define arithmetic and comparison syntax.","text":"operator overloading overload operators only when the operation is unsurprising. return `notimplemented` when an operand type is unsupported. implement equality deliberately when value comparison matters."},{"slug":"attribute-access","title":"Attribute Access","section":"Data Model","summary":"Attribute hooks customize lookup, missing attributes, and assignment.","text":"attribute access `__getattr__` is narrower than `__getattribute__` because it handles only missing attributes. `__setattr__` affects every assignment on the instance. use `property` or descriptors when the behavior is attached to a known attribute name."},{"slug":"bound-and-unbound-methods","title":"Bound and Unbound Methods","section":"Data Model","summary":"instance.method binds self automatically; Class.method is a plain function.","text":"bound and unbound methods `instance.method` produces a bound method whose `__self__` is the instance. `class.method` produces the plain function and requires you to pass the instance. \"unbound method\" is the historical python 2 term; since python 3, `class.method` is simply a function, which is what this page demonstrates. each bound method is its own object; storing one captures its instance. the binding is implemented by the descriptor protocol on the function object."},{"slug":"descriptors","title":"Descriptors","section":"Data Model","summary":"Descriptors customize attribute access through __get__, __set__, or __delete__.","text":"descriptors descriptors are class attributes that participate in instance attribute access. data descriptors with `__set__` can validate or transform assignments. `property` is usually simpler for one-off managed attributes; descriptors shine when the behavior is reusable."},{"slug":"metaclasses","title":"Metaclasses","section":"Classes","summary":"A metaclass customizes how classes themselves are created.","text":"metaclasses metaclasses customize class creation, not instance behavior directly. most code should prefer class decorators, functions, or ordinary inheritance. you are most likely to meet metaclasses inside frameworks and orms."},{"slug":"context-managers","title":"Context Managers","section":"Data Model","summary":"with ensures setup and cleanup happen together.","text":"context managers files, locks, and temporary state commonly use context managers. `__enter__` and `__exit__` power the protocol. use `finally` when cleanup must happen after errors too. returning true from `__exit__` suppresses an exception; do that only intentionally."},{"slug":"delete-statements","title":"Delete Statements","section":"Data Model","summary":"del removes bindings, items, and attributes rather than producing a value.","text":"delete statements `del` removes bindings or container entries. assign `none` when absence should remain an explicit value. use container methods such as `pop()` when you need the removed value back."},{"slug":"exceptions","title":"Exceptions","section":"Errors","summary":"Use try, except, else, and finally to separate success, recovery, and cleanup.","text":"exceptions catch the most specific exception you can. `else` is for success code that should run only if the `try` block did not fail. `finally` runs whether the operation succeeded or failed. avoid bare `except:` and broad `except exception:` — they hide bugs and absorb signals like `keyboardinterrupt`."},{"slug":"assertions","title":"Assertions","section":"Errors","summary":"assert documents internal assumptions and fails loudly when they are false.","text":"assertions use `assert` for internal invariants and debugging assumptions. use explicit exceptions for user input, files, network responses, and other expected failures. assertions can be disabled with python optimization flags, so do not rely on them for security checks."},{"slug":"exception-chaining","title":"Exception Chaining","section":"Errors","summary":"raise from preserves the original cause when translating exceptions.","text":"exception chaining use `raise ... from error` when translating exceptions across a boundary. the new exception's `__cause__` points to the original exception. chaining keeps user-facing errors clear without losing debugging context."},{"slug":"exception-groups","title":"Exception Groups","section":"Errors","summary":"except* handles matching exceptions inside an ExceptionGroup.","text":"exception groups `except*` is for `exceptiongroup`, not ordinary single exceptions. each `except*` clause handles matching members of the group. exception groups often appear around concurrent work."},{"slug":"warnings","title":"Warnings","section":"Errors","summary":"warnings report soft problems without immediately stopping the program.","text":"warnings use warnings for soft problems callers can act on later. use exceptions when the current operation cannot continue. `stacklevel` should point the warning at the caller rather than inside the helper."},{"slug":"modules","title":"Modules","section":"Modules","summary":"Modules organize code into namespaces and expose reusable definitions.","text":"modules prefer plain `import module` when the namespace improves readability. use focused imports for a small number of clear names. place imports near the top of the file. imports execute module top-level code once, then reuse the cached module object."},{"slug":"import-aliases","title":"Import Aliases","section":"Modules","summary":"as gives imported modules or names a local alias.","text":"import aliases `import module as alias` keeps module-style access under a shorter or clearer name. `from module import name as alias` imports one name under a local alias. prefer plain imports unless an alias improves clarity or follows a strong convention. avoid `from module import *` because it makes dependencies harder to see."},{"slug":"packages","title":"Packages","section":"Modules","summary":"Packages organize modules into importable directories.","text":"packages a package is a module that can contain submodules. dotted imports should mirror a meaningful project structure. use `from .submodule import name` inside a package to re-export submodule names; set `__all__` to declare the public surface. prefer ordinary imports unless the module name is truly dynamic."},{"slug":"virtual-environments","title":"Virtual Environments","section":"Modules","summary":"Virtual environments isolate a project's Python packages.","text":"virtual environments use `python -m venv .venv` for everyday standard-python project setup. a venv isolates installed packages; it does not change how imports are written. this site's runner uses a deployment dependency model, not an activated shell environment. that runner constraint is separate from the standard python `venv` workflow you would use in local projects."},{"slug":"type-hints","title":"Type Hints","section":"Types","summary":"Annotations document expected types and power static analysis.","text":"type hints python does not enforce most type hints at runtime. tools like type checkers and editors use annotations to catch mistakes earlier. use `x | y` for unions and `optional[x]` for \"x or none\"; both spellings mean the same thing. reach for a `type` alias when a domain name reads better than a raw primitive type. use runtime validation when untrusted input must be rejected while the program runs."},{"slug":"runtime-type-checks","title":"Runtime Type Checks","section":"Types","summary":"type, isinstance, and issubclass inspect runtime relationships.","text":"runtime type checks `type()` is exact; `isinstance()` follows inheritance. runtime checks inspect objects, not static annotations. prefer behavior, protocols, or clear validation over scattered type checks."},{"slug":"union-and-optional-types","title":"Union and Optional Types","section":"Types","summary":"The | operator describes values that may have more than one static type.","text":"union and optional types use `a | b` when a value may have either type. `t | none` means absence is an expected case, not an error by itself. narrow unions before using behavior that belongs to only one member type."},{"slug":"type-aliases","title":"Type Aliases","section":"Types","summary":"Type aliases give a meaningful name to a repeated type shape.","text":"type aliases use aliases to name repeated or domain-specific annotation shapes. a type alias does not validate values at runtime. use `newtype` when two values share a runtime representation but should not be mixed statically."},{"slug":"typed-dicts","title":"TypedDict","section":"Types","summary":"TypedDict describes dictionaries with known string keys.","text":"typed dicts use `typeddict` for dictionary records from json or apis. type checkers understand required and optional keys. runtime behavior is still ordinary dictionary behavior."},{"slug":"structured-data-shapes","title":"Structured Data Shapes","section":"Classes","summary":"dataclass, NamedTuple, and TypedDict each model records with different trade-offs.","text":"structured data shapes `@dataclass` — mutable, attribute access, methods; good default when behavior travels with data. `typing.namedtuple` — immutable, attribute + index access, tuple semantics; good for small records that flow through unpacking. `typing.typeddict` — runtime is `dict`, schema is type-checker-only; good for json-shaped data. `collections.namedtuple` is the older, untyped form of `namedtuple`; prefer the `typing` version in new code."},{"slug":"literal-and-final","title":"Literal and Final","section":"Types","summary":"Literal restricts exact values, while Final marks names that should not be rebound.","text":"literal and final `literal` narrows values to a small exact set. `final` prevents rebinding in static analysis, not at runtime. use enums when the option set needs names, behavior, or iteration over members."},{"slug":"callable-types","title":"Callable Types","section":"Types","summary":"Callable annotations describe functions passed as values.","text":"callable types use `callable[[arg], return]` for simple function-shaped values. the annotation documents how the callback will be called. for complex call signatures, protocols can be clearer."},{"slug":"generics-and-typevar","title":"Generics and TypeVar","section":"Types","summary":"Generics preserve type information across reusable functions and classes.","text":"generics and typevar a `typevar` stands for a type chosen by the caller. python 3.12+ also accepts the inline pep 695 spelling `def first[t](items: list[t]) -> t`, which declares the variable without a separate `typevar` line; the explicit form shown here works everywhere and reads the same way. generic functions avoid losing information to `object` or `any`. use generics when input and output types are connected."},{"slug":"paramspec","title":"ParamSpec","section":"Types","summary":"ParamSpec preserves callable parameter types through wrappers.","text":"paramspec `paramspec` preserves a callable's parameter list through transparent wrappers. pair `paramspec` with a `typevar` when the return type should also be preserved. python 3.12+ also accepts the inline pep 695 spelling `def wrap[**p, r](func: callable[p, r])`, which declares both variables in the signature itself. if the wrapper changes the public signature, write that new signature directly instead."},{"slug":"overloads","title":"Overloads","section":"Types","summary":"overload describes APIs whose return type depends on argument types.","text":"overloads put `@overload` declarations immediately before the implementation. overloads improve static precision; they do not create runtime dispatch. if all callers can work with one broad return type, a simple union annotation is usually enough."},{"slug":"casts-and-any","title":"Casts and Any","section":"Types","summary":"Any and cast are escape hatches for places static analysis cannot prove.","text":"casts and any `any` disables most static checking for a value. `cast()` tells the type checker to trust you without changing the runtime object. prefer narrowing with checks when possible."},{"slug":"newtype","title":"NewType","section":"Types","summary":"NewType creates distinct static identities for runtime-compatible values.","text":"newtype `newtype` helps type checkers distinguish values that share a runtime representation. at runtime, the value is still the underlying type. use aliases for readability; use `newtype` for static separation."},{"slug":"protocols","title":"Protocols","section":"Types","summary":"Protocol describes required behavior for structural typing.","text":"protocols protocols are for structural typing: compatibility by shape rather than explicit inheritance. type checkers understand protocols; normal runtime method calls still do the work. prefer inheritance when shared implementation matters, and protocols when only required behavior matters."},{"slug":"abstract-base-classes","title":"Abstract Base Classes","section":"Classes","summary":"ABC and abstractmethod enforce that subclasses implement required methods.","text":"abstract base classes `abc` plus `@abstractmethod` blocks instantiation until every abstract method has an implementation. abcs are nominal — subclasses opt in by inheriting; `isinstance()` reflects that opt-in. protocols are structural — any class with the right shape qualifies, regardless of inheritance. prefer an abc when shared implementation or explicit opt-in matters; prefer a protocol when only behavior at the api boundary matters."},{"slug":"enums","title":"Enums","section":"Types","summary":"Enum defines symbolic names for a fixed set of values.","text":"enums enums make states and choices explicit. members have names and values. comparing enum members avoids string typo bugs. prefer raw strings for open-ended text; prefer enums for a closed set of named choices."},{"slug":"regular-expressions","title":"Regular Expressions","section":"Text","summary":"The re module searches and extracts text using regular expressions.","text":"regular expressions use raw strings for regex patterns so backslashes are easier to read. use capturing groups when the point is extraction, not just matching. `re.match` anchors at the start; `re.search` finds the first match anywhere. `re.compile` saves work when the pattern runs more than once. `re.sub` rewrites matches; flags like `re.ignorecase` change matching behavior without rewriting the pattern. reach for string methods before regex when the pattern is simple."},{"slug":"number-parsing","title":"Number Parsing","section":"Standard Library","summary":"int() and float() parse text into numbers and raise ValueError on bad input.","text":"number parsing `int()` and `float()` are constructors that also parse strings. `int(text, base)` makes non-decimal input explicit. catch `valueerror` for recoverable user input; do not hide unexpected data corruption."},{"slug":"custom-exceptions","title":"Custom Exceptions","section":"Errors","summary":"Custom exception classes name failures that belong to your domain.","text":"custom exceptions subclass `exception` for errors callers are expected to catch. a custom exception name can be clearer than reusing a generic `valueerror` everywhere. catch custom exceptions at a boundary that can recover or report clearly."},{"slug":"json","title":"JSON","section":"Standard Library","summary":"json encodes Python values as JSON text and decodes them back.","text":"json `dumps()` returns a string; `loads()` accepts a string. json `true`, `false`, and `null` become python `true`, `false`, and `none`. use `sort_keys=true` when stable text output matters. json only represents data shapes, not arbitrary python objects or behavior."},{"slug":"logging","title":"Logging","section":"Standard Library","summary":"logging records operational events without using print as infrastructure.","text":"logging configure logging once; call named loggers throughout the program. logger and handler levels both participate in filtering. use exceptions for control flow failures, logging for operational evidence, and warnings for soft compatibility problems."},{"slug":"testing","title":"Testing","section":"Standard Library","summary":"Tests make expected behavior executable and repeatable.","text":"testing test method names should describe behavior, not implementation details. a good unit test is deterministic and independent of test order. use broader integration tests when the behavior depends on several components working together."},{"slug":"subprocesses","title":"Subprocesses","section":"Standard Library","summary":"subprocess runs external commands with explicit arguments and captured outputs.","text":"subprocesses use a list of arguments instead of shell strings when possible. capture output when the parent program needs to inspect it. `check=true` turns non-zero exits into exceptions. the verified output came from a real child process under standard cpython at build time; the in-browser sandbox has no process table, so live runs of this page fail there."},{"slug":"threads-and-processes","title":"Threads and Processes","section":"Standard Library","summary":"Threads share memory, while processes run in separate interpreters.","text":"threads and processes threads share memory, so mutable shared state needs care. processes avoid shared interpreter state but require values to cross a process boundary. prefer `asyncio` for coroutine-based i/o and executors for ordinary blocking callables. the thread-pool output came from real worker threads under standard cpython at build time; the in-browser sandbox cannot create threads or processes, so live runs of this page fail there."},{"slug":"networking","title":"Networking","section":"Standard Library","summary":"Networking code exchanges bytes across explicit protocol boundaries.","text":"networking network protocols move bytes, not python `str` objects. close real sockets when finished, usually with a context manager or `finally` block. use high-level http libraries for application http unless socket-level control is the lesson. the verified output came from a real `socketpair()` under standard cpython at build time; the in-browser sandbox cannot open sockets, so live runs of this page fail there."},{"slug":"datetime","title":"Dates and Times","section":"Standard Library","summary":"datetime represents dates, times, durations, formatting, and parsing.","text":"datetime use timezone-aware datetimes for instants that cross system or user boundaries. use `date` for calendar days, `time` for clock times, `datetime` for both, and `timedelta` for durations. prefer iso 8601 strings for interchange; use `strftime` for human-facing display."},{"slug":"csv-data","title":"CSV Data","section":"Standard Library","summary":"csv reads and writes row-shaped text data.","text":"csv data let `csv` handle quoting and delimiters instead of calling `split(\",\")`. csv fields are text until your code converts them. reach for json when records need nested lists, dictionaries, booleans, or numbers that preserve their type."},{"slug":"async-await","title":"Async Await","section":"Async","summary":"async def creates coroutines, and await pauses until awaitable work completes.","text":"async await calling an async function creates a coroutine object. `await` yields control until an awaitable completes. workers request handlers are async, so this pattern appears around fetches and bindings. prefer ordinary functions when there is no awaitable work to coordinate."},{"slug":"async-iteration-and-context","title":"Async Iteration and Context","section":"Async","summary":"async for and async with consume asynchronous streams and cleanup protocols.","text":"async iteration and context `async for` consumes asynchronous iterators. `async with` awaits asynchronous setup and cleanup. these forms are common around i/o-shaped resources."}] diff --git a/public/search-index.88d2f30fd230.json b/public/search-index.88d2f30fd230.json new file mode 100644 index 0000000..88b538f --- /dev/null +++ b/public/search-index.88d2f30fd230.json @@ -0,0 +1 @@ +[{"slug":"hello-world","title":"Hello World","section":"Basics","summary":"The first Python program prints a line of text.","keywords":"","text":"hello world print writes text followed by newline strings can be delimited with single or double quotes every python program starts executing statements from top to bottom calling is the smallest useful because it shows how evaluates an expression and sends standard output are ordinary values so message passed changed stored in variable produced function this example keeps first intentionally small run compare what you see source appears on which why successive calls land separate lines whole one statement string literal passes that value panel exactly line"},{"slug":"values","title":"Values","section":"Basics","summary":"Python programs evaluate expressions into objects such as text, numbers, booleans, and None.","keywords":"","text":"values are objects names point to them and operations usually create new use is none for the absence marker not this overview introduces boundaries that later pages explain in detail python program works by evaluating expressions into text integers floats booleans many richer types introduced they declarations permanently fix type produce which you can print store compare or pass functions page map whole territory equality vs identity mutable immutable truthiness literal missing key an exception start with several built does require before binding these each value still object count ratio ready true __name__ methods operators evaluate original bindings remain ordinary reuse upper boolean combine facts checked because it singleton"},{"slug":"literals","title":"Literals","section":"Basics","summary":"Literals write values directly in Python source code.","keywords":"","text":"literals are good for small local values constants better repeated with meaning is an empty dictionary use set bytes binary data string unicode text evaluates to the ellipsis object source code forms numbers containers booleans none and few specialized markers they how program writes directly literal form only beginning later examples explain each value family in depth strings lists dicts represents intentional absence when give or meaningful name so explains why that matters numeric write complex imaginary part whole fraction complex_number print imag integer also accept hexadecimal octal prefixes underscores group digits visually without changing flags xff mask b1010 million _000_000 raw keep backslashes rather than embed expressions inline python raw_pattern py score formatted container create tuples dictionaries sets answers different question about order position lookup uniqueness point names ada grace scores unique go sorted true false singleton like used truth placeholders curly brace by default not non because keyless items can be type __name__"},{"slug":"numbers","title":"Numbers","section":"Basics","summary":"Python numbers include integers, floats, and complex values.","keywords":"int float integer decimal arithmetic math","text":"numbers python int has arbitrary precision it grows as large memory allows float is approximate double floating point use for true division and floor math isclose instead of comparison reach decimal when exact the domain requirement numeric model starts with complex integers are floats values carry real imaginary parts operators encode different questions means returns gives remainder computes powers rounding display not substitute understanding approximation financial code usually needs which separate topic whole valued arithmetic even both inputs count ratio print modulo useful you need quotient behavior built in literal suffix marks part imag so between expected computed rarely right test compare or work question these same number to within tolerance import round"},{"slug":"booleans","title":"Booleans","section":"Basics","summary":"Booleans represent truth values and combine with logical operators.","keywords":"true false bool","text":"booleans boolean constants are true and false with capital letters or short circuit python does not evaluate the right side if left already determines result prefer truthiness for containers explicit comparisons when exact condition matters bool subclasses int isinstance is exclude explicitly only real integers should pass values they produced by combined logical operators that means evaluated needed which keeps guard checks efficient safe also connected to many objects can be tested in conditions even literally use facts either spells combine truth these read like english possible logged_in has_permission print produce too so compose naturally validation name ada len subclass of occasionally footgun behaves as arithmetic check must reject them value test sum is_strict_int"},{"slug":"operators","title":"Operators","section":"Basics","summary":"Operators combine, compare, and test values in expressions.","keywords":"","text":"operators use the clearest operator for question arithmetic comparison boolean logic membership identity or bitwise manipulation and short circuit so right side may not run have precedence parentheses when grouping would otherwise be hard to read is matrix multiplication no built in type implements it overloading examples shows how class gives its own meaning are punctuation keywords that combine values into expressions some compute new compare ask relationship questions such as this page surface map focused explain deeper behavior of numbers booleans conditions sets assignment by they computes answers true false truth searches container specialized should only appear data shape calls them floor division remainder powers count print produce python comparisons can chain which keeps range checks readable score py work on integer bit patterns useful masks flags ordinary exclusive shifts left b0011 b0101 b0100 walrus assigns inside an expression parenthesized part both names length passes where earns place items size len runs cannot already determine result here fail with zero error if ran but settles first last operand evaluated empty produces"},{"slug":"none","title":"None","section":"Basics","summary":"None represents expected absence, distinct from missing keys and errors.","keywords":"null nil missing","text":"none use is rather than singleton identity value for expected absence that callers can test calls only change something in place such as list sort return dictionary defaults missing mapping keys and exceptions invalid operations represents the of it usual result when call has nothing to hand back but itself meaningful because idiomatic python checks with or not this avoids confusing equality several nearby shapes lookup supply default key an operation raise exception instead returning anything here check print does its work without producing returns reorders so hands sorted data names assigning name common slip same rule applies every function examples functions finishes grace ada another boundary get one indexing profile timezone would raises keyerror reports utc"},{"slug":"variables","title":"Variables","section":"Basics","summary":"Names are bound to values with assignment.","keywords":"","text":"variables python are names bound to objects not boxes with fixed types rebinding name is normal use augmented assignment for counters and accumulators creates or rebinds it does require declaration permanently attach type the changes which object refers such as idiomatic way update clear values that matter later flexibility makes naming more important less when value needs reuse explanation prefer direct expression intermediate would add noise binds once can be used anywhere needed message hi print rebind same different attached first hello reads current binding computes an updated stores result back under count"},{"slug":"constants","title":"Constants","section":"Basics","summary":"Python uses naming conventions and optional types for values that should not change.","keywords":"","text":"constants python are convention not runtime lock use all caps names for fixed module level configuration add final when static tooling should flag accidental rebinding has no const keyword ordinary modules such as max_retries to say treat this changing state the interpreter will still let code rebind name that is why primarily an api and readability if project also uses typing can make machine checkable named remove magic values from give repeated literals one place change communicate design intent value callers comparing against instead of bare keeps meaning beside check gives limit attempts print useful literal deserves at domain boundary api_version lets type checkers reject reassignment but runs import"},{"slug":"truthiness","title":"Truthiness","section":"Basics","summary":"Python conditions use truthiness, not only explicit booleans.","keywords":"","text":"truthiness empty containers and zero like numbers are false in conditions use explicit comparisons when they communicate intent better than is one of python most important conveniences can test objects directly instead requiring boolean everywhere numeric none other values true this makes common checks such as if items concise idiomatic it reads naturally but choose the distinction matters checking whether value exactly an list so not condition tests object no len comparison needed name ada print non string asks did we get word reach for treats differently from missing has bool reveals truth any would convert to"},{"slug":"equality-and-identity","title":"Equality and Identity","section":"Data Model","summary":"== compares values, while is compares object identity.","keywords":"is == equal same object","text":"equality and identity use for ordinary value comparisons is primarily checks against singletons such as none equal mutable containers can still be independent objects never to compare numbers cpython small integer cache makes the result an implementation detail python separates from asks whether two should considered same while names point object this distinction matters because lists mutating one not imply other unless they share operator best reserved values comparison readers expect different compares list contents both refer left right print when are another name so through changes seen append singleton special integers unreliable caches roughly but larger ones large reserve small_a small_b big_a int big_b"},{"slug":"mutability","title":"Mutability","section":"Data Model","summary":"Some objects change in place, while others return new values.","keywords":"mutable immutable in-place alias aliasing","text":"mutability lists and dictionaries are mutable strings tuples immutable aliasing is useful but copy containers when independent changes needed pay attention to whether an operation mutates in place or returns new value objects python can be such as change while produce values instead names share one object so through name visible another this powerful it also the source of many beginner surprises boundary matters across append list string methods return sorted sort existing first second point same appending seen both workers print do not upper leaving original unchanged text upper_text some apis make explicit mutate numbers ordered"},{"slug":"object-lifecycle","title":"Object Lifecycle","section":"Basics","summary":"Names keep objects reachable until the last reference goes away.","keywords":"","text":"object lifecycle assignment binds names to objects it does not copy the del name removes one reference necessarily itself python reclaims unreachable automatically so lifetime bugs usually come from keeping references longer than intended live independently that refer them adds another an rebinding points somewhere else can be reclaimed only after is no reachable most programs do manually destroy they control by controlling which containers local variables and attributes still hold this example uses item list has visible state important evidence or deleting while refers two same mutating through would affect seen other box draft alias print change original reaches first until removed too published old"},{"slug":"strings","title":"Strings","section":"Text","summary":"Strings are immutable Unicode text sequences.","keywords":"str text unicode join split","text":"strings use str for text and bytes binary data len counts unicode code points encode utf encoded ascii is useful baseline because each point one byte string methods return new are immutable user visible characters can be more subtle than combining marks emoji sequences may need specialized handling python stores as so it represent english thai accented letters ordinary with the same type matters length different questions word hello uses five greeting has six but needs eighteen when you mean to only at boundaries such files network protocols apis operations upper strip instead of changing original compare three words by count take in caf two character takes abstracts over all french print indexing works not first its ord returns integer which often displayed hexadecimal teaching encoding hex turns into another system representation clean"},{"slug":"bytes-and-bytearray","title":"Bytes and Bytearray","section":"Text","summary":"bytes and bytearray store binary data, not Unicode text.","keywords":"","text":"bytes and bytearray encode text when an external boundary needs decode you want again indexing returns integers from to use binary data must be changed in place str stores unicode raw byte values the matters whenever leaves python for file network protocol subprocess or format encoding turns into with named such as utf decoding back lengths can differ because one character may require several immutable stable uses ascii characters more than many other caf print len program decoder match used at object integer value not is packet py ord"},{"slug":"string-formatting","title":"String Formatting","section":"Text","summary":"f-strings turn values into readable text at the point of use.","keywords":"f-string fstring format interpolation","text":"string formatting use strings for most new code expressions inside braces are evaluated before format specifications after control alignment width padding and precision formatted literals or exist because programs constantly need to turn values into human readable text they keep the expression next words it explains presentation details such as this separates value being computed from way should be displayed relate directly anything is then surrounding an evaluates inserts their form clearer than joining several converted by hand name ada score rank message scored print display without changing underlying here right aligned left zero pads of five characters with one decimal place row debug useful while learning logging prints both"},{"slug":"conditionals","title":"Conditionals","section":"Control Flow","summary":"if, elif, and else choose which block runs.","keywords":"if elif else branch","text":"conditionals python has no mandatory parentheses around conditions the colon and indentation define block comparison operators such as can be chained in value keep branch bodies short move larger work into functions so decision remains easy to scan if elif else let program choose one path based on condition uses show which statements belong each use truthiness booleans directly many objects empty lists or strings are considered false order branches from most specific general flat instead of nested ternary expression only when you choosing between two values start with that will test conditional is useful visible meaningful for ordered choice tests top bottom runs first matching temperature print cold comfortable hot part flow collections items reads there anything coat hat packing len either side needs multiple normal status ok danger"},{"slug":"for-loops","title":"For Loops","section":"Control Flow","summary":"for iterates over values produced by an iterable.","keywords":"loop iterate iteration range enumerate zip","text":"for loops loop consumes an iterable until it is exhausted reach while when the stopping condition must be rechecked manually iter and next expose protocol that uses internally asks values runs indented block once per value python not primarily numeric counter consumer of lists ranges files generators any object implements iterator prefer direct iteration you need each use range numbers themselves are data enumerate position both matter body execution continues after neighboring shape conditions keeps code focused on in collection name ada grace guido print yields lazily those integers thing being iterated over number usual way to keep beside without indexing back into list index start"},{"slug":"break-and-continue","title":"Break and Continue","section":"Control Flow","summary":"break exits a loop early, while continue skips to the next iteration.","keywords":"","text":"break and continue skips to the next loop iteration exits nearest enclosing immediately prefer plain if else when does not need early skip or stop behavior control they exist for loops whose body discovers an rule item level use current should run rest of no later be processed alternative is ordinary nesting keep normal path flatter easier read empty name ignored moves on value names ada grace in print after never because has already ended commands load save delete command"},{"slug":"loop-else","title":"Loop Else","section":"Control Flow","summary":"A loop else block runs only when the loop did not end with break.","keywords":"","text":"loop else runs when the was not ended by break it is best for search loops with clear found split works both and while python can have an clause name surprising at first means no happened condition false this useful searches put successful early exit in then path use sparingly clearest visibly searching something if reaches block skipped branch succeeded names ada grace guido print missing finishes without examined every value nothing linus"},{"slug":"iterating-over-iterables","title":"Iterating over Iterables","section":"Iteration","summary":"for loops consume values from any iterable object.","keywords":"enumerate zip reversed","text":"iterating over iterables for loop consumes values from an iterable different producers can feed the same protocol prefer enumerate range len when you need index python statement any object lists strings dictionaries ranges generators files and many standard library helpers this makes iteration value stream rather than special case arrays producer decides how are made them one at time use positions together dict items keys these express intent better manual indexing start with ordinary list stores asks it only iterate collection directly there is no variable because body does not names ada grace guido name in print both position produces pairs without too but clearest way to say that needs scores score"},{"slug":"iterators","title":"Iterators","section":"Iteration","summary":"iter and next expose the protocol behind for loops.","keywords":"","text":"iterators iterables produce values next consumes one value from an iterator many are pass even when the original collection is reusable iterable object that can for loop remembers where production currently iter asks and performs those steps you until exhausted this core stream protocol in python produces another piece of code them streams advances position names ada grace guido print same because two were already consumed sees only remaining name list itself asking it fresh starts new over stored again"},{"slug":"iterator-vs-iterable","title":"Iterator vs Iterable","section":"Iteration","summary":"Iterables produce fresh iterators; iterators are one-pass.","keywords":"","text":"iterator vs iterable an produces each time iter is called on it values until exhausted returns fresh the same code that traverses its input more than once must receive or materialize first this matters most for functions examples cannot know what callers will pass can produce when asked object remembers where production currently distinction because iterables be traversed many times while iterators only call itself self iteration property how loops accept either kind and also why over twice silently breaks handed instead of list takeaway api design caller may want second at boundary if you loop asks under hood so data names ada grace print one calling position tracking has been stays stream brand new rule lets shows up whenever makes two passes summing then counting works but wrong answer finds already with both matter numbers sum len items"},{"slug":"match-statements","title":"Match Statements","section":"Control Flow","summary":"match selects cases using structural pattern matching.","keywords":"switch case pattern matching","text":"match statements compares structure not just equality patterns can bind names such as and while matching mapping when the named keys are present extra in subject ignored rather than failing case put catch all last because cases tried from top to bottom structural pattern lets program choose branch based on shape of data it is especially useful commands messages or parsed have few known forms both check constants move checks action extracts one readable step order matters python tries specific shapes should appear before broad fallback use value decision this command dictionary with an coordinates first that binds print other describe valid complete fragment changes so quit broader belong after unknown final would run jump invalid"},{"slug":"advanced-match-patterns","title":"Advanced Match Patterns","section":"Control Flow","summary":"match patterns can destructure sequences, combine alternatives, and add guards.","keywords":"","text":"advanced match patterns use case as wildcard fallback guards refine pattern after the structure matches or and star keep shape based branches compact structural matching is more than equality checks can destructure sequences several alternatives capture rest of sequence these forms when data decision if only single boolean condition ordinary statements are usually clearer catches everything not matched earlier by position guard adds that must also be true command move print to unknown an accepts in one captures for exit echo hello python quit stop words join values did cases here rejects negative coordinate so same accepted falls through commands"},{"slug":"while-loops","title":"While Loops","section":"Control Flow","summary":"while repeats until changing state makes a condition false.","keywords":"loop repeat","text":"while loops use when changing state decides whether the loop continues update inside body so condition can become false prefer for you already have collection range iterator or generator to consume repeats remains true unlike which consumes an existing iterable is driven repetition where next step depends on what happened far must make progress toward stopping that might be decrementing counter reading until sentinel value waiting some external changes reach values own another iteration needed not controls here owns countdown and updates it each time through remaining print launch in liftoff stops special appears does know advance how many retries will need keeps going says stop responses iter retry ok status"},{"slug":"assignment-expressions","title":"Assignment Expressions","section":"Control Flow","summary":"The walrus operator assigns a value inside an expression.","keywords":"walrus :=","text":"assignment expressions name expression assigns and evaluates to the assigned value use it avoid computing same twice prefer normal when becomes hard scan operator while evaluating an is often called walrus testing are naturally one step separate would make code easier read boundary readability can remove duplication but should not hide important state changes computed condition tests here empty strings skipped because their length zero messages hello python for message in if len print idea works loops examples that until sentinel appears comparison stay together queue retry ok status pop"},{"slug":"sentinel-iteration","title":"Sentinel Iteration","section":"Iteration","summary":"iter(callable, sentinel) repeats calls until a marker value appears.","keywords":"","text":"sentinel iteration the callable passed to iter must take no arguments stops and is not yielded when loop needs richer branching an explicit while may be clearer calls zero argument over it yields each result until returns value itself this shape useful for repeated reads file blocks socket chunks empty response queue items stop marker removes common true plus break scaffolding body otherwise just read then process method taken from object such as popleft already fits wrap parameterized reader in lambda or functools partial underlying api parameters two form turns polling into iterator parentheses that next queued item time called string without appearing anything after left unread collections import deque py thon ignored print list equivalent manual comparison use condition more complicated than single word chunk if"},{"slug":"lists","title":"Lists","section":"Collections","summary":"Lists are ordered, mutable collections.","keywords":"array arrays sequence append","text":"lists are mutable sequences methods such as append change the list in place negative indexes count from end sorted returns new sort sorts existing python general purpose sequence type use them when order matters and collection may grow shrink or be rearranged indexing reads individual positions is first item backward mutation copying matter changes while ordered leaves original alone create with square brackets because this same object numbers print to read convenient for reading you want an copy still need afterward"},{"slug":"tuples","title":"Tuples","section":"Collections","summary":"Tuples group a fixed number of positional values.","keywords":"immutable sequence record","text":"tuples are immutable sequences with fixed length use for small records where position has meaning lists variable collections of similar items reach dataclass or namedtuple when fields deserve names everywhere they re used ordered exist groups coordinates rgb colors database rows and multiple return values the number positions is part data shape unpacking can give each useful name because you cannot append replace in place if needs to grow change list usually better fit tuple size record known turns those into at point print so indexing len work different from their item references after creation red pair naturally need graduate named ada score carry intent holds grows its own gives scores student math year subject"},{"slug":"unpacking","title":"Unpacking","section":"Collections","summary":"Unpacking binds names from sequences and mappings concisely.","keywords":"destructuring star splat","text":"unpacking starred collects the remaining values into list dictionary with is common when calling functions structured data prefer indexing you need one position naming several positions makes shape clearer binds multiple names from iterable or mapping it structure of visible at point where are introduced handles variable length sequences by collecting middle this keeps head tail patterns readable in call spreads sequence positional arguments and keyword connecting to function calls widely used configuration adapters code that bridges apis tuple assigns each name statement receives first element second assignment fails loudly if number elements disagree which catches mistakes early print however many don claim here last take ends gathers rest same works whether has four forty stars work separate format keys as so site never repeats language hand bridge between collection shaped parsed json signatures args kwargs examples shows receiving side sep ada python writes"},{"slug":"dicts","title":"Dictionaries","section":"Collections","summary":"Dictionaries map keys to values for records, lookup, and structured data.","keywords":"dictionary dictionaries mapping map hash key value lookup","text":"dicts dictionaries preserve insertion order in modern python use get when missing key has reasonable default direct indexing should be treated as an error snapshot keys with list before deleting items loop adding or removing during iteration raises runtimeerror are built mapping type they exist for data where names more meaningful than numeric positions records lookup tables counters and json like payloads is required absence expected the code fallback unlike lists answer what value belongs to this rather at position iterating keeps each next its dictionary small record fields have communicates that while profile name ada language year print timezone utc table identify values different from scores grace guido needs both it avoids looping over then back into score changed size reassigning existing allowed build of changes apply them after so deletions see stable view inventory apple pear plum if del"},{"slug":"sets","title":"Sets","section":"Collections","summary":"Sets store unique values and make membership checks explicit.","keywords":"unique membership union intersection","text":"sets use when uniqueness and membership are the main operations prefer lists order or repeated values part of meaning unordered so sort them examples need deterministic display store unique hashable de duplication matter more than list can answer with in but set communicates that is operation algebra then expresses how groups relate to each other because often wrap output sorted creating removes duplicates keep convert point languages python go unique_languages print checks everyday also says central data shape allowed rust ruby union intersection difference describe relationships between without manual loops compiled"},{"slug":"slices","title":"Slices","section":"Collections","summary":"Slices copy meaningful ranges from ordered sequences.","keywords":"slicing index range substring","text":"slices slice stop indexes are excluded so adjacent ranges compose cleanly omitted bounds mean the beginning or end of sequence negative step walks backward is common reversed copy idiom slicing reads range from an ordered with start it exists because python code often needs meaningful piece page prefix tail stride view index that convention makes lengths and line up items split without overlap return new objects for built in lists strings use indexing one item when result should still be through letters first_page rest print middle you want to skip walk these operations original list unchanged every_other reversed_letters"},{"slug":"comprehensions","title":"Comprehensions","section":"Collections","summary":"Comprehensions build collections by mapping and filtering iterables.","keywords":"list comprehension dict comprehension","text":"comprehensions the left side says what to produce for clause where values come from use an if simple filters list dict and set build concrete collections immediately switch loop when transformation needs multiple steps or explanations are expression forms building iterables read them right this value each item optionally only condition is true they best direct transformations still easy scan work several statements names explicit usually clearer dictionary eager generator expressions similar syntax stream later covered in iteration section comprehension maps input one output calls title every name collects results new ada guido grace titled print add some items should appear can transform key pairs while preserving shape scores high_scores score keeps unique here two people have same so resulting has printed through sorted because sets no display order rely on unique_scores"},{"slug":"comprehension-patterns","title":"Comprehension Patterns","section":"Collections","summary":"Comprehensions can use multiple for clauses and filters when the shape stays clear.","keywords":"","text":"comprehension patterns read clauses from left to right multiple for act like nested loops prefer an explicit loop when the stops being obvious comprehensions can contain more than one clause and if filter are in same order as use these forms only while shape remains easy scan starts needing several names comments or branches is usually better build concrete collections immediately just simpler list dict set behave leftmost outer next runs inside it colors red blue sizes variants color size print values they useful simple conditions but clearer rules need explanation numbers range filtered"},{"slug":"sorting","title":"Sorting","section":"Collections","summary":"sorted returns a new ordered list and key functions choose the sort value.","keywords":"sort sorted key reverse order","text":"sorting sorted makes new list sort mutates an existing key should return the value python compares for each item is stable so equal keys keep their original relative order accepts any iterable and returns collection left untouched which useful in expressions pipelines use to say what be compared this idiomatic way records tuples dictionaries objects by field reverse true descending instead when you intentionally want mutate place printing afterward shows that input did not change names guido ada grace print function computes compare lambda user score expression small unnamed takes one record its lambdas examples covers form here are highest first output resulting users name ranked sorts it mutation point no separate copy needed"},{"slug":"collections-module","title":"Collections Module","section":"Collections","summary":"collections provides specialized containers for common data shapes.","keywords":"counter defaultdict deque namedtuple","text":"collections module counter counts defaultdict groups deque queues and namedtuple names record fields prefer the built in containers until specialized shape makes code clearer for new structured records with defaults methods consider dataclasses instead of provides common shapes that would otherwise require repetitive plumbing use it when has name counting grouping queueing or lightweight these types are not replacements list dict tuple set they small standard library tools cases where an ordinary container hide intent behind manual bookkeeping examples below map each type to question answers is how many times did value appear from import banana print most_common key gathers multiple values missing case should create empty automatically team ada red grace blue lin append queue operations at both ends tiny immutable needs as well positions first second popleft point"},{"slug":"copying-collections","title":"Copying Collections","section":"Collections","summary":"Copies can duplicate the outer container while nested objects may still be shared.","keywords":"","text":"copying collections assignment aliases it does not copy shallow copies duplicate the outer container only deep are useful for nested independence but they can be expensive and surprising objects with external resources answers two different questions do you need new or also independent plain gives another name same object duplicates deepcopy recursively contained most python code wants deliberate rebuild use when shared state would wrong involved safe to outputs below show footgun directly has list its inner lists still collection rows ada grace alias print is creates append lovelace at level so later mutation of appear in import"},{"slug":"functions","title":"Functions","section":"Functions","summary":"Use def to name reusable behavior and return results.","keywords":"def return parameter argument docstring","text":"functions use return for values the caller should receive defaults keep common calls concise keyword arguments make options readable at call site never mutable value as default argument none and build container inside function body package behavior behind name def creates object that can accept compute result short sites easier to read reaches end without produces when calculation has useful code repeats or piece of be tested independently sends back print it store pass another greet hello python provide clear which option is being overridden format_total amount currency usd eur an explicit returns makes side effect only easy distinguish from producing ones log message saved are evaluated once defined not on each same list shared across so successive see other mutations sentinel create fresh append_broken item items append append_fixed if"},{"slug":"guard-clauses","title":"Guard Clauses","section":"Control Flow","summary":"Guard clauses handle boundary cases early so the main path stays flat.","keywords":"","text":"guard clauses are readability pattern not separate python feature they work best when the early cases true boundaries for exceptional failures raise an exception instead of returning sentinel string clause is return break or continue that handles case rest function should process point new syntax moving out way so successful path can be read straight through use guards has clear invalid empty already finished if every branch equally important ordinary elif chain may clearer contrast below shows payoff nested version makes valid live inside two conditions while names first and leaves calculation at outer indentation level correct but useful buried both tests def nested_discount price percent round discount print impossible inputs then lets sit top body guarded_discount"},{"slug":"exceptions","title":"Exceptions","section":"Errors","summary":"Use try, except, else, and finally to separate success, recovery, and cleanup.","keywords":"try except finally raise error","text":"exceptions catch the most specific exception you can else is for success code that should run only if try block did not fail finally runs whether operation succeeded or failed avoid bare except and broad they hide bugs absorb signals like keyboardinterrupt represent errors unusual conditions interrupt normal control flow marks may handles failure where recovery makes sense keep successful path separate from when no was raised while either way cleanup bookkeeping use an cannot produce valid result prefer ordinary conditionals expected branches are whenever possible programming mistakes targeted valueerror handler documents exactly what keeping in contain might def parse_int text return int number print invalid checked parsing fails raises catching explicit python swallow far more than meant to handle including two functions look interchangeable on good input divergence appears buggy call passing list error yet version converts it into quiet none lets typeerror surface safe_parse_broken safe_parse_fixed as type __name__"},{"slug":"keyword-only-arguments","title":"Keyword-only Arguments","section":"Functions","summary":"Use * to require selected function arguments to be named.","keywords":"","text":"keyword only arguments put before options that callers should name flags avoid mysterious positional true and false defaults work normally for parameters bare in function signature marks the following as must those explicitly are useful such timeouts modes where calls would be ambiguous or easy to misread they let required data stay while optional controls remain self documenting at call site after named default still apply when caller omits them def connect host timeout secure scheme https if else http print example com naming option makes explicit reader does not have remember which slot especially good because is hard interpret localhost enforced passing positionally raises typeerror instead of silently filling wrong try except error type __name__"},{"slug":"positional-only-parameters","title":"Positional-only Parameters","section":"Functions","summary":"Use / to mark parameters that callers must pass by position.","keywords":"","text":"positional only parameters marks before it as after keyword use these markers when the call shape is part of api design in function signature callers must pass those arguments by position not this useful parameter names are implementation details or an should match built functions that accept values together and let draw clear boundaries inputs ordinary options value main input while factor remains can be named def scale clamp false result if min return print makes such explicit at site here would visibly caps true restriction enforced advisory passing raises typeerror try except error type __name__"},{"slug":"args-and-kwargs","title":"Args and Kwargs","section":"Functions","summary":"*args collects extra positional arguments and **kwargs collects named ones.","keywords":"variadic star arguments","text":"args and kwargs use these tools when function naturally accepts flexible shape prefer explicit parameters the accepted arguments are known fixed is tuple dictionary let accept positional keyword they definition counterpart to unpacking at call site useful for wrappers decorators logging helpers apis that forward another should not replace clear signatures if has stable interface document expectations better than bag of collects extra into this fits functions any number similar values def total numbers return sum print named names become string keys describe metadata owner ada public true can combine put parts last so remains visible report title items scores"},{"slug":"multiple-return-values","title":"Multiple Return Values","section":"Functions","summary":"Python returns multiple values by returning a tuple and unpacking it.","keywords":"","text":"multiple return values comma creates tuple returns one containing two unpacking at the call site gives each returned position meaningful name use class like record when result has many fields python are with friendly syntax positions most callers unpack that immediately good target names make meaning of explicit this for small fixed groups results larger records dataclass or named usually communicates better returning separated by commas is visible if caller stores directly def divide_with_remainder total size quotient remainder print soon after document what means boxes leftover"},{"slug":"closures","title":"Closures","section":"Functions","summary":"Inner functions can remember values from an enclosing scope.","keywords":"","text":"closures closure keeps access to names from the scope where inner function was created each call outer can create separate remembered environment are useful for callbacks small factories and decorators bind not values capture loop variables with lambda freeze them at definition time is that remembers it this lets you configure behavior once later creates why double triple share same code but keep different factors foundation define inside another when needs remember setup returned factor def make_multiplier multiply value return print calling again uses lambdas examples one expression functions defined in all reference variable so sees its final by binding as default argument own late range append bound"},{"slug":"partial-functions","title":"Partial Functions","section":"Functions","summary":"functools.partial pre-fills arguments to make a more specific callable.","keywords":"","text":"partial functions adapts callable by pre filling arguments the resulting object can be passed anywhere with remaining parameters is expected use regular function when adapter needs more logic than argument binding functools turns general into specific remembering some positional or keyword it useful another api wants one callback but your underlying context still keeps original in func filled args and keywords prefer named wrapper adapted behavior branching validation docstring adaptation simply call this these already supplied without callers repeat same fixed every time they want specialized def apply_tax rate amount return round print stores that returns shaped for from import vat service_tax objects expose stored which helpful debugging wiring __name__"},{"slug":"scope-global-nonlocal","title":"Global and Nonlocal","section":"Functions","summary":"global and nonlocal choose which outer binding assignment should update.","keywords":"","text":"scope global nonlocal assignment inside function is local unless declared otherwise prefer for closure state and avoid module truly intended passing values returning results usually easier to test than rebinding outer names normally creates or updates name the current are explicit escape hatches outside that use when an inner should update in enclosing rarely clearer these statements affect binding not object mutation mutating shared list different from itself tells level without it count would try assign def bump_global print nearest this useful small closures keep make_counter total bump return counter"},{"slug":"recursion","title":"Recursion","section":"Functions","summary":"Recursive functions solve nested problems by calling themselves on smaller pieces.","keywords":"","text":"recursion every recursive function needs base case that stops the calls fits nested data better than flat repetition python limits depth so loops are often for very deep or simple itself to solve smaller piece of same problem exists is naturally trees menus expression nodes and directory like structures can be answered directly must move toward by passing part prefer over sequence when shape too leaf node it has no children return its own value without making another call def total subtotal child in print non solves each then combines those totals with tree"},{"slug":"lambdas","title":"Lambdas","section":"Functions","summary":"lambda creates small anonymous function expressions.","keywords":"anonymous function","text":"lambdas are expressions not statements prefer def for multi step or reused behavior common as key functions because the is local to one call lambda creates small anonymous function expression it most useful when python asks and short enough read inline can only contain use deserves name needs would be easier test separately often appear callbacks tiny adapters keep them simple that site remains clearer than named helper assigning works although usually reusable add_tax price round print idiomatic passed directly another sorted calls this once each item items notebook pen bag by_price better should explained produces same sort but gives operation return"},{"slug":"generators","title":"Generators","section":"Iteration","summary":"yield creates an iterator that produces values on demand.","keywords":"yield lazy","text":"generators generator functions are concise way to create custom iterators every is an iterator yield defers work and streams values return produces the whole result up front consumed as you iterate over it prefer list when need reuse stored results can be streamed once function convenient write your own one value pauses resumes next requested useful for pipelines large inputs infinite sequences because they avoid building entire collection in memory use request manually or loop consume until exhausted calling returns asks def countdown while numbers print repeatedly calls stops builds before handing back on demand keeps its repeated after pass countdown_eager append stream same written by hand class examples classes that needs __iter__ __next__ explicit stopiteration expresses protocol with __init__ self if raise"},{"slug":"yield-from","title":"Yield From","section":"Iteration","summary":"yield from delegates part of a generator to another iterable.","keywords":"","text":"yield from iterable yields each value that it keeps generator pipelines compact use plain when producing one directly lets every another is way to delegate part of stream mostly stitching together other iterables or sub generators the producer pipeline visible without writing nested for loop consumer still sees values delegates caller receives even though came list def page header intro body footer print delegation useful flattening row replaces an inner would item by hand flatten rows in"},{"slug":"generator-expressions","title":"Generator Expressions","section":"Iteration","summary":"Generator expressions use comprehension-like syntax to stream values lazily.","keywords":"","text":"generator expressions list dict and set comprehensions build concrete collections produce one pass iterators use when the consumer can process values at time look like with parentheses but they an iterator instead of building collection immediately them such as sum any or for loop this keeps transformation close to avoids storing intermediate lists other expression is consumed are requested create new you need another comprehension eager it builds that useful store reuse results numbers list_squares number in print lazy creates produces after two next calls only remaining squares left stream_squares common inside reducing functions argument extra be omitted"},{"slug":"itertools","title":"Itertools","section":"Iteration","summary":"itertools composes lazy iterator streams.","keywords":"chain islice product permutations combinations","text":"itertools composes producer and transformer streams iterator pipelines avoid building intermediate lists use islice to take finite piece from an infinite convert list only when you need concrete results the module contains tools for composing combining slicing grouping repeating values without changing consumer protocol many functions are lazy they describe work do later instead of immediately so helpers such as useful taking window let each step stay small one object produces another transforms them final or loop pulls through pipeline count can produce forever takes nothing is materialized until consumes import counter print chain presents several iterables stream this avoids just over combined inputs pages intro setup deploy compose with ordinary python expressions compress keeps items whose corresponding selector true scores high_scores score in"},{"slug":"decorators","title":"Decorators","section":"Functions","summary":"Decorators wrap or register functions using @ syntax.","keywords":"wrapper wraps","text":"decorators decorator is shorthand for assigning func can wrap replace or register functions use functools wraps in production wrappers that should preserve metadata callable receives function and returns replacement the syntax applies transformation at definition time are common frameworks because they handlers add behavior while keeping decorated focused on core action rebinding to return value usually so debugging help text framework introspection still see original just takes another applying it manually shows wrapping step from import def loud wrapper name upper greet hello manual_greet print python performs same after decoration welcome refers returned by message workers copies useful onto __name__ __doc__"},{"slug":"classes","title":"Classes","section":"Classes","summary":"Classes bundle data and behavior into new object types.","keywords":"object oriented oop instance self init method","text":"classes self is the instance method operating on __init__ initializes each new object class attributes are shared across instances belong to one put mutable defaults in not body use when behavior belongs with state dictionaries for looser structured data define types by bundling they useful several values and operations together should travel as alternative often dictionary plus separate functions that fine loose but gives stable api keeps next it changes methods receive keep because has its own initializer starting counter def start value first second print attached particular receiving call so increment amount return name defined directly attribute every reading falls back no of assigning itself at once step classic footgun per containers owns copy cart items add item append shared_a shared_b apple fixedcart own_a own_b"},{"slug":"inheritance-and-super","title":"Inheritance and Super","section":"Classes","summary":"Inheritance reuses behavior, and super delegates to a parent implementation.","keywords":"subclass parent base class","text":"inheritance and super models an is specialized kind of relationship calls the next implementation in method resolution order prefer composition when object only needs to use another lets one class specialize child gets parent behavior can add or override methods should extend instead replacing it entirely objects merely collaborate best really version names its parentheses dog instances get animal __init__ because does not define own initializer def self name speak return makes sound base barks pet nina print delegates reuse result then isinstance"},{"slug":"classmethods-and-staticmethods","title":"Classmethods and Staticmethods","section":"Classes","summary":"Three method shapes: instance, class, and static — each receives a different first argument.","keywords":"","text":"classmethods and staticmethods instance methods need an can be called on the class use classmethod for alternate constructors level operations that respect subclassing staticmethod only when function is truly independent of state but still belongs in namespace free often right answer neither decorator applies regular method receives as self makes receive cls instead which standard shape removes implicit first argument entirely leaving plain attached to namespacing pressure justifies decorators name organization date from_string reads better than floating parse_date is_leap_year keeps helper next it even does not any pick work depends constructor or operation happens live near its this default particular object data def __init__ year month day display return today print itself canonical parses some other input format calls because actual subclasses calling same get their own type text int part split later strips lives like touch side by nothing either demo instance_method __name__ class_method static_method no receiver"},{"slug":"dataclasses","title":"Dataclasses","section":"Classes","summary":"dataclass generates common class methods for data containers.","keywords":"record struct","text":"dataclasses type annotations define dataclass fields copy replace obj field value copies with changes before python use generate methods but remain normal classes for advanced defaults such as per instance lists or dictionaries is standard library decorator that mainly store data it generates __init__ and __repr__ from annotated reduce boilerplate while keeping explicit they are good fit simple records configuration objects values passed between layers work like class attributes appear in the generated initializer uses to an so can be constructed without writing by hand import user name str active bool true ada print still exposes ordinary regular useful filled overridden keyword representation includes names which during debugging inactive guido false builds new some changed leaves original alone was added general form of also works on named tuples dates paused"},{"slug":"properties","title":"Properties","section":"Classes","summary":"@property keeps attribute syntax while adding computation or validation.","keywords":"","text":"properties let apis start simple and grow validation or computation later callers access property like an attribute not method use methods instead when work is expensive action class keep style api while running code behind the scenes write box area but can compute value from current state setter validate assignment without changing public spelling of this boundary plain attributes are enough for data computed protected cheap operations actions with side effects should usually remain explicit read only exposes through stays because it calculated width height each time rectangle def __init__ self return _width if raise valueerror must be positive print lets normal syntax validates normalizes belongs inside every caller obey same rule invalid raises exception at try except as error"},{"slug":"special-methods","title":"Special Methods","section":"Data Model","summary":"Special methods connect your objects to Python syntax and built-ins.","keywords":"dunder magic methods","text":"special methods dunder are looked up by python data model protocols __repr__ is the developer facing form __str__ user print falls back to when missing defining __eq__ removes default __hash__ restore it type should be hashable container __contains__ __getitem__ __setitem__ __bool__ make instances behave like built in containers __call__ makes callable __enter__ __exit__ them context managers implement smallest protocol that your object feel native often called connect defined classes syntax and ins such as len iter repr implementing these lets objects participate rather than forcing callers learn custom method names for common operations good boring best way they work with language features programmers already know start normal class stores its build on ordinary instance state bag def __init__ self items list __len__ let ask size using standard return __iter__ iterable then tools can consume without name give useful representation printed or inspected no add an end str prefer repl still use keep unambiguous debugging friendly join decides what equality means comparing contents __lt__ orders those same so ordering stays consistent define one comparison functools total_ordering fill rest alone enough sorted only types you treat immutable this hashes current last two lines show hazard found set becomes unfindable once change because hash longer points at bucket was stored other isinstance tuple seen append powers power subscription truthiness if while see examples full surface item index value bool function stateful whose configuration deserves manager used focused pages go deeper multiplier factor triple trace enter exc exit false inside"},{"slug":"truth-and-size","title":"Truth and Size","section":"Data Model","summary":"__bool__ and __len__ decide how objects behave in truth tests and len().","keywords":"","text":"truth and size prefer __len__ for sized containers __bool__ when has domain meaning keep tests unsurprising surprising falsy objects make conditionals harder to read ask an object whether it should count as true usually answer through their while can with emptiness is not the right idea supports len obj also provides fallback value length zero false non more direct wins both are present use these methods match of your queue be no items account might only active regardless its balance lets class inbox def __init__ self messages list return print hi bye if but python uses bool expresses directly just container"},{"slug":"container-protocols","title":"Container Protocols","section":"Data Model","summary":"Container methods connect objects to indexing, membership, and item assignment.","keywords":"","text":"container protocols implement the narrowest protocol your object needs use keyerror and indexerror consistently with built in containers if plain dict or list is enough prefer it over custom let class behave like collection represents instead of inventing method names such as has lookup can support indexing assignment key methods are small familiar __contains__ powers __getitem__ obj __setitem__ value add only operations honestly this keeps public interface aligned python callers same syntax for records caches tables sequence objects gives to scores def __init__ self _scores name score ada print answers membership tests written return connects bracket internal storage"},{"slug":"callable-objects","title":"Callable Objects","section":"Data Model","summary":"__call__ lets an instance behave like a function while keeping state.","keywords":"","text":"callable objects obj checks whether an object can be called are good for named stateful behavior prefer plain functions when no instance state is needed not the only in python any with parentheses its class defines __call__ useful needs remembered configuration or evolving closure do this too often clearer has multiple fields methods tradeoff ceremony use function simple small captured and naming improves interface starts as ordinary stored on multiplier def __init__ self factor calls double print makes usable call syntax value return because still it remember across"},{"slug":"operator-overloading","title":"Operator Overloading","section":"Data Model","summary":"Operator methods let objects define arithmetic and comparison syntax.","keywords":"","text":"operator overloading overload operators only when the operation is unsurprising return notimplemented an operand type unsupported implement equality deliberately value comparison matters lets class define what expressions such as mean for its objects this useful part of domain vocabulary method should preserve meaning readers expect from vectors can add component by money amounts in same currency surprising overloads make code harder to trust python also has reflected methods __radd__ cases where left does not know how handle right that keeps mixed operations possible without making every other __add__ defines combines two checking and returning foreign types try instead crashing inside yours vector def __init__ self if isinstance __repr__ print __eq__ it user defined compare identity most here against unrelated answer false never raise falls back both sides decline __matmul__ which reserves matrix style multiplication no built implements so works on classes opt dot product makes results inspectable while debugging repr"},{"slug":"attribute-access","title":"Attribute Access","section":"Data Model","summary":"Attribute hooks customize lookup, missing attributes, and assignment.","keywords":"","text":"attribute access __getattr__ is narrower than __getattribute__ because it handles only missing attributes __setattr__ affects every assignment on the instance use property or descriptors when behavior attached to known name usually simple obj looks up an python exposes hooks for uncommon cases where lookup needs be customized runs normal fails which makes safer hook computed fallback so should used sparingly and carefully prefer ordinary first reach these object intentionally adapting another interface validating all assignments exposing dynamic fields starting point __init__ stores one real _values backing dictionary in next cells customize around class settings def self values dict theme dark print can provide try return except keyerror as error raise attributeerror from intercepts including ones underscore names are stored through avoids recursing your own public go value if startswith else volume"},{"slug":"bound-and-unbound-methods","title":"Bound and Unbound Methods","section":"Data Model","summary":"instance.method binds self automatically; Class.method is a plain function.","keywords":"","text":"bound and unbound methods instance method produces whose __self__ is the class plain function requires you to pass historical python term since simply which what this page demonstrates each its own object storing one captures binding implemented by descriptor protocol on when write returns callable that already remembers as self get underlying back calling it passing an yourself distinction why can be stored in collections passed callbacks called later without losing track of they belong carries so two callables produced from different instances stay independent even their same mechanism attached implements __get__ hook turns attribute access into does not need detail use but explains happening underneath through require again counter def __init__ start value increment return bound_counter print there no first argument explicitly using fresh here makes output previous cell unbound_counter type __name__ are values lists other functions handlers for range append at work lives invokes knows descriptor_counter func __dict__ rebound"},{"slug":"descriptors","title":"Descriptors","section":"Data Model","summary":"Descriptors customize attribute access through __get__, __set__, or __delete__.","keywords":"","text":"descriptors are class attributes that participate in instance attribute access data with __set__ can validate or transform assignments property is usually simpler for one off managed shine when the behavior reusable descriptor an object stored on defines __get__ __delete__ lookup finds python calls method instead of returning directly machinery behind methods validators and many orm fields use them should control classes single simple this example implements positive number validator __set_name__ learns name owner created validates writes reads value back from lives lets it learn which serving def self private_name obj if none return getattr raise valueerror must be setattr product price print assigning item reading __init__ try except as error"},{"slug":"metaclasses","title":"Metaclasses","section":"Classes","summary":"A metaclass customizes how classes themselves are created.","keywords":"","text":"metaclasses customize class creation not instance behavior directly most code should prefer decorators functions or ordinary inheritance you are likely to meet inside frameworks and orms metaclass is the of python never needs one but syntax appears in that register validate modify classes as they created keyword statement chooses object builds this advanced machinery usually simpler use only when itself problem being solved customizes __new__ receives name bases namespace before exists tagged type def mcls tag lower return super print __name__ applies building rule here adds attribute new event pass"},{"slug":"context-managers","title":"Context Managers","section":"Data Model","summary":"with ensures setup and cleanup happen together.","keywords":"with statement","text":"context managers files locks and temporary state commonly use __enter__ __exit__ power the protocol finally when cleanup must happen after errors too returning true from suppresses an exception do that only intentionally define setup around block of code with statement guarantees runs exits even is raised powered by contextlib contextmanager decorator concise way to write same idea as generator full class would be noisy production often uses for transactions resources need reliable release based manager implements value returned bound it tag def __init__ self name print return exc_type exc tb false section content writes shape before yield import try note body still raises or letting re raise allows keep propagating error valueerror boom except handled"},{"slug":"delete-statements","title":"Delete Statements","section":"Data Model","summary":"del removes bindings, items, and attributes rather than producing a value.","keywords":"","text":"delete statements del removes bindings or container entries assign none when absence should remain an explicit value use methods such as pop you need the removed back binding item it is statement not function and does return name no longer be bound mapping key sequence index mutating by removing one part this different from assigning still while slot deleting dictionary mutates gone has been set to profile ada temporary true print list that position shifts later items left current namespace rebinding cached in locals"},{"slug":"assertions","title":"Assertions","section":"Errors","summary":"assert documents internal assumptions and fails loudly when they are false.","keywords":"","text":"assertions use assert for internal invariants and debugging assumptions explicit exceptions user input files network responses other expected failures can be disabled with python optimization flags so do not rely on them security checks an assumption if the condition is false raises assertionerror optional message programmer validating or external data validation should raise ordinary that production code expects to handle make executable while keeping successful path compact when assertion true execution continues normally documents function expectation def average scores must empty return sum len print this signals broken normal recovery try except as error"},{"slug":"exception-chaining","title":"Exception Chaining","section":"Errors","summary":"raise from preserves the original cause when translating exceptions.","keywords":"","text":"exception chaining use raise from error when translating exceptions across boundary the new __cause__ points to original keeps user facing errors clear without losing debugging context connects higher level lower that caused it syntax is newerror implementation details into domain specific while preserving cause for this different hiding caller can catch and tooling still inspect low where happens then class configerror pass def read_port text try return int except valueerror as port must be number print __name__ handles remains available abc type"},{"slug":"exception-groups","title":"Exception Groups","section":"Errors","summary":"except* handles matching exceptions inside an ExceptionGroup.","keywords":"","text":"exception groups except is for exceptiongroup not ordinary single exceptions each clause handles matching members of the group often appear around concurrent work represents several unrelated raised together exists code that may receive multiple failures at once especially use one only when value being handled an and subgroup needs its own handling receives smaller containing bundles objects this different from because more than failure present errors batch failed valueerror bad port typeerror mode print len handler sees error type try raise as __name__"},{"slug":"warnings","title":"Warnings","section":"Errors","summary":"warnings report soft problems without immediately stopping the program.","keywords":"","text":"warnings use for soft problems callers can act on later exceptions when the current operation cannot continue stacklevel should point warning at caller rather than inside helper python and prefer deprecated whole functions classes call warn directly narrower cases such as one argument reports problem that know about but it does not have to stop deprecations are classic case old api still return value while telling users migrate sit between logging records operational evidence path make compatibility or correctness concerns visible according filter tests often capture so asserted instead of merely printed filters also turn into errors project wants enforce cleanup in returned matters migration notice must be import def old_name is deprecationwarning result with catch_warnings record true caught simplefilter always print category __name__ str message promote selected which useful ci calls fail build error try except became adds decorator states deprecation once definition calling function emits aimed kept __deprecated__ type checkers flag uses before program runs new_name older_name"},{"slug":"modules","title":"Modules","section":"Modules","summary":"Modules organize code into namespaces and expose reusable definitions.","keywords":"import random math standard library","text":"modules prefer plain import module when the namespace improves readability use focused imports for small number of clear names place near top file execute level code once then reuse cached object organize python into files and namespaces executes stores it in cache gives your program access to its definitions this page focuses on forms package layout aliases dynamic have their own neighboring examples such as math sqrt source name should stay visible from statistics mean imported is at call site importing prefix makes where pi came radius area print round brings one definition current keeps common operation concise without every scores are objects too attributes include metadata __name__ which records sys later instead executing again"},{"slug":"import-aliases","title":"Import Aliases","section":"Modules","summary":"as gives imported modules or names a local alias.","keywords":"","text":"import aliases module as alias keeps style access under shorter or clearer name from imports one local prefer plain unless an improves clarity follows strong convention avoid because it makes dependencies harder to see gives imported use when conventional short readability two would otherwise collide the alternative is which usually better already clear that make readers guess where came star in examples and production modules they hide blur boundary between namespace but changes here stats can still mean belongs statistics scores print __name__ with also be aliased this explains role than original math sqrt square_root"},{"slug":"packages","title":"Packages","section":"Modules","summary":"Packages organize modules into importable directories.","keywords":"","text":"packages package is module that can contain submodules dotted imports should mirror meaningful project structure use from submodule import name inside to re export names set __all__ declare the public surface prefer ordinary unless truly dynamic are modules other they let group related code behind paths such as json decoder or email message at runtime importing gives python path through in on disk usually directory with files and often an __init__ py file when one has grown into small namespace of keep boring explicit so readers tell where imported definitions come itself exposes print __name__ makes available under jsondecoder importlib import_module by string it useful for plugin systems but clearer dependency known exports root lists make visible this cell builds temporary shapes both forms concrete os sys tempfile temporarydirectory tmp pkg join makedirs open init write square area n__all__ def side return insert try finally remove pop none"},{"slug":"virtual-environments","title":"Virtual Environments","section":"Modules","summary":"Virtual environments isolate a project's Python packages.","keywords":"venv pip install packages","text":"virtual environments use python venv for everyday standard project setup isolates installed packages it does not change how imports are written this site runner uses deployment dependency model an activated shell environment that constraint is separate from the workflow you would in local projects isolate global installation and other usual command line one create activate then install dependencies there live example built declared rather than so runnable part keeps to deterministic evidence while page still teaches changes import paths language package layout rules or module names creates directory with its own interpreter entry points location after activation pip installs into another by deployed instead of subprocess sys run executable check true bin requests envbuilder exposes same creation mechanism as temporary leaving files behind pathlib tempfile temporarydirectory env_path path builder with_pip false config pyvenv cfg read_text print name home"},{"slug":"type-hints","title":"Type Hints","section":"Types","summary":"Annotations document expected types and power static analysis.","keywords":"typing annotations annotation","text":"type hints python does not enforce most at runtime tools like checkers and editors use annotations to catch mistakes earlier for unions optional or none both spellings mean the same thing reach alias when domain name reads better than raw primitive validation untrusted input must be rejected while program runs are that document expected shapes values parameters return results they exist so readers can understand api boundaries before stores many but of them communication static analysis exceptions checks required alternative an annotation is prose tests good code often uses all three important parameter still function normally def total numbers list int sum print on object introspection this information without changing call syntax __annotations__ passes string where hint says calls because body format any value label score str high pep express either result absent typing older supported spelling idea equivalent find options if in else ada grace guido from import lookup table get statement names it reused with intent keeps underlying lets talk about concept rather spells typealias deprecated since aliases page covers modern depth grade pass fail"},{"slug":"runtime-type-checks","title":"Runtime Type Checks","section":"Types","summary":"type, isinstance, and issubclass inspect runtime relationships.","keywords":"","text":"runtime type checks is exact isinstance follows inheritance inspect objects not static annotations prefer behavior protocols or clear validation over scattered real while the program running they are different from hints which mostly guide tools before runs use when class matters subclasses should count and issubclass checking relationships most apis but useful at input boundaries do turn every function into wall of calls if code only needs an object that can perform operation duck typing protocol may be clearer reports dog instance exactly animal pass pet print __name__ accepts usually what api want rather than individual"},{"slug":"union-and-optional-types","title":"Union and Optional Types","section":"Types","summary":"The | operator describes values that may have more than one static type.","keywords":"","text":"union and optional types use when value may have either type none means absence is an expected case not error by itself narrow unions before using behavior that belongs to only one member says of several static shapes int str callers pass integer or string the modern spelling for annotation documents but code still needs handle non are useful at boundaries where input flexible inside function with isinstance pattern check so rest has clear shape body should operations make sense every def label return item print accepts explicit calling methods greeting name if hello guest upper ada annotations visible runtime python does enforce them called __annotations__"},{"slug":"type-aliases","title":"Type Aliases","section":"Types","summary":"Type aliases give a meaningful name to a repeated type shape.","keywords":"","text":"type aliases use to name repeated or domain specific annotation shapes alias does not validate values at runtime newtype when two share representation but should be mixed statically gives an shape it helps readers and checkers understand the role of value without repeating long expression everywhere python supports statement for explicit older assignment style still appear in code makes intent clear creates typealiastype object create new if you need static distinction between compatible such as user ids order instead names here scores means dictionary from integer userid int dict def best_user return max key get print modern are objects that keep their introspection __name__ common they just ordinary bound existing legacyname str ada is"},{"slug":"typed-dicts","title":"TypedDict","section":"Types","summary":"TypedDict describes dictionaries with known string keys.","keywords":"","text":"typed dicts use typeddict for dictionary records from json or apis readonly python tells type checkers key must not be reassigned it does freeze the understand required and optional keys runtime behavior is still ordinary describes with known useful like data that should remain instead of becoming class instance important boundary static versus can know name string score an integer but at value dict external dataclass when your own program wants attribute access methods construction dictionaries typing import user str int def describe return record ada print plain isinstance __name__ notrequired marks treat as lookup uses normal tools such get userwithnickname nickname none added in allow code to reassign here checker accepts update would reject account id same only which are read itself accept write grace sorted __readonly_keys__"},{"slug":"structured-data-shapes","title":"Structured Data Shapes","section":"Classes","summary":"dataclass, NamedTuple, and TypedDict each model records with different trade-offs.","keywords":"","text":"structured data shapes dataclass mutable attribute access methods good default when behavior travels with typing namedtuple immutable index tuple semantics for small records that flow through unpacking typeddict runtime is dict schema type checker only json shaped collections the older untyped form of prefer version in new code and are three ways to give record name they model same but differ mutability syntax what information costs at regular class __init__ __repr__ generated you so instances accessed subclass named positions support both obj field plain lives pick shape matches problem or help benefit from should stay as boundary normal annotated fields can carry like any other dataclasses import userclass str score int ada print helper _replace produces modified copy without mutating original since assigning would fail usertuple dictionary annotations exist value behaves useful crosses an api mapping userdict __name__ identities its own literally difference drives choice whose rest program already expects isinstance"},{"slug":"literal-and-final","title":"Literal and Final","section":"Types","summary":"Literal restricts exact values, while Final marks names that should not be rebound.","keywords":"","text":"literal and final narrows values to small exact set prevents rebinding in static analysis not at runtime use enums when the option needs names behavior or iteration over members make two different promises value allowed options tells type checker that name should be rebound after its first assignment both annotations help api boundaries function can accept only known modes module publish constant other code treat as fixed python still runs same rules so these are for tools readers rather than locks closed is clearer broad str int would bug design especially constants class attributes describes reject debug mode even though it an ordinary string from typing import read write def open_label return opening print marks stronger documentation all caps convention because flag reassignment default_mode annotation lock rebinds mistake human reader"},{"slug":"callable-types","title":"Callable Types","section":"Types","summary":"Callable annotations describe functions passed as values.","keywords":"","text":"callable types use arg return for simple function shaped values the annotation documents how callback will be called complex call signatures protocols can clearer annotations describe that like functions they are useful when accepts strategy predicate or transformation int says one integer argument result helps tools and readers while runtime still only needs an object is actually shapes protocol named attributes overloaded more descriptive interface passed in by receiving from collections abc import def apply_twice value func add_one number print structural with __call__ also satisfy shape class doubler self callability separate question static checks whether python"},{"slug":"generics-and-typevar","title":"Generics and TypeVar","section":"Types","summary":"Generics preserve type information across reusable functions and classes.","keywords":"","text":"generics and typevar def first class box declare type parameters inline this syntax needs python or later str gives parameter default that is the legacy spelling of same idea still what older codebases use generic functions avoid losing information to object any when input output types are connected connect across an api plain function returns loses can say returned value has as element stands for chosen by caller in items list brackets after name says strings produces string integers integer reusable but preserves relationship between code declares variable with typing both spellings mean thing checker square so return follows print ada grace reusing expresses results each its own scoped definition pair left right tuple takes way whatever goes through __init__ get hands back recorded on nothing checks them at runtime self item none __type_params__ lets reads bare setting while int overrides it stored __default__ before had be created separately then used works common existing annotations show rather than from import last __annotations__"},{"slug":"paramspec","title":"ParamSpec","section":"Types","summary":"ParamSpec preserves callable parameter types through wrappers.","keywords":"","text":"paramspec preserves callable parameter list through transparent wrappers pair with typevar when the return type should also be preserved python accepts inline pep spelling def wrap func which declares both variables in signature itself if wrapper changes public write that new directly instead is for decorators and functions keep wrapped shape without it generic decorator often falls back to says this returns right but no longer know what arguments are valid use forwards args kwargs original function changing plain deliberately different set of parameters annotate forwarded separate keeps tied sometimes too broad ellipsis means any argument as far checker can tell from collections abc import typing erased print __name__ captures lets forward exactly logged calling decorated still runs normally benefit static tools checking add receives two integers left int"},{"slug":"overloads","title":"Overloads","section":"Types","summary":"overload describes APIs whose return type depends on argument types.","keywords":"","text":"overloads put overload declarations immediately before the implementation improve static precision they do not create runtime dispatch if all callers can work with one broad return type simple union annotation is usually enough lets checkers describe function whose depends on argument types are only promises still single that appears after them use when would be too vague for example double returns an int while ha str loses relationship at stubs cases must inspect or operate value just like any other python give tools precise call shapes integer in out string from typing import def print signatures there it accept every shape promised by annotations visible were checker __annotations__"},{"slug":"casts-and-any","title":"Casts and Any","section":"Types","summary":"Any and cast are escape hatches for places static analysis cannot prove.","keywords":"","text":"casts and any disables most static checking for value cast tells the type checker to trust you without changing runtime object prefer narrowing with checks when possible are escape hatches they useful at messy boundaries where cannot prove what is but also remove protection overused tools stop operations on treat as it returns same unchanged use another invariant already proves see that proof still whatever was actually assigned from typing import raw score score_text dict str int print does not convert or validate list __name__ real check narrows by inspecting this safer input untrusted if isinstance"},{"slug":"newtype","title":"NewType","section":"Types","summary":"NewType creates distinct static identities for runtime-compatible values.","keywords":"","text":"newtype helps type checkers distinguish values that share runtime representation at the value is still underlying use aliases for readability static separation creates distinct identity represented by an existing it useful ids units and other should not be mixed accidentally key boundary versus behavior checker can userid from orderid but both are plain integers alias when you only want clearer name shape mixing two compatible shapes treated as mistake analysis typing import int def load_user user_id str return user uid print compares like has same oid __name__ constructor keeps tools introspection"},{"slug":"protocols","title":"Protocols","section":"Types","summary":"Protocol describes required behavior for structural typing.","keywords":"","text":"protocols are for structural typing compatibility by shape rather than explicit inheritance type checkers understand normal runtime method calls still do the work prefer when shared implementation matters and only required behavior protocol describes methods or attributes an object must provide it exists if has right can treat as compatible this is different from says class explicitly derived parent callers need particular at ordinary lookup applies mainly static analysis documentation api boundaries names ellipsis marks body intentionally unspecified similar to interface declaration import greeter def greet self str print __name__ satisfy without inheriting person so __init__ name return hello ada use annotation boundary function cares that does not care about concrete welcome"},{"slug":"abstract-base-classes","title":"Abstract Base Classes","section":"Classes","summary":"ABC and abstractmethod enforce that subclasses implement required methods.","keywords":"","text":"abstract base classes abc plus abstractmethod blocks instantiation until every method has an implementation abcs are nominal subclasses opt in by inheriting isinstance reflects that protocols structural any class with the right shape qualifies regardless of inheritance prefer when shared or explicit matters protocol only behavior at api boundary and describe interface must implement refuses to instantiate concrete subclass provides which catches forgot this construction time rather than first call different from is participates contract it methods no required reach for you want mean explicitly opted care about cost small amount ceremony type level benefit half implemented cannot be created accident declares trying construct itself fails because least one lives alongside area so inherit free import def self float str return try except typeerror as error print implements can instantiated also inherits non square __init__ side forgets value adds fires not something later tries missing incomplete pass contrast hasarea accepts triangle does satisfies but both inherited typing height total_area shapes list sum"},{"slug":"enums","title":"Enums","section":"Types","summary":"Enum defines symbolic names for a fixed set of values.","keywords":"enumeration constants","text":"enums make states and choices explicit members have names values comparing enum avoids string typo bugs prefer raw strings for open ended text closed set of named defines fixed this makes modes easier to read than scattered through program each member has name value is helps avoid typos that plain would allow use when must be one small known statuses directions roles similar an symbolic underlying the what readers usually care about in code from import class status pending done current print compare with not keeps valid"},{"slug":"regular-expressions","title":"Regular Expressions","section":"Text","summary":"The re module searches and extracts text using regular expressions.","keywords":"regex re pattern match","text":"regular expressions use raw strings for regex patterns so backslashes are easier to read capturing groups when the point is extraction not just matching re match anchors at start search finds first anywhere compile saves work pattern runs more than once sub rewrites matches flags like ignorecase change behavior without rewriting reach string methods before simple compact language searching and extracting text python module provides standard interface of occurrence findall collects every reuses has structure repeated records alternatives optional parts or pieces you want capture prefer ordinary substring checks because simpler code maintain such as adjust pair them with same used repeatedly keep readable in return inside parentheses import ada grace za name score print int object exposes captured by position group check membership clearer only picking right one keeps anchoring intent visible an explicit none produces reusable gives also caches recently compiled internally practical wins readability place attach speed scoreline changing replaces replacement returns rewritten casey"},{"slug":"number-parsing","title":"Number Parsing","section":"Standard Library","summary":"int() and float() parse text into numbers and raise ValueError on bad input.","keywords":"","text":"number parsing int and float are constructors that also parse strings text base makes non decimal input explicit catch valueerror for recoverable user do not hide unexpected data corruption turns from files forms command lines or network messages into numeric objects parses whole scientific notation invalid raises specific exception when bad is expected let it fail loudly the string supposed to be trusted program accepts which useful at protocol boundaries where numbers written in hexadecimal binary another use parsed values real print pass format says ff boundary normal texts python try except skip"},{"slug":"custom-exceptions","title":"Custom Exceptions","section":"Errors","summary":"Custom exception classes name failures that belong to your domain.","keywords":"","text":"custom exceptions subclass exception for errors callers are expected to catch name can be clearer than reusing generic valueerror everywhere at boundary that recover or report clearly give names failures in your problem domain named is easier and explain error with only string message raise the point where invalid state discovered include specific occurrence recovery makes sense such as returning an response asking corrected input create when failure has class empty first emptycarterror pass print __name__ detected normal inputs still follow ordinary success path def checkout items if not cart return paid book precise type without accidentally catching unrelated try except"},{"slug":"files-and-pathlib","title":"Files and pathlib","section":"Standard Library","summary":"pathlib names files and directories, and open() reads and writes their text.","keywords":"","text":"files and pathlib path is name for place building one with does not create or open file pass encoding utf to read_text write_text so text means the same bytes everywhere use closed when block ends loop over object read line by iterdir lists directory rglob searches below it sort results order matters catch filenotfounderror at instead of trusting an earlier exists check names in system anything itself knows how join take apart ask questions such as whether reading writing are separate steps handle whole small call while gives that closes you can this page works inside temporary leaves nothing behind real programs calls on paths they were given should always rather than rely platform default operator joins into new touches disk notes be taken suffix before any import shutil tempfile from root mkdtemp txt print creates writes string returns which suits passing makes every machine first nsecond splitlines even if body raises mode appends replacing opened iterator lines each still ending its newline large processed without loading them write third number enumerate start rstrip directories too mkdir entries directly level matching pattern listing up reports summary csv total n3 sorted relative_to as_posix is_dir opening there catching usually better checking because appear vanish between rmtree removes everything missing try except error type __name__"},{"slug":"json","title":"JSON","section":"Standard Library","summary":"json encodes Python values as JSON text and decodes them back.","keywords":"serialize deserialize parse dump load","text":"json dumps returns string loads accepts true false and null become python none use sort_keys when stable text output matters only represents data shapes not arbitrary objects or behavior the module converts between values dictionaries lists strings numbers booleans map naturally to structures you need back options such as indent control readable is format way preserve encode simple at service boundaries expect decode errors incoming valid encodes keeps dictionary keys in order for reproducible import payload language versions missing print formatting change value useful human pretty splitlines decodes into becomes decoded invalid raises jsondecodeerror so input should handle failures explicitly try bad except error __class__ __name__"},{"slug":"logging","title":"Logging","section":"Standard Library","summary":"logging records operational events without using print as infrastructure.","keywords":"log logger debug","text":"logging configure once call named loggers throughout the program logger and handler levels both participate in filtering use exceptions for control flow failures operational evidence warnings soft compatibility problems records events without using print as infrastructure names where an event came from decides go formatter chooses their text shape level which are important enough to emit services command line tools scheduled jobs libraries that need diagnostics operators can filter intentional user facing output example writes stdout so page stays deterministic real applications usually handlers at startup then getlogger __name__ each module name part of produced choose how is shown import sys worker setlevel debug streamhandler info parts levelname message join setformatter propagate false hidden detail service started warning disk almost full thresholds raising suppresses later changing sites after threshold change error write failed"},{"slug":"testing","title":"Testing","section":"Standard Library","summary":"Tests make expected behavior executable and repeatable.","keywords":"unittest test assert pytest","text":"testing test method names should describe behavior not implementation details good unit is deterministic and independent of order use broader integration tests when the depends on several components working together turn expected into code that can be run again useful usually small example with clear input action assertion python unittest library provides cases assertions suites runners projects often pytest for ergonomics but same idea remains fails changes broad practice also includes fixtures property coverage this stays smallest standard loop define assert result suite inspect success starts enough to name function ordinary supplies representative def add left right return print testcase groups methods setup runs before each build per assertequal checks values assertraises asserts block raises exception type import divide if raise zerodivisionerror denominator zero class addtests self test_adds_numbers test_adds_empty_strings py test_divide_by_zero_raises in dir startswith test_ runner executes records whether every passed capturing stream keeps page output io loader defaulttestloader loadtestsfromtestcase stringio texttestrunner verbosity testsrun wassuccessful"},{"slug":"subprocesses","title":"Subprocesses","section":"Standard Library","summary":"subprocess runs external commands with explicit arguments and captured outputs.","keywords":"","text":"subprocesses use list of arguments instead shell strings when possible capture output the parent program needs to inspect it check true turns non zero exits into exceptions verified came from real child process under standard cpython at build time in browser sandbox has no table so live runs this page fail there subprocess is boundary for running external commands starts another waits and gives you result object with exit code captured python right tool calling git compilers shells or interpreter site example runner does not expose an operating system teaches proper run contract labels pretending command can here treat return as failure important between objects prepares environment then reports back through streams status spawns capture_output stores stdout stderr on text decodes them raises calledprocesserror carries portable evidence ran button cannot spawn processes pressing fails below was produced by really spawning import sys executable print strip returncode"},{"slug":"threads-and-processes","title":"Threads and Processes","section":"Standard Library","summary":"Threads share memory, while processes run in separate interpreters.","keywords":"","text":"threads and processes share memory so mutable shared state needs care avoid interpreter but require values to cross process boundary prefer asyncio for coroutine based executors ordinary blocking callables the thread pool output came from real worker under standard cpython at build time in browser sandbox cannot create or live runs of this page fail there are two ways run work outside current control path useful overlapping shaped waits while when cpu bound separate python threadpoolexecutor processpoolexecutor tools lesson site example runner does not expose native child keeps proper executor model visible separates idea what can execute here is different through async code cooperatively awaits coroutines choose smallest concurrency that matches bottleneck square across its gil map returns results input order with block joins workers body exits pressing fails was produced concurrent futures import def number return max_workers as print list heavier isolated would otherwise serialise spawn either cell only inspects class name rather than running __name__"},{"slug":"networking","title":"Networking","section":"Standard Library","summary":"Networking code exchanges bytes across explicit protocol boundaries.","keywords":"","text":"networking network protocols move bytes not python str objects close real sockets when finished usually with context manager or finally block use high level http libraries for application unless socket control is the lesson verified output came from socketpair under standard cpython at build time in browser sandbox cannot open so live runs of this page fail there code sends and receives across protocol boundaries higher clients hide many details but core rule remains text encoded before it leaves process decoded after come back version uses connected endpoints such as create_connection local deterministic demonstration site example runner does expose arbitrary os outbound calls teaches contract while making constraint explicit useful mental model endpoint plus cleanup connects two transfers byte strings must be closed conversation returns sendall writes into one end recv reads up to off other boundary whole point ping encode utf produces which what actually moves try closes both even if raises second print decode pressing run here fails pair import left right message data"},{"slug":"datetime","title":"Dates and Times","section":"Standard Library","summary":"datetime represents dates, times, durations, formatting, and parsing.","keywords":"date time timezone timedelta","text":"datetime use timezone aware datetimes for instants that cross system or user boundaries date calendar days time clock times both and timedelta durations prefer iso strings interchange strftime human facing display the module covers several related ideas together avoid ambiguity in real systems utc is clear default examples because output stays stable portable formatting parsing helpers such as fromisoformat to turn text back into objects separates dates combined import types you need explicitly day of combine them when mean an instant isoformat produces machine readable it good apis logs from release_day meeting_time created_at tzinfo print adding one another without manually changing fields expires_at hours reading iso_text t12 parsed"},{"slug":"csv-data","title":"CSV Data","section":"Standard Library","summary":"csv reads and writes row-shaped text data.","keywords":"csv spreadsheet rows","text":"csv data let handle quoting and delimiters instead of calling split fields are text until your code converts them reach for json when records need nested lists dictionaries booleans or numbers that preserve their type is row shaped each line record comma separated field arrives as string the module understands newlines so it safer than splitting lines by yourself use dictreader header names columns convert explicitly after reading dictwriter program needs to produce same shape again good fit flat tabular another structured format values types survive boundary uses dictionary keys still strings because import io name score nada ngrace rows list stringio print __name__ numeric at where leaves starts doing arithmetic sum int in turns back into with column order output newline writer fieldnames passed writeheader writerow ada true getvalue splitlines"},{"slug":"async-await","title":"Async Await","section":"Async","summary":"async def creates coroutines, and await pauses until awaitable work completes.","keywords":"asyncio coroutine concurrency","text":"async await calling an function creates coroutine object yields control until awaitable completes workers request handlers are so this pattern appears around fetches and bindings prefer ordinary functions when there is no work to coordinate def it the body runs event loop awaits or schedules pauses current another lets one make progress on other while task waits for cloudflare asynchronous understanding practical fetch calls service interactions even small example uses asyncio sleep as stand in alternative that immediately use code shaped waiting not faster replacement cpu bound python computes its result hands value straight back synchronous form baseline rest of page contrasts against slug_to_title slug return replace title print returns called has produced final yet import fetch_title __class__ __name__ close inside get eventual run starts top level main gather several awaitables their results order shape used independent operations can together titles json datetime with forms context managers iteration class implements __aenter__ __aexit__ act manager yield becomes generator dedicated examples explains protocols depth session self open false stream driver"},{"slug":"async-iteration-and-context","title":"Async Iteration and Context","section":"Async","summary":"async for and async with consume asynchronous streams and cleanup protocols.","keywords":"","text":"async iteration and context for consumes asynchronous iterators with awaits setup cleanup these forms are common around shaped resources an iterator stream whose next value may require await surrounds block appear network streams database cursors locks service clients where both wait on use ordinary when producing the or cleaning up does not need to anything syntax mirrors but protocol methods generator can before yielding each those values import asyncio def titles slug in sleep yield replace title print __name__ manager defines __aenter__ __aexit__ class session self open return exc_type exc tb close top level coroutine combines protocols resource then consume inside it main run"}] diff --git a/public/search-index.json b/public/search-index.json index 263003e..88b538f 100644 --- a/public/search-index.json +++ b/public/search-index.json @@ -1 +1 @@ -[{"slug":"hello-world","title":"Hello World","section":"Basics","summary":"The first Python program prints a line of text.","text":"hello world `print()` writes text followed by a newline. strings can be delimited with single or double quotes."},{"slug":"values","title":"Values","section":"Basics","summary":"Python programs evaluate expressions into objects such as text, numbers, booleans, and None.","text":"values values are objects; names point to them and operations usually create new values. use `is none` for the absence marker, not `== none`. this overview introduces boundaries that later pages explain in detail."},{"slug":"literals","title":"Literals","section":"Basics","summary":"Literals write values directly in Python source code.","text":"literals literals are good for small local values; constants are better for repeated values with meaning. `{}` is an empty dictionary. use `set()` for an empty set. bytes literals are binary data; string literals are unicode text. `...` evaluates to the `ellipsis` object."},{"slug":"numbers","title":"Numbers","section":"Basics","summary":"Python numbers include integers, floats, and complex values.","text":"numbers python's `int` has arbitrary precision; it grows as large as memory allows. python's `float` is approximate double-precision floating point. use `/` for true division and `//` for floor division. use `math.isclose` instead of `==` for floating-point comparison; reach for `decimal.decimal` when exact decimal precision is the domain requirement."},{"slug":"booleans","title":"Booleans","section":"Basics","summary":"Booleans represent truth values and combine with logical operators.","text":"booleans boolean constants are `true` and `false`, with capital letters. `and` and `or` short-circuit: python does not evaluate the right side if the left side already determines the result. prefer truthiness for containers and explicit comparisons when the exact boolean condition matters. `bool` subclasses `int`; `isinstance(true, int)` is `true`. exclude booleans explicitly when only \"real\" integers should pass."},{"slug":"operators","title":"Operators","section":"Basics","summary":"Operators combine, compare, and test values in expressions.","text":"operators use the clearest operator for the question: arithmetic, comparison, boolean logic, membership, identity, or bitwise manipulation. `and` and `or` short-circuit, so the right side may not run. operators have precedence; use parentheses when grouping would otherwise be hard to read. custom operator behavior should make an object feel more natural, not more clever."},{"slug":"none","title":"None","section":"Basics","summary":"None represents expected absence, distinct from missing keys and errors.","text":"none use `is none` rather than `== none`; `none` is a singleton identity value. use `none` for expected absence that callers can test. use dictionary defaults for missing mapping keys and exceptions for invalid operations."},{"slug":"variables","title":"Variables","section":"Basics","summary":"Names are bound to values with assignment.","text":"variables python variables are names bound to objects, not boxes with fixed types. rebinding a name is normal. use augmented assignment for counters and accumulators."},{"slug":"constants","title":"Constants","section":"Basics","summary":"Python uses naming conventions and optional types for values that should not change.","text":"constants python constants are a convention, not a runtime lock. use all-caps names for fixed module-level configuration. add `final` when static tooling should flag accidental rebinding."},{"slug":"truthiness","title":"Truthiness","section":"Basics","summary":"Python conditions use truthiness, not only explicit booleans.","text":"truthiness empty containers and zero-like numbers are false in conditions. use explicit comparisons when they communicate intent better than truthiness."},{"slug":"equality-and-identity","title":"Equality and Identity","section":"Data Model","summary":"== compares values, while is compares object identity.","text":"equality and identity use `==` for ordinary value comparisons. use `is` primarily for identity checks against singletons such as `none`. equal mutable containers can still be independent objects. never use `is` to compare numbers; cpython's small-integer cache makes the result an implementation detail."},{"slug":"mutability","title":"Mutability","section":"Data Model","summary":"Some objects change in place, while others return new values.","text":"mutability lists and dictionaries are mutable; strings and tuples are immutable. aliasing is useful, but copy mutable containers when independent changes are needed. pay attention to whether an operation mutates in place or returns a new value."},{"slug":"object-lifecycle","title":"Object Lifecycle","section":"Basics","summary":"Names keep objects reachable until the last reference goes away.","text":"object lifecycle assignment binds names to objects; it does not copy the object. `del name` removes one reference, not necessarily the object itself. python reclaims unreachable objects automatically, so lifetime bugs usually come from keeping references longer than intended."},{"slug":"strings","title":"Strings","section":"Text","summary":"Strings are immutable Unicode text sequences.","text":"strings use `str` for text and `bytes` for binary data. `len(text)` counts unicode code points; `len(text.encode(\"utf-8\"))` counts encoded bytes. ascii text is a useful baseline because each ascii code point is one utf-8 byte. string methods return new strings because strings are immutable. user-visible “characters” can be more subtle than code points; combining marks and emoji sequences may need specialized text handling."},{"slug":"bytes-and-bytearray","title":"Bytes and Bytearray","section":"Text","summary":"bytes and bytearray store binary data, not Unicode text.","text":"bytes and bytearray encode text when an external boundary needs bytes. decode bytes when you want text again. indexing `bytes` returns integers from 0 to 255. use `bytearray` when binary data must be changed in place."},{"slug":"string-formatting","title":"String Formatting","section":"Text","summary":"f-strings turn values into readable text at the point of use.","text":"string formatting use `f\"...\"` strings for most new formatting code. expressions inside braces are evaluated before formatting. format specifications after `:` control alignment, width, padding, and precision."},{"slug":"conditionals","title":"Conditionals","section":"Control Flow","summary":"if, elif, and else choose which block runs.","text":"conditionals python has no mandatory parentheses around conditions; the colon and indentation define the block. comparison operators such as `<` and `==` can be chained, as in `0 < value < 10`. keep branch bodies short; move larger work into functions so the decision remains easy to scan."},{"slug":"guard-clauses","title":"Guard Clauses","section":"Control Flow","summary":"Guard clauses handle boundary cases early so the main path stays flat.","text":"guard clauses guard clauses are a readability pattern, not a separate python feature. they work best when the early cases are true boundaries. for exceptional failures, raise an exception instead of returning a sentinel string."},{"slug":"assignment-expressions","title":"Assignment Expressions","section":"Control Flow","summary":"The walrus operator assigns a value inside an expression.","text":"assignment expressions `name := expression` assigns and evaluates to the assigned value. use it to avoid computing the same value twice. prefer a normal assignment when the expression becomes hard to scan."},{"slug":"for-loops","title":"For Loops","section":"Control Flow","summary":"for iterates over values produced by an iterable.","text":"for loops a `for` loop consumes an iterable until it is exhausted. reach for `while` when the stopping condition must be rechecked manually. `iter()` and `next()` expose the protocol that `for` uses internally."},{"slug":"break-and-continue","title":"Break and Continue","section":"Control Flow","summary":"break exits a loop early, while continue skips to the next iteration.","text":"break and continue `continue` skips to the next loop iteration. `break` exits the nearest enclosing loop immediately. prefer plain `if`/`else` when the loop does not need early skip or early stop behavior."},{"slug":"loop-else","title":"Loop Else","section":"Control Flow","summary":"A loop else block runs only when the loop did not end with break.","text":"loop else loop `else` runs when the loop was not ended by `break`. it is best for search loops with a clear found/not-found split. it works with both `for` and `while` loops."},{"slug":"iterating-over-iterables","title":"Iterating over Iterables","section":"Iteration","summary":"for loops consume values from any iterable object.","text":"iterating over iterables a `for` loop consumes values from an iterable. different producers can feed the same loop protocol. prefer `enumerate()` over `range(len(...))` when you need an index."},{"slug":"iterators","title":"Iterators","section":"Iteration","summary":"iter and next expose the protocol behind for loops.","text":"iterators iterables produce iterators; iterators produce values. `next()` consumes one value from an iterator. many iterators are one-pass even when the original collection is reusable."},{"slug":"iterator-vs-iterable","title":"Iterator vs Iterable","section":"Iteration","summary":"Iterables produce fresh iterators; iterators are one-pass.","text":"iterator vs iterable an iterable produces an iterator each time `iter()` is called on it; an iterator produces values until it is exhausted. `iter(iterable)` returns a fresh iterator; `iter(iterator)` returns the same iterator. functions that traverse their input more than once must accept an iterable or materialize the input at the boundary."},{"slug":"sentinel-iteration","title":"Sentinel Iteration","section":"Iteration","summary":"iter(callable, sentinel) repeats calls until a marker value appears.","text":"sentinel iteration the callable passed to `iter(callable, sentinel)` must take no arguments. the sentinel stops iteration and is not yielded. when the loop needs richer branching, an explicit `while` loop may be clearer."},{"slug":"match-statements","title":"Match Statements","section":"Control Flow","summary":"match selects cases using structural pattern matching.","text":"match statements `match` compares structure, not just equality. patterns can bind names such as `x` and `y` while matching. mapping patterns match when the named keys are present; extra keys in the subject are ignored rather than failing the case. put the catch-all `_` case last, because cases are tried from top to bottom."},{"slug":"advanced-match-patterns","title":"Advanced Match Patterns","section":"Control Flow","summary":"match patterns can destructure sequences, combine alternatives, and add guards.","text":"advanced match patterns use `case _` as a wildcard fallback. guards refine a pattern after the structure matches. or patterns and star patterns keep shape-based branches compact."},{"slug":"while-loops","title":"While Loops","section":"Control Flow","summary":"while repeats until changing state makes a condition false.","text":"while loops use `while` when changing state decides whether the loop continues. update loop state inside the body so the condition can become false. prefer `for` when you already have a collection, range, iterator, or generator to consume."},{"slug":"lists","title":"Lists","section":"Collections","summary":"Lists are ordered, mutable collections.","text":"lists lists are mutable sequences: methods such as `append()` change the list in place. negative indexes count from the end. `sorted()` returns a new list; `list.sort()` sorts the existing list in place."},{"slug":"tuples","title":"Tuples","section":"Collections","summary":"Tuples group a fixed number of positional values.","text":"tuples tuples are immutable sequences with fixed length. use tuples for small records where position has meaning. use lists for variable-length collections of similar items. reach for a dataclass or `namedtuple` when fields deserve names everywhere they're used."},{"slug":"unpacking","title":"Unpacking","section":"Collections","summary":"Unpacking binds names from sequences and mappings concisely.","text":"unpacking starred unpacking collects the remaining values into a list. dictionary unpacking with ** is common when calling functions with structured data. prefer indexing when you need one position; prefer unpacking when naming several positions makes the shape clearer."},{"slug":"dicts","title":"Dictionaries","section":"Collections","summary":"Dictionaries map keys to values for records, lookup, and structured data.","text":"dicts dictionaries preserve insertion order in modern python. use `get()` when a missing key has a reasonable default. use direct indexing when a missing key should be treated as an error. snapshot keys with `list(d.keys())` before deleting items in a loop; adding or removing keys during iteration raises `runtimeerror`."},{"slug":"sets","title":"Sets","section":"Collections","summary":"Sets store unique values and make membership checks explicit.","text":"sets use sets when uniqueness and membership are the main operations. prefer lists when order or repeated values are part of the meaning. sets are unordered, so sort them when examples need deterministic display."},{"slug":"slices","title":"Slices","section":"Collections","summary":"Slices copy meaningful ranges from ordered sequences.","text":"slices slice stop indexes are excluded, so adjacent ranges compose cleanly. omitted bounds mean the beginning or end of the sequence. a negative step walks backward; `[::-1]` is a common reversed-copy idiom."},{"slug":"comprehensions","title":"Comprehensions","section":"Collections","summary":"Comprehensions build collections by mapping and filtering iterables.","text":"comprehensions the left side says what to produce; the `for` clause says where values come from. use an `if` clause for simple filters. list, dict, and set comprehensions build concrete collections immediately. switch to a loop when the transformation needs multiple steps or explanations."},{"slug":"comprehension-patterns","title":"Comprehension Patterns","section":"Collections","summary":"Comprehensions can use multiple for clauses and filters when the shape stays clear.","text":"comprehension patterns read comprehension clauses from left to right. multiple `for` clauses act like nested loops. prefer an explicit loop when the comprehension stops being obvious."},{"slug":"sorting","title":"Sorting","section":"Collections","summary":"sorted returns a new ordered list and key functions choose the sort value.","text":"sorting `sorted()` makes a new list; `list.sort()` mutates an existing list. `key=` should return the value python compares for each item. python's sort is stable, so equal keys keep their original relative order."},{"slug":"collections-module","title":"Collections Module","section":"Collections","summary":"collections provides specialized containers for common data shapes.","text":"collections module `counter` counts, `defaultdict` groups, `deque` queues, and `namedtuple` names record fields. prefer the built-in containers until a specialized shape makes the code clearer. for new structured records with defaults and methods, consider `dataclasses` instead of `namedtuple`."},{"slug":"copying-collections","title":"Copying Collections","section":"Collections","summary":"Copies can duplicate the outer container while nested objects may still be shared.","text":"copying collections assignment aliases; it does not copy. shallow copies duplicate the outer container only. deep copies are useful for nested independence, but they can be expensive and surprising for objects with external resources."},{"slug":"functions","title":"Functions","section":"Functions","summary":"Use def to name reusable behavior and return results.","text":"functions use `return` for values the caller should receive. defaults keep common calls concise. keyword arguments make options readable at the call site. never use a mutable value as a default argument; use `none` and build the container inside the function body."},{"slug":"keyword-only-arguments","title":"Keyword-only Arguments","section":"Functions","summary":"Use * to require selected function arguments to be named.","text":"keyword only arguments put `*` before options that callers should name. keyword-only flags avoid mysterious positional `true` and `false` arguments. defaults work normally for keyword-only parameters."},{"slug":"positional-only-parameters","title":"Positional-only Parameters","section":"Functions","summary":"Use / to mark parameters that callers must pass by position.","text":"positional only parameters `/` marks parameters before it as positional-only. `*` marks parameters after it as keyword-only. use these markers when the call shape is part of the api design."},{"slug":"args-and-kwargs","title":"Args and Kwargs","section":"Functions","summary":"*args collects extra positional arguments and **kwargs collects named ones.","text":"args and kwargs use these tools when a function naturally accepts a flexible shape. prefer explicit parameters when the accepted arguments are known and fixed. `*args` is a tuple; `**kwargs` is a dictionary."},{"slug":"multiple-return-values","title":"Multiple Return Values","section":"Functions","summary":"Python returns multiple values by returning a tuple and unpacking it.","text":"multiple return values a comma creates a tuple; `return a, b` returns one tuple containing two values. unpacking at the call site gives each returned position a meaningful name. use a class-like record when the result has many fields."},{"slug":"closures","title":"Closures","section":"Functions","summary":"Inner functions can remember values from an enclosing scope.","text":"closures a closure keeps access to names from the scope where the inner function was created. each call to the outer function can create a separate remembered environment. closures are useful for callbacks, small factories, and decorators. closures bind names, not values; capture loop variables with `lambda x=x: ...` to freeze them at definition time."},{"slug":"partial-functions","title":"Partial Functions","section":"Functions","summary":"functools.partial pre-fills arguments to make a more specific callable.","text":"partial functions `partial` adapts a callable by pre-filling arguments. the resulting object can be passed anywhere a callable with the remaining parameters is expected. use a regular function when the adapter needs more logic than argument binding."},{"slug":"scope-global-nonlocal","title":"Global and Nonlocal","section":"Functions","summary":"global and nonlocal choose which outer binding assignment should update.","text":"scope global nonlocal assignment inside a function is local unless declared otherwise. prefer `nonlocal` for closure state and avoid `global` unless module state is truly intended. passing values and returning results is usually easier to test than rebinding outer names."},{"slug":"recursion","title":"Recursion","section":"Functions","summary":"Recursive functions solve nested problems by calling themselves on smaller pieces.","text":"recursion every recursive function needs a base case that stops the calls. recursion fits nested data better than flat repetition. python limits recursion depth, so loops are often better for very deep or simple repetition."},{"slug":"lambdas","title":"Lambdas","section":"Functions","summary":"lambda creates small anonymous function expressions.","text":"lambdas lambdas are expressions, not statements. prefer `def` for multi-step or reused behavior. lambdas are common as `key=` functions because the behavior is local to one call."},{"slug":"generators","title":"Generators","section":"Iteration","summary":"yield creates an iterator that produces values on demand.","text":"generators generator functions are a concise way to create custom iterators; every generator is an iterator. `yield` defers work and streams values; `return` produces the whole result up front. a generator is consumed as you iterate over it. prefer a list when you need to reuse stored results; prefer a generator when values can be streamed once."},{"slug":"yield-from","title":"Yield From","section":"Iteration","summary":"yield from delegates part of a generator to another iterable.","text":"yield from `yield from iterable` yields each value from that iterable. it keeps generator pipelines compact. use a plain `yield` when producing one value directly."},{"slug":"generator-expressions","title":"Generator Expressions","section":"Iteration","summary":"Generator expressions use comprehension-like syntax to stream values lazily.","text":"generator expressions list, dict, and set comprehensions build concrete collections. generator expressions produce one-pass iterators. use generator expressions when the consumer can process values one at a time."},{"slug":"itertools","title":"Itertools","section":"Iteration","summary":"itertools composes lazy iterator streams.","text":"itertools `itertools` composes producer and transformer streams. iterator pipelines avoid building intermediate lists. use `islice()` to take a finite piece from an infinite iterator. convert to a list only when you need concrete results."},{"slug":"decorators","title":"Decorators","section":"Functions","summary":"Decorators wrap or register functions using @ syntax.","text":"decorators `@decorator` is shorthand for assigning `func = decorator(func)`. decorators can wrap, replace, or register functions. use `functools.wraps` in production wrappers that should preserve metadata."},{"slug":"classes","title":"Classes","section":"Classes","summary":"Classes bundle data and behavior into new object types.","text":"classes `self` is the instance the method is operating on. `__init__` initializes each new object. class attributes are shared across instances; instance attributes belong to one object. put mutable defaults in `__init__`, not on the class body. use classes when behavior belongs with state; use dictionaries for looser structured data."},{"slug":"inheritance-and-super","title":"Inheritance and Super","section":"Classes","summary":"Inheritance reuses behavior, and super delegates to a parent implementation.","text":"inheritance and super inheritance models an “is a specialized kind of” relationship. `super()` calls the next implementation in the method resolution order. prefer composition when an object only needs to use another object."},{"slug":"classmethods-and-staticmethods","title":"Classmethods and Staticmethods","section":"Classes","summary":"Three method shapes: instance, class, and static — each receives a different first argument.","text":"classmethods and staticmethods instance methods need an instance; classmethods and staticmethods can be called on the class. use `@classmethod` for alternate constructors and class-level operations that respect subclassing. use `@staticmethod` only when a function is truly independent of instance and class state but still belongs in the class's namespace. a free function is often the right answer when neither decorator applies."},{"slug":"dataclasses","title":"Dataclasses","section":"Classes","summary":"dataclass generates common class methods for data containers.","text":"dataclasses type annotations define dataclass fields. dataclasses generate methods but remain normal python classes. use `field()` for advanced defaults such as per-instance lists or dictionaries."},{"slug":"properties","title":"Properties","section":"Classes","summary":"@property keeps attribute syntax while adding computation or validation.","text":"properties properties let apis start simple and grow validation or computation later. callers access a property like an attribute, not like a method. use methods instead when work is expensive or action-like."},{"slug":"special-methods","title":"Special Methods","section":"Data Model","summary":"Special methods connect your objects to Python syntax and built-ins.","text":"special methods dunder methods are looked up by python's data model protocols. `__repr__` is the developer-facing form; `__str__` is the user-facing form. `print()` falls back to `__repr__` when `__str__` is missing. defining `__eq__` removes the default `__hash__`; restore it when the type should be hashable. container protocols (`__contains__`, `__getitem__`, `__setitem__`, `__bool__`) make instances behave like built-in containers. `__call__` makes instances callable; `__enter__`/`__exit__` make them context managers. implement the smallest protocol that makes your object feel native."},{"slug":"truth-and-size","title":"Truth and Size","section":"Data Model","summary":"__bool__ and __len__ decide how objects behave in truth tests and len().","text":"truth and size prefer `__len__` for sized containers. prefer `__bool__` when truth has domain meaning. keep truth tests unsurprising; surprising falsy objects make conditionals harder to read."},{"slug":"container-protocols","title":"Container Protocols","section":"Data Model","summary":"Container methods connect objects to indexing, membership, and item assignment.","text":"container protocols implement the narrowest container protocol your object needs. use `keyerror` and `indexerror` consistently with built-in containers. if a plain `dict` or `list` is enough, prefer it over a custom container."},{"slug":"callable-objects","title":"Callable Objects","section":"Data Model","summary":"__call__ lets an instance behave like a function while keeping state.","text":"callable objects `callable(obj)` checks whether an object can be called. callable objects are good for named, stateful behavior. prefer plain functions when no instance state is needed."},{"slug":"operator-overloading","title":"Operator Overloading","section":"Data Model","summary":"Operator methods let objects define arithmetic and comparison syntax.","text":"operator overloading overload operators only when the operation is unsurprising. return `notimplemented` when an operand type is unsupported. implement equality deliberately when value comparison matters."},{"slug":"attribute-access","title":"Attribute Access","section":"Data Model","summary":"Attribute hooks customize lookup, missing attributes, and assignment.","text":"attribute access `__getattr__` is narrower than `__getattribute__` because it handles only missing attributes. `__setattr__` affects every assignment on the instance. use `property` or descriptors when the behavior is attached to a known attribute name."},{"slug":"bound-and-unbound-methods","title":"Bound and Unbound Methods","section":"Data Model","summary":"instance.method binds self automatically; Class.method is a plain function.","text":"bound and unbound methods `instance.method` produces a bound method whose `__self__` is the instance. `class.method` produces the plain function and requires you to pass the instance. \"unbound method\" is the historical python 2 term; since python 3, `class.method` is simply a function, which is what this page demonstrates. each bound method is its own object; storing one captures its instance. the binding is implemented by the descriptor protocol on the function object."},{"slug":"descriptors","title":"Descriptors","section":"Data Model","summary":"Descriptors customize attribute access through __get__, __set__, or __delete__.","text":"descriptors descriptors are class attributes that participate in instance attribute access. data descriptors with `__set__` can validate or transform assignments. `property` is usually simpler for one-off managed attributes; descriptors shine when the behavior is reusable."},{"slug":"metaclasses","title":"Metaclasses","section":"Classes","summary":"A metaclass customizes how classes themselves are created.","text":"metaclasses metaclasses customize class creation, not instance behavior directly. most code should prefer class decorators, functions, or ordinary inheritance. you are most likely to meet metaclasses inside frameworks and orms."},{"slug":"context-managers","title":"Context Managers","section":"Data Model","summary":"with ensures setup and cleanup happen together.","text":"context managers files, locks, and temporary state commonly use context managers. `__enter__` and `__exit__` power the protocol. use `finally` when cleanup must happen after errors too. returning true from `__exit__` suppresses an exception; do that only intentionally."},{"slug":"delete-statements","title":"Delete Statements","section":"Data Model","summary":"del removes bindings, items, and attributes rather than producing a value.","text":"delete statements `del` removes bindings or container entries. assign `none` when absence should remain an explicit value. use container methods such as `pop()` when you need the removed value back."},{"slug":"exceptions","title":"Exceptions","section":"Errors","summary":"Use try, except, else, and finally to separate success, recovery, and cleanup.","text":"exceptions catch the most specific exception you can. `else` is for success code that should run only if the `try` block did not fail. `finally` runs whether the operation succeeded or failed. avoid bare `except:` and broad `except exception:` — they hide bugs and absorb signals like `keyboardinterrupt`."},{"slug":"assertions","title":"Assertions","section":"Errors","summary":"assert documents internal assumptions and fails loudly when they are false.","text":"assertions use `assert` for internal invariants and debugging assumptions. use explicit exceptions for user input, files, network responses, and other expected failures. assertions can be disabled with python optimization flags, so do not rely on them for security checks."},{"slug":"exception-chaining","title":"Exception Chaining","section":"Errors","summary":"raise from preserves the original cause when translating exceptions.","text":"exception chaining use `raise ... from error` when translating exceptions across a boundary. the new exception's `__cause__` points to the original exception. chaining keeps user-facing errors clear without losing debugging context."},{"slug":"exception-groups","title":"Exception Groups","section":"Errors","summary":"except* handles matching exceptions inside an ExceptionGroup.","text":"exception groups `except*` is for `exceptiongroup`, not ordinary single exceptions. each `except*` clause handles matching members of the group. exception groups often appear around concurrent work."},{"slug":"warnings","title":"Warnings","section":"Errors","summary":"warnings report soft problems without immediately stopping the program.","text":"warnings use warnings for soft problems callers can act on later. use exceptions when the current operation cannot continue. `stacklevel` should point the warning at the caller rather than inside the helper."},{"slug":"modules","title":"Modules","section":"Modules","summary":"Modules organize code into namespaces and expose reusable definitions.","text":"modules prefer plain `import module` when the namespace improves readability. use focused imports for a small number of clear names. place imports near the top of the file. imports execute module top-level code once, then reuse the cached module object."},{"slug":"import-aliases","title":"Import Aliases","section":"Modules","summary":"as gives imported modules or names a local alias.","text":"import aliases `import module as alias` keeps module-style access under a shorter or clearer name. `from module import name as alias` imports one name under a local alias. prefer plain imports unless an alias improves clarity or follows a strong convention. avoid `from module import *` because it makes dependencies harder to see."},{"slug":"packages","title":"Packages","section":"Modules","summary":"Packages organize modules into importable directories.","text":"packages a package is a module that can contain submodules. dotted imports should mirror a meaningful project structure. use `from .submodule import name` inside a package to re-export submodule names; set `__all__` to declare the public surface. prefer ordinary imports unless the module name is truly dynamic."},{"slug":"virtual-environments","title":"Virtual Environments","section":"Modules","summary":"Virtual environments isolate a project's Python packages.","text":"virtual environments use `python -m venv .venv` for everyday standard-python project setup. a venv isolates installed packages; it does not change how imports are written. this site's runner uses a deployment dependency model, not an activated shell environment. that runner constraint is separate from the standard python `venv` workflow you would use in local projects."},{"slug":"type-hints","title":"Type Hints","section":"Types","summary":"Annotations document expected types and power static analysis.","text":"type hints python does not enforce most type hints at runtime. tools like type checkers and editors use annotations to catch mistakes earlier. use `x | y` for unions and `optional[x]` for \"x or none\"; both spellings mean the same thing. reach for a `type` alias when a domain name reads better than a raw primitive type. use runtime validation when untrusted input must be rejected while the program runs."},{"slug":"runtime-type-checks","title":"Runtime Type Checks","section":"Types","summary":"type, isinstance, and issubclass inspect runtime relationships.","text":"runtime type checks `type()` is exact; `isinstance()` follows inheritance. runtime checks inspect objects, not static annotations. prefer behavior, protocols, or clear validation over scattered type checks."},{"slug":"union-and-optional-types","title":"Union and Optional Types","section":"Types","summary":"The | operator describes values that may have more than one static type.","text":"union and optional types use `a | b` when a value may have either type. `t | none` means absence is an expected case, not an error by itself. narrow unions before using behavior that belongs to only one member type."},{"slug":"type-aliases","title":"Type Aliases","section":"Types","summary":"Type aliases give a meaningful name to a repeated type shape.","text":"type aliases use aliases to name repeated or domain-specific annotation shapes. a type alias does not validate values at runtime. use `newtype` when two values share a runtime representation but should not be mixed statically."},{"slug":"typed-dicts","title":"TypedDict","section":"Types","summary":"TypedDict describes dictionaries with known string keys.","text":"typed dicts use `typeddict` for dictionary records from json or apis. type checkers understand required and optional keys. runtime behavior is still ordinary dictionary behavior."},{"slug":"structured-data-shapes","title":"Structured Data Shapes","section":"Classes","summary":"dataclass, NamedTuple, and TypedDict each model records with different trade-offs.","text":"structured data shapes `@dataclass` — mutable, attribute access, methods; good default when behavior travels with data. `typing.namedtuple` — immutable, attribute + index access, tuple semantics; good for small records that flow through unpacking. `typing.typeddict` — runtime is `dict`, schema is type-checker-only; good for json-shaped data. `collections.namedtuple` is the older, untyped form of `namedtuple`; prefer the `typing` version in new code."},{"slug":"literal-and-final","title":"Literal and Final","section":"Types","summary":"Literal restricts exact values, while Final marks names that should not be rebound.","text":"literal and final `literal` narrows values to a small exact set. `final` prevents rebinding in static analysis, not at runtime. use enums when the option set needs names, behavior, or iteration over members."},{"slug":"callable-types","title":"Callable Types","section":"Types","summary":"Callable annotations describe functions passed as values.","text":"callable types use `callable[[arg], return]` for simple function-shaped values. the annotation documents how the callback will be called. for complex call signatures, protocols can be clearer."},{"slug":"generics-and-typevar","title":"Generics and TypeVar","section":"Types","summary":"Generics preserve type information across reusable functions and classes.","text":"generics and typevar a `typevar` stands for a type chosen by the caller. python 3.12+ also accepts the inline pep 695 spelling `def first[t](items: list[t]) -> t`, which declares the variable without a separate `typevar` line; the explicit form shown here works everywhere and reads the same way. generic functions avoid losing information to `object` or `any`. use generics when input and output types are connected."},{"slug":"paramspec","title":"ParamSpec","section":"Types","summary":"ParamSpec preserves callable parameter types through wrappers.","text":"paramspec `paramspec` preserves a callable's parameter list through transparent wrappers. pair `paramspec` with a `typevar` when the return type should also be preserved. python 3.12+ also accepts the inline pep 695 spelling `def wrap[**p, r](func: callable[p, r])`, which declares both variables in the signature itself. if the wrapper changes the public signature, write that new signature directly instead."},{"slug":"overloads","title":"Overloads","section":"Types","summary":"overload describes APIs whose return type depends on argument types.","text":"overloads put `@overload` declarations immediately before the implementation. overloads improve static precision; they do not create runtime dispatch. if all callers can work with one broad return type, a simple union annotation is usually enough."},{"slug":"casts-and-any","title":"Casts and Any","section":"Types","summary":"Any and cast are escape hatches for places static analysis cannot prove.","text":"casts and any `any` disables most static checking for a value. `cast()` tells the type checker to trust you without changing the runtime object. prefer narrowing with checks when possible."},{"slug":"newtype","title":"NewType","section":"Types","summary":"NewType creates distinct static identities for runtime-compatible values.","text":"newtype `newtype` helps type checkers distinguish values that share a runtime representation. at runtime, the value is still the underlying type. use aliases for readability; use `newtype` for static separation."},{"slug":"protocols","title":"Protocols","section":"Types","summary":"Protocol describes required behavior for structural typing.","text":"protocols protocols are for structural typing: compatibility by shape rather than explicit inheritance. type checkers understand protocols; normal runtime method calls still do the work. prefer inheritance when shared implementation matters, and protocols when only required behavior matters."},{"slug":"abstract-base-classes","title":"Abstract Base Classes","section":"Classes","summary":"ABC and abstractmethod enforce that subclasses implement required methods.","text":"abstract base classes `abc` plus `@abstractmethod` blocks instantiation until every abstract method has an implementation. abcs are nominal — subclasses opt in by inheriting; `isinstance()` reflects that opt-in. protocols are structural — any class with the right shape qualifies, regardless of inheritance. prefer an abc when shared implementation or explicit opt-in matters; prefer a protocol when only behavior at the api boundary matters."},{"slug":"enums","title":"Enums","section":"Types","summary":"Enum defines symbolic names for a fixed set of values.","text":"enums enums make states and choices explicit. members have names and values. comparing enum members avoids string typo bugs. prefer raw strings for open-ended text; prefer enums for a closed set of named choices."},{"slug":"regular-expressions","title":"Regular Expressions","section":"Text","summary":"The re module searches and extracts text using regular expressions.","text":"regular expressions use raw strings for regex patterns so backslashes are easier to read. use capturing groups when the point is extraction, not just matching. `re.match` anchors at the start; `re.search` finds the first match anywhere. `re.compile` saves work when the pattern runs more than once. `re.sub` rewrites matches; flags like `re.ignorecase` change matching behavior without rewriting the pattern. reach for string methods before regex when the pattern is simple."},{"slug":"number-parsing","title":"Number Parsing","section":"Standard Library","summary":"int() and float() parse text into numbers and raise ValueError on bad input.","text":"number parsing `int()` and `float()` are constructors that also parse strings. `int(text, base)` makes non-decimal input explicit. catch `valueerror` for recoverable user input; do not hide unexpected data corruption."},{"slug":"custom-exceptions","title":"Custom Exceptions","section":"Errors","summary":"Custom exception classes name failures that belong to your domain.","text":"custom exceptions subclass `exception` for errors callers are expected to catch. a custom exception name can be clearer than reusing a generic `valueerror` everywhere. catch custom exceptions at a boundary that can recover or report clearly."},{"slug":"json","title":"JSON","section":"Standard Library","summary":"json encodes Python values as JSON text and decodes them back.","text":"json `dumps()` returns a string; `loads()` accepts a string. json `true`, `false`, and `null` become python `true`, `false`, and `none`. use `sort_keys=true` when stable text output matters. json only represents data shapes, not arbitrary python objects or behavior."},{"slug":"logging","title":"Logging","section":"Standard Library","summary":"logging records operational events without using print as infrastructure.","text":"logging configure logging once; call named loggers throughout the program. logger and handler levels both participate in filtering. use exceptions for control flow failures, logging for operational evidence, and warnings for soft compatibility problems."},{"slug":"testing","title":"Testing","section":"Standard Library","summary":"Tests make expected behavior executable and repeatable.","text":"testing test method names should describe behavior, not implementation details. a good unit test is deterministic and independent of test order. use broader integration tests when the behavior depends on several components working together."},{"slug":"subprocesses","title":"Subprocesses","section":"Standard Library","summary":"subprocess runs external commands with explicit arguments and captured outputs.","text":"subprocesses use a list of arguments instead of shell strings when possible. capture output when the parent program needs to inspect it. `check=true` turns non-zero exits into exceptions. the verified output came from a real child process under standard cpython at build time; the in-browser sandbox has no process table, so live runs of this page fail there."},{"slug":"threads-and-processes","title":"Threads and Processes","section":"Standard Library","summary":"Threads share memory, while processes run in separate interpreters.","text":"threads and processes threads share memory, so mutable shared state needs care. processes avoid shared interpreter state but require values to cross a process boundary. prefer `asyncio` for coroutine-based i/o and executors for ordinary blocking callables. the thread-pool output came from real worker threads under standard cpython at build time; the in-browser sandbox cannot create threads or processes, so live runs of this page fail there."},{"slug":"networking","title":"Networking","section":"Standard Library","summary":"Networking code exchanges bytes across explicit protocol boundaries.","text":"networking network protocols move bytes, not python `str` objects. close real sockets when finished, usually with a context manager or `finally` block. use high-level http libraries for application http unless socket-level control is the lesson. the verified output came from a real `socketpair()` under standard cpython at build time; the in-browser sandbox cannot open sockets, so live runs of this page fail there."},{"slug":"datetime","title":"Dates and Times","section":"Standard Library","summary":"datetime represents dates, times, durations, formatting, and parsing.","text":"datetime use timezone-aware datetimes for instants that cross system or user boundaries. use `date` for calendar days, `time` for clock times, `datetime` for both, and `timedelta` for durations. prefer iso 8601 strings for interchange; use `strftime` for human-facing display."},{"slug":"csv-data","title":"CSV Data","section":"Standard Library","summary":"csv reads and writes row-shaped text data.","text":"csv data let `csv` handle quoting and delimiters instead of calling `split(\",\")`. csv fields are text until your code converts them. reach for json when records need nested lists, dictionaries, booleans, or numbers that preserve their type."},{"slug":"async-await","title":"Async Await","section":"Async","summary":"async def creates coroutines, and await pauses until awaitable work completes.","text":"async await calling an async function creates a coroutine object. `await` yields control until an awaitable completes. workers request handlers are async, so this pattern appears around fetches and bindings. prefer ordinary functions when there is no awaitable work to coordinate."},{"slug":"async-iteration-and-context","title":"Async Iteration and Context","section":"Async","summary":"async for and async with consume asynchronous streams and cleanup protocols.","text":"async iteration and context `async for` consumes asynchronous iterators. `async with` awaits asynchronous setup and cleanup. these forms are common around i/o-shaped resources."}] +[{"slug":"hello-world","title":"Hello World","section":"Basics","summary":"The first Python program prints a line of text.","keywords":"","text":"hello world print writes text followed by newline strings can be delimited with single or double quotes every python program starts executing statements from top to bottom calling is the smallest useful because it shows how evaluates an expression and sends standard output are ordinary values so message passed changed stored in variable produced function this example keeps first intentionally small run compare what you see source appears on which why successive calls land separate lines whole one statement string literal passes that value panel exactly line"},{"slug":"values","title":"Values","section":"Basics","summary":"Python programs evaluate expressions into objects such as text, numbers, booleans, and None.","keywords":"","text":"values are objects names point to them and operations usually create new use is none for the absence marker not this overview introduces boundaries that later pages explain in detail python program works by evaluating expressions into text integers floats booleans many richer types introduced they declarations permanently fix type produce which you can print store compare or pass functions page map whole territory equality vs identity mutable immutable truthiness literal missing key an exception start with several built does require before binding these each value still object count ratio ready true __name__ methods operators evaluate original bindings remain ordinary reuse upper boolean combine facts checked because it singleton"},{"slug":"literals","title":"Literals","section":"Basics","summary":"Literals write values directly in Python source code.","keywords":"","text":"literals are good for small local values constants better repeated with meaning is an empty dictionary use set bytes binary data string unicode text evaluates to the ellipsis object source code forms numbers containers booleans none and few specialized markers they how program writes directly literal form only beginning later examples explain each value family in depth strings lists dicts represents intentional absence when give or meaningful name so explains why that matters numeric write complex imaginary part whole fraction complex_number print imag integer also accept hexadecimal octal prefixes underscores group digits visually without changing flags xff mask b1010 million _000_000 raw keep backslashes rather than embed expressions inline python raw_pattern py score formatted container create tuples dictionaries sets answers different question about order position lookup uniqueness point names ada grace scores unique go sorted true false singleton like used truth placeholders curly brace by default not non because keyless items can be type __name__"},{"slug":"numbers","title":"Numbers","section":"Basics","summary":"Python numbers include integers, floats, and complex values.","keywords":"int float integer decimal arithmetic math","text":"numbers python int has arbitrary precision it grows as large memory allows float is approximate double floating point use for true division and floor math isclose instead of comparison reach decimal when exact the domain requirement numeric model starts with complex integers are floats values carry real imaginary parts operators encode different questions means returns gives remainder computes powers rounding display not substitute understanding approximation financial code usually needs which separate topic whole valued arithmetic even both inputs count ratio print modulo useful you need quotient behavior built in literal suffix marks part imag so between expected computed rarely right test compare or work question these same number to within tolerance import round"},{"slug":"booleans","title":"Booleans","section":"Basics","summary":"Booleans represent truth values and combine with logical operators.","keywords":"true false bool","text":"booleans boolean constants are true and false with capital letters or short circuit python does not evaluate the right side if left already determines result prefer truthiness for containers explicit comparisons when exact condition matters bool subclasses int isinstance is exclude explicitly only real integers should pass values they produced by combined logical operators that means evaluated needed which keeps guard checks efficient safe also connected to many objects can be tested in conditions even literally use facts either spells combine truth these read like english possible logged_in has_permission print produce too so compose naturally validation name ada len subclass of occasionally footgun behaves as arithmetic check must reject them value test sum is_strict_int"},{"slug":"operators","title":"Operators","section":"Basics","summary":"Operators combine, compare, and test values in expressions.","keywords":"","text":"operators use the clearest operator for question arithmetic comparison boolean logic membership identity or bitwise manipulation and short circuit so right side may not run have precedence parentheses when grouping would otherwise be hard to read is matrix multiplication no built in type implements it overloading examples shows how class gives its own meaning are punctuation keywords that combine values into expressions some compute new compare ask relationship questions such as this page surface map focused explain deeper behavior of numbers booleans conditions sets assignment by they computes answers true false truth searches container specialized should only appear data shape calls them floor division remainder powers count print produce python comparisons can chain which keeps range checks readable score py work on integer bit patterns useful masks flags ordinary exclusive shifts left b0011 b0101 b0100 walrus assigns inside an expression parenthesized part both names length passes where earns place items size len runs cannot already determine result here fail with zero error if ran but settles first last operand evaluated empty produces"},{"slug":"none","title":"None","section":"Basics","summary":"None represents expected absence, distinct from missing keys and errors.","keywords":"null nil missing","text":"none use is rather than singleton identity value for expected absence that callers can test calls only change something in place such as list sort return dictionary defaults missing mapping keys and exceptions invalid operations represents the of it usual result when call has nothing to hand back but itself meaningful because idiomatic python checks with or not this avoids confusing equality several nearby shapes lookup supply default key an operation raise exception instead returning anything here check print does its work without producing returns reorders so hands sorted data names assigning name common slip same rule applies every function examples functions finishes grace ada another boundary get one indexing profile timezone would raises keyerror reports utc"},{"slug":"variables","title":"Variables","section":"Basics","summary":"Names are bound to values with assignment.","keywords":"","text":"variables python are names bound to objects not boxes with fixed types rebinding name is normal use augmented assignment for counters and accumulators creates or rebinds it does require declaration permanently attach type the changes which object refers such as idiomatic way update clear values that matter later flexibility makes naming more important less when value needs reuse explanation prefer direct expression intermediate would add noise binds once can be used anywhere needed message hi print rebind same different attached first hello reads current binding computes an updated stores result back under count"},{"slug":"constants","title":"Constants","section":"Basics","summary":"Python uses naming conventions and optional types for values that should not change.","keywords":"","text":"constants python are convention not runtime lock use all caps names for fixed module level configuration add final when static tooling should flag accidental rebinding has no const keyword ordinary modules such as max_retries to say treat this changing state the interpreter will still let code rebind name that is why primarily an api and readability if project also uses typing can make machine checkable named remove magic values from give repeated literals one place change communicate design intent value callers comparing against instead of bare keeps meaning beside check gives limit attempts print useful literal deserves at domain boundary api_version lets type checkers reject reassignment but runs import"},{"slug":"truthiness","title":"Truthiness","section":"Basics","summary":"Python conditions use truthiness, not only explicit booleans.","keywords":"","text":"truthiness empty containers and zero like numbers are false in conditions use explicit comparisons when they communicate intent better than is one of python most important conveniences can test objects directly instead requiring boolean everywhere numeric none other values true this makes common checks such as if items concise idiomatic it reads naturally but choose the distinction matters checking whether value exactly an list so not condition tests object no len comparison needed name ada print non string asks did we get word reach for treats differently from missing has bool reveals truth any would convert to"},{"slug":"equality-and-identity","title":"Equality and Identity","section":"Data Model","summary":"== compares values, while is compares object identity.","keywords":"is == equal same object","text":"equality and identity use for ordinary value comparisons is primarily checks against singletons such as none equal mutable containers can still be independent objects never to compare numbers cpython small integer cache makes the result an implementation detail python separates from asks whether two should considered same while names point object this distinction matters because lists mutating one not imply other unless they share operator best reserved values comparison readers expect different compares list contents both refer left right print when are another name so through changes seen append singleton special integers unreliable caches roughly but larger ones large reserve small_a small_b big_a int big_b"},{"slug":"mutability","title":"Mutability","section":"Data Model","summary":"Some objects change in place, while others return new values.","keywords":"mutable immutable in-place alias aliasing","text":"mutability lists and dictionaries are mutable strings tuples immutable aliasing is useful but copy containers when independent changes needed pay attention to whether an operation mutates in place or returns new value objects python can be such as change while produce values instead names share one object so through name visible another this powerful it also the source of many beginner surprises boundary matters across append list string methods return sorted sort existing first second point same appending seen both workers print do not upper leaving original unchanged text upper_text some apis make explicit mutate numbers ordered"},{"slug":"object-lifecycle","title":"Object Lifecycle","section":"Basics","summary":"Names keep objects reachable until the last reference goes away.","keywords":"","text":"object lifecycle assignment binds names to objects it does not copy the del name removes one reference necessarily itself python reclaims unreachable automatically so lifetime bugs usually come from keeping references longer than intended live independently that refer them adds another an rebinding points somewhere else can be reclaimed only after is no reachable most programs do manually destroy they control by controlling which containers local variables and attributes still hold this example uses item list has visible state important evidence or deleting while refers two same mutating through would affect seen other box draft alias print change original reaches first until removed too published old"},{"slug":"strings","title":"Strings","section":"Text","summary":"Strings are immutable Unicode text sequences.","keywords":"str text unicode join split","text":"strings use str for text and bytes binary data len counts unicode code points encode utf encoded ascii is useful baseline because each point one byte string methods return new are immutable user visible characters can be more subtle than combining marks emoji sequences may need specialized handling python stores as so it represent english thai accented letters ordinary with the same type matters length different questions word hello uses five greeting has six but needs eighteen when you mean to only at boundaries such files network protocols apis operations upper strip instead of changing original compare three words by count take in caf two character takes abstracts over all french print indexing works not first its ord returns integer which often displayed hexadecimal teaching encoding hex turns into another system representation clean"},{"slug":"bytes-and-bytearray","title":"Bytes and Bytearray","section":"Text","summary":"bytes and bytearray store binary data, not Unicode text.","keywords":"","text":"bytes and bytearray encode text when an external boundary needs decode you want again indexing returns integers from to use binary data must be changed in place str stores unicode raw byte values the matters whenever leaves python for file network protocol subprocess or format encoding turns into with named such as utf decoding back lengths can differ because one character may require several immutable stable uses ascii characters more than many other caf print len program decoder match used at object integer value not is packet py ord"},{"slug":"string-formatting","title":"String Formatting","section":"Text","summary":"f-strings turn values into readable text at the point of use.","keywords":"f-string fstring format interpolation","text":"string formatting use strings for most new code expressions inside braces are evaluated before format specifications after control alignment width padding and precision formatted literals or exist because programs constantly need to turn values into human readable text they keep the expression next words it explains presentation details such as this separates value being computed from way should be displayed relate directly anything is then surrounding an evaluates inserts their form clearer than joining several converted by hand name ada score rank message scored print display without changing underlying here right aligned left zero pads of five characters with one decimal place row debug useful while learning logging prints both"},{"slug":"conditionals","title":"Conditionals","section":"Control Flow","summary":"if, elif, and else choose which block runs.","keywords":"if elif else branch","text":"conditionals python has no mandatory parentheses around conditions the colon and indentation define block comparison operators such as can be chained in value keep branch bodies short move larger work into functions so decision remains easy to scan if elif else let program choose one path based on condition uses show which statements belong each use truthiness booleans directly many objects empty lists or strings are considered false order branches from most specific general flat instead of nested ternary expression only when you choosing between two values start with that will test conditional is useful visible meaningful for ordered choice tests top bottom runs first matching temperature print cold comfortable hot part flow collections items reads there anything coat hat packing len either side needs multiple normal status ok danger"},{"slug":"for-loops","title":"For Loops","section":"Control Flow","summary":"for iterates over values produced by an iterable.","keywords":"loop iterate iteration range enumerate zip","text":"for loops loop consumes an iterable until it is exhausted reach while when the stopping condition must be rechecked manually iter and next expose protocol that uses internally asks values runs indented block once per value python not primarily numeric counter consumer of lists ranges files generators any object implements iterator prefer direct iteration you need each use range numbers themselves are data enumerate position both matter body execution continues after neighboring shape conditions keeps code focused on in collection name ada grace guido print yields lazily those integers thing being iterated over number usual way to keep beside without indexing back into list index start"},{"slug":"break-and-continue","title":"Break and Continue","section":"Control Flow","summary":"break exits a loop early, while continue skips to the next iteration.","keywords":"","text":"break and continue skips to the next loop iteration exits nearest enclosing immediately prefer plain if else when does not need early skip or stop behavior control they exist for loops whose body discovers an rule item level use current should run rest of no later be processed alternative is ordinary nesting keep normal path flatter easier read empty name ignored moves on value names ada grace in print after never because has already ended commands load save delete command"},{"slug":"loop-else","title":"Loop Else","section":"Control Flow","summary":"A loop else block runs only when the loop did not end with break.","keywords":"","text":"loop else runs when the was not ended by break it is best for search loops with clear found split works both and while python can have an clause name surprising at first means no happened condition false this useful searches put successful early exit in then path use sparingly clearest visibly searching something if reaches block skipped branch succeeded names ada grace guido print missing finishes without examined every value nothing linus"},{"slug":"iterating-over-iterables","title":"Iterating over Iterables","section":"Iteration","summary":"for loops consume values from any iterable object.","keywords":"enumerate zip reversed","text":"iterating over iterables for loop consumes values from an iterable different producers can feed the same protocol prefer enumerate range len when you need index python statement any object lists strings dictionaries ranges generators files and many standard library helpers this makes iteration value stream rather than special case arrays producer decides how are made them one at time use positions together dict items keys these express intent better manual indexing start with ordinary list stores asks it only iterate collection directly there is no variable because body does not names ada grace guido name in print both position produces pairs without too but clearest way to say that needs scores score"},{"slug":"iterators","title":"Iterators","section":"Iteration","summary":"iter and next expose the protocol behind for loops.","keywords":"","text":"iterators iterables produce values next consumes one value from an iterator many are pass even when the original collection is reusable iterable object that can for loop remembers where production currently iter asks and performs those steps you until exhausted this core stream protocol in python produces another piece of code them streams advances position names ada grace guido print same because two were already consumed sees only remaining name list itself asking it fresh starts new over stored again"},{"slug":"iterator-vs-iterable","title":"Iterator vs Iterable","section":"Iteration","summary":"Iterables produce fresh iterators; iterators are one-pass.","keywords":"","text":"iterator vs iterable an produces each time iter is called on it values until exhausted returns fresh the same code that traverses its input more than once must receive or materialize first this matters most for functions examples cannot know what callers will pass can produce when asked object remembers where production currently distinction because iterables be traversed many times while iterators only call itself self iteration property how loops accept either kind and also why over twice silently breaks handed instead of list takeaway api design caller may want second at boundary if you loop asks under hood so data names ada grace print one calling position tracking has been stays stream brand new rule lets shows up whenever makes two passes summing then counting works but wrong answer finds already with both matter numbers sum len items"},{"slug":"match-statements","title":"Match Statements","section":"Control Flow","summary":"match selects cases using structural pattern matching.","keywords":"switch case pattern matching","text":"match statements compares structure not just equality patterns can bind names such as and while matching mapping when the named keys are present extra in subject ignored rather than failing case put catch all last because cases tried from top to bottom structural pattern lets program choose branch based on shape of data it is especially useful commands messages or parsed have few known forms both check constants move checks action extracts one readable step order matters python tries specific shapes should appear before broad fallback use value decision this command dictionary with an coordinates first that binds print other describe valid complete fragment changes so quit broader belong after unknown final would run jump invalid"},{"slug":"advanced-match-patterns","title":"Advanced Match Patterns","section":"Control Flow","summary":"match patterns can destructure sequences, combine alternatives, and add guards.","keywords":"","text":"advanced match patterns use case as wildcard fallback guards refine pattern after the structure matches or and star keep shape based branches compact structural matching is more than equality checks can destructure sequences several alternatives capture rest of sequence these forms when data decision if only single boolean condition ordinary statements are usually clearer catches everything not matched earlier by position guard adds that must also be true command move print to unknown an accepts in one captures for exit echo hello python quit stop words join values did cases here rejects negative coordinate so same accepted falls through commands"},{"slug":"while-loops","title":"While Loops","section":"Control Flow","summary":"while repeats until changing state makes a condition false.","keywords":"loop repeat","text":"while loops use when changing state decides whether the loop continues update inside body so condition can become false prefer for you already have collection range iterator or generator to consume repeats remains true unlike which consumes an existing iterable is driven repetition where next step depends on what happened far must make progress toward stopping that might be decrementing counter reading until sentinel value waiting some external changes reach values own another iteration needed not controls here owns countdown and updates it each time through remaining print launch in liftoff stops special appears does know advance how many retries will need keeps going says stop responses iter retry ok status"},{"slug":"assignment-expressions","title":"Assignment Expressions","section":"Control Flow","summary":"The walrus operator assigns a value inside an expression.","keywords":"walrus :=","text":"assignment expressions name expression assigns and evaluates to the assigned value use it avoid computing same twice prefer normal when becomes hard scan operator while evaluating an is often called walrus testing are naturally one step separate would make code easier read boundary readability can remove duplication but should not hide important state changes computed condition tests here empty strings skipped because their length zero messages hello python for message in if len print idea works loops examples that until sentinel appears comparison stay together queue retry ok status pop"},{"slug":"sentinel-iteration","title":"Sentinel Iteration","section":"Iteration","summary":"iter(callable, sentinel) repeats calls until a marker value appears.","keywords":"","text":"sentinel iteration the callable passed to iter must take no arguments stops and is not yielded when loop needs richer branching an explicit while may be clearer calls zero argument over it yields each result until returns value itself this shape useful for repeated reads file blocks socket chunks empty response queue items stop marker removes common true plus break scaffolding body otherwise just read then process method taken from object such as popleft already fits wrap parameterized reader in lambda or functools partial underlying api parameters two form turns polling into iterator parentheses that next queued item time called string without appearing anything after left unread collections import deque py thon ignored print list equivalent manual comparison use condition more complicated than single word chunk if"},{"slug":"lists","title":"Lists","section":"Collections","summary":"Lists are ordered, mutable collections.","keywords":"array arrays sequence append","text":"lists are mutable sequences methods such as append change the list in place negative indexes count from end sorted returns new sort sorts existing python general purpose sequence type use them when order matters and collection may grow shrink or be rearranged indexing reads individual positions is first item backward mutation copying matter changes while ordered leaves original alone create with square brackets because this same object numbers print to read convenient for reading you want an copy still need afterward"},{"slug":"tuples","title":"Tuples","section":"Collections","summary":"Tuples group a fixed number of positional values.","keywords":"immutable sequence record","text":"tuples are immutable sequences with fixed length use for small records where position has meaning lists variable collections of similar items reach dataclass or namedtuple when fields deserve names everywhere they re used ordered exist groups coordinates rgb colors database rows and multiple return values the number positions is part data shape unpacking can give each useful name because you cannot append replace in place if needs to grow change list usually better fit tuple size record known turns those into at point print so indexing len work different from their item references after creation red pair naturally need graduate named ada score carry intent holds grows its own gives scores student math year subject"},{"slug":"unpacking","title":"Unpacking","section":"Collections","summary":"Unpacking binds names from sequences and mappings concisely.","keywords":"destructuring star splat","text":"unpacking starred collects the remaining values into list dictionary with is common when calling functions structured data prefer indexing you need one position naming several positions makes shape clearer binds multiple names from iterable or mapping it structure of visible at point where are introduced handles variable length sequences by collecting middle this keeps head tail patterns readable in call spreads sequence positional arguments and keyword connecting to function calls widely used configuration adapters code that bridges apis tuple assigns each name statement receives first element second assignment fails loudly if number elements disagree which catches mistakes early print however many don claim here last take ends gathers rest same works whether has four forty stars work separate format keys as so site never repeats language hand bridge between collection shaped parsed json signatures args kwargs examples shows receiving side sep ada python writes"},{"slug":"dicts","title":"Dictionaries","section":"Collections","summary":"Dictionaries map keys to values for records, lookup, and structured data.","keywords":"dictionary dictionaries mapping map hash key value lookup","text":"dicts dictionaries preserve insertion order in modern python use get when missing key has reasonable default direct indexing should be treated as an error snapshot keys with list before deleting items loop adding or removing during iteration raises runtimeerror are built mapping type they exist for data where names more meaningful than numeric positions records lookup tables counters and json like payloads is required absence expected the code fallback unlike lists answer what value belongs to this rather at position iterating keeps each next its dictionary small record fields have communicates that while profile name ada language year print timezone utc table identify values different from scores grace guido needs both it avoids looping over then back into score changed size reassigning existing allowed build of changes apply them after so deletions see stable view inventory apple pear plum if del"},{"slug":"sets","title":"Sets","section":"Collections","summary":"Sets store unique values and make membership checks explicit.","keywords":"unique membership union intersection","text":"sets use when uniqueness and membership are the main operations prefer lists order or repeated values part of meaning unordered so sort them examples need deterministic display store unique hashable de duplication matter more than list can answer with in but set communicates that is operation algebra then expresses how groups relate to each other because often wrap output sorted creating removes duplicates keep convert point languages python go unique_languages print checks everyday also says central data shape allowed rust ruby union intersection difference describe relationships between without manual loops compiled"},{"slug":"slices","title":"Slices","section":"Collections","summary":"Slices copy meaningful ranges from ordered sequences.","keywords":"slicing index range substring","text":"slices slice stop indexes are excluded so adjacent ranges compose cleanly omitted bounds mean the beginning or end of sequence negative step walks backward is common reversed copy idiom slicing reads range from an ordered with start it exists because python code often needs meaningful piece page prefix tail stride view index that convention makes lengths and line up items split without overlap return new objects for built in lists strings use indexing one item when result should still be through letters first_page rest print middle you want to skip walk these operations original list unchanged every_other reversed_letters"},{"slug":"comprehensions","title":"Comprehensions","section":"Collections","summary":"Comprehensions build collections by mapping and filtering iterables.","keywords":"list comprehension dict comprehension","text":"comprehensions the left side says what to produce for clause where values come from use an if simple filters list dict and set build concrete collections immediately switch loop when transformation needs multiple steps or explanations are expression forms building iterables read them right this value each item optionally only condition is true they best direct transformations still easy scan work several statements names explicit usually clearer dictionary eager generator expressions similar syntax stream later covered in iteration section comprehension maps input one output calls title every name collects results new ada guido grace titled print add some items should appear can transform key pairs while preserving shape scores high_scores score keeps unique here two people have same so resulting has printed through sorted because sets no display order rely on unique_scores"},{"slug":"comprehension-patterns","title":"Comprehension Patterns","section":"Collections","summary":"Comprehensions can use multiple for clauses and filters when the shape stays clear.","keywords":"","text":"comprehension patterns read clauses from left to right multiple for act like nested loops prefer an explicit loop when the stops being obvious comprehensions can contain more than one clause and if filter are in same order as use these forms only while shape remains easy scan starts needing several names comments or branches is usually better build concrete collections immediately just simpler list dict set behave leftmost outer next runs inside it colors red blue sizes variants color size print values they useful simple conditions but clearer rules need explanation numbers range filtered"},{"slug":"sorting","title":"Sorting","section":"Collections","summary":"sorted returns a new ordered list and key functions choose the sort value.","keywords":"sort sorted key reverse order","text":"sorting sorted makes new list sort mutates an existing key should return the value python compares for each item is stable so equal keys keep their original relative order accepts any iterable and returns collection left untouched which useful in expressions pipelines use to say what be compared this idiomatic way records tuples dictionaries objects by field reverse true descending instead when you intentionally want mutate place printing afterward shows that input did not change names guido ada grace print function computes compare lambda user score expression small unnamed takes one record its lambdas examples covers form here are highest first output resulting users name ranked sorts it mutation point no separate copy needed"},{"slug":"collections-module","title":"Collections Module","section":"Collections","summary":"collections provides specialized containers for common data shapes.","keywords":"counter defaultdict deque namedtuple","text":"collections module counter counts defaultdict groups deque queues and namedtuple names record fields prefer the built in containers until specialized shape makes code clearer for new structured records with defaults methods consider dataclasses instead of provides common shapes that would otherwise require repetitive plumbing use it when has name counting grouping queueing or lightweight these types are not replacements list dict tuple set they small standard library tools cases where an ordinary container hide intent behind manual bookkeeping examples below map each type to question answers is how many times did value appear from import banana print most_common key gathers multiple values missing case should create empty automatically team ada red grace blue lin append queue operations at both ends tiny immutable needs as well positions first second popleft point"},{"slug":"copying-collections","title":"Copying Collections","section":"Collections","summary":"Copies can duplicate the outer container while nested objects may still be shared.","keywords":"","text":"copying collections assignment aliases it does not copy shallow copies duplicate the outer container only deep are useful for nested independence but they can be expensive and surprising objects with external resources answers two different questions do you need new or also independent plain gives another name same object duplicates deepcopy recursively contained most python code wants deliberate rebuild use when shared state would wrong involved safe to outputs below show footgun directly has list its inner lists still collection rows ada grace alias print is creates append lovelace at level so later mutation of appear in import"},{"slug":"functions","title":"Functions","section":"Functions","summary":"Use def to name reusable behavior and return results.","keywords":"def return parameter argument docstring","text":"functions use return for values the caller should receive defaults keep common calls concise keyword arguments make options readable at call site never mutable value as default argument none and build container inside function body package behavior behind name def creates object that can accept compute result short sites easier to read reaches end without produces when calculation has useful code repeats or piece of be tested independently sends back print it store pass another greet hello python provide clear which option is being overridden format_total amount currency usd eur an explicit returns makes side effect only easy distinguish from producing ones log message saved are evaluated once defined not on each same list shared across so successive see other mutations sentinel create fresh append_broken item items append append_fixed if"},{"slug":"guard-clauses","title":"Guard Clauses","section":"Control Flow","summary":"Guard clauses handle boundary cases early so the main path stays flat.","keywords":"","text":"guard clauses are readability pattern not separate python feature they work best when the early cases true boundaries for exceptional failures raise an exception instead of returning sentinel string clause is return break or continue that handles case rest function should process point new syntax moving out way so successful path can be read straight through use guards has clear invalid empty already finished if every branch equally important ordinary elif chain may clearer contrast below shows payoff nested version makes valid live inside two conditions while names first and leaves calculation at outer indentation level correct but useful buried both tests def nested_discount price percent round discount print impossible inputs then lets sit top body guarded_discount"},{"slug":"exceptions","title":"Exceptions","section":"Errors","summary":"Use try, except, else, and finally to separate success, recovery, and cleanup.","keywords":"try except finally raise error","text":"exceptions catch the most specific exception you can else is for success code that should run only if try block did not fail finally runs whether operation succeeded or failed avoid bare except and broad they hide bugs absorb signals like keyboardinterrupt represent errors unusual conditions interrupt normal control flow marks may handles failure where recovery makes sense keep successful path separate from when no was raised while either way cleanup bookkeeping use an cannot produce valid result prefer ordinary conditionals expected branches are whenever possible programming mistakes targeted valueerror handler documents exactly what keeping in contain might def parse_int text return int number print invalid checked parsing fails raises catching explicit python swallow far more than meant to handle including two functions look interchangeable on good input divergence appears buggy call passing list error yet version converts it into quiet none lets typeerror surface safe_parse_broken safe_parse_fixed as type __name__"},{"slug":"keyword-only-arguments","title":"Keyword-only Arguments","section":"Functions","summary":"Use * to require selected function arguments to be named.","keywords":"","text":"keyword only arguments put before options that callers should name flags avoid mysterious positional true and false defaults work normally for parameters bare in function signature marks the following as must those explicitly are useful such timeouts modes where calls would be ambiguous or easy to misread they let required data stay while optional controls remain self documenting at call site after named default still apply when caller omits them def connect host timeout secure scheme https if else http print example com naming option makes explicit reader does not have remember which slot especially good because is hard interpret localhost enforced passing positionally raises typeerror instead of silently filling wrong try except error type __name__"},{"slug":"positional-only-parameters","title":"Positional-only Parameters","section":"Functions","summary":"Use / to mark parameters that callers must pass by position.","keywords":"","text":"positional only parameters marks before it as after keyword use these markers when the call shape is part of api design in function signature callers must pass those arguments by position not this useful parameter names are implementation details or an should match built functions that accept values together and let draw clear boundaries inputs ordinary options value main input while factor remains can be named def scale clamp false result if min return print makes such explicit at site here would visibly caps true restriction enforced advisory passing raises typeerror try except error type __name__"},{"slug":"args-and-kwargs","title":"Args and Kwargs","section":"Functions","summary":"*args collects extra positional arguments and **kwargs collects named ones.","keywords":"variadic star arguments","text":"args and kwargs use these tools when function naturally accepts flexible shape prefer explicit parameters the accepted arguments are known fixed is tuple dictionary let accept positional keyword they definition counterpart to unpacking at call site useful for wrappers decorators logging helpers apis that forward another should not replace clear signatures if has stable interface document expectations better than bag of collects extra into this fits functions any number similar values def total numbers return sum print named names become string keys describe metadata owner ada public true can combine put parts last so remains visible report title items scores"},{"slug":"multiple-return-values","title":"Multiple Return Values","section":"Functions","summary":"Python returns multiple values by returning a tuple and unpacking it.","keywords":"","text":"multiple return values comma creates tuple returns one containing two unpacking at the call site gives each returned position meaningful name use class like record when result has many fields python are with friendly syntax positions most callers unpack that immediately good target names make meaning of explicit this for small fixed groups results larger records dataclass or named usually communicates better returning separated by commas is visible if caller stores directly def divide_with_remainder total size quotient remainder print soon after document what means boxes leftover"},{"slug":"closures","title":"Closures","section":"Functions","summary":"Inner functions can remember values from an enclosing scope.","keywords":"","text":"closures closure keeps access to names from the scope where inner function was created each call outer can create separate remembered environment are useful for callbacks small factories and decorators bind not values capture loop variables with lambda freeze them at definition time is that remembers it this lets you configure behavior once later creates why double triple share same code but keep different factors foundation define inside another when needs remember setup returned factor def make_multiplier multiply value return print calling again uses lambdas examples one expression functions defined in all reference variable so sees its final by binding as default argument own late range append bound"},{"slug":"partial-functions","title":"Partial Functions","section":"Functions","summary":"functools.partial pre-fills arguments to make a more specific callable.","keywords":"","text":"partial functions adapts callable by pre filling arguments the resulting object can be passed anywhere with remaining parameters is expected use regular function when adapter needs more logic than argument binding functools turns general into specific remembering some positional or keyword it useful another api wants one callback but your underlying context still keeps original in func filled args and keywords prefer named wrapper adapted behavior branching validation docstring adaptation simply call this these already supplied without callers repeat same fixed every time they want specialized def apply_tax rate amount return round print stores that returns shaped for from import vat service_tax objects expose stored which helpful debugging wiring __name__"},{"slug":"scope-global-nonlocal","title":"Global and Nonlocal","section":"Functions","summary":"global and nonlocal choose which outer binding assignment should update.","keywords":"","text":"scope global nonlocal assignment inside function is local unless declared otherwise prefer for closure state and avoid module truly intended passing values returning results usually easier to test than rebinding outer names normally creates or updates name the current are explicit escape hatches outside that use when an inner should update in enclosing rarely clearer these statements affect binding not object mutation mutating shared list different from itself tells level without it count would try assign def bump_global print nearest this useful small closures keep make_counter total bump return counter"},{"slug":"recursion","title":"Recursion","section":"Functions","summary":"Recursive functions solve nested problems by calling themselves on smaller pieces.","keywords":"","text":"recursion every recursive function needs base case that stops the calls fits nested data better than flat repetition python limits depth so loops are often for very deep or simple itself to solve smaller piece of same problem exists is naturally trees menus expression nodes and directory like structures can be answered directly must move toward by passing part prefer over sequence when shape too leaf node it has no children return its own value without making another call def total subtotal child in print non solves each then combines those totals with tree"},{"slug":"lambdas","title":"Lambdas","section":"Functions","summary":"lambda creates small anonymous function expressions.","keywords":"anonymous function","text":"lambdas are expressions not statements prefer def for multi step or reused behavior common as key functions because the is local to one call lambda creates small anonymous function expression it most useful when python asks and short enough read inline can only contain use deserves name needs would be easier test separately often appear callbacks tiny adapters keep them simple that site remains clearer than named helper assigning works although usually reusable add_tax price round print idiomatic passed directly another sorted calls this once each item items notebook pen bag by_price better should explained produces same sort but gives operation return"},{"slug":"generators","title":"Generators","section":"Iteration","summary":"yield creates an iterator that produces values on demand.","keywords":"yield lazy","text":"generators generator functions are concise way to create custom iterators every is an iterator yield defers work and streams values return produces the whole result up front consumed as you iterate over it prefer list when need reuse stored results can be streamed once function convenient write your own one value pauses resumes next requested useful for pipelines large inputs infinite sequences because they avoid building entire collection in memory use request manually or loop consume until exhausted calling returns asks def countdown while numbers print repeatedly calls stops builds before handing back on demand keeps its repeated after pass countdown_eager append stream same written by hand class examples classes that needs __iter__ __next__ explicit stopiteration expresses protocol with __init__ self if raise"},{"slug":"yield-from","title":"Yield From","section":"Iteration","summary":"yield from delegates part of a generator to another iterable.","keywords":"","text":"yield from iterable yields each value that it keeps generator pipelines compact use plain when producing one directly lets every another is way to delegate part of stream mostly stitching together other iterables or sub generators the producer pipeline visible without writing nested for loop consumer still sees values delegates caller receives even though came list def page header intro body footer print delegation useful flattening row replaces an inner would item by hand flatten rows in"},{"slug":"generator-expressions","title":"Generator Expressions","section":"Iteration","summary":"Generator expressions use comprehension-like syntax to stream values lazily.","keywords":"","text":"generator expressions list dict and set comprehensions build concrete collections produce one pass iterators use when the consumer can process values at time look like with parentheses but they an iterator instead of building collection immediately them such as sum any or for loop this keeps transformation close to avoids storing intermediate lists other expression is consumed are requested create new you need another comprehension eager it builds that useful store reuse results numbers list_squares number in print lazy creates produces after two next calls only remaining squares left stream_squares common inside reducing functions argument extra be omitted"},{"slug":"itertools","title":"Itertools","section":"Iteration","summary":"itertools composes lazy iterator streams.","keywords":"chain islice product permutations combinations","text":"itertools composes producer and transformer streams iterator pipelines avoid building intermediate lists use islice to take finite piece from an infinite convert list only when you need concrete results the module contains tools for composing combining slicing grouping repeating values without changing consumer protocol many functions are lazy they describe work do later instead of immediately so helpers such as useful taking window let each step stay small one object produces another transforms them final or loop pulls through pipeline count can produce forever takes nothing is materialized until consumes import counter print chain presents several iterables stream this avoids just over combined inputs pages intro setup deploy compose with ordinary python expressions compress keeps items whose corresponding selector true scores high_scores score in"},{"slug":"decorators","title":"Decorators","section":"Functions","summary":"Decorators wrap or register functions using @ syntax.","keywords":"wrapper wraps","text":"decorators decorator is shorthand for assigning func can wrap replace or register functions use functools wraps in production wrappers that should preserve metadata callable receives function and returns replacement the syntax applies transformation at definition time are common frameworks because they handlers add behavior while keeping decorated focused on core action rebinding to return value usually so debugging help text framework introspection still see original just takes another applying it manually shows wrapping step from import def loud wrapper name upper greet hello manual_greet print python performs same after decoration welcome refers returned by message workers copies useful onto __name__ __doc__"},{"slug":"classes","title":"Classes","section":"Classes","summary":"Classes bundle data and behavior into new object types.","keywords":"object oriented oop instance self init method","text":"classes self is the instance method operating on __init__ initializes each new object class attributes are shared across instances belong to one put mutable defaults in not body use when behavior belongs with state dictionaries for looser structured data define types by bundling they useful several values and operations together should travel as alternative often dictionary plus separate functions that fine loose but gives stable api keeps next it changes methods receive keep because has its own initializer starting counter def start value first second print attached particular receiving call so increment amount return name defined directly attribute every reading falls back no of assigning itself at once step classic footgun per containers owns copy cart items add item append shared_a shared_b apple fixedcart own_a own_b"},{"slug":"inheritance-and-super","title":"Inheritance and Super","section":"Classes","summary":"Inheritance reuses behavior, and super delegates to a parent implementation.","keywords":"subclass parent base class","text":"inheritance and super models an is specialized kind of relationship calls the next implementation in method resolution order prefer composition when object only needs to use another lets one class specialize child gets parent behavior can add or override methods should extend instead replacing it entirely objects merely collaborate best really version names its parentheses dog instances get animal __init__ because does not define own initializer def self name speak return makes sound base barks pet nina print delegates reuse result then isinstance"},{"slug":"classmethods-and-staticmethods","title":"Classmethods and Staticmethods","section":"Classes","summary":"Three method shapes: instance, class, and static — each receives a different first argument.","keywords":"","text":"classmethods and staticmethods instance methods need an can be called on the class use classmethod for alternate constructors level operations that respect subclassing staticmethod only when function is truly independent of state but still belongs in namespace free often right answer neither decorator applies regular method receives as self makes receive cls instead which standard shape removes implicit first argument entirely leaving plain attached to namespacing pressure justifies decorators name organization date from_string reads better than floating parse_date is_leap_year keeps helper next it even does not any pick work depends constructor or operation happens live near its this default particular object data def __init__ year month day display return today print itself canonical parses some other input format calls because actual subclasses calling same get their own type text int part split later strips lives like touch side by nothing either demo instance_method __name__ class_method static_method no receiver"},{"slug":"dataclasses","title":"Dataclasses","section":"Classes","summary":"dataclass generates common class methods for data containers.","keywords":"record struct","text":"dataclasses type annotations define dataclass fields copy replace obj field value copies with changes before python use generate methods but remain normal classes for advanced defaults such as per instance lists or dictionaries is standard library decorator that mainly store data it generates __init__ and __repr__ from annotated reduce boilerplate while keeping explicit they are good fit simple records configuration objects values passed between layers work like class attributes appear in the generated initializer uses to an so can be constructed without writing by hand import user name str active bool true ada print still exposes ordinary regular useful filled overridden keyword representation includes names which during debugging inactive guido false builds new some changed leaves original alone was added general form of also works on named tuples dates paused"},{"slug":"properties","title":"Properties","section":"Classes","summary":"@property keeps attribute syntax while adding computation or validation.","keywords":"","text":"properties let apis start simple and grow validation or computation later callers access property like an attribute not method use methods instead when work is expensive action class keep style api while running code behind the scenes write box area but can compute value from current state setter validate assignment without changing public spelling of this boundary plain attributes are enough for data computed protected cheap operations actions with side effects should usually remain explicit read only exposes through stays because it calculated width height each time rectangle def __init__ self return _width if raise valueerror must be positive print lets normal syntax validates normalizes belongs inside every caller obey same rule invalid raises exception at try except as error"},{"slug":"special-methods","title":"Special Methods","section":"Data Model","summary":"Special methods connect your objects to Python syntax and built-ins.","keywords":"dunder magic methods","text":"special methods dunder are looked up by python data model protocols __repr__ is the developer facing form __str__ user print falls back to when missing defining __eq__ removes default __hash__ restore it type should be hashable container __contains__ __getitem__ __setitem__ __bool__ make instances behave like built in containers __call__ makes callable __enter__ __exit__ them context managers implement smallest protocol that your object feel native often called connect defined classes syntax and ins such as len iter repr implementing these lets objects participate rather than forcing callers learn custom method names for common operations good boring best way they work with language features programmers already know start normal class stores its build on ordinary instance state bag def __init__ self items list __len__ let ask size using standard return __iter__ iterable then tools can consume without name give useful representation printed or inspected no add an end str prefer repl still use keep unambiguous debugging friendly join decides what equality means comparing contents __lt__ orders those same so ordering stays consistent define one comparison functools total_ordering fill rest alone enough sorted only types you treat immutable this hashes current last two lines show hazard found set becomes unfindable once change because hash longer points at bucket was stored other isinstance tuple seen append powers power subscription truthiness if while see examples full surface item index value bool function stateful whose configuration deserves manager used focused pages go deeper multiplier factor triple trace enter exc exit false inside"},{"slug":"truth-and-size","title":"Truth and Size","section":"Data Model","summary":"__bool__ and __len__ decide how objects behave in truth tests and len().","keywords":"","text":"truth and size prefer __len__ for sized containers __bool__ when has domain meaning keep tests unsurprising surprising falsy objects make conditionals harder to read ask an object whether it should count as true usually answer through their while can with emptiness is not the right idea supports len obj also provides fallback value length zero false non more direct wins both are present use these methods match of your queue be no items account might only active regardless its balance lets class inbox def __init__ self messages list return print hi bye if but python uses bool expresses directly just container"},{"slug":"container-protocols","title":"Container Protocols","section":"Data Model","summary":"Container methods connect objects to indexing, membership, and item assignment.","keywords":"","text":"container protocols implement the narrowest protocol your object needs use keyerror and indexerror consistently with built in containers if plain dict or list is enough prefer it over custom let class behave like collection represents instead of inventing method names such as has lookup can support indexing assignment key methods are small familiar __contains__ powers __getitem__ obj __setitem__ value add only operations honestly this keeps public interface aligned python callers same syntax for records caches tables sequence objects gives to scores def __init__ self _scores name score ada print answers membership tests written return connects bracket internal storage"},{"slug":"callable-objects","title":"Callable Objects","section":"Data Model","summary":"__call__ lets an instance behave like a function while keeping state.","keywords":"","text":"callable objects obj checks whether an object can be called are good for named stateful behavior prefer plain functions when no instance state is needed not the only in python any with parentheses its class defines __call__ useful needs remembered configuration or evolving closure do this too often clearer has multiple fields methods tradeoff ceremony use function simple small captured and naming improves interface starts as ordinary stored on multiplier def __init__ self factor calls double print makes usable call syntax value return because still it remember across"},{"slug":"operator-overloading","title":"Operator Overloading","section":"Data Model","summary":"Operator methods let objects define arithmetic and comparison syntax.","keywords":"","text":"operator overloading overload operators only when the operation is unsurprising return notimplemented an operand type unsupported implement equality deliberately value comparison matters lets class define what expressions such as mean for its objects this useful part of domain vocabulary method should preserve meaning readers expect from vectors can add component by money amounts in same currency surprising overloads make code harder to trust python also has reflected methods __radd__ cases where left does not know how handle right that keeps mixed operations possible without making every other __add__ defines combines two checking and returning foreign types try instead crashing inside yours vector def __init__ self if isinstance __repr__ print __eq__ it user defined compare identity most here against unrelated answer false never raise falls back both sides decline __matmul__ which reserves matrix style multiplication no built implements so works on classes opt dot product makes results inspectable while debugging repr"},{"slug":"attribute-access","title":"Attribute Access","section":"Data Model","summary":"Attribute hooks customize lookup, missing attributes, and assignment.","keywords":"","text":"attribute access __getattr__ is narrower than __getattribute__ because it handles only missing attributes __setattr__ affects every assignment on the instance use property or descriptors when behavior attached to known name usually simple obj looks up an python exposes hooks for uncommon cases where lookup needs be customized runs normal fails which makes safer hook computed fallback so should used sparingly and carefully prefer ordinary first reach these object intentionally adapting another interface validating all assignments exposing dynamic fields starting point __init__ stores one real _values backing dictionary in next cells customize around class settings def self values dict theme dark print can provide try return except keyerror as error raise attributeerror from intercepts including ones underscore names are stored through avoids recursing your own public go value if startswith else volume"},{"slug":"bound-and-unbound-methods","title":"Bound and Unbound Methods","section":"Data Model","summary":"instance.method binds self automatically; Class.method is a plain function.","keywords":"","text":"bound and unbound methods instance method produces whose __self__ is the class plain function requires you to pass historical python term since simply which what this page demonstrates each its own object storing one captures binding implemented by descriptor protocol on when write returns callable that already remembers as self get underlying back calling it passing an yourself distinction why can be stored in collections passed callbacks called later without losing track of they belong carries so two callables produced from different instances stay independent even their same mechanism attached implements __get__ hook turns attribute access into does not need detail use but explains happening underneath through require again counter def __init__ start value increment return bound_counter print there no first argument explicitly using fresh here makes output previous cell unbound_counter type __name__ are values lists other functions handlers for range append at work lives invokes knows descriptor_counter func __dict__ rebound"},{"slug":"descriptors","title":"Descriptors","section":"Data Model","summary":"Descriptors customize attribute access through __get__, __set__, or __delete__.","keywords":"","text":"descriptors are class attributes that participate in instance attribute access data with __set__ can validate or transform assignments property is usually simpler for one off managed shine when the behavior reusable descriptor an object stored on defines __get__ __delete__ lookup finds python calls method instead of returning directly machinery behind methods validators and many orm fields use them should control classes single simple this example implements positive number validator __set_name__ learns name owner created validates writes reads value back from lives lets it learn which serving def self private_name obj if none return getattr raise valueerror must be setattr product price print assigning item reading __init__ try except as error"},{"slug":"metaclasses","title":"Metaclasses","section":"Classes","summary":"A metaclass customizes how classes themselves are created.","keywords":"","text":"metaclasses customize class creation not instance behavior directly most code should prefer decorators functions or ordinary inheritance you are likely to meet inside frameworks and orms metaclass is the of python never needs one but syntax appears in that register validate modify classes as they created keyword statement chooses object builds this advanced machinery usually simpler use only when itself problem being solved customizes __new__ receives name bases namespace before exists tagged type def mcls tag lower return super print __name__ applies building rule here adds attribute new event pass"},{"slug":"context-managers","title":"Context Managers","section":"Data Model","summary":"with ensures setup and cleanup happen together.","keywords":"with statement","text":"context managers files locks and temporary state commonly use __enter__ __exit__ power the protocol finally when cleanup must happen after errors too returning true from suppresses an exception do that only intentionally define setup around block of code with statement guarantees runs exits even is raised powered by contextlib contextmanager decorator concise way to write same idea as generator full class would be noisy production often uses for transactions resources need reliable release based manager implements value returned bound it tag def __init__ self name print return exc_type exc tb false section content writes shape before yield import try note body still raises or letting re raise allows keep propagating error valueerror boom except handled"},{"slug":"delete-statements","title":"Delete Statements","section":"Data Model","summary":"del removes bindings, items, and attributes rather than producing a value.","keywords":"","text":"delete statements del removes bindings or container entries assign none when absence should remain an explicit value use methods such as pop you need the removed back binding item it is statement not function and does return name no longer be bound mapping key sequence index mutating by removing one part this different from assigning still while slot deleting dictionary mutates gone has been set to profile ada temporary true print list that position shifts later items left current namespace rebinding cached in locals"},{"slug":"assertions","title":"Assertions","section":"Errors","summary":"assert documents internal assumptions and fails loudly when they are false.","keywords":"","text":"assertions use assert for internal invariants and debugging assumptions explicit exceptions user input files network responses other expected failures can be disabled with python optimization flags so do not rely on them security checks an assumption if the condition is false raises assertionerror optional message programmer validating or external data validation should raise ordinary that production code expects to handle make executable while keeping successful path compact when assertion true execution continues normally documents function expectation def average scores must empty return sum len print this signals broken normal recovery try except as error"},{"slug":"exception-chaining","title":"Exception Chaining","section":"Errors","summary":"raise from preserves the original cause when translating exceptions.","keywords":"","text":"exception chaining use raise from error when translating exceptions across boundary the new __cause__ points to original keeps user facing errors clear without losing debugging context connects higher level lower that caused it syntax is newerror implementation details into domain specific while preserving cause for this different hiding caller can catch and tooling still inspect low where happens then class configerror pass def read_port text try return int except valueerror as port must be number print __name__ handles remains available abc type"},{"slug":"exception-groups","title":"Exception Groups","section":"Errors","summary":"except* handles matching exceptions inside an ExceptionGroup.","keywords":"","text":"exception groups except is for exceptiongroup not ordinary single exceptions each clause handles matching members of the group often appear around concurrent work represents several unrelated raised together exists code that may receive multiple failures at once especially use one only when value being handled an and subgroup needs its own handling receives smaller containing bundles objects this different from because more than failure present errors batch failed valueerror bad port typeerror mode print len handler sees error type try raise as __name__"},{"slug":"warnings","title":"Warnings","section":"Errors","summary":"warnings report soft problems without immediately stopping the program.","keywords":"","text":"warnings use for soft problems callers can act on later exceptions when the current operation cannot continue stacklevel should point warning at caller rather than inside helper python and prefer deprecated whole functions classes call warn directly narrower cases such as one argument reports problem that know about but it does not have to stop deprecations are classic case old api still return value while telling users migrate sit between logging records operational evidence path make compatibility or correctness concerns visible according filter tests often capture so asserted instead of merely printed filters also turn into errors project wants enforce cleanup in returned matters migration notice must be import def old_name is deprecationwarning result with catch_warnings record true caught simplefilter always print category __name__ str message promote selected which useful ci calls fail build error try except became adds decorator states deprecation once definition calling function emits aimed kept __deprecated__ type checkers flag uses before program runs new_name older_name"},{"slug":"modules","title":"Modules","section":"Modules","summary":"Modules organize code into namespaces and expose reusable definitions.","keywords":"import random math standard library","text":"modules prefer plain import module when the namespace improves readability use focused imports for small number of clear names place near top file execute level code once then reuse cached object organize python into files and namespaces executes stores it in cache gives your program access to its definitions this page focuses on forms package layout aliases dynamic have their own neighboring examples such as math sqrt source name should stay visible from statistics mean imported is at call site importing prefix makes where pi came radius area print round brings one definition current keeps common operation concise without every scores are objects too attributes include metadata __name__ which records sys later instead executing again"},{"slug":"import-aliases","title":"Import Aliases","section":"Modules","summary":"as gives imported modules or names a local alias.","keywords":"","text":"import aliases module as alias keeps style access under shorter or clearer name from imports one local prefer plain unless an improves clarity follows strong convention avoid because it makes dependencies harder to see gives imported use when conventional short readability two would otherwise collide the alternative is which usually better already clear that make readers guess where came star in examples and production modules they hide blur boundary between namespace but changes here stats can still mean belongs statistics scores print __name__ with also be aliased this explains role than original math sqrt square_root"},{"slug":"packages","title":"Packages","section":"Modules","summary":"Packages organize modules into importable directories.","keywords":"","text":"packages package is module that can contain submodules dotted imports should mirror meaningful project structure use from submodule import name inside to re export names set __all__ declare the public surface prefer ordinary unless truly dynamic are modules other they let group related code behind paths such as json decoder or email message at runtime importing gives python path through in on disk usually directory with files and often an __init__ py file when one has grown into small namespace of keep boring explicit so readers tell where imported definitions come itself exposes print __name__ makes available under jsondecoder importlib import_module by string it useful for plugin systems but clearer dependency known exports root lists make visible this cell builds temporary shapes both forms concrete os sys tempfile temporarydirectory tmp pkg join makedirs open init write square area n__all__ def side return insert try finally remove pop none"},{"slug":"virtual-environments","title":"Virtual Environments","section":"Modules","summary":"Virtual environments isolate a project's Python packages.","keywords":"venv pip install packages","text":"virtual environments use python venv for everyday standard project setup isolates installed packages it does not change how imports are written this site runner uses deployment dependency model an activated shell environment that constraint is separate from the workflow you would in local projects isolate global installation and other usual command line one create activate then install dependencies there live example built declared rather than so runnable part keeps to deterministic evidence while page still teaches changes import paths language package layout rules or module names creates directory with its own interpreter entry points location after activation pip installs into another by deployed instead of subprocess sys run executable check true bin requests envbuilder exposes same creation mechanism as temporary leaving files behind pathlib tempfile temporarydirectory env_path path builder with_pip false config pyvenv cfg read_text print name home"},{"slug":"type-hints","title":"Type Hints","section":"Types","summary":"Annotations document expected types and power static analysis.","keywords":"typing annotations annotation","text":"type hints python does not enforce most at runtime tools like checkers and editors use annotations to catch mistakes earlier for unions optional or none both spellings mean the same thing reach alias when domain name reads better than raw primitive validation untrusted input must be rejected while program runs are that document expected shapes values parameters return results they exist so readers can understand api boundaries before stores many but of them communication static analysis exceptions checks required alternative an annotation is prose tests good code often uses all three important parameter still function normally def total numbers list int sum print on object introspection this information without changing call syntax __annotations__ passes string where hint says calls because body format any value label score str high pep express either result absent typing older supported spelling idea equivalent find options if in else ada grace guido from import lookup table get statement names it reused with intent keeps underlying lets talk about concept rather spells typealias deprecated since aliases page covers modern depth grade pass fail"},{"slug":"runtime-type-checks","title":"Runtime Type Checks","section":"Types","summary":"type, isinstance, and issubclass inspect runtime relationships.","keywords":"","text":"runtime type checks is exact isinstance follows inheritance inspect objects not static annotations prefer behavior protocols or clear validation over scattered real while the program running they are different from hints which mostly guide tools before runs use when class matters subclasses should count and issubclass checking relationships most apis but useful at input boundaries do turn every function into wall of calls if code only needs an object that can perform operation duck typing protocol may be clearer reports dog instance exactly animal pass pet print __name__ accepts usually what api want rather than individual"},{"slug":"union-and-optional-types","title":"Union and Optional Types","section":"Types","summary":"The | operator describes values that may have more than one static type.","keywords":"","text":"union and optional types use when value may have either type none means absence is an expected case not error by itself narrow unions before using behavior that belongs to only one member says of several static shapes int str callers pass integer or string the modern spelling for annotation documents but code still needs handle non are useful at boundaries where input flexible inside function with isinstance pattern check so rest has clear shape body should operations make sense every def label return item print accepts explicit calling methods greeting name if hello guest upper ada annotations visible runtime python does enforce them called __annotations__"},{"slug":"type-aliases","title":"Type Aliases","section":"Types","summary":"Type aliases give a meaningful name to a repeated type shape.","keywords":"","text":"type aliases use to name repeated or domain specific annotation shapes alias does not validate values at runtime newtype when two share representation but should be mixed statically gives an shape it helps readers and checkers understand the role of value without repeating long expression everywhere python supports statement for explicit older assignment style still appear in code makes intent clear creates typealiastype object create new if you need static distinction between compatible such as user ids order instead names here scores means dictionary from integer userid int dict def best_user return max key get print modern are objects that keep their introspection __name__ common they just ordinary bound existing legacyname str ada is"},{"slug":"typed-dicts","title":"TypedDict","section":"Types","summary":"TypedDict describes dictionaries with known string keys.","keywords":"","text":"typed dicts use typeddict for dictionary records from json or apis readonly python tells type checkers key must not be reassigned it does freeze the understand required and optional keys runtime behavior is still ordinary describes with known useful like data that should remain instead of becoming class instance important boundary static versus can know name string score an integer but at value dict external dataclass when your own program wants attribute access methods construction dictionaries typing import user str int def describe return record ada print plain isinstance __name__ notrequired marks treat as lookup uses normal tools such get userwithnickname nickname none added in allow code to reassign here checker accepts update would reject account id same only which are read itself accept write grace sorted __readonly_keys__"},{"slug":"structured-data-shapes","title":"Structured Data Shapes","section":"Classes","summary":"dataclass, NamedTuple, and TypedDict each model records with different trade-offs.","keywords":"","text":"structured data shapes dataclass mutable attribute access methods good default when behavior travels with typing namedtuple immutable index tuple semantics for small records that flow through unpacking typeddict runtime is dict schema type checker only json shaped collections the older untyped form of prefer version in new code and are three ways to give record name they model same but differ mutability syntax what information costs at regular class __init__ __repr__ generated you so instances accessed subclass named positions support both obj field plain lives pick shape matches problem or help benefit from should stay as boundary normal annotated fields can carry like any other dataclasses import userclass str score int ada print helper _replace produces modified copy without mutating original since assigning would fail usertuple dictionary annotations exist value behaves useful crosses an api mapping userdict __name__ identities its own literally difference drives choice whose rest program already expects isinstance"},{"slug":"literal-and-final","title":"Literal and Final","section":"Types","summary":"Literal restricts exact values, while Final marks names that should not be rebound.","keywords":"","text":"literal and final narrows values to small exact set prevents rebinding in static analysis not at runtime use enums when the option needs names behavior or iteration over members make two different promises value allowed options tells type checker that name should be rebound after its first assignment both annotations help api boundaries function can accept only known modes module publish constant other code treat as fixed python still runs same rules so these are for tools readers rather than locks closed is clearer broad str int would bug design especially constants class attributes describes reject debug mode even though it an ordinary string from typing import read write def open_label return opening print marks stronger documentation all caps convention because flag reassignment default_mode annotation lock rebinds mistake human reader"},{"slug":"callable-types","title":"Callable Types","section":"Types","summary":"Callable annotations describe functions passed as values.","keywords":"","text":"callable types use arg return for simple function shaped values the annotation documents how callback will be called complex call signatures protocols can clearer annotations describe that like functions they are useful when accepts strategy predicate or transformation int says one integer argument result helps tools and readers while runtime still only needs an object is actually shapes protocol named attributes overloaded more descriptive interface passed in by receiving from collections abc import def apply_twice value func add_one number print structural with __call__ also satisfy shape class doubler self callability separate question static checks whether python"},{"slug":"generics-and-typevar","title":"Generics and TypeVar","section":"Types","summary":"Generics preserve type information across reusable functions and classes.","keywords":"","text":"generics and typevar def first class box declare type parameters inline this syntax needs python or later str gives parameter default that is the legacy spelling of same idea still what older codebases use generic functions avoid losing information to object any when input output types are connected connect across an api plain function returns loses can say returned value has as element stands for chosen by caller in items list brackets after name says strings produces string integers integer reusable but preserves relationship between code declares variable with typing both spellings mean thing checker square so return follows print ada grace reusing expresses results each its own scoped definition pair left right tuple takes way whatever goes through __init__ get hands back recorded on nothing checks them at runtime self item none __type_params__ lets reads bare setting while int overrides it stored __default__ before had be created separately then used works common existing annotations show rather than from import last __annotations__"},{"slug":"paramspec","title":"ParamSpec","section":"Types","summary":"ParamSpec preserves callable parameter types through wrappers.","keywords":"","text":"paramspec preserves callable parameter list through transparent wrappers pair with typevar when the return type should also be preserved python accepts inline pep spelling def wrap func which declares both variables in signature itself if wrapper changes public write that new directly instead is for decorators and functions keep wrapped shape without it generic decorator often falls back to says this returns right but no longer know what arguments are valid use forwards args kwargs original function changing plain deliberately different set of parameters annotate forwarded separate keeps tied sometimes too broad ellipsis means any argument as far checker can tell from collections abc import typing erased print __name__ captures lets forward exactly logged calling decorated still runs normally benefit static tools checking add receives two integers left int"},{"slug":"overloads","title":"Overloads","section":"Types","summary":"overload describes APIs whose return type depends on argument types.","keywords":"","text":"overloads put overload declarations immediately before the implementation improve static precision they do not create runtime dispatch if all callers can work with one broad return type simple union annotation is usually enough lets checkers describe function whose depends on argument types are only promises still single that appears after them use when would be too vague for example double returns an int while ha str loses relationship at stubs cases must inspect or operate value just like any other python give tools precise call shapes integer in out string from typing import def print signatures there it accept every shape promised by annotations visible were checker __annotations__"},{"slug":"casts-and-any","title":"Casts and Any","section":"Types","summary":"Any and cast are escape hatches for places static analysis cannot prove.","keywords":"","text":"casts and any disables most static checking for value cast tells the type checker to trust you without changing runtime object prefer narrowing with checks when possible are escape hatches they useful at messy boundaries where cannot prove what is but also remove protection overused tools stop operations on treat as it returns same unchanged use another invariant already proves see that proof still whatever was actually assigned from typing import raw score score_text dict str int print does not convert or validate list __name__ real check narrows by inspecting this safer input untrusted if isinstance"},{"slug":"newtype","title":"NewType","section":"Types","summary":"NewType creates distinct static identities for runtime-compatible values.","keywords":"","text":"newtype helps type checkers distinguish values that share runtime representation at the value is still underlying use aliases for readability static separation creates distinct identity represented by an existing it useful ids units and other should not be mixed accidentally key boundary versus behavior checker can userid from orderid but both are plain integers alias when you only want clearer name shape mixing two compatible shapes treated as mistake analysis typing import int def load_user user_id str return user uid print compares like has same oid __name__ constructor keeps tools introspection"},{"slug":"protocols","title":"Protocols","section":"Types","summary":"Protocol describes required behavior for structural typing.","keywords":"","text":"protocols are for structural typing compatibility by shape rather than explicit inheritance type checkers understand normal runtime method calls still do the work prefer when shared implementation matters and only required behavior protocol describes methods or attributes an object must provide it exists if has right can treat as compatible this is different from says class explicitly derived parent callers need particular at ordinary lookup applies mainly static analysis documentation api boundaries names ellipsis marks body intentionally unspecified similar to interface declaration import greeter def greet self str print __name__ satisfy without inheriting person so __init__ name return hello ada use annotation boundary function cares that does not care about concrete welcome"},{"slug":"abstract-base-classes","title":"Abstract Base Classes","section":"Classes","summary":"ABC and abstractmethod enforce that subclasses implement required methods.","keywords":"","text":"abstract base classes abc plus abstractmethod blocks instantiation until every method has an implementation abcs are nominal subclasses opt in by inheriting isinstance reflects that protocols structural any class with the right shape qualifies regardless of inheritance prefer when shared or explicit matters protocol only behavior at api boundary and describe interface must implement refuses to instantiate concrete subclass provides which catches forgot this construction time rather than first call different from is participates contract it methods no required reach for you want mean explicitly opted care about cost small amount ceremony type level benefit half implemented cannot be created accident declares trying construct itself fails because least one lives alongside area so inherit free import def self float str return try except typeerror as error print implements can instantiated also inherits non square __init__ side forgets value adds fires not something later tries missing incomplete pass contrast hasarea accepts triangle does satisfies but both inherited typing height total_area shapes list sum"},{"slug":"enums","title":"Enums","section":"Types","summary":"Enum defines symbolic names for a fixed set of values.","keywords":"enumeration constants","text":"enums make states and choices explicit members have names values comparing enum avoids string typo bugs prefer raw strings for open ended text closed set of named defines fixed this makes modes easier to read than scattered through program each member has name value is helps avoid typos that plain would allow use when must be one small known statuses directions roles similar an symbolic underlying the what readers usually care about in code from import class status pending done current print compare with not keeps valid"},{"slug":"regular-expressions","title":"Regular Expressions","section":"Text","summary":"The re module searches and extracts text using regular expressions.","keywords":"regex re pattern match","text":"regular expressions use raw strings for regex patterns so backslashes are easier to read capturing groups when the point is extraction not just matching re match anchors at start search finds first anywhere compile saves work pattern runs more than once sub rewrites matches flags like ignorecase change behavior without rewriting reach string methods before simple compact language searching and extracting text python module provides standard interface of occurrence findall collects every reuses has structure repeated records alternatives optional parts or pieces you want capture prefer ordinary substring checks because simpler code maintain such as adjust pair them with same used repeatedly keep readable in return inside parentheses import ada grace za name score print int object exposes captured by position group check membership clearer only picking right one keeps anchoring intent visible an explicit none produces reusable gives also caches recently compiled internally practical wins readability place attach speed scoreline changing replaces replacement returns rewritten casey"},{"slug":"number-parsing","title":"Number Parsing","section":"Standard Library","summary":"int() and float() parse text into numbers and raise ValueError on bad input.","keywords":"","text":"number parsing int and float are constructors that also parse strings text base makes non decimal input explicit catch valueerror for recoverable user do not hide unexpected data corruption turns from files forms command lines or network messages into numeric objects parses whole scientific notation invalid raises specific exception when bad is expected let it fail loudly the string supposed to be trusted program accepts which useful at protocol boundaries where numbers written in hexadecimal binary another use parsed values real print pass format says ff boundary normal texts python try except skip"},{"slug":"custom-exceptions","title":"Custom Exceptions","section":"Errors","summary":"Custom exception classes name failures that belong to your domain.","keywords":"","text":"custom exceptions subclass exception for errors callers are expected to catch name can be clearer than reusing generic valueerror everywhere at boundary that recover or report clearly give names failures in your problem domain named is easier and explain error with only string message raise the point where invalid state discovered include specific occurrence recovery makes sense such as returning an response asking corrected input create when failure has class empty first emptycarterror pass print __name__ detected normal inputs still follow ordinary success path def checkout items if not cart return paid book precise type without accidentally catching unrelated try except"},{"slug":"files-and-pathlib","title":"Files and pathlib","section":"Standard Library","summary":"pathlib names files and directories, and open() reads and writes their text.","keywords":"","text":"files and pathlib path is name for place building one with does not create or open file pass encoding utf to read_text write_text so text means the same bytes everywhere use closed when block ends loop over object read line by iterdir lists directory rglob searches below it sort results order matters catch filenotfounderror at instead of trusting an earlier exists check names in system anything itself knows how join take apart ask questions such as whether reading writing are separate steps handle whole small call while gives that closes you can this page works inside temporary leaves nothing behind real programs calls on paths they were given should always rather than rely platform default operator joins into new touches disk notes be taken suffix before any import shutil tempfile from root mkdtemp txt print creates writes string returns which suits passing makes every machine first nsecond splitlines even if body raises mode appends replacing opened iterator lines each still ending its newline large processed without loading them write third number enumerate start rstrip directories too mkdir entries directly level matching pattern listing up reports summary csv total n3 sorted relative_to as_posix is_dir opening there catching usually better checking because appear vanish between rmtree removes everything missing try except error type __name__"},{"slug":"json","title":"JSON","section":"Standard Library","summary":"json encodes Python values as JSON text and decodes them back.","keywords":"serialize deserialize parse dump load","text":"json dumps returns string loads accepts true false and null become python none use sort_keys when stable text output matters only represents data shapes not arbitrary objects or behavior the module converts between values dictionaries lists strings numbers booleans map naturally to structures you need back options such as indent control readable is format way preserve encode simple at service boundaries expect decode errors incoming valid encodes keeps dictionary keys in order for reproducible import payload language versions missing print formatting change value useful human pretty splitlines decodes into becomes decoded invalid raises jsondecodeerror so input should handle failures explicitly try bad except error __class__ __name__"},{"slug":"logging","title":"Logging","section":"Standard Library","summary":"logging records operational events without using print as infrastructure.","keywords":"log logger debug","text":"logging configure once call named loggers throughout the program logger and handler levels both participate in filtering use exceptions for control flow failures operational evidence warnings soft compatibility problems records events without using print as infrastructure names where an event came from decides go formatter chooses their text shape level which are important enough to emit services command line tools scheduled jobs libraries that need diagnostics operators can filter intentional user facing output example writes stdout so page stays deterministic real applications usually handlers at startup then getlogger __name__ each module name part of produced choose how is shown import sys worker setlevel debug streamhandler info parts levelname message join setformatter propagate false hidden detail service started warning disk almost full thresholds raising suppresses later changing sites after threshold change error write failed"},{"slug":"testing","title":"Testing","section":"Standard Library","summary":"Tests make expected behavior executable and repeatable.","keywords":"unittest test assert pytest","text":"testing test method names should describe behavior not implementation details good unit is deterministic and independent of order use broader integration tests when the depends on several components working together turn expected into code that can be run again useful usually small example with clear input action assertion python unittest library provides cases assertions suites runners projects often pytest for ergonomics but same idea remains fails changes broad practice also includes fixtures property coverage this stays smallest standard loop define assert result suite inspect success starts enough to name function ordinary supplies representative def add left right return print testcase groups methods setup runs before each build per assertequal checks values assertraises asserts block raises exception type import divide if raise zerodivisionerror denominator zero class addtests self test_adds_numbers test_adds_empty_strings py test_divide_by_zero_raises in dir startswith test_ runner executes records whether every passed capturing stream keeps page output io loader defaulttestloader loadtestsfromtestcase stringio texttestrunner verbosity testsrun wassuccessful"},{"slug":"subprocesses","title":"Subprocesses","section":"Standard Library","summary":"subprocess runs external commands with explicit arguments and captured outputs.","keywords":"","text":"subprocesses use list of arguments instead shell strings when possible capture output the parent program needs to inspect it check true turns non zero exits into exceptions verified came from real child process under standard cpython at build time in browser sandbox has no table so live runs this page fail there subprocess is boundary for running external commands starts another waits and gives you result object with exit code captured python right tool calling git compilers shells or interpreter site example runner does not expose an operating system teaches proper run contract labels pretending command can here treat return as failure important between objects prepares environment then reports back through streams status spawns capture_output stores stdout stderr on text decodes them raises calledprocesserror carries portable evidence ran button cannot spawn processes pressing fails below was produced by really spawning import sys executable print strip returncode"},{"slug":"threads-and-processes","title":"Threads and Processes","section":"Standard Library","summary":"Threads share memory, while processes run in separate interpreters.","keywords":"","text":"threads and processes share memory so mutable shared state needs care avoid interpreter but require values to cross process boundary prefer asyncio for coroutine based executors ordinary blocking callables the thread pool output came from real worker under standard cpython at build time in browser sandbox cannot create or live runs of this page fail there are two ways run work outside current control path useful overlapping shaped waits while when cpu bound separate python threadpoolexecutor processpoolexecutor tools lesson site example runner does not expose native child keeps proper executor model visible separates idea what can execute here is different through async code cooperatively awaits coroutines choose smallest concurrency that matches bottleneck square across its gil map returns results input order with block joins workers body exits pressing fails was produced concurrent futures import def number return max_workers as print list heavier isolated would otherwise serialise spawn either cell only inspects class name rather than running __name__"},{"slug":"networking","title":"Networking","section":"Standard Library","summary":"Networking code exchanges bytes across explicit protocol boundaries.","keywords":"","text":"networking network protocols move bytes not python str objects close real sockets when finished usually with context manager or finally block use high level http libraries for application unless socket control is the lesson verified output came from socketpair under standard cpython at build time in browser sandbox cannot open so live runs of this page fail there code sends and receives across protocol boundaries higher clients hide many details but core rule remains text encoded before it leaves process decoded after come back version uses connected endpoints such as create_connection local deterministic demonstration site example runner does expose arbitrary os outbound calls teaches contract while making constraint explicit useful mental model endpoint plus cleanup connects two transfers byte strings must be closed conversation returns sendall writes into one end recv reads up to off other boundary whole point ping encode utf produces which what actually moves try closes both even if raises second print decode pressing run here fails pair import left right message data"},{"slug":"datetime","title":"Dates and Times","section":"Standard Library","summary":"datetime represents dates, times, durations, formatting, and parsing.","keywords":"date time timezone timedelta","text":"datetime use timezone aware datetimes for instants that cross system or user boundaries date calendar days time clock times both and timedelta durations prefer iso strings interchange strftime human facing display the module covers several related ideas together avoid ambiguity in real systems utc is clear default examples because output stays stable portable formatting parsing helpers such as fromisoformat to turn text back into objects separates dates combined import types you need explicitly day of combine them when mean an instant isoformat produces machine readable it good apis logs from release_day meeting_time created_at tzinfo print adding one another without manually changing fields expires_at hours reading iso_text t12 parsed"},{"slug":"csv-data","title":"CSV Data","section":"Standard Library","summary":"csv reads and writes row-shaped text data.","keywords":"csv spreadsheet rows","text":"csv data let handle quoting and delimiters instead of calling split fields are text until your code converts them reach for json when records need nested lists dictionaries booleans or numbers that preserve their type is row shaped each line record comma separated field arrives as string the module understands newlines so it safer than splitting lines by yourself use dictreader header names columns convert explicitly after reading dictwriter program needs to produce same shape again good fit flat tabular another structured format values types survive boundary uses dictionary keys still strings because import io name score nada ngrace rows list stringio print __name__ numeric at where leaves starts doing arithmetic sum int in turns back into with column order output newline writer fieldnames passed writeheader writerow ada true getvalue splitlines"},{"slug":"async-await","title":"Async Await","section":"Async","summary":"async def creates coroutines, and await pauses until awaitable work completes.","keywords":"asyncio coroutine concurrency","text":"async await calling an function creates coroutine object yields control until awaitable completes workers request handlers are so this pattern appears around fetches and bindings prefer ordinary functions when there is no work to coordinate def it the body runs event loop awaits or schedules pauses current another lets one make progress on other while task waits for cloudflare asynchronous understanding practical fetch calls service interactions even small example uses asyncio sleep as stand in alternative that immediately use code shaped waiting not faster replacement cpu bound python computes its result hands value straight back synchronous form baseline rest of page contrasts against slug_to_title slug return replace title print returns called has produced final yet import fetch_title __class__ __name__ close inside get eventual run starts top level main gather several awaitables their results order shape used independent operations can together titles json datetime with forms context managers iteration class implements __aenter__ __aexit__ act manager yield becomes generator dedicated examples explains protocols depth session self open false stream driver"},{"slug":"async-iteration-and-context","title":"Async Iteration and Context","section":"Async","summary":"async for and async with consume asynchronous streams and cleanup protocols.","keywords":"","text":"async iteration and context for consumes asynchronous iterators with awaits setup cleanup these forms are common around shaped resources an iterator stream whose next value may require await surrounds block appear network streams database cursors locks service clients where both wait on use ordinary when producing the or cleaning up does not need to anything syntax mirrors but protocol methods generator can before yielding each those values import asyncio def titles slug in sleep yield replace title print __name__ manager defines __aenter__ __aexit__ class session self open return exc_type exc tb close top level coroutine combines protocols resource then consume inside it main run"}] diff --git a/public/search.e5a5822d9917.js b/public/search.4d7b3a480c78.js similarity index 92% rename from public/search.e5a5822d9917.js rename to public/search.4d7b3a480c78.js index 9f18203..b4ddd2b 100644 --- a/public/search.e5a5822d9917.js +++ b/public/search.4d7b3a480c78.js @@ -10,6 +10,8 @@ export function rankExamples(query, entries, limit = 8) { const slug = entry.slug.toLowerCase(); const section = entry.section.toLowerCase(); const summary = entry.summary.toLowerCase(); + const keywords = (entry.keywords || '').split(' '); + const words = entry.text.split(' '); let score = 0; let matched = true; for (const token of tokens) { @@ -17,10 +19,14 @@ export function rankExamples(query, entries, limit = 8) { if (title === token) tokenScore = 100; else if (title.startsWith(token)) tokenScore = 80; else if (new RegExp(`\\b${token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`).test(title)) tokenScore = 60; + else if (keywords.includes(token)) tokenScore = 55; else if (slug.includes(token)) tokenScore = 50; + else if (keywords.some((keyword) => keyword.startsWith(token))) tokenScore = 40; else if (section.startsWith(token)) tokenScore = 30; else if (summary.includes(token)) tokenScore = 25; - else if (entry.text.includes(token)) tokenScore = 15; + // A whole word on the page outranks a fragment of a longer word. + else if (words.includes(token)) tokenScore = 15; + else if (token.length >= 3 && words.some((word) => word.startsWith(token))) tokenScore = 8; if (!tokenScore) { matched = false; break; } score += tokenScore; } diff --git a/public/search.js b/public/search.js index 9f18203..b4ddd2b 100644 --- a/public/search.js +++ b/public/search.js @@ -10,6 +10,8 @@ export function rankExamples(query, entries, limit = 8) { const slug = entry.slug.toLowerCase(); const section = entry.section.toLowerCase(); const summary = entry.summary.toLowerCase(); + const keywords = (entry.keywords || '').split(' '); + const words = entry.text.split(' '); let score = 0; let matched = true; for (const token of tokens) { @@ -17,10 +19,14 @@ export function rankExamples(query, entries, limit = 8) { if (title === token) tokenScore = 100; else if (title.startsWith(token)) tokenScore = 80; else if (new RegExp(`\\b${token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`).test(title)) tokenScore = 60; + else if (keywords.includes(token)) tokenScore = 55; else if (slug.includes(token)) tokenScore = 50; + else if (keywords.some((keyword) => keyword.startsWith(token))) tokenScore = 40; else if (section.startsWith(token)) tokenScore = 30; else if (summary.includes(token)) tokenScore = 25; - else if (entry.text.includes(token)) tokenScore = 15; + // A whole word on the page outranks a fragment of a longer word. + else if (words.includes(token)) tokenScore = 15; + else if (token.length >= 3 && words.some((word) => word.startsWith(token))) tokenScore = 8; if (!tokenScore) { matched = false; break; } score += tokenScore; } diff --git a/public/site.32ce5906d3c1.css b/public/site.2a72bda337b4.css similarity index 96% rename from public/site.32ce5906d3c1.css rename to public/site.2a72bda337b4.css index 960f7ad..3348b7e 100644 --- a/public/site.32ce5906d3c1.css +++ b/public/site.2a72bda337b4.css @@ -99,6 +99,10 @@ .text-link:hover { color: var(--accent-text); } .example-shell { padding: clamp(var(--space-3), 3vw, var(--space-5)) 0; } .example-intro { max-width: 68ch; margin-bottom: var(--space-5); } + .example-explanation { margin-top: var(--space-3); } + .example-explanation p { margin: 0 0 var(--space-2); } + .example-explanation p:last-child { margin-bottom: 0; } + .editor-keys-hint { margin: .6rem 0 0; font-size: .85rem; } .literate-program { margin: var(--space-5) 0; border-block: 1px solid var(--hairline); } .lesson-step { display: grid; grid-template-columns: minmax(18rem, .9fr) minmax(0, 1.35fr); gap: clamp(var(--space-4), 4vw, var(--space-6)); align-items: start; padding: var(--space-4) 0; border-top: 1px dashed var(--hairline-soft); } .lesson-step:first-child { border-top: 0; } @@ -226,6 +230,16 @@ .cell-banner--1 { margin-block: var(--space-6); } .cell-banner--1 figure { width: 100%; max-width: clamp(280px, 65vw, 640px); } .cell-banner--1 figcaption { max-width: 42ch; } + /* Narrow screens: a figure may not shrink below the scale at which its + smallest labels stay readable. Each SVG carries its intrinsic width as + --fig-w; it fills the banner up to that width, and a figure too wide + for the phone keeps 72% of it and scrolls sideways inside its own box + instead of shrinking its text to a few pixels. */ + @media (max-width: 700px) { + .cell-banner { grid-template-columns: minmax(0, 1fr); } + .cell-banner figure, .cell-banner--1 figure, .journey-section-figure { max-width: 100%; min-width: 0; justify-items: start; overflow-x: auto; overscroll-behavior-x: contain; scrollbar-width: thin; } + .cell-banner svg, .journey-section-figure svg { max-width: none; width: min(var(--fig-w, 100%), max(100%, calc(var(--fig-w, 100%) * 0.72))); } + } /* Dark palette: same warm hue family as the light theme, inverted. Marginalia figures paint with the --fig-* tokens, so redefining them here recolours every figure with the page: no light chip, no diff --git a/public/site.css b/public/site.css index 960f7ad..3348b7e 100644 --- a/public/site.css +++ b/public/site.css @@ -99,6 +99,10 @@ .text-link:hover { color: var(--accent-text); } .example-shell { padding: clamp(var(--space-3), 3vw, var(--space-5)) 0; } .example-intro { max-width: 68ch; margin-bottom: var(--space-5); } + .example-explanation { margin-top: var(--space-3); } + .example-explanation p { margin: 0 0 var(--space-2); } + .example-explanation p:last-child { margin-bottom: 0; } + .editor-keys-hint { margin: .6rem 0 0; font-size: .85rem; } .literate-program { margin: var(--space-5) 0; border-block: 1px solid var(--hairline); } .lesson-step { display: grid; grid-template-columns: minmax(18rem, .9fr) minmax(0, 1.35fr); gap: clamp(var(--space-4), 4vw, var(--space-6)); align-items: start; padding: var(--space-4) 0; border-top: 1px dashed var(--hairline-soft); } .lesson-step:first-child { border-top: 0; } @@ -226,6 +230,16 @@ .cell-banner--1 { margin-block: var(--space-6); } .cell-banner--1 figure { width: 100%; max-width: clamp(280px, 65vw, 640px); } .cell-banner--1 figcaption { max-width: 42ch; } + /* Narrow screens: a figure may not shrink below the scale at which its + smallest labels stay readable. Each SVG carries its intrinsic width as + --fig-w; it fills the banner up to that width, and a figure too wide + for the phone keeps 72% of it and scrolls sideways inside its own box + instead of shrinking its text to a few pixels. */ + @media (max-width: 700px) { + .cell-banner { grid-template-columns: minmax(0, 1fr); } + .cell-banner figure, .cell-banner--1 figure, .journey-section-figure { max-width: 100%; min-width: 0; justify-items: start; overflow-x: auto; overscroll-behavior-x: contain; scrollbar-width: thin; } + .cell-banner svg, .journey-section-figure svg { max-width: none; width: min(var(--fig-w, 100%), max(100%, calc(var(--fig-w, 100%) * 0.72))); } + } /* Dark palette: same warm hue family as the light theme, inverted. Marginalia figures paint with the --fig-* tokens, so redefining them here recolours every figure with the page: no light chip, no diff --git a/public/syntax-highlight.743e2535f133.js b/public/syntax-highlight.c4fabad2b399.js similarity index 84% rename from public/syntax-highlight.743e2535f133.js rename to public/syntax-highlight.c4fabad2b399.js index 9395950..8ec518e 100644 --- a/public/syntax-highlight.743e2535f133.js +++ b/public/syntax-highlight.c4fabad2b399.js @@ -54,8 +54,9 @@ for (const source of document.querySelectorAll('.cell-source')) { source.append(button); } -// Read-only Python cells are the only pages that need Shiki. Avoid even -// requesting the CDN module on the home, About, and other code-free pages. +// Read-only Python cells are the only pages that need the highlighter. Avoid +// even requesting its bundle on the home, About, and other code-free pages. +// layout.html names the fingerprinted bundle on this module's script tag. const sourceBlocks = [...document.querySelectorAll('pre code.language-python')].map((code) => ({ source: code.textContent, pre: code.closest('pre'), @@ -64,9 +65,10 @@ const sourceBlocks = [...document.querySelectorAll('pre code.language-python')]. if (sourceBlocks.length) { let codeToHtml = null; try { - ({ codeToHtml } = await import('https://esm.sh/shiki@4.4.3')); + const bundle = document.querySelector('script[data-highlighter]')?.dataset.highlighter; + if (bundle) ({ codeToHtml } = await import(bundle)); } catch (_) { - // Plain server-rendered code remains readable when the optional CDN fails. + // Plain server-rendered code remains readable when the bundle fails to load. } if (codeToHtml) { @@ -75,7 +77,7 @@ if (sourceBlocks.length) { const theme = themePreference.matches ? 'github-dark' : 'github-light'; for (const block of sourceBlocks) { try { - const highlighted = await codeToHtml(block.source, { lang: 'python', theme }); + const highlighted = await codeToHtml(block.source, { theme }); const wrapper = document.createElement('div'); wrapper.innerHTML = highlighted; const shikiPre = wrapper.firstElementChild; diff --git a/public/syntax-highlight.js b/public/syntax-highlight.js index 9395950..8ec518e 100644 --- a/public/syntax-highlight.js +++ b/public/syntax-highlight.js @@ -54,8 +54,9 @@ for (const source of document.querySelectorAll('.cell-source')) { source.append(button); } -// Read-only Python cells are the only pages that need Shiki. Avoid even -// requesting the CDN module on the home, About, and other code-free pages. +// Read-only Python cells are the only pages that need the highlighter. Avoid +// even requesting its bundle on the home, About, and other code-free pages. +// layout.html names the fingerprinted bundle on this module's script tag. const sourceBlocks = [...document.querySelectorAll('pre code.language-python')].map((code) => ({ source: code.textContent, pre: code.closest('pre'), @@ -64,9 +65,10 @@ const sourceBlocks = [...document.querySelectorAll('pre code.language-python')]. if (sourceBlocks.length) { let codeToHtml = null; try { - ({ codeToHtml } = await import('https://esm.sh/shiki@4.4.3')); + const bundle = document.querySelector('script[data-highlighter]')?.dataset.highlighter; + if (bundle) ({ codeToHtml } = await import(bundle)); } catch (_) { - // Plain server-rendered code remains readable when the optional CDN fails. + // Plain server-rendered code remains readable when the bundle fails to load. } if (codeToHtml) { @@ -75,7 +77,7 @@ if (sourceBlocks.length) { const theme = themePreference.matches ? 'github-dark' : 'github-light'; for (const block of sourceBlocks) { try { - const highlighted = await codeToHtml(block.source, { lang: 'python', theme }); + const highlighted = await codeToHtml(block.source, { theme }); const wrapper = document.createElement('div'); wrapper.innerHTML = highlighted; const shikiPre = wrapper.firstElementChild; diff --git a/scripts/audit_rubric_snapshot.py b/scripts/audit_rubric_snapshot.py index f9b0426..c8d0560 100755 --- a/scripts/audit_rubric_snapshot.py +++ b/scripts/audit_rubric_snapshot.py @@ -221,7 +221,7 @@ def render_report(date: str) -> str: waiver_lines = [ f"- Accepted waiver: `{slug}` at " f"{EXAMPLE_QUALITY_SCORES.get(slug, (0.0, ''))[0]:g} " - f"(floor {entry.get('accepted_min', '?')}, expires {entry.get('expires', '?')})." + f"(floor {entry.get('accepted_min', '?')}, {'permanent' if entry.get('permanent') is True else 'expires ' + str(entry.get('expires', '?'))})." for slug, entry in sorted(waivers.items()) ] or ["- Accepted waivers: none."] diff --git a/scripts/build_browser_bundles.mjs b/scripts/build_browser_bundles.mjs new file mode 100755 index 0000000..2c2139d --- /dev/null +++ b/scripts/build_browser_bundles.mjs @@ -0,0 +1,23 @@ +#!/usr/bin/env node +// Bundle the browser modules that depend on npm packages into public/. +// The packages are pinned in package-lock.json, so the code visitors run +// changes only when a commit changes it; nothing is fetched from a CDN. +import { build } from 'esbuild'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); + +for (const name of ['editor', 'highlighter']) { + await build({ + entryPoints: [path.join(root, 'web', `${name}.js`)], + outfile: path.join(root, 'public', `${name}.js`), + bundle: true, + format: 'esm', + target: 'es2022', + minify: true, + legalComments: 'none', + logLevel: 'warning', + }); + console.log(`Bundled public/${name}.js`); +} diff --git a/scripts/build_search_index.py b/scripts/build_search_index.py index c45553c..58f99c8 100755 --- a/scripts/build_search_index.py +++ b/scripts/build_search_index.py @@ -2,14 +2,22 @@ """Build the client-side search index from the example catalog. The index is a small JSON array served as a fingerprinted static asset. -`text` concatenates the note lines so searches can hit concepts the -title does not mention (for example "walrus" for assignment -expressions); it is lowercased at build time so the client never -normalizes entry content. +Each entry carries: + +- `keywords`: words a learner might type that the title does not contain + ("dictionary" for Dicts, "mutable" for Mutability), ranked just below a + title match; +- `text`: every distinct word of the page's prose, notes and code, so a + search can hit a name the page uses (`zip`, `join`, `docstring`) even + when no heading mentions it. + +Both are lowercased at build time so the client never normalizes entry +content. """ from __future__ import annotations import json +import re import sys from pathlib import Path @@ -20,19 +28,90 @@ TARGET = ROOT / "public" / "search-index.json" +# Everyday names for a page's subject. Add a line when a query that should +# find a page does not; scripts/check_search_ranking.mjs pins the important +# ones. +KEYWORDS = { + "dicts": "dictionary dictionaries mapping map hash key value lookup", + "lists": "array arrays sequence append", + "tuples": "immutable sequence record", + "sets": "unique membership union intersection", + "strings": "str text unicode join split", + "string-formatting": "f-string fstring format interpolation", + "mutability": "mutable immutable in-place alias aliasing", + "equality-and-identity": "is == equal same object", + "assignment-expressions": "walrus :=", + "for-loops": "loop iterate iteration range enumerate zip", + "while-loops": "loop repeat", + "conditionals": "if elif else branch", + "functions": "def return parameter argument docstring", + "lambdas": "anonymous function", + "comprehensions": "list comprehension dict comprehension", + "iterating-over-iterables": "enumerate zip reversed", + "itertools": "chain islice product permutations combinations", + "collections-module": "counter defaultdict deque namedtuple", + "exceptions": "try except finally raise error", + "context-managers": "with statement", + "modules": "import random math standard library", + "classes": "object oriented oop instance self init method", + "inheritance-and-super": "subclass parent base class", + "special-methods": "dunder magic methods", + "none": "null nil missing", + "numbers": "int float integer decimal arithmetic math", + "booleans": "true false bool", + "slices": "slicing index range substring", + "sorting": "sort sorted key reverse order", + "regular-expressions": "regex re pattern match", + "json": "serialize deserialize parse dump load", + "datetime": "date time timezone timedelta", + "csv-data": "csv spreadsheet rows", + "testing": "unittest test assert pytest", + "type-hints": "typing annotations annotation", + "generators": "yield lazy", + "decorators": "wrapper wraps", + "async-await": "asyncio coroutine concurrency", + "match-statements": "switch case pattern matching", + "unpacking": "destructuring star splat", + "args-and-kwargs": "variadic star arguments", + "dataclasses": "record struct", + "enums": "enumeration constants", + "logging": "log logger debug", + "virtual-environments": "venv pip install packages", +} + +_WORD_RE = re.compile(r"[a-z_][a-z0-9_]{1,}") + + +def _word_bag(example: dict) -> str: + """Distinct lowercase words from everything a reader sees on the page.""" + parts = [example["slug"].replace("-", " ")] + parts.extend(example.get("notes", [])) + parts.extend(example.get("explanation", [])) + for cell in example.get("cells", []): + parts.extend(cell["prose"]) + parts.append(cell["code"]) + parts.append(example["code"]) + seen: dict[str, None] = {} + for word in _WORD_RE.findall(" ".join(parts).lower()): + seen.setdefault(word) + return " ".join(seen) + def build_entries() -> list[dict[str, str]]: + known = {example["slug"] for example in list_examples()} + unknown = sorted(set(KEYWORDS) - known) + if unknown: + raise SystemExit(f"KEYWORDS names slugs that are not in the catalog: {unknown}") entries = [] for example in list_examples(): - text_parts = [example["slug"].replace("-", " ")] - text_parts.extend(example.get("notes", [])) entries.append( { "slug": example["slug"], "title": example["title"], "section": example["section"], "summary": example["summary"], - "text": " ".join(text_parts).lower(), + "keywords": KEYWORDS.get(example["slug"], ""), + "text": _word_bag(example), } ) return entries diff --git a/scripts/build_social_cards.mjs b/scripts/build_social_cards.mjs index 665a176..a135f59 100755 --- a/scripts/build_social_cards.mjs +++ b/scripts/build_social_cards.mjs @@ -91,6 +91,7 @@ try { if (name.endsWith('.jpg') && !expected.has(name)) await unlink(path.join(outputDir, name)); } let written = 0; + const unfit = []; for (const [name, file] of Object.entries(manifest)) { await client.send('Page.navigate', { url: `file://${path.join(cardDir, file)}` }); for (let i = 0; i < 50; i++) { @@ -101,6 +102,8 @@ try { if (ready.result.value) break; await sleep(50); } + const fit = await client.send('Runtime.evaluate', { expression: 'document.body.dataset.fit', returnByValue: true }); + if (fit.result.value !== 'ok') unfit.push(`${name}: ${fit.result.value ?? 'fit script did not run'}`); const shot = await client.send('Page.captureScreenshot', { format: 'jpeg', quality: 90, clip: { x: 0, y: 0, width, height, scale: 1 }, @@ -109,6 +112,10 @@ try { written += 1; } client.close(); + if (unfit.length) { + console.error(`Social cards whose text does not fit:\n ${unfit.join('\n ')}`); + process.exitCode = 1; + } console.log(`Rasterized ${written} social cards to public/og/.`); } finally { chrome.kill('SIGTERM'); diff --git a/scripts/build_social_cards.py b/scripts/build_social_cards.py index 1606516..984f2bc 100755 --- a/scripts/build_social_cards.py +++ b/scripts/build_social_cards.py @@ -50,8 +50,38 @@ """ +# Cards are rasterised with whatever fonts the building machine has, so their +# text cannot be sized for one font. This script fits the text to the card in +# the browser that renders it: the eyebrow onto one line, the title within its +# column, and the summary above the brand line, shrinking each in small steps +# down to a floor. It then records on whether everything fits; +# scripts/build_social_cards.mjs refuses to write a card that does not. +_FIT_SCRIPT = """ +(() => { + const q = (s) => document.querySelector(s); + const copy = q('.copy'), eyebrow = q('.eyebrow'), title = q('h1'), summary = q('.summary'), brand = q('.brand'); + const px = (el) => parseFloat(getComputedStyle(el).fontSize); + const shrink = (el, floor, bad) => { while (bad() && px(el) > floor) el.style.fontSize = (px(el) - 1) + 'px'; }; + const lines = (el) => Math.round(el.getBoundingClientRect().height / parseFloat(getComputedStyle(el).lineHeight)); + eyebrow.style.whiteSpace = 'nowrap'; + shrink(eyebrow, 18, () => eyebrow.scrollWidth > copy.clientWidth); + shrink(title, 44, () => title.scrollWidth > title.clientWidth + 1 || lines(title) > 2); + shrink(summary, 20, () => summary.getBoundingClientRect().bottom > brand.getBoundingClientRect().top - 20); + const problems = []; + if (eyebrow.scrollWidth > copy.clientWidth) problems.push('eyebrow wider than its column'); + if (title.scrollWidth > title.clientWidth + 1) problems.push('title wider than its column'); + if (summary.getBoundingClientRect().bottom > brand.getBoundingClientRect().top - 20) problems.push('summary runs into the brand line'); + if (copy.scrollHeight > copy.clientHeight + 1) problems.push('text column taller than the card'); + document.body.dataset.fit = problems.length ? problems.join('; ') : 'ok'; +})(); +""" + + def _card_shell(body: str) -> str: - return "\n" f"{body}\n" + return ( + "\n" + f"{body}\n" + ) def _card_body(*, eyebrow: str, title: str, summary: str, figure_svg: str = "") -> str: diff --git a/scripts/check_browser_layout.mjs b/scripts/check_browser_layout.mjs index d1e4b6e..b977a0c 100755 --- a/scripts/check_browser_layout.mjs +++ b/scripts/check_browser_layout.mjs @@ -404,7 +404,7 @@ try { const state = { status: document.getElementById('site-search-status')?.textContent, outlineWidth: getComputedStyle(input).outlineWidth, - shikiRequests: performance.getEntriesByType('resource').filter(entry => entry.name.includes('esm.sh/shiki')).length, + shikiRequests: performance.getEntriesByType('resource').filter(entry => entry.name.includes('/highlighter.')).length, }; window.fetch = originalFetch; return state; @@ -500,16 +500,16 @@ try { })()`); const darkFigures = await evaluateValue(figureThemeExpression(figureTokens.dark)); - // Keep esm.sh import requests pending. The runner has no imports and is - // emitted after its markup, so its controls must attach before the editor's - // CDN graph can let DOMContentLoaded fire. + // Keep the editor and highlighter bundles pending. The runner has no + // imports and is emitted after its markup, so its controls must attach + // before those much larger downloads can let DOMContentLoaded fire. let heldCdnRequests = 0; const removePauseListener = client.on('Fetch.requestPaused', () => { heldCdnRequests += 1; }); - await client.send('Fetch.enable', { patterns: [{ urlPattern: 'https://esm.sh/*' }] }); + await client.send('Fetch.enable', { patterns: [{ urlPattern: '*/editor.*.js' }, { urlPattern: '*/highlighter.*.js' }] }); const offlineCode = Array.from({ length: 80 }, (_, index) => `print(${index})`).join('\n'); const offlineUrl = `${target}#code=${Buffer.from(offlineCode, 'utf8').toString('base64')}`; await client.send('Page.navigate', { url: offlineUrl }); - await waitFor(`!!document.querySelector('.share-button') && !!document.querySelector('.copy-button') && document.getElementById('code-editor')?.value === ${JSON.stringify(offlineCode)}`, 'runner controls while CDN is pending'); + await waitFor(`!!document.querySelector('.share-button') && !!document.querySelector('.copy-button') && document.getElementById('code-editor')?.value === ${JSON.stringify(offlineCode)}`, 'runner controls while the editor bundle is pending'); const offlineRunner = await evaluateValue(`(() => { const textarea = document.getElementById('code-editor'); const panel = textarea.parentElement; @@ -830,8 +830,8 @@ try { if (JSON.stringify(lightTheme.editorColors) === JSON.stringify(darkTheme.editorColors)) failures.push('CodeMirror did not react to the OS theme change'); if (darkTheme.runContrast < 4.5) failures.push(`Dark Run-button contrast is ${darkTheme.runContrast.toFixed(2)}:1`); if (Number.parseFloat(darkTheme.editorOutlineWidth) < 3) failures.push('CodeMirror focus indicator is too weak'); - if (heldCdnRequests === 0) failures.push('CDN-pending runner test did not hold an esm.sh request'); - if (offlineRunner.editorLoaded) failures.push('CDN-pending test unexpectedly loaded CodeMirror'); + if (heldCdnRequests === 0) failures.push('Pending-bundle runner test did not hold an editor or highlighter request'); + if (offlineRunner.editorLoaded) failures.push('Pending-bundle test unexpectedly loaded CodeMirror'); if (offlineRunner.fallbackHeight < 1000) failures.push(`Shared fallback textarea did not resize (${offlineRunner.fallbackHeight}px)`); if (!fragmentBound.unchanged || !fragmentBound.notice?.includes('invalid or too large')) failures.push('Oversized shared-code fragment was decoded or not announced'); if (turnstileRetry.scriptAttempts !== 2 || !turnstileRetry.firstFailure.includes('press Run to retry') || turnstileRetry.finalOutput !== 'retry succeeded') failures.push('Transient Turnstile CDN failure was cached instead of retried'); @@ -887,7 +887,65 @@ try { if (!rejectedRun.output.includes('verification failed') || rejectedRun.busy) failures.push('Rejected Turnstile token did not end the run with the server message'); if (rejectedRetry.fetchCount !== 4 || rejectedRetry.solves !== 2) failures.push('A new Run after a rejected token did not earn exactly one fresh challenge'); + // The editor must behave like a code editor: Enter after a block opener + // indents, Tab indents rather than leaving the field, undo restores the + // document, and Ctrl+Enter runs. Keys go through the real input pipeline. + await client.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 1400, deviceScaleFactor: 1, mobile: false }); + await client.send('Page.navigate', { url: `${target}${target.includes('?') ? '&' : '?'}browser_editor_keys=${Date.now()}` }); + await waitFor("document.readyState === 'complete' && !!window.pythonByExampleEditor && !!document.querySelector('.cm-content')", 'editor keys page'); + const pageOrigin = new URL(target).origin; + const thirdPartyRequests = await evaluateValue(`performance.getEntriesByType('resource').map(entry => entry.name).filter(name => !name.startsWith(${JSON.stringify(pageOrigin)}))`); + const editorValue = "document.getElementById('code-editor').value"; + async function pressKey(key, code, keyCode, modifiers = 0) { + for (const type of ['rawKeyDown', 'keyUp']) { + await client.send('Input.dispatchKeyEvent', { type, key, code, windowsVirtualKeyCode: keyCode, modifiers }); + } + } + await evaluateValue("(window.pythonByExampleEditor.setValue(''), window.pythonByExampleEditor.focus(), true)"); + await client.send('Input.insertText', { text: 'def f():' }); + await pressKey('Enter', 'Enter', 13); + await client.send('Input.insertText', { text: 'return 1' }); + await sleep(100); + const afterEnter = await evaluateValue(editorValue); + await pressKey('Enter', 'Enter', 13); + await pressKey('Tab', 'Tab', 9); + await sleep(100); + const afterTab = await evaluateValue(`({ value: ${editorValue}, focusInEditor: !!document.activeElement?.closest('.cm-editor') })`); + await pressKey('z', 'KeyZ', 90, 2); + await pressKey('z', 'KeyZ', 90, 2); + await sleep(100); + const afterUndo = await evaluateValue(editorValue); + await evaluateValue("(window.pythonByExampleEditor.setValue('print(6 * 7)'), window.pythonByExampleEditor.focus(), true)"); + await pressKey('Enter', 'Enter', 13, 2); + await waitFor("document.querySelector('.output-panel code')?.textContent.trim() === '42'", 'Ctrl+Enter run'); + const editorKeys = { afterEnter, afterTab, afterUndo, hintVisible: await evaluateValue("!document.getElementById('editor-keys-hint')?.hidden") }; + if (thirdPartyRequests.length) failures.push(`Example page requested third-party resources before Run: ${thirdPartyRequests.slice(0, 3).join(', ')}`); + if (afterEnter !== 'def f():\n return 1') failures.push(`Enter after a block opener did not indent (${JSON.stringify(afterEnter)})`); + if (!afterTab.focusInEditor || !afterTab.value.endsWith('\n ')) failures.push(`Tab did not indent inside the editor (${JSON.stringify(afterTab)})`); + if (!afterUndo.startsWith('def f():') || afterUndo === afterTab.value) failures.push(`Undo did not restore the document (${JSON.stringify(afterUndo)})`); + if (!editorKeys.hintVisible) failures.push('The editor keyboard hint stayed hidden'); + + // Figures on a phone: the smallest label on the widest figures must stay + // readable, and a figure wider than the screen scrolls inside its own box + // instead of widening the page. + await client.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 1800, deviceScaleFactor: 2, mobile: true }); + const phoneFigures = []; + for (const slug of ['string-formatting', 'object-lifecycle', 'networking', 'metaclasses', 'values']) { + await client.send('Page.navigate', { url: `${pageOrigin}/examples/${slug}?browser_phone_figures=${Date.now()}` }); + await waitFor(`location.pathname === '/examples/${slug}' && document.readyState === 'complete' && !!document.querySelector('.cell-banner svg')`, `phone figure page ${slug}`); + phoneFigures.push(await evaluateValue(`(() => { + const sizes = [...document.querySelectorAll('.cell-banner svg text')].map(text => text.getBoundingClientRect().height && Number.parseFloat(getComputedStyle(text).fontSize) * (text.ownerSVGElement.getBoundingClientRect().width / text.ownerSVGElement.viewBox.baseVal.width)); + return { slug: ${JSON.stringify(slug)}, minLabelPx: Math.min(...sizes.filter(Boolean)), pageOverflow: document.documentElement.scrollWidth - document.documentElement.clientWidth }; + })()`)); + } + for (const figure of phoneFigures) { + if (!(figure.minLabelPx >= 8.5)) failures.push(`${figure.slug}: smallest figure label is ${figure.minLabelPx?.toFixed(1)}px on a 390px phone`); + if (figure.pageOverflow > 0) failures.push(`${figure.slug}: figures widen the phone page by ${figure.pageOverflow}px`); + } + console.log(JSON.stringify({ + editorKeys, + phoneFigures, runnerInteraction: interaction.result.value, runnerOrdering, share: { codeLength: share.code.length, urlLength: share.url.length, editorHeight: share.editorHeight }, diff --git a/scripts/check_inline_links.py b/scripts/check_inline_links.py index 8810e1c..ee3b197 100755 --- a/scripts/check_inline_links.py +++ b/scripts/check_inline_links.py @@ -39,7 +39,10 @@ def main() -> int: for cell in example["cells"]: surfaces += [(cell.get("line", 1), paragraph) for paragraph in cell.get("prose", [])] for line, text in surfaces: - for match in LINK_RE.finditer(text): + # render_inline splits prose on backticks first, so `first[T](items)` + # inside a code span is code, never a link. Check only the prose. + prose_only = " ".join(text.split("`")[::2]) + for match in LINK_RE.finditer(prose_only): label, target = match.group(1), match.group(2) internal = INTERNAL_RE.match(target) if not internal: diff --git a/scripts/check_quality_scores.py b/scripts/check_quality_scores.py index a329fe4..68decce 100755 --- a/scripts/check_quality_scores.py +++ b/scripts/check_quality_scores.py @@ -6,9 +6,12 @@ examples below the hard minimum must either have a narrow waiver or be tracked in the improvement backlog with a concrete next action. -Waivers are time-boxed: `expires` must be an ISO date in the future, -and a waiver whose example has recovered to target is flagged as stale -so the registry only ever describes live editorial debt. +Waivers are time-boxed by default: `expires` must be an ISO date in the +future. A waiver whose reason will never stop being true (Hello World is +tiny on purpose) sets `permanent = true` instead of `expires`; setting both +is an error, so a permanent waiver stays a deliberate, visible choice. Either +way, a waiver whose example has recovered to target is flagged as stale so +the registry only ever describes live editorial debt. A waiver that expires within WAIVER_WARNING_DAYS prints a warning in every CI run. `make check-waiver-expiry` (manual, not in CI) runs @@ -65,13 +68,22 @@ def waiver_expiry_findings( """Return (errors, warnings) for waiver expiry dates. Expired or malformed dates are errors. Dates inside the warning window - are warnings, or errors when `fail_within_days` is set. + are warnings, or errors when `fail_within_days` is set. A waiver with + `permanent = true` has no date to check; it must not also carry `expires`, + and `permanent` must be the boolean true, not a truthy string. """ errors: list[str] = [] warnings: list[str] = [] window = WAIVER_WARNING_DAYS if fail_within_days is None else fail_within_days for slug in sorted(waivers): - expires = waivers[slug].get("expires") + entry = waivers[slug] + expires = entry.get("expires") + if "permanent" in entry: + if entry["permanent"] is not True: + errors.append(f"quality waiver {slug}: permanent must be true or omitted, got {entry['permanent']!r}") + elif expires is not None: + errors.append(f"quality waiver {slug}: set either permanent = true or expires, not both") + continue if expiry_error := check_expiry_date(expires, today=today): errors.append(f"quality waiver {slug}: {expiry_error}") elif warning := expiry_warning(expires, today=today, within_days=window): @@ -149,7 +161,7 @@ def main(argv: list[str] | None = None) -> int: continue entry = waivers[slug] if not _entry_has_text(entry, "reason") or not isinstance(entry.get("accepted_min"), (int, float)): - errors.append(f"quality waiver {slug} must include accepted_min, reason, and expires") + errors.append(f"quality waiver {slug} must include accepted_min, reason, and expires (or permanent = true)") waived_score = EXAMPLE_QUALITY_SCORES.get(slug, (0.0, ""))[0] if waived_score >= target: errors.append(f"quality waiver {slug} is stale because score is now {waived_score:.1f}") @@ -219,7 +231,8 @@ def main(argv: list[str] | None = None) -> int: "Quality score gate OK " f"(target={target:.1f}, hard_min={hard_min:.1f}, " f"below_target={len(below_target)}, tracked_below_min={len(below_hard_min)}, " - f"tracked_weak_sections={len(weak_sections)}, waivers={len(waivers)})." + f"tracked_weak_sections={len(weak_sections)}, waivers={len(waivers)}, " + f"permanent_waivers={sum(1 for entry in waivers.values() if entry.get('permanent') is True)})." ) return 0 diff --git a/scripts/check_runtime_examples.py b/scripts/check_runtime_examples.py new file mode 100755 index 0000000..fd26e3b --- /dev/null +++ b/scripts/check_runtime_examples.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Run every example's complete program in the real sandbox. + +`verify_examples.py` executes the catalog under host CPython. This check +posts each program to a running Worker (the local dev Worker by default), +so it exercises what a learner gets when they press Run: the Pyodide +runtime, the Dynamic Worker harness, and the page that renders the output. + +Pages whose frontmatter sets `sandbox_limit` teach something the sandbox +cannot do (child processes, threads, sockets). For those the check asserts +that Run explains the limit instead of expecting the CPython output. +""" +from __future__ import annotations + +import argparse +import html +import re +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +from concurrent.futures import ThreadPoolExecutor + +from _common import load_catalog + +RELOAD_RETRIES = 30 +RELOAD_RETRY_SECONDS = 2 +OUTPUT_RE = re.compile(r'
]*>.*?
(.*?)
', re.DOTALL) + + +def run_in_worker(base_url: str, slug: str, code: str) -> str: + request = urllib.request.Request( + f"{base_url}/examples/{slug}", + data=urllib.parse.urlencode({"code": code}).encode("utf-8"), + headers={"Content-Type": "application/x-www-form-urlencoded"}, + method="POST", + ) + # The dev Worker answers 503 or refuses connections while it reloads after + # a rebuild; wait that out instead of failing the whole catalog. + for attempt in range(RELOAD_RETRIES + 1): + try: + with urllib.request.urlopen(request, timeout=120) as response: + page = response.read().decode("utf-8") + break + except urllib.error.HTTPError as error: + if error.code != 503 or attempt == RELOAD_RETRIES: + raise + except urllib.error.URLError: + if attempt == RELOAD_RETRIES: + raise + time.sleep(RELOAD_RETRY_SECONDS) + match = OUTPUT_RE.search(page) + if match is None: + raise RuntimeError("response has no output panel") + return html.unescape(match.group(1)) + + +def check(base_url: str, example: dict) -> str | None: + slug = example["slug"] + try: + actual = run_in_worker(base_url, slug, example["code"]) + except Exception as error: # noqa: BLE001 - report every transport failure per page + return f"{slug}: request failed: {error.__class__.__name__}: {error}" + limit = example.get("sandbox_limit") + if limit: + if limit not in actual or "sandbox" not in actual: + return f"{slug}: sandbox_limit page did not explain the limit ({limit!r}); got {actual[:200]!r}" + return None + if actual.rstrip("\n") != example["expected_output"].rstrip("\n"): + return f"{slug}: sandbox output differs from expected_output\n expected: {example['expected_output'][:300]!r}\n actual: {actual[:300]!r}" + return None + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("base_url", nargs="?", default="http://127.0.0.1:9696") + parser.add_argument("--jobs", type=int, default=4) + parser.add_argument("slugs", nargs="*") + args = parser.parse_args() + _, examples = load_catalog() + if args.slugs: + examples = [example for example in examples if example["slug"] in set(args.slugs)] + with ThreadPoolExecutor(max_workers=args.jobs) as pool: + failures = [failure for failure in pool.map(lambda example: check(args.base_url.rstrip("/"), example), examples) if failure] + for failure in failures: + print(f"FAIL: {failure}", file=sys.stderr) + if failures: + return 1 + print(f"All {len(examples)} example programs ran in the sandbox and matched their expected output.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/check_search_ranking.mjs b/scripts/check_search_ranking.mjs index d57c0a7..5179495 100755 --- a/scripts/check_search_ranking.mjs +++ b/scripts/check_search_ranking.mjs @@ -41,6 +41,16 @@ expect( const multiToken = rankExamples('for loop', entries); expect(multiToken.some((entry) => entry.slug === 'for-loops'), '"for loop" should surface for-loops'); +// Everyday words for a page's subject, and names a page uses without +// putting them in a heading, must find that page. +for (const [query, slug] of [['dictionary', 'dicts'], ['mutable', 'mutability'], ['regex', 'regular-expressions'], ['null', 'none']]) { + const top = rankExamples(query, entries)[0]?.slug; + expect(top === slug, `"${query}" should rank ${slug} first, got ${top}`); +} +for (const query of ['zip', 'join', 'random', 'docstring', 'enumerate']) { + expect(rankExamples(query, entries).length > 0, `"${query}" should return at least one example`); +} + expect(rankExamples('zzzznonexistent', entries).length === 0, 'nonsense query should return nothing'); expect(rankExamples('', entries).length === 0, 'empty query should return nothing'); expect(rankExamples('closures', entries, 3).length <= 3, 'limit should cap results'); diff --git a/scripts/fingerprint_assets.py b/scripts/fingerprint_assets.py index 665dfb0..2f49804 100755 --- a/scripts/fingerprint_assets.py +++ b/scripts/fingerprint_assets.py @@ -13,6 +13,7 @@ ASSETS = { "SITE_CSS": "site.css", "SYNTAX_JS": "syntax-highlight.js", + "HIGHLIGHTER_JS": "highlighter.js", "EDITOR_JS": "editor.js", "RUNNER_JS": "runner.js", "SEARCH_JS": "search.js", @@ -81,6 +82,8 @@ def main() -> None: " Cache-Control: public, max-age=31536000, immutable\n\n" "/syntax-highlight.*.js\n" " Cache-Control: public, max-age=31536000, immutable\n\n" + "/highlighter.*.js\n" + " Cache-Control: public, max-age=31536000, immutable\n\n" "/editor.*.js\n" " Cache-Control: public, max-age=31536000, immutable\n\n" "/runner.*.js\n" diff --git a/scripts/score_example_criteria.py b/scripts/score_example_criteria.py index 5e45768..c35e17a 100755 --- a/scripts/score_example_criteria.py +++ b/scripts/score_example_criteria.py @@ -56,18 +56,23 @@ def criterion_scores(example: dict) -> dict[str, float]: overlap = len(code_tokens & prose_tokens) generic_penalty = 0.2 * sum(phrase in all_text.lower() for phrase in GENERIC_PHRASES) + # Accuracy and practical usefulness cannot be observed from the page text, + # so these two criteria only penalise metasyntactic names and never reach + # 1.0. They used to award credit for containing `print(` and for names + # such as "Ada" or "price"; those were proxies a page could satisfy + # without being accurate or useful, so the credit is withheld instead. return { "conceptual_payoff": clamp(0.45 + min(len(prose) / 900, 0.35) + min(overlap / 30, 0.2) - generic_penalty), "rationale": clamp(0.35 + 0.35 * bool(RATIONALE_WORDS.search(all_text)) + min(len(example.get("notes", [])) / 6, 0.3) - generic_penalty), "alternatives_and_boundaries": clamp(0.25 + 0.25 * bool(BOUNDARY_WORDS.search(all_text)) + 0.2 * bool(unsupported_cells) + min(notes.lower().count("prefer") / 2, 0.2)), "executable_determinism": clamp(0.75 + 0.25 * bool(example.get("expected_output")) - 0.25 * bool(example.get("version_sensitive"))), - "python_idiom_and_accuracy": clamp(0.75 + 0.15 * bool(example.get("doc_url")) + 0.1 * ("print(" in code) - 0.25 * bool(TOY_WORDS.search(code))), + "python_idiom_and_accuracy": clamp(0.75 + 0.15 * bool(example.get("doc_url")) - 0.25 * bool(TOY_WORDS.search(code))), "literate_fit": clamp(0.35 + min(len(normal_cells) / 4, 0.35) + 0.3 * all(cell.get("prose") for cell in normal_cells)), "source_result_pairing": clamp(0.35 + 0.45 * all(outputs) + min(output_lines / 8, 0.2)), "concept_decomposition": clamp(0.25 + min(len(normal_cells) / 3, 0.55) + 0.2 * (len(normal_cells) >= 3)), "progressive_walkthrough": clamp(0.35 + min(distinct_cell_starts / max(len(normal_cells), 1), 0.45) + 0.2 * (len(normal_cells) >= 2)), "representative_coverage": clamp(0.3 + min(output_lines / 10, 0.25) + min(len(example.get("see_also", [])) / 4, 0.25) + 0.2 * (len(normal_cells) >= 3)), - "practical_usefulness": clamp(0.55 + 0.25 * (not bool(TOY_WORDS.search(code))) + 0.2 * bool(re.search(r"Ada|Grace|project|config|score|price|request|path|file|service|team", code))), + "practical_usefulness": clamp(0.55 + 0.25 * (not bool(TOY_WORDS.search(code)))), "editorial_progression": clamp(0.35 + min(len(example.get("explanation", [])) / 3, 0.25) + min(len(example.get("notes", [])) / 4, 0.25) + 0.15 * bool(example.get("see_also"))), } diff --git a/src/app.py b/src/app.py index 9f165e1..84fc8fa 100644 --- a/src/app.py +++ b/src/app.py @@ -12,6 +12,7 @@ from .asset_manifest import ASSET_PATHS from .editorial_registry import journeys as load_journeys from .editorial_registry import see_also_edge_labels as load_see_also_edge_labels + from .example_loader import _source_text as _example_source_text from .examples import EXAMPLES, EXAMPLES_BY_SLUG, PYTHON_VERSION, REFERENCE_URL from .marginalia import render_banner, render_for_section from .textfmt import render_inline @@ -19,6 +20,7 @@ from asset_manifest import ASSET_PATHS from editorial_registry import journeys as load_journeys from editorial_registry import see_also_edge_labels as load_see_also_edge_labels + from example_loader import _source_text as _example_source_text from examples import EXAMPLES, EXAMPLES_BY_SLUG, PYTHON_VERSION, REFERENCE_URL from marginalia import render_banner, render_for_section from textfmt import render_inline @@ -71,6 +73,12 @@ def _recommended_examples(slug, limit=4): MAX_DYNAMIC_OUTPUT_BYTES = 64 * 1024 DYNAMIC_OUTPUT_LIMIT_MESSAGE = "Program output exceeded the 64 kB limit. Reduce output and try again." +# Learner tracebacks name this file instead of the harness module. +EXAMPLE_FILENAME = "example.py" +INPUT_UNAVAILABLE_MESSAGE = ( + "input() is not available here: the sandbox runs your program without a terminal. " + "Assign the value directly instead, for example name = \"Ada\"." +) def build_dynamic_worker_code(example_code: str) -> str: @@ -78,11 +86,15 @@ def build_dynamic_worker_code(example_code: str) -> str: return f'''from workers import WorkerEntrypoint, Response import contextlib import io +import linecache import traceback EXAMPLE_CODE = {example_code!r} +EXAMPLE_FILENAME = {EXAMPLE_FILENAME!r} MAX_OUTPUT_BYTES = {MAX_DYNAMIC_OUTPUT_BYTES} OUTPUT_LIMIT_MESSAGE = {DYNAMIC_OUTPUT_LIMIT_MESSAGE!r} +INPUT_UNAVAILABLE_MESSAGE = {INPUT_UNAVAILABLE_MESSAGE!r} +TEXT_HEADERS = {{"Content-Type": "text/plain; charset=utf-8"}} class OutputLimitExceeded(Exception): @@ -129,23 +141,74 @@ def getvalue(self): return "".join(checked) +def _no_input(prompt=""): + raise EOFError(INPUT_UNAVAILABLE_MESSAGE) + + +# The file this module was loaded from, however the loader named it. +HARNESS_FILENAME = _no_input.__code__.co_filename + + +def _drop_harness_frames(summary, seen): + # Chained exceptions (raise ... from, or errors while handling another) + # each carry their own stack. + if summary is None or id(summary) in seen: + return + seen.add(id(summary)) + summary.stack = traceback.StackSummary.from_list( + [frame for frame in summary.stack if frame.filename != HARNESS_FILENAME] + ) + _drop_harness_frames(summary.__cause__, seen) + _drop_harness_frames(summary.__context__, seen) + + +def _learner_traceback(error): + # Show the learner their own frames only: register the source so each + # frame prints its line, and drop the frames that belong to this harness + # (the exec() call and the input() stand-in). + linecache.cache[EXAMPLE_FILENAME] = ( + len(EXAMPLE_CODE), None, EXAMPLE_CODE.splitlines(True), EXAMPLE_FILENAME + ) + summary = traceback.TracebackException.from_exception(error) + _drop_harness_frames(summary, set()) + return "".join(summary.format()) + + +def _exit_note(error): + # exit() and sys.exit() end the program; they are not failures. A + # message or non-zero status is reported the way a shell would show it. + code = error.code + if code is None or code == 0: + return "" + if isinstance(code, int): + return f"[exited with status {{code}}]\\n" + return f"{{code}}\\n" + + class Default(WorkerEntrypoint): async def fetch(self, request): - stdout = BoundedStdout() - namespace = {{"__name__": "__main__"}} + # stdout and stderr share one bounded sink, so warnings, logging and + # print(..., file=sys.stderr) appear in program order. + output = BoundedStdout() + namespace = {{"__name__": "__main__", "input": _no_input}} + status = 200 try: - with contextlib.redirect_stdout(stdout): - exec(EXAMPLE_CODE, namespace) - return Response(BoundedStdout.getvalue(stdout), headers={{"Content-Type": "text/plain; charset=utf-8"}}) - except OutputLimitExceeded: - return Response(OUTPUT_LIMIT_MESSAGE, status=413, headers={{"Content-Type": "text/plain; charset=utf-8"}}) - except Exception: - error_output = BoundedStdout() try: - traceback.print_exc(file=error_output) + with contextlib.redirect_stdout(output), contextlib.redirect_stderr(output): + exec(compile(EXAMPLE_CODE, EXAMPLE_FILENAME, "exec", dont_inherit=True), namespace) except OutputLimitExceeded: - return Response(OUTPUT_LIMIT_MESSAGE, status=413, headers={{"Content-Type": "text/plain; charset=utf-8"}}) - return Response(error_output.getvalue(), status=500, headers={{"Content-Type": "text/plain; charset=utf-8"}}) + raise + except SystemExit as error: + output.write(_exit_note(error)) + except KeyboardInterrupt as error: + status = 500 + output.write(_learner_traceback(error)) + except Exception as error: + status = 500 + output.write(_learner_traceback(error)) + return Response(BoundedStdout.getvalue(output), status=status, headers=TEXT_HEADERS) + except OutputLimitExceeded: + return Response(OUTPUT_LIMIT_MESSAGE, status=413, headers=TEXT_HEADERS) ''' @@ -221,10 +284,10 @@ def _layout(title: str, content: str, description: str | None = None, path: str og_url_tag = f'' if canonical_url else "" robots_meta = "" if canonical_url else '' page_title = title if title == "Python By Example" else f"{title} · Python By Example" - # The CDN-backed editor stays in the head, but the dependency-free runner + # The editor bundle stays in the head, but the small dependency-free runner # is emitted after page content. Its async module can then attach Run, - # Reset, share, and navigation without waiting for the editor's esm.sh - # graph or for DOMContentLoaded (which that graph delays). + # Reset, share, and navigation without waiting for the much larger editor + # bundle or for DOMContentLoaded (which that download delays). editor_scripts = f'' if include_editor else "" runner_script = f'' if include_editor else "" if include_search: @@ -245,6 +308,7 @@ def _layout(title: str, content: str, description: str | None = None, path: str "OG_TYPE": html.escape(og_type), "SITE_CSS": html.escape(ASSET_PATHS["SITE_CSS"]), "SYNTAX_JS": html.escape(ASSET_PATHS["SYNTAX_JS"]), + "HIGHLIGHTER_JS": html.escape(ASSET_PATHS["HIGHLIGHTER_JS"]), "EDITOR_SCRIPTS": editor_scripts, "RUNNER_SCRIPT": runner_script, "CONTENT": content, @@ -313,13 +377,13 @@ def render_journeys_index(): description = "Curated Python By Example journeys that compose individual examples into larger mental maps with per-section learner outcomes." cards = [] for journey in JOURNEYS: - section_titles = "".join(f'
  • {html.escape(section["title"])}
  • ' for section in journey["sections"]) + section_titles = "".join(f'
  • {render_inline(section["title"])}
  • ' for section in journey["sections"]) cards.append( f'''

    Journey

    {html.escape(journey["title"])}

    -

    {html.escape(journey["summary"])}

    +

    {render_inline(journey["summary"])}

      {section_titles}
    ''' ) @@ -350,7 +414,7 @@ def render_journeys_index(): def render_journey_page(journey): - overview = "".join(f'
  • {html.escape(section["title"])}
  • ' for section in journey["sections"]) + overview = "".join(f'
  • {render_inline(section["title"])}
  • ' for section in journey["sections"]) sections = [] for section in journey["sections"]: rows = [] @@ -363,19 +427,19 @@ def render_journey_page(journey): target = f'Missing example: {label}' else: target = f'{html.escape(example["title"])}' - rows.append(f'
  • {target}

    {html.escape(sentence)}

  • ') + rows.append(f'
  • {target}

    {render_inline(sentence)}

  • ') else: sentence = f"This gap should {description}." - rows.append(f'
  • Gap · {html.escape(value)}

    {html.escape(sentence)}

  • ') + rows.append(f'
  • Gap · {render_inline(value)}

    {render_inline(sentence)}

  • ') figure_html = render_for_section(section["title"]) - sections.append(f'

    {html.escape(section["title"])}

    {html.escape(section["summary"])}

    {figure_html}
      {"".join(rows)}
    ') + sections.append(f'

    {render_inline(section["title"])}

    {render_inline(section["summary"])}

    {figure_html}
      {"".join(rows)}
    ') content = f'''

    Journey

    {html.escape(journey["title"])}

    -

    {html.escape(journey["summary"])}

    +

    {render_inline(journey["summary"])}

    In this journey

      {overview}
    {"".join(sections)} @@ -429,7 +493,7 @@ def render_privacy() -> str: return _layout( "Privacy", _template("privacy.html"), - description="How Python By Example handles runner submissions, operational logs, Cloudflare Turnstile verification, cookies, and optional code-editor CDN requests.", + description="How Python By Example handles runner submissions, operational logs, Cloudflare Turnstile verification, cookies, and the self-hosted code editor.", path="/privacy", og_image=f"{SITE_URL}/og/privacy.jpg", structured_data={ @@ -456,6 +520,39 @@ def render_sitemap() -> str: ) +def example_markdown(slug: str) -> str | None: + """The authored Markdown source of an example, or None for unknown slugs.""" + if get_example(slug) is None: + return None + return _example_source_text(f"{slug}.md") + + +def render_llms_txt() -> str: + """A plain-text map of the site for language models and other tools.""" + lines = [ + "# Python By Example", + "", + ( + f"> Python {PYTHON_VERSION} taught through {len(list_examples())} small, runnable examples. " + "Each page explains one concept with annotated source, verified output, and a link to the official documentation." + ), + "", + "Each example is also available as Markdown by adding `.md` to its URL.", + ] + by_section: dict[str, list[dict]] = {} + for example in list_examples(): + by_section.setdefault(example["section"], []).append(example) + for section, examples in by_section.items(): + lines += ["", f"## {section}", ""] + lines += [ + f'- [{example["title"]}]({SITE_URL}/examples/{example["slug"]}.md): {example["summary"]}' + for example in examples + ] + lines += ["", "## Journeys", ""] + lines += [f'- [{journey["title"]}]({SITE_URL}/journeys/{journey["slug"]}): {journey["summary"]}' for journey in JOURNEYS] + return "\n".join(lines) + "\n" + + def render_example_not_found(slug: str) -> str: recommendations = "".join( f'
  • {html.escape(item["title"])}
  • ' @@ -631,6 +728,18 @@ def _render_walkthrough(slug: str, walkthrough: list[dict]) -> str: return "".join(parts) +def sandbox_limit_note(example) -> str: + """What Run says first on a page that teaches something the sandbox lacks.""" + limit = example.get("sandbox_limit") + if not limit: + return "" + return ( + f"This page uses {limit}, which the in-browser sandbox does not provide, " + "so Run ends with the error below. The expected output shown on this page " + "came from standard CPython.\n\n" + ) + + def _turnstile_challenge_container(site_key: str | None) -> str: if not site_key: return "" @@ -641,7 +750,7 @@ def _turnstile_challenge_container(site_key: str | None) -> str: def _turnstile_required_marker(required: bool) -> str: if not required: return "" - return '' + return '' def render_example_page( @@ -653,6 +762,9 @@ def render_example_page( turnstile_required=False, ): notes = [render_inline(note) for note in example.get("notes", [])] + intro_html = "".join(f"

    {render_inline(paragraph)}

    " for paragraph in example.get("explanation", [])) + if intro_html: + intro_html = f'
    {intro_html}
    ' walkthrough = _walkthrough_cells(example) shown_output = output if output is not None else example.get("expected_output", "Run this example to see output here.") output_heading = "Output" if output is not None else "Expected output" @@ -685,6 +797,7 @@ def render_example_page( "SECTION": html.escape(example["section"]), "TITLE": html.escape(example["title"]), "SUMMARY": html.escape(example["summary"]), + "INTRO": intro_html, "WALKTHROUGH": walkthrough_html, "NOTES": notes_html, "SEE_ALSO": see_also_html, diff --git a/src/asset_manifest.py b/src/asset_manifest.py index 061c7c6..11b8395 100644 --- a/src/asset_manifest.py +++ b/src/asset_manifest.py @@ -1,3 +1,3 @@ # Generated by scripts/fingerprint_assets.py. Do not edit by hand. -ASSET_PATHS = {'SITE_CSS': '/site.32ce5906d3c1.css', 'SYNTAX_JS': '/syntax-highlight.743e2535f133.js', 'EDITOR_JS': '/editor.3659b44c8480.js', 'RUNNER_JS': '/runner.05ddb60aa9e7.js', 'SEARCH_JS': '/search.e5a5822d9917.js', 'SEARCH_INDEX': '/search-index.332712b2e502.json'} -HTML_CACHE_VERSION = '93bb0fecab44' +ASSET_PATHS = {'SITE_CSS': '/site.2a72bda337b4.css', 'SYNTAX_JS': '/syntax-highlight.c4fabad2b399.js', 'HIGHLIGHTER_JS': '/highlighter.b1b5aad7a305.js', 'EDITOR_JS': '/editor.d656e57507ca.js', 'RUNNER_JS': '/runner.36d32891c1eb.js', 'SEARCH_JS': '/search.4d7b3a480c78.js', 'SEARCH_INDEX': '/search-index.88d2f30fd230.json'} +HTML_CACHE_VERSION = 'f2d4086f497e' diff --git a/src/editorial_registry_data.py b/src/editorial_registry_data.py index 62f94aa..5fa527e 100644 --- a/src/editorial_registry_data.py +++ b/src/editorial_registry_data.py @@ -1,2 +1,2 @@ # Generated by scripts/embed_editorial_registry.py. Do not edit by hand. -REGISTRY_TOML = '# Quality and editorial registries.\n#\n# Source of truth for rubric checks, journey structure, edge labels,\n# figure attachments/captions, and curated scores. Executable paint\n# functions stay in `src/marginalia.py`; mutable editorial data lives here.\n\n[[confusable_pairs]]\nname = "__str__ vs __repr__"\nowner = "special-methods"\ntokens = ["__str__", "__repr__"]\n\n[[confusable_pairs]]\nname = "is vs =="\nowner = "equality-and-identity"\ntokens = [" is ", "=="]\n\n[[confusable_pairs]]\nname = "list vs tuple"\nowner = "tuples"\ntokens = ["list", "tuple"]\n\n[[confusable_pairs]]\nname = "classmethod vs staticmethod vs instance method"\nowner = "classmethods-and-staticmethods"\ntokens = ["@classmethod", "@staticmethod", "self"]\n\n[[confusable_pairs]]\nname = "isinstance vs type=="\nowner = "runtime-type-checks"\ntokens = ["isinstance(", "type("]\n\n[[confusable_pairs]]\nname = "generator vs class iterator"\nowner = "generators"\ntokens = ["yield", "__next__"]\n\n[[confusable_pairs]]\nname = "iterator vs iterable"\nowner = "iterator-vs-iterable"\ntokens = ["iterable", "iterator", "iter("]\n\n[[confusable_pairs]]\nname = "mutable vs immutable class attributes"\nowner = "classes"\ntokens = ["class attribute", "__init__"]\n\n[[confusable_pairs]]\nname = "eager vs lazy production"\nowner = "generators"\ntokens = ["return", "yield"]\n\n[[confusable_pairs]]\nname = "Protocol vs ABC"\nowner = "abstract-base-classes"\ntokens = ["Protocol", "ABC"]\n\n[[confusable_pairs]]\nname = "dataclass vs NamedTuple vs TypedDict"\nowner = "structured-data-shapes"\ntokens = ["@dataclass", "NamedTuple", "TypedDict"]\n\n[[confusable_pairs]]\nname = "bound vs unbound methods"\nowner = "bound-and-unbound-methods"\ntokens = ["bound method", "Class.method"]\n\n[[confusable_pairs]]\nname = "yield vs return"\nowner = "generators"\ntokens = ["yield", "return"]\n\n[[confusable_pairs]]\nname = "shallow vs deep copy"\nowner = "copying-collections"\ntokens = ["copy(", "deepcopy("]\n\n[[confusable_pairs]]\nname = "sync vs async functions"\nowner = "async-await"\ntokens = ["async def", "def "]\n\n[broad_surface_tours]\n\n[broad_surface_tours.special-methods]\nrequired_tokens = [\n "__init__", "__repr__", "__str__", "__eq__", "__hash__", "__lt__",\n "__len__", "__iter__", "__contains__", "__getitem__", "__setitem__",\n "__call__", "__enter__", "__exit__", "__bool__",\n]\n\n[broad_surface_tours.operators]\nrequired_tokens = ["+", "==", " is ", " in ", "and", "or", "&", ":="]\n\n[broad_surface_tours.type-hints]\nrequired_tokens = ["list[", " | ", "Optional", "TypeAlias"]\n\n[broad_surface_tours.testing]\nrequired_tokens = ["TestCase", "assertEqual", "assertRaises", "setUp"]\n\n[broad_surface_tours.async-await]\nrequired_tokens = ["async def", "await", "asyncio.run", "asyncio.gather", "async for", "async with"]\n\n[broad_surface_tours.packages]\nrequired_tokens = ["__init__.py", "from .", "__all__"]\n\n[broad_surface_tours.regular-expressions]\nrequired_tokens = ["re.match", "re.search", "re.findall", "re.compile", "re.IGNORECASE", "re.sub"]\n\n[broad_surface_tours.literals]\nrequired_tokens = ["0x", "0b", "_", "f\\"", "True", "None"]\n\n[[footguns]]\nname = "Mutable default class attribute"\nowner = "classes"\nbroken_tokens = ["items = []"]\nfixed_tokens = ["self.items = []"]\n\n[[footguns]]\nname = "Mutable default function argument"\nowner = "functions"\nbroken_tokens = ["items=[]", "append_broken"]\nfixed_tokens = ["items=None", "append_fixed"]\n\n[[footguns]]\nname = "Late-binding closure in a loop"\nowner = "closures"\nbroken_tokens = ["lambda: i", "[2, 2, 2]"]\nfixed_tokens = ["lambda i=i", "[0, 1, 2]"]\n\n[[footguns]]\nname = "Integer identity caching"\nowner = "equality-and-identity"\nbroken_tokens = ["small_a is small_b", "big_a is big_b"]\nfixed_tokens = ["big_a == big_b", "small-integer cache"]\n\n[[footguns]]\nname = "Shallow vs deep copy"\nowner = "copying-collections"\nbroken_tokens = ["copy("]\nfixed_tokens = ["deepcopy("]\n\n[[footguns]]\nname = "Generator one-pass exhaustion"\nowner = "generators"\nbroken_tokens = ["yield"]\nfixed_tokens = ["list("]\n\n[[footguns]]\nname = "Dictionary mutation during iteration"\nowner = "dicts"\nbroken_tokens = ["for ", "del "]\nfixed_tokens = ["list(", ".keys("]\n\n[[footguns]]\nname = "Floating-point equality"\nowner = "numbers"\nbroken_tokens = ["0.1", "0.2"]\nfixed_tokens = ["isclose", "math"]\n\n[[footguns]]\nname = "bool as a subclass of int"\nowner = "booleans"\nbroken_tokens = ["isinstance(True, int)", "True + True"]\nfixed_tokens = ["not isinstance(value, bool)", "is_strict_int"]\n\n[[footguns]]\nname = "Bare except swallowing KeyboardInterrupt"\nowner = "exceptions"\nbroken_tokens = ["except Exception"]\nfixed_tokens = ["except ValueError"]\n\n[paired_pages]\n# Pages whose titles differ only by a suffix or modifier; at least one\n# member of each pair must demonstrate the relationship in a cell.\npairs = [\n ["iterators", "iterating-over-iterables"],\n ["iterators", "iterator-vs-iterable"],\n ["generators", "generator-expressions"],\n ["comprehensions", "comprehension-patterns"],\n]\n\n[paired_pages.cell_tokens]\n"iterators|iterating-over-iterables" = ["iterable", "iterator"]\n"iterators|iterator-vs-iterable" = ["iterable", "iterator", "iter("]\n"generators|generator-expressions" = ["generator", "expression"]\n"comprehensions|comprehension-patterns" = ["nested loops", "explicit loop"]\n\n[quality_gates]\nexample_target = 9.0\nexample_hard_min = 8.5\njourney_section_min = 8.5\njourney_average_min = 8.8\n\n[quality_waivers.hello-world]\naccepted_min = 7.0\nreason = "Traditional first example is intentionally tiny: program -> output is the goal, not a full concept tour."\nexpires = "2026-12-01"\n\n[no_figure_rationales]\n# Slugs may be added here only when the page is constraint-shaped,\n# infrastructure-shaped, or aggregator-shaped and a single mechanism\n# figure would distort the lesson. A weak figure is redrawn, not removed:\n# a page that had a figure keeps one. Current production attaches\n# figures to every example, so this registry is intentionally empty.\n\n[journey_outcomes]\n\n[journey_outcomes."runtime::Start with executable evidence."]\njourney = "runtime"\nsection = "Start with executable evidence."\nsupport = [\n "hello-world",\n "values",\n "literals",\n "variables",\n "constants",\n]\noutcomes = [\n "start with a complete program and its output",\n "see that Python programs manipulate runtime objects",\n "write small values directly in source code",\n "understand that names bind to objects rather than storing values themselves",\n]\n\n[journey_outcomes."runtime::Separate value, identity, and absence."]\njourney = "runtime"\nsection = "Separate value, identity, and absence."\nsupport = [\n "none",\n "booleans",\n "truthiness",\n "equality-and-identity",\n "mutability",\n "object-lifecycle",\n]\noutcomes = [\n "represent expected absence with a singleton object",\n "combine facts with boolean operators",\n "predict how objects behave in boolean contexts",\n "distinguish value equality from object identity",\n]\n\n[journey_outcomes."runtime::Read expressions as object operations."]\njourney = "runtime"\nsection = "Read expressions as object operations."\nsupport = [\n "numbers",\n "operators",\n "strings",\n "string-formatting",\n "bytes-and-bytearray",\n]\noutcomes = [\n "use numeric objects and arithmetic operators",\n "combine, compare, and test values with expression syntax",\n "treat text as Unicode rather than raw bytes",\n "turn objects into readable text at output boundaries",\n]\n\n[journey_outcomes."control-flow::Choose between paths."]\njourney = "control-flow"\nsection = "Choose between paths."\nsupport = [\n "booleans",\n "truthiness",\n "operators",\n "conditionals",\n]\noutcomes = [\n "combine facts into readable conditions",\n "use object truth values without hiding intent",\n "build comparisons and boolean expressions for conditions",\n "choose between branches with clear predicates",\n]\n\n[journey_outcomes."control-flow::Name and shape decisions."]\njourney = "control-flow"\nsection = "Name and shape decisions."\nsupport = [\n "assignment-expressions",\n "match-statements",\n "advanced-match-patterns",\n]\noutcomes = [\n "name an intermediate value inside a condition when it improves clarity",\n "dispatch on the shape of data rather than only on boolean tests",\n "combine destructuring, alternatives, and guards in pattern matching",\n]\n\n[journey_outcomes."control-flow::Stop as soon as the answer is known."]\njourney = "control-flow"\nsection = "Stop as soon as the answer is known."\nsupport = [\n "guard-clauses",\n "assertions",\n "exceptions",\n]\noutcomes = [\n "show how early returns reduce nested conditional code",\n "state assumptions that should fail loudly while developing",\n "leave the current path when ordinary return values are not enough",\n]\n\n[journey_outcomes."iteration::Choose the right loop shape."]\njourney = "iteration"\nsection = "Choose the right loop shape."\nsupport = [\n "for-loops",\n "while-loops",\n "break-and-continue",\n "loop-else",\n "sentinel-iteration",\n]\noutcomes = [\n "consume values from an iterable",\n "repeat while a condition must be rechecked",\n "interrupt or skip loop work intentionally",\n "attach completion logic to loops that did not break",\n]\n\n[journey_outcomes."iteration::See the protocol behind `for`."]\njourney = "iteration"\nsection = "See the protocol behind `for`."\nsupport = [\n "iterating-over-iterables",\n "iterator-vs-iterable",\n "iterators",\n "generators",\n]\noutcomes = [\n "separate value producers from value consumers",\n "use `iter()` and `next()` to expose the protocol behind `for`",\n "write functions that produce values lazily",\n]\n\n[journey_outcomes."iteration::Compose lazy value streams."]\njourney = "iteration"\nsection = "Compose lazy value streams."\nsupport = [\n "generator-expressions",\n "itertools",\n "yield-from",\n]\noutcomes = [\n "create lazy one-pass streams with expression syntax",\n "compose iterator streams without materializing every value",\n "delegate part of a generator to another iterable",\n]\n\n[journey_outcomes."shapes::Pick the container that matches the question."]\njourney = "shapes"\nsection = "Pick the container that matches the question."\nsupport = [\n "lists",\n "tuples",\n "dicts",\n "sets",\n "collections-module",\n]\noutcomes = [\n "store ordered mutable data",\n "group fixed-position values",\n "look up values by key",\n "model uniqueness and membership",\n]\n\n[journey_outcomes."shapes::Move between shapes deliberately."]\njourney = "shapes"\nsection = "Move between shapes deliberately."\nsupport = [\n "unpacking",\n "slices",\n "comprehensions",\n "comprehension-patterns",\n "sorting",\n "copying-collections",\n]\noutcomes = [\n "bind names from structured values",\n "select ranges from sequences",\n "build concrete collections from compact loops",\n "compose filters and nested transformations",\n]\n\n[journey_outcomes."shapes::Cross text and data boundaries."]\njourney = "shapes"\nsection = "Cross text and data boundaries."\nsupport = [\n "number-parsing",\n "json",\n "regular-expressions",\n "datetime",\n "csv-data",\n]\noutcomes = [\n "turn text into numbers safely",\n "move structured data across a text boundary",\n "extract structure from text patterns",\n "represent dates, times, and durations as typed values",\n]\n\n[journey_outcomes."interfaces::Start with functions as named behavior."]\njourney = "interfaces"\nsection = "Start with functions as named behavior."\nsupport = [\n "functions",\n "keyword-only-arguments",\n "positional-only-parameters",\n "args-and-kwargs",\n "multiple-return-values",\n]\noutcomes = [\n "package behavior behind a name",\n "make important call-site choices explicit",\n "hide parameter names that should remain implementation details",\n "accept flexible call shapes when forwarding or adapting APIs",\n]\n\n[journey_outcomes."interfaces::Use functions as values."]\njourney = "interfaces"\nsection = "Use functions as values."\nsupport = [\n "scope-global-nonlocal",\n "closures",\n "recursion",\n "lambdas",\n "decorators",\n "partial-functions",\n]\noutcomes = [\n "control where assignment happens",\n "capture state in nested functions",\n "solve self-similar problems with a base case",\n "write small unnamed functions for expression positions",\n]\n\n[journey_outcomes."interfaces::Bundle behavior with state."]\njourney = "interfaces"\nsection = "Bundle behavior with state."\nsupport = [\n "classes",\n "inheritance-and-super",\n "dataclasses",\n "properties",\n "classmethods-and-staticmethods",\n "special-methods",\n "truth-and-size",\n "container-protocols",\n "callable-objects",\n "operator-overloading",\n "attribute-access",\n "bound-and-unbound-methods",\n "descriptors",\n "metaclasses",\n]\noutcomes = [\n "bundle state and behavior into a new object type",\n "reuse and extend behavior through parent classes",\n "generate common methods for data containers",\n "keep attribute syntax while adding computation or validation",\n]\n\n[journey_outcomes."types::Keep runtime and static analysis separate."]\njourney = "types"\nsection = "Keep runtime and static analysis separate."\nsupport = [\n "type-hints",\n "protocols",\n "abstract-base-classes",\n "enums",\n "runtime-type-checks",\n]\noutcomes = [\n "document expected types and feed type checkers",\n "describe required behavior by structural shape",\n "name a fixed set of symbolic values",\n "show `type()`, `isinstance()`, and `issubclass()` without turning Python into Java",\n]\n\n[journey_outcomes."types::Describe realistic data shapes."]\njourney = "types"\nsection = "Describe realistic data shapes."\nsupport = [\n "union-and-optional-types",\n "type-aliases",\n "typed-dicts",\n "structured-data-shapes",\n "literal-and-final",\n "callable-types",\n]\noutcomes = [\n "show `X | Y` and `None`-aware APIs",\n "name complex types with `type` statements or aliases",\n "type dictionary records that come from JSON",\n "express constrained values and names that should not be rebound",\n]\n\n[journey_outcomes."types::Scale annotations for reusable libraries."]\njourney = "types"\nsection = "Scale annotations for reusable libraries."\nsupport = [\n "generics-and-typevar",\n "paramspec",\n "overloads",\n "casts-and-any",\n "newtype",\n]\noutcomes = [\n "write reusable typed containers and functions",\n "preserve callable signatures through decorators",\n "describe APIs whose return type depends on the input shape",\n "show escape hatches and their tradeoffs",\n]\n\n[journey_outcomes."reliability::Make failure explicit."]\njourney = "reliability"\nsection = "Make failure explicit."\nsupport = [\n "exceptions",\n "assertions",\n "exception-chaining",\n "exception-groups",\n "custom-exceptions",\n "warnings",\n]\noutcomes = [\n "signal and recover from errors",\n "state internal assumptions",\n "preserve the cause while translating an error",\n "handle multiple failures together",\n]\n\n[journey_outcomes."reliability::Control resource and module boundaries."]\njourney = "reliability"\nsection = "Control resource and module boundaries."\nsupport = [\n "context-managers",\n "delete-statements",\n "modules",\n "import-aliases",\n "packages",\n "virtual-environments",\n]\noutcomes = [\n "pair setup with reliable cleanup",\n "remove names, attributes, and items intentionally",\n "split code into importable files",\n "make imported names clear at use sites",\n]\n\n[journey_outcomes."reliability::Handle operations that outlive one expression."]\njourney = "reliability"\nsection = "Handle operations that outlive one expression."\nsupport = [\n "async-await",\n "async-iteration-and-context",\n "logging",\n "testing",\n "subprocesses",\n "threads-and-processes",\n "networking",\n]\noutcomes = [\n "await concurrent I/O-shaped work",\n "consume async streams and cleanup protocols",\n "record operational events without using `print()`",\n "write deterministic tests with `unittest` or `pytest`",\n]\n\n[score_model]\n# Criterion weights mirror docs/example-quality-rubric.md. The registry\n# makes the scoring model inspectable even before every example is broken\n# down into per-criterion subscores.\nconceptual_payoff = 1.0\nrationale = 0.75\nalternatives_and_boundaries = 0.75\nexecutable_determinism = 1.0\npython_idiom_and_accuracy = 1.0\nliterate_fit = 0.75\nsource_result_pairing = 0.75\nconcept_decomposition = 0.75\nprogressive_walkthrough = 0.75\nrepresentative_coverage = 0.75\npractical_usefulness = 0.75\neditorial_progression = 1.0\n\n# Editorial registries loaded by the site at runtime.\n# Keep prose, captions, scores, journey ordering, and edge labels here;\n# keep executable paint functions in src/marginalia.py.\n\n[[journeys]]\nslug = "runtime"\ntitle = "Runtime"\nsummary = "This journey builds the smallest coherent model of Python at runtime: programs run statements, names refer to objects, objects have types, and operations ask those objects to do work."\n\n[[journeys.sections]]\ntitle = "Start with executable evidence."\nsummary = "Learners first need to see that every page is a runnable program with visible output."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "hello-world"\ndescription = "start with a complete program and its output"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "values"\ndescription = "see that Python programs manipulate runtime objects"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "literals"\ndescription = "write small values directly in source code"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "variables"\ndescription = "understand that names bind to objects rather than storing values themselves"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "constants"\ndescription = "learn the convention Python uses for values that should not change"\n\n[[journeys.sections]]\ntitle = "Separate value, identity, and absence."\nsummary = "This section prevents early confusion about equality, object identity, missing values, and truth tests."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "none"\ndescription = "represent expected absence with a singleton object"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "booleans"\ndescription = "combine facts with boolean operators"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "truthiness"\ndescription = "predict how objects behave in boolean contexts"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "equality-and-identity"\ndescription = "distinguish value equality from object identity"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "mutability"\ndescription = "predict when operations change an object in place"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "object-lifecycle"\ndescription = "explain references, garbage collection, and why identity can outlive a single name"\n\n[[journeys.sections]]\ntitle = "Read expressions as object operations."\nsummary = "This section connects operators, text, and formatting to Python\'s data model."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "numbers"\ndescription = "use numeric objects and arithmetic operators"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "operators"\ndescription = "combine, compare, and test values with expression syntax"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "strings"\ndescription = "treat text as Unicode rather than raw bytes"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "string-formatting"\ndescription = "turn objects into readable text at output boundaries"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "bytes-and-bytearray"\ndescription = "contrast text with binary data and explicit decoding"\n\n[[journeys]]\nslug = "control-flow"\ntitle = "Control Flow"\nsummary = "This journey follows how a Python program chooses which path runs, names facts at decision points, and exits early when the remaining work no longer applies."\n\n[[journeys.sections]]\ntitle = "Choose between paths."\nsummary = "Start with ordinary branching and boolean predicates before reaching for more compact forms."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "booleans"\ndescription = "combine facts into readable conditions"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "truthiness"\ndescription = "use object truth values without hiding intent"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "operators"\ndescription = "build comparisons and boolean expressions for conditions"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "conditionals"\ndescription = "choose between branches with clear predicates"\n\n[[journeys.sections]]\ntitle = "Name and shape decisions."\nsummary = "Some branches become clearer when the code names an intermediate value or dispatches on data shape."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "assignment-expressions"\ndescription = "name an intermediate value inside a condition when it improves clarity"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "match-statements"\ndescription = "dispatch on the shape of data rather than only on boolean tests"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "advanced-match-patterns"\ndescription = "combine destructuring, alternatives, and guards in pattern matching"\n\n[[journeys.sections]]\ntitle = "Stop as soon as the answer is known."\nsummary = "Early exits make the successful path easier to read by moving exceptional or completed cases out of the way."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "guard-clauses"\ndescription = "show how early returns reduce nested conditional code"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "assertions"\ndescription = "state assumptions that should fail loudly while developing"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "exceptions"\ndescription = "leave the current path when ordinary return values are not enough"\n\n[[journeys]]\nslug = "iteration"\ntitle = "Iteration"\nsummary = "This journey follows repeated work from ordinary loops to the iterator protocol: consume values, stop deliberately, and produce lazy streams only when they help."\n\n[[journeys.sections]]\ntitle = "Choose the right loop shape."\nsummary = "Loops differ by what they consume, when they stop, and whether completion itself carries meaning."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "for-loops"\ndescription = "consume values from an iterable"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "while-loops"\ndescription = "repeat while a condition must be rechecked"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "break-and-continue"\ndescription = "interrupt or skip loop work intentionally"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "loop-else"\ndescription = "attach completion logic to loops that did not break"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "sentinel-iteration"\ndescription = "show `iter(callable, sentinel)` for repeated reads until a marker appears"\n\n[[journeys.sections]]\ntitle = "See the protocol behind `for`."\nsummary = "The important mental shift is that loops consume producers through a protocol rather than special-casing lists."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "iterating-over-iterables"\ndescription = "separate value producers from value consumers"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "iterator-vs-iterable"\ndescription = "distinguish re-iterable collections from one-pass iterators"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "iterators"\ndescription = "use `iter()` and `next()` to expose the protocol behind `for`"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "generators"\ndescription = "write functions that produce values lazily"\n\n[[journeys.sections]]\ntitle = "Compose lazy value streams."\nsummary = "Iterator pipelines are useful when code can transform values one at a time instead of materializing every intermediate result."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "generator-expressions"\ndescription = "create lazy one-pass streams with expression syntax"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "itertools"\ndescription = "compose iterator streams without materializing every value"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "yield-from"\ndescription = "delegate part of a generator to another iterable"\n\n[[journeys]]\nslug = "shapes"\ntitle = "Shapes"\nsummary = "This journey teaches the core Python habit of choosing a data shape, transforming it directly, and making the result visible."\n\n[[journeys.sections]]\ntitle = "Pick the container that matches the question."\nsummary = "Lists, tuples, dictionaries, and sets answer different questions about order, position, lookup, and uniqueness."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "lists"\ndescription = "store ordered mutable data"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "tuples"\ndescription = "group fixed-position values"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "dicts"\ndescription = "look up values by key"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "sets"\ndescription = "model uniqueness and membership"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "collections-module"\ndescription = "show `deque`, `Counter`, `defaultdict`, and `namedtuple` as specialized shapes"\n\n[[journeys.sections]]\ntitle = "Move between shapes deliberately."\nsummary = "Most everyday Python code is data reshaping, so learners need the idioms for selecting, unpacking, and rebuilding values."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "unpacking"\ndescription = "bind names from structured values"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "slices"\ndescription = "select ranges from sequences"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "comprehensions"\ndescription = "build concrete collections from compact loops"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "comprehension-patterns"\ndescription = "compose filters and nested transformations"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "sorting"\ndescription = "order records with key functions"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "copying-collections"\ndescription = "contrast shallow copies, deep copies, and shared nested data"\n\n[[journeys.sections]]\ntitle = "Cross text and data boundaries."\nsummary = "Programs often receive text and produce structured data, so parsing and serialization belong in the data journey."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "number-parsing"\ndescription = "turn text into numbers safely"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "json"\ndescription = "move structured data across a text boundary"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "regular-expressions"\ndescription = "extract structure from text patterns"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "datetime"\ndescription = "represent dates, times, and durations as typed values"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "csv-data"\ndescription = "show row-shaped text data and dictionary records"\n\n[[journeys]]\nslug = "interfaces"\ntitle = "Interfaces"\nsummary = "This journey shows how Python grows from simple functions to callable APIs, object interfaces, protocols, and metaclasses."\n\n[[journeys.sections]]\ntitle = "Start with functions as named behavior."\nsummary = "Functions are the first abstraction boundary because they name behavior and control how callers provide information."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "functions"\ndescription = "package behavior behind a name"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "keyword-only-arguments"\ndescription = "make important call-site choices explicit"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "positional-only-parameters"\ndescription = "hide parameter names that should remain implementation details"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "args-and-kwargs"\ndescription = "accept flexible call shapes when forwarding or adapting APIs"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "multiple-return-values"\ndescription = "return multiple related values as a tuple"\n\n[[journeys.sections]]\ntitle = "Use functions as values."\nsummary = "Python functions can capture state, be passed around, and wrap other functions."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "scope-global-nonlocal"\ndescription = "control where assignment happens"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "closures"\ndescription = "capture state in nested functions"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "recursion"\ndescription = "solve self-similar problems with a base case"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "lambdas"\ndescription = "write small unnamed functions for expression positions"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "decorators"\ndescription = "wrap behavior without changing call sites"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "partial-functions"\ndescription = "show how to pre-fill arguments with `functools.partial`"\n\n[[journeys.sections]]\ntitle = "Bundle behavior with state."\nsummary = "Classes become useful when data and behavior need to move together behind a stable interface."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "classes"\ndescription = "bundle state and behavior into a new object type"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "inheritance-and-super"\ndescription = "reuse and extend behavior through parent classes"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "dataclasses"\ndescription = "generate common methods for data containers"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "properties"\ndescription = "keep attribute syntax while adding computation or validation"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "classmethods-and-staticmethods"\ndescription = "choose between instance, class, and static behavior on a class"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "special-methods"\ndescription = "connect objects to Python syntax and built-ins"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "truth-and-size"\ndescription = "make objects work with truth tests and `len()`"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "container-protocols"\ndescription = "support membership, lookup, and assignment syntax"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "callable-objects"\ndescription = "make stateful instances callable like functions"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "operator-overloading"\ndescription = "define operators only when the operation is unsurprising"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "attribute-access"\ndescription = "customize fallback lookup and assignment carefully"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "bound-and-unbound-methods"\ndescription = "explain how attribute access turns a function into a bound method"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "descriptors"\ndescription = "explain the protocol behind methods, properties, and managed attributes"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "metaclasses"\ndescription = "customize class creation when ordinary class tools are not enough"\n\n[[journeys]]\nslug = "types"\ntitle = "Types"\nsummary = "This journey maps Python\'s runtime object model to optional static annotations so learners know what types can and cannot promise."\n\n[[journeys.sections]]\ntitle = "Keep runtime and static analysis separate."\nsummary = "The first lesson is that annotations describe expectations for tools while ordinary Python objects still run the program."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "type-hints"\ndescription = "document expected types and feed type checkers"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "protocols"\ndescription = "describe required behavior by structural shape"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "abstract-base-classes"\ndescription = "contrast runtime-enforced nominal interfaces with structural protocols"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "enums"\ndescription = "name a fixed set of symbolic values"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "runtime-type-checks"\ndescription = "show `type()`, `isinstance()`, and `issubclass()` without turning Python into Java"\n\n[[journeys.sections]]\ntitle = "Describe realistic data shapes."\nsummary = "Typed Python becomes useful when annotations explain optional values, unions, callables, and JSON-like records."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "union-and-optional-types"\ndescription = "show `X | Y` and `None`-aware APIs"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "type-aliases"\ndescription = "name complex types with `type` statements or aliases"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "typed-dicts"\ndescription = "type dictionary records that come from JSON"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "structured-data-shapes"\ndescription = "choose between dataclass, NamedTuple, and TypedDict for records"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "literal-and-final"\ndescription = "express constrained values and names that should not be rebound"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "callable-types"\ndescription = "type functions that are passed as arguments"\n\n[[journeys.sections]]\ntitle = "Scale annotations for reusable libraries."\nsummary = "Advanced typing exists to preserve information across reusable functions, containers, and decorators."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "generics-and-typevar"\ndescription = "write reusable typed containers and functions"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "paramspec"\ndescription = "preserve callable signatures through decorators"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "overloads"\ndescription = "describe APIs whose return type depends on the input shape"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "casts-and-any"\ndescription = "show escape hatches and their tradeoffs"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "newtype"\ndescription = "create distinct static identities for runtime-compatible values"\n\n[[journeys]]\nslug = "reliability"\ntitle = "Reliability"\nsummary = "This journey follows the boundaries where programs fail, clean up, split into modules, communicate with the outside world, and run concurrent work."\n\n[[journeys.sections]]\ntitle = "Make failure explicit."\nsummary = "Robust Python code distinguishes expected absence, broken assumptions, recoverable errors, and domain-specific failures."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "exceptions"\ndescription = "signal and recover from errors"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "assertions"\ndescription = "state internal assumptions"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "exception-chaining"\ndescription = "preserve the cause while translating an error"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "exception-groups"\ndescription = "handle multiple failures together"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "custom-exceptions"\ndescription = "name failures in the language of the problem domain"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "warnings"\ndescription = "signal soft problems and deprecations"\n\n[[journeys.sections]]\ntitle = "Control resource and module boundaries."\nsummary = "Cleanup, deletion, imports, and modules define where responsibilities begin and end."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "context-managers"\ndescription = "pair setup with reliable cleanup"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "delete-statements"\ndescription = "remove names, attributes, and items intentionally"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "modules"\ndescription = "split code into importable files"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "import-aliases"\ndescription = "make imported names clear at use sites"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "packages"\ndescription = "show package directories, `__init__.py`, and public module boundaries"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "virtual-environments"\ndescription = "isolate dependencies for a project"\n\n[[journeys.sections]]\ntitle = "Handle operations that outlive one expression."\nsummary = "I/O, testing, logging, subprocesses, and concurrency require different control boundaries from ordinary expressions."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "async-await"\ndescription = "await concurrent I/O-shaped work"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "async-iteration-and-context"\ndescription = "consume async streams and cleanup protocols"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "logging"\ndescription = "record operational events without using `print()`"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "testing"\ndescription = "write deterministic tests with `unittest` or `pytest`"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "subprocesses"\ndescription = "run external commands safely"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "threads-and-processes"\ndescription = "contrast concurrency choices beyond `asyncio`"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "networking"\ndescription = "make HTTP or socket boundaries explicit"\n\n# Explicit see_also edge labels; default labels are inferred in src/app.py.\n[[see_also_edge_labels]]\nsource = "break-and-continue"\ntarget = "loop-else"\nlabel = "contrast"\n\n[[see_also_edge_labels]]\nsource = "assignment-expressions"\ntarget = "conditionals"\nlabel = "contrast"\n\n[[see_also_edge_labels]]\nsource = "yield-from"\ntarget = "generators"\nlabel = "prerequisite"\n\n[[see_also_edge_labels]]\nsource = "async-iteration-and-context"\ntarget = "async-await"\nlabel = "prerequisite"\n\n[[see_also_edge_labels]]\nsource = "delete-statements"\ntarget = "mutability"\nlabel = "shared mechanism"\n\n[[see_also_edge_labels]]\nsource = "positional-only-parameters"\ntarget = "keyword-only-arguments"\nlabel = "contrast"\n\n[[see_also_edge_labels]]\nsource = "assertions"\ntarget = "exceptions"\nlabel = "alternative"\n\n[[see_also_edge_labels]]\nsource = "exception-chaining"\ntarget = "exceptions"\nlabel = "builds on"\n\n[[see_also_edge_labels]]\nsource = "exception-groups"\ntarget = "exceptions"\nlabel = "alternative"\n\n[[see_also_edge_labels]]\nsource = "operators"\ntarget = "numbers"\nlabel = "related syntax"\n\n[[see_also_edge_labels]]\nsource = "operators"\ntarget = "booleans"\nlabel = "condition building"\n\n[[see_also_edge_labels]]\nsource = "operators"\ntarget = "assignment-expressions"\nlabel = "specialized expression"\n\n[[see_also_edge_labels]]\nsource = "literals"\ntarget = "values"\nlabel = "value surface"\n\n[[see_also_edge_labels]]\nsource = "literals"\ntarget = "strings"\nlabel = "text literal"\n\n[[see_also_edge_labels]]\nsource = "literals"\ntarget = "sets"\nlabel = "container literal"\n\n# Example-cell figure attachments. figure names refer to FIGURES paint functions.\n[[figure_attachments]]\nslug = "mutability"\nanchor = "cell-0"\nfigure = "aliasing-mutation"\ncaption = "Two names share one mutable list — appending through one name changes the object visible through both."\n\n[[figure_attachments]]\nslug = "mutability"\nanchor = "cell-0"\nfigure = "tuple-no-mutation"\ncaption = "By contrast, a tuple is frozen — its contents cannot change in place, so aliasing carries no mutation hazard."\n\n[[figure_attachments]]\nslug = "variables"\nanchor = "cell-0"\nfigure = "variables-bind"\ncaption = "A name is a label that points at an object. Assignment binds the label; the object exists independently."\n\n[[figure_attachments]]\nslug = "lists"\nanchor = "cell-0"\nfigure = "list-append"\ncaption = "Lists are mutable sequences. `.append` extends the same list object — no new list is created."\n\n[[figure_attachments]]\nslug = "dicts"\nanchor = "cell-0"\nfigure = "dict-buckets"\ncaption = "hash(key) picks the slot: \\"year\\" lands in an empty one, and profile[\\"name\\"] goes straight to its slot without scanning the other entries."\n\n[[figure_attachments]]\nslug = "unpacking"\nanchor = "cell-0"\nfigure = "unpacking-bind"\ncaption = "Left-side names bind to right-side positions; `*rest` gathers the middle into a list."\n\n[[figure_attachments]]\nslug = "comprehensions"\nanchor = "cell-0"\nfigure = "comprehension-equivalence"\ncaption = "A comprehension is a compact spelling of the equivalent for-loop with append, made into one expression."\n\n[[figure_attachments]]\nslug = "classes"\nanchor = "cell-0"\nfigure = "class-triangle"\ncaption = "Every Python value sits on the instance → class → type triangle; the metaclass is the type of the class."\n\n[[figure_attachments]]\nslug = "inheritance-and-super"\nanchor = "cell-0"\nfigure = "mro-chain"\ncaption = "Multiple inheritance forms a graph; C3 linearisation flattens it into the MRO Python uses for attribute lookup."\n\n[[figure_attachments]]\nslug = "dataclasses"\nanchor = "cell-0"\nfigure = "dataclass-fields"\ncaption = "Field declarations become the generated __init__ signature: declaration is the constructor."\n\n[[figure_attachments]]\nslug = "special-methods"\nanchor = "cell-0"\nfigure = "operator-dispatch"\ncaption = "Operators are method calls. `a + b` dispatches to `a.__add__(b)`; the data model exposes the syntax."\n\n[[figure_attachments]]\nslug = "decorators"\nanchor = "cell-0"\nfigure = "decorator-rebind"\ncaption = "@dec rebinds the name to wrapper(f₀); the original function survives only in the wrapper\'s closure cell."\n\n[[figure_attachments]]\nslug = "recursion"\nanchor = "cell-1"\nfigure = "call-stack"\ncaption = "At the leaf with value 4, three frames of total are stacked, each waiting on the one below; unwinding returns 4, then 3 + 4 = 7, then 1 + 2 + 7 = 10."\n\n[[figure_attachments]]\nslug = "exception-chaining"\nanchor = "cell-0"\nfigure = "exception-cause-context"\ncaption = "`raise X from Y` sets `__cause__` (explicit); raising during except sets `__context__` (implicit)."\n\n[[figure_attachments]]\nslug = "hello-world"\nanchor = "cell-0"\nfigure = "program-output"\ncaption = "Every Python program starts as source and produces text on standard output. The smallest mental model."\n\n[[figure_attachments]]\nslug = "numbers"\nanchor = "cell-0"\nfigure = "number-lines"\ncaption = "Ints have unbounded precision; floats use IEEE doubles whose representable values thin out near the extremes."\n\n[[figure_attachments]]\nslug = "operators"\nanchor = "cell-0"\nfigure = "expression-tree"\ncaption = "An expression like `(2 + 3) * 4` parses as a tree; operator precedence and parentheses determine its shape."\n\n[[figure_attachments]]\nslug = "none"\nanchor = "cell-0"\nfigure = "none-singleton"\ncaption = "`None` is a single object: every name that points at None points at the same object."\n\n[[figure_attachments]]\nslug = "equality-and-identity"\nanchor = "cell-0"\nfigure = "identity-and-equality"\ncaption = "Two names can share one object (`is` and `==` both true) or hold two equal-but-distinct objects (only `==` true)."\n\n[[figure_attachments]]\nslug = "strings"\nanchor = "cell-0"\nfigure = "codepoints-bytes"\ncaption = "Strings are sequences of Unicode codepoints. UTF-8 encoding turns them into bytes; `é` takes two bytes, `c` takes one."\n\n[[figure_attachments]]\nslug = "for-loops"\nanchor = "cell-1"\nfigure = "iterator-unroll"\ncaption = "Each call to next() advances the caret one cell along the iterable — the same shape behind range(), strings, and any sequence."\n\n[[figure_attachments]]\nslug = "sorting"\nanchor = "cell-1"\nfigure = "sort-stability"\ncaption = "Python\'s sort is stable: items with equal keys keep their original order, so chained sorts compose predictably."\n\n[[figure_attachments]]\nslug = "keyword-only-arguments"\nanchor = "cell-0"\nfigure = "kw-only-separator"\ncaption = "A bare `*` divides positional or keyword arguments from keyword-only ones; callers must pass `c` and `d` by name."\n\n[[figure_attachments]]\nslug = "positional-only-parameters"\nanchor = "cell-0"\nfigure = "positional-only-separator"\ncaption = "A bare `/` divides positional-only arguments from positional-or-keyword ones; callers cannot name `a` or `b`."\n\n[[figure_attachments]]\nslug = "positional-only-parameters"\nanchor = "cell-0"\nfigure = "kw-only-separator"\ncaption = "In the same signature, the bare `*` works the other way: parameters after it, such as `clamp`, must be named at the call site."\n\n[[figure_attachments]]\nslug = "closures"\nanchor = "cell-0"\nfigure = "closure-cell"\ncaption = "make_multiplier(2) has returned, but the function object double names still points into that frame\'s cell, so the captured factor outlives the call."\n\n[[figure_attachments]]\nslug = "scope-global-nonlocal"\nanchor = "cell-0"\nfigure = "scope-rings"\ncaption = "Name lookup walks LEGB — local, enclosing, global, built-in — outward, returning the first binding it finds."\n\n[[figure_attachments]]\nslug = "generators"\nanchor = "cell-0"\nfigure = "generator-resume"\ncaption = "The cell\'s two next() calls on countdown(3), one timeline each: every call resumes the body to the next yield gate, and the local n survives the pause."\n\n[[figure_attachments]]\nslug = "type-hints"\nanchor = "cell-0"\nfigure = "annotation-ghost"\ncaption = "Annotations describe expected types for tools; the runtime accepts any object regardless."\n\n[[figure_attachments]]\nslug = "exceptions"\nanchor = "cell-0"\nfigure = "exception-lanes"\ncaption = "try, except, else, and finally as parallel lanes; a single coral path traces what actually runs."\n\n[[figure_attachments]]\nslug = "context-managers"\nanchor = "cell-0"\nfigure = "context-bowtie"\ncaption = "A context manager pairs setup with reliable cleanup; the raise path still routes through __exit__."\n\n[[figure_attachments]]\nslug = "async-await"\nanchor = "cell-1"\nfigure = "async-swimlane"\ncaption = "On await, the coroutine yields to the loop; the loop runs other work and resumes when the awaitable is ready."\n\n[[figure_attachments]]\nslug = "iterators"\nanchor = "cell-0"\nfigure = "iter-protocol"\ncaption = "iter() exposes the iterator behind for; next() pulls one value at a time until exhausted."\n\n[[figure_attachments]]\nslug = "slices"\nanchor = "cell-0"\nfigure = "slice-ruler"\ncaption = "Slice indices sit between cells; [:3] and [3:] partition the sequence at index 3, never overlapping or losing an item."\n\n[[figure_attachments]]\nslug = "operator-overloading"\nanchor = "cell-0"\nfigure = "operator-dispatch"\ncaption = "Defining `__add__` on a class lets `+` dispatch into the class\'s own behavior."\n\n[[figure_attachments]]\nslug = "iterator-vs-iterable"\nanchor = "cell-0"\nfigure = "iter-protocol"\ncaption = "An iterable knows how to produce an iterator (via iter()); the iterator knows how to produce values (via next())."\n\n[[figure_attachments]]\nslug = "iterator-vs-iterable"\nanchor = "cell-1"\nfigure = "iterator-unroll"\ncaption = "The iterator\'s caret only moves forward — after the first `list(stream)` drains it, nothing is left for the second."\n\n[[figure_attachments]]\nslug = "type-aliases"\nanchor = "cell-0"\nfigure = "type-alias-name"\ncaption = "A type alias names a complex annotation once so call sites read as the domain meaning, not the type composition."\n\n[[figure_attachments]]\nslug = "typed-dicts"\nanchor = "cell-0"\nfigure = "typed-dict-shape"\ncaption = "TypedDict gives each key a typed value, so `obj[\'x\']` is checked against the declared shape."\n\n[[figure_attachments]]\nslug = "union-and-optional-types"\nanchor = "cell-0"\nfigure = "union-types"\ncaption = "`int | str | None` says one slot may hold any of three shapes — including expected absence."\n\n[[figure_attachments]]\nslug = "generics-and-typevar"\nanchor = "cell-0"\nfigure = "generic-preservation"\ncaption = "A generic preserves the input type through the call: the same T flows in and out of fn[T]."\n\n[[figure_attachments]]\nslug = "abstract-base-classes"\nanchor = "cell-0"\nfigure = "class-triangle"\ncaption = "An ABC sits on the same triangle as concrete classes; subclasses inherit the abstract methods they must implement."\n\n[[figure_attachments]]\nslug = "copying-collections"\nanchor = "cell-0"\nfigure = "aliasing-mutation"\ncaption = "Without copy() two names share the same object; mutating through one is visible through the other."\n\n[[figure_attachments]]\nslug = "truth-and-size"\nanchor = "cell-0"\nfigure = "truth-and-size"\ncaption = "bool(x) calls __bool__ first; if absent, __len__() != 0; if neither, defaults to True."\n\n[[figure_attachments]]\nslug = "descriptors"\nanchor = "cell-0"\nfigure = "descriptor-protocol"\ncaption = "Attribute access on an instance routes through the descriptor\'s __get__/__set__/__delete__ when the attribute is a descriptor."\n\n[[figure_attachments]]\nslug = "bound-and-unbound-methods"\nanchor = "cell-0"\nfigure = "bound-unbound"\ncaption = "Accessing a method via an instance binds self; accessing it via the class returns the underlying function."\n\n[[figure_attachments]]\nslug = "classmethods-and-staticmethods"\nanchor = "cell-0"\nfigure = "method-kinds"\ncaption = "Three method kinds, three first-argument conventions: classmethod gets the class, staticmethod gets nothing, instance gets self."\n\n[[figure_attachments]]\nslug = "callable-objects"\nanchor = "cell-0"\nfigure = "callable-objects"\ncaption = "Defining __call__ makes any object callable; functions are just one shape that satisfies this protocol."\n\n[[figure_attachments]]\nslug = "attribute-access"\nanchor = "cell-0"\nfigure = "attribute-lookup"\ncaption = "obj.x checks instance __dict__, then class __dict__, then __getattr__; the first hit wins."\n\n[[figure_attachments]]\nslug = "guard-clauses"\nanchor = "cell-0"\nfigure = "guard-clauses"\ncaption = "Early returns handle the exceptional cases first so the main work is the body of the function, not its tail."\n\n[[figure_attachments]]\nslug = "bytes-and-bytearray"\nanchor = "cell-3"\nfigure = "bytes-vs-bytearray"\ncaption = "Both objects hold the same two bytes as integers; b\\"py\\" cannot change, while packet[0] = ord(\\"P\\") rewrites the first slot of the bytearray in place."\n\n[[figure_attachments]]\nslug = "sentinel-iteration"\nanchor = "cell-0"\nfigure = "sentinel-iteration"\ncaption = "iter(read_chunk, \\"\\") keeps calling read_chunk and yields \\"py\\" and \\"thon\\"; the empty string is the sentinel, so it stops the loop and is never yielded."\n\n[[figure_attachments]]\nslug = "partial-functions"\nanchor = "cell-0"\nfigure = "partial-functions"\ncaption = "`functools.partial(f, 1)` pre-fills `a=1`, returning a thinner callable `g(b, c)` that only needs the rest."\n\n[[figure_attachments]]\nslug = "args-and-kwargs"\nanchor = "cell-0"\nfigure = "args-kwargs"\ncaption = "*args captures the extra positionals as a tuple; **kwargs captures the extra keywords as a dict."\n\n[[figure_attachments]]\nslug = "multiple-return-values"\nanchor = "cell-0"\nfigure = "multiple-return"\ncaption = "A function returning multiple values really returns one tuple; the caller unpacks it into named bindings."\n\n[[figure_attachments]]\nslug = "lambdas"\nanchor = "cell-0"\nfigure = "lambda-expression"\ncaption = "A lambda is a function literal: parameters before the colon, a single expression after, no statement body."\n\n[[figure_attachments]]\nslug = "properties"\nanchor = "cell-0"\nfigure = "property-fork"\ncaption = "When x is a property, attribute access routes through fget/fset instead of touching __dict__."\n\n[[figure_attachments]]\nslug = "metaclasses"\nanchor = "cell-0"\nfigure = "metaclass-triangle"\ncaption = "A metaclass is the type of a class, just as a class is the type of its instances; type is the default metaclass."\n\n[[figure_attachments]]\nslug = "metaclasses"\nanchor = "cell-0"\nfigure = "class-triangle"\ncaption = "The class makes instances — the same triangle one level down, with type as the default apex."\n\n[[figure_attachments]]\nslug = "modules"\nanchor = "cell-0"\nfigure = "sys-path-resolution"\ncaption = "An import walks sys.path entry by entry; the first directory containing the module wins."\n\n[[figure_attachments]]\nslug = "import-aliases"\nanchor = "cell-0"\nfigure = "import-alias"\ncaption = "`import x as y` binds the name y to the same module object x would have."\n\n[[figure_attachments]]\nslug = "protocols"\nanchor = "cell-0"\nfigure = "protocol-check"\ncaption = "An object satisfies a protocol structurally — by having the required methods — not by inheriting it."\n\n[[figure_attachments]]\nslug = "enums"\nanchor = "cell-0"\nfigure = "enum-members"\ncaption = "An enum names a fixed set of symbolic values; no new members appear at runtime."\n\n[[figure_attachments]]\nslug = "datetime"\nanchor = "cell-0"\nfigure = "datetime-instant"\ncaption = "An aware datetime carries a UTC offset; one instant in time reads differently on two clocks."\n\n[[figure_attachments]]\nslug = "json"\nanchor = "cell-0"\nfigure = "json-python-mapping"\ncaption = "Six type pairs bridge the JSON text boundary; each json value maps to one Python type."\n\n[[figure_attachments]]\nslug = "regular-expressions"\nanchor = "cell-0"\nfigure = "regex-groups"\ncaption = "findall returns only what the parentheses capture: `([A-Za-z]+)` takes the name and `(\\\\d+)` the score, one (name, score) pair per record."\n\n[[figure_attachments]]\nslug = "number-parsing"\nanchor = "cell-0"\nfigure = "number-parse"\ncaption = "int() turns text into a typed number; malformed input raises ValueError instead of guessing."\n\n[[figure_attachments]]\nslug = "string-formatting"\nanchor = "cell-1"\nfigure = "format-spec"\ncaption = "The format spec is a railroad of optional stations in a fixed order; this cell\'s 05.1f visits zero-pad, width, precision and type and bypasses the rest."\n\n[[figure_attachments]]\nslug = "truthiness"\nanchor = "cell-0"\nfigure = "truthy-check"\ncaption = "bool(x) is True except for a small fixed set: 0, 0.0, \\"\\", [], {}, None, False."\n\n[[figure_attachments]]\nslug = "booleans"\nanchor = "cell-0"\nfigure = "boolean-truth-table"\ncaption = "`a and b` returns True only when both are True; otherwise it returns the first falsy value."\n\n[[figure_attachments]]\nslug = "sets"\nanchor = "cell-0"\nfigure = "set-buckets"\ncaption = "Sets are hash buckets without values; `x in s` averages O(1) regardless of size."\n\n[[figure_attachments]]\nslug = "tuples"\nanchor = "cell-3"\nfigure = "tuple-frozen"\ncaption = "Tuples are ordered, immutable sequences; positions matter, contents do not change once constructed."\n\n[[figure_attachments]]\nslug = "tuples"\nanchor = "cell-3"\nfigure = "list-append"\ncaption = "A list is the other intent: a variable number of similar items, growing in place with `.append`."\n\n[[figure_attachments]]\nslug = "yield-from"\nanchor = "cell-0"\nfigure = "yield-delegation"\ncaption = "`yield from inner` delegates iteration to an inner generator; its yields surface here unchanged."\n\n[[figure_attachments]]\nslug = "itertools"\nanchor = "cell-0"\nfigure = "itertools-chain"\ncaption = "chain stitches two iterables into one stream without materialising either: values arrive lazily."\n\n[[figure_attachments]]\nslug = "assertions"\nanchor = "cell-0"\nfigure = "assertion-check"\ncaption = "assert tests a condition; True passes silently, False raises AssertionError with the optional message."\n\n[[figure_attachments]]\nslug = "custom-exceptions"\nanchor = "cell-0"\nfigure = "custom-exception-chain"\ncaption = "Subclassing an existing exception gains a domain name without changing semantics."\n\n[[figure_attachments]]\nslug = "exception-groups"\nanchor = "cell-0"\nfigure = "exception-group-peel"\ncaption = "except* peels matched leaves out of an ExceptionGroup; survivors regroup and propagate."\n\n[[figure_attachments]]\nslug = "delete-statements"\nanchor = "cell-0"\nfigure = "delete-name-erased"\ncaption = "`del x` removes the name; the object survives if any other reference holds it, otherwise gets collected."\n\n[[figure_attachments]]\nslug = "conditionals"\nanchor = "cell-0"\nfigure = "branch-fork"\ncaption = "A predicate sorts a value into one of several branches; if/elif/else is the explicit spelling."\n\n[[figure_attachments]]\nslug = "match-statements"\nanchor = "cell-0"\nfigure = "match-dispatch-ladder"\ncaption = "match dispatches by pattern shape; the value flows down the patterns and the first match wins."\n\n[[figure_attachments]]\nslug = "assignment-expressions"\nanchor = "cell-0"\nfigure = "naming-decisions"\ncaption = "The walrus binds a name during the surrounding expression; one expression, two outputs."\n\n[[figure_attachments]]\nslug = "iterating-over-iterables"\nanchor = "cell-0"\nfigure = "iter-protocol"\ncaption = "`for` desugars to iter()+next(): one iter() call, then next() until StopIteration ends the loop."\n\n[[figure_attachments]]\nslug = "generator-expressions"\nanchor = "cell-1"\nfigure = "lazy-stream"\ncaption = "A generator expression composes filter and map lazily; values flow only when next() pulls them."\n\n[[figure_attachments]]\nslug = "async-iteration-and-context"\nanchor = "cell-0"\nfigure = "async-swimlane"\ncaption = "async iteration and async with both rest on the same loop-vs-coroutine handoff as await."\n\n[[figure_attachments]]\nslug = "loop-else"\nanchor = "cell-0"\nfigure = "loop-else-gate"\ncaption = "The loop\'s else branch runs only when the loop falls through naturally; break skips it."\n\n[[figure_attachments]]\nslug = "break-and-continue"\nanchor = "cell-0"\nfigure = "early-exit"\ncaption = "break exits the loop; continue skips to the next iteration. Both interrupt the natural fall-through."\n\n[[figure_attachments]]\nslug = "comprehension-patterns"\nanchor = "cell-0"\nfigure = "comprehension-equivalence"\ncaption = "Nested clauses compose left to right; the comprehension is still equivalent to a for-loop with append."\n\n[[figure_attachments]]\nslug = "container-protocols"\nanchor = "cell-0"\nfigure = "container-methods"\ncaption = "Container syntax routes to narrow protocol methods: assignment to __setitem__, membership to __contains__, lookup to __getitem__."\n\n[[figure_attachments]]\nslug = "functions"\nanchor = "cell-0"\nfigure = "function-with-body"\ncaption = "A function takes inputs, evaluates a body, and returns a value: `greet(\'Ada\')` produces `\'Hello, Ada\'`."\n\n[[figure_attachments]]\nslug = "constants"\nanchor = "cell-0"\nfigure = "constants-bind"\ncaption = "UPPER_CASE is a naming convention, not a language constraint; the binding behaves like any other variable."\n\n[[figure_attachments]]\nslug = "values"\nanchor = "cell-0"\nfigure = "value-type-lookup"\ncaption = "text names a str object, and type(text) is str: the type carries upper() and the rest of the behaviour, not the name."\n\n[[figure_attachments]]\nslug = "literals"\nanchor = "cell-0"\nfigure = "literal-forms"\ncaption = "Each Python type has its own literal spellings; ints accept decimal, hex, and binary; strings accept either quote."\n\n[[figure_attachments]]\nslug = "logging"\nanchor = "cell-0"\nfigure = "logging-threshold"\ncaption = "The handler\'s level is a gate: debug is below INFO and never reaches stdout, while info and warning pass through unchanged."\n\n[[figure_attachments]]\nslug = "collections-module"\nanchor = "cell-0"\nfigure = "collections-containers"\ncaption = "Four specialised containers for shapes the built-in types don\'t cover well: deque, Counter, defaultdict, namedtuple."\n\n[[figure_attachments]]\nslug = "while-loops"\nanchor = "cell-0"\nfigure = "while-backedge"\ncaption = "`while` repeats the body while the test stays true; the back-edge returns control to the test before each pass."\n\n[[figure_attachments]]\nslug = "while-loops"\nanchor = "cell-0"\nfigure = "loop-repetition"\ncaption = "Each loop shape has its own stopping rule: `for` ends when the iterable is exhausted, `while` when the condition turns false, sentinel iteration when the marker value appears."\n\n[[figure_attachments]]\nslug = "advanced-match-patterns"\nanchor = "cell-0"\nfigure = "match-pattern-variants"\ncaption = "Capture, alternative, guard, and class patterns each name a different way a value can match a case."\n\n[[figure_attachments]]\nslug = "packages"\nanchor = "cell-0"\nfigure = "package-tree"\ncaption = "A directory with __init__.py becomes an importable package; submodules and subpackages nest beneath it."\n\n[[figure_attachments]]\nslug = "virtual-environments"\nanchor = "cell-0"\nfigure = "venv-boundary"\ncaption = "A venv carries its own interpreter and site-packages, isolating a project\'s dependencies from the system."\n\n[[figure_attachments]]\nslug = "subprocesses"\nanchor = "cell-0"\nfigure = "subprocess-spawn"\ncaption = "subprocess.run spawns a child process and captures its stdout, stderr, and exit code as portable evidence."\n\n[[figure_attachments]]\nslug = "testing"\nanchor = "cell-0"\nfigure = "aaa-pattern"\ncaption = "arrange-act-assert: set up the state, perform the behavior under test, compare the result to expectations."\n\n[[figure_attachments]]\nslug = "networking"\nanchor = "cell-0"\nfigure = "socket-byte-boundary"\ncaption = "Text crosses the socket as bytes — `encode` marks the python → wire boundary, `decode` brings the bytes back to a Python `str`."\n\n[[figure_attachments]]\nslug = "threads-and-processes"\nanchor = "cell-0"\nfigure = "gil-lanes"\ncaption = "Threads share memory but the GIL serialises Python bytecode; processes run in parallel with isolated memory."\n\n[[figure_attachments]]\nslug = "casts-and-any"\nanchor = "cell-0"\nfigure = "cast-escape"\ncaption = "cast(T, x) tells the type checker to treat x as T; the runtime is unaffected."\n\n[[figure_attachments]]\nslug = "newtype"\nanchor = "cell-0"\nfigure = "newtype-phantom"\ncaption = "NewType creates a distinct static identity backed by the same runtime type — UserId is int with a name."\n\n[[figure_attachments]]\nslug = "overloads"\nanchor = "cell-0"\nfigure = "overload-signatures"\ncaption = "@overload declares static call signatures for double(int) and double(str); one runtime implementation handles both."\n\n[[figure_attachments]]\nslug = "paramspec"\nanchor = "cell-0"\nfigure = "paramspec-preserve"\ncaption = "ParamSpec preserves the wrapped function\'s signature through a decorator, parameter for parameter."\n\n[[figure_attachments]]\nslug = "literal-and-final"\nanchor = "cell-0"\nfigure = "literal-constrained"\ncaption = "Literal narrows a slot to a fixed set of constant values; Final says the binding will not change."\n\n[[figure_attachments]]\nslug = "callable-types"\nanchor = "cell-0"\nfigure = "callable-type"\ncaption = "A Callable annotation describes the callback slot: this argument list must produce this return type."\n\n[[figure_attachments]]\nslug = "runtime-type-checks"\nanchor = "cell-0"\nfigure = "isinstance-check"\ncaption = "isinstance and issubclass ask the runtime; the answer is a bool, not a static type refinement."\n\n[[figure_attachments]]\nslug = "structured-data-shapes"\nanchor = "cell-0"\nfigure = "structured-shapes"\ncaption = "The same record can be a mutable dataclass, an immutable NamedTuple, or a runtime dict described by TypedDict."\n\n[[figure_attachments]]\nslug = "csv-data"\nanchor = "cell-0"\nfigure = "csv-records"\ncaption = "CSV files are rows of records; each line has the same columns in the same order."\n\n[[figure_attachments]]\nslug = "warnings"\nanchor = "cell-0"\nfigure = "warning-signal"\ncaption = "A warning is a soft signal: the message is reported, but execution continues unless filters elevate it."\n\n[[figure_attachments]]\nslug = "object-lifecycle"\nanchor = "cell-0"\nfigure = "object-lifecycle"\ncaption = "Names keep the same object reachable; deleting one name matters only when it removes the last reference."\n\n# Journey-section figures keyed by the visible section title.\n[[journey_section_figures]]\nsection = "Start with executable evidence."\nfigure = "runtime-evidence-loop"\ncaption = "Examples are evidence loops: source, a run step, and visible output stay together."\n\n[[journey_section_figures]]\nsection = "Separate value, identity, and absence."\nfigure = "runtime-object-axes"\ncaption = "Runtime objects answer separate questions: equal value, same identity, or the singleton that marks absence."\n\n[[journey_section_figures]]\nsection = "Read expressions as object operations."\nfigure = "runtime-expression-model"\ncaption = "Expression syntax enters the data model; object methods produce the result."\n\n[[journey_section_figures]]\nsection = "Choose between paths."\nfigure = "control-decision-map"\ncaption = "Facts flow into one decision point; exactly one branch owns the next step."\n\n[[journey_section_figures]]\nsection = "Name and shape decisions."\nfigure = "control-fact-shape"\ncaption = "Name a fact when a condition needs it; match shape when the data structure is the decision."\n\n[[journey_section_figures]]\nsection = "Stop as soon as the answer is known."\nfigure = "control-stop-boundary"\ncaption = "Early exits draw a boundary: once the answer is found, the tail stays unread."\n\n[[journey_section_figures]]\nsection = "Choose the right loop shape."\nfigure = "iteration-loop-selector"\ncaption = "Choose the loop from its stopping rule: exhaustion, condition, or sentinel marker."\n\n[[journey_section_figures]]\nsection = "See the protocol behind `for`."\nfigure = "iteration-protocol-map"\ncaption = "for is surface syntax; iter() creates an iterator and next() pulls values until StopIteration."\n\n[[journey_section_figures]]\nsection = "Compose lazy value streams."\nfigure = "iteration-lazy-pull"\ncaption = "Lazy pipelines run from the consumer\'s pull: next() requests one value through each stage."\n\n[[journey_section_figures]]\nsection = "Pick the container that matches the question."\nfigure = "container-questions"\ncaption = "Each container answers a different question: ordered, fixed, lookup, unique."\n\n[[journey_section_figures]]\nsection = "Move between shapes deliberately."\nfigure = "reshape-pipeline"\ncaption = "Most everyday code reshapes data: one input, one transform, one new value."\n\n[[journey_section_figures]]\nsection = "Cross text and data boundaries."\nfigure = "text-data-boundary"\ncaption = "Programs receive text and produce structured data; parsing makes the boundary explicit."\n\n[[journey_section_figures]]\nsection = "Start with functions as named behavior."\nfigure = "function-signature"\ncaption = "A function is the first abstraction boundary: arguments in, body, return value out."\n\n[[journey_section_figures]]\nsection = "Use functions as values."\nfigure = "function-as-value"\ncaption = "Functions are first-class values. A second name binds to the same function object."\n\n[[journey_section_figures]]\nsection = "Bundle behavior with state."\nfigure = "class-with-state"\ncaption = "Classes group fields and methods so data and behavior move together behind one interface."\n\n[[journey_section_figures]]\nsection = "Keep runtime and static analysis separate."\nfigure = "type-runtime-static-split"\ncaption = "Runtime values run the program; static tools inspect separate annotations and report before execution."\n\n[[journey_section_figures]]\nsection = "Describe realistic data shapes."\nfigure = "type-shape-catalog"\ncaption = "Real data contracts combine fields, variants, and expected absence instead of one scalar type."\n\n[[journey_section_figures]]\nsection = "Scale annotations for reusable libraries."\nfigure = "type-library-contract"\ncaption = "Reusable APIs carry caller contracts through the library boundary with generics, parameters, and overloads."\n\n[[journey_section_figures]]\nsection = "Make failure explicit."\nfigure = "reliability-signal-map"\ncaption = "Different failure shapes need explicit signals: assertions, recovery, chained causes, or warnings."\n\n[[journey_section_figures]]\nsection = "Control resource and module boundaries."\nfigure = "reliability-boundary-map"\ncaption = "Reliable programs name their boundaries: resources clean up, modules import, environments constrain runtime."\n\n[[journey_section_figures]]\nsection = "Handle operations that outlive one expression."\nfigure = "reliability-operation-boundary"\ncaption = "Async, threaded, test, and logging work cross an operation boundary before evidence comes back."\n\n# Curated scores for example-cell figures.\n[[example_figure_scores]]\nslug = "variables"\nscore = 9.5\ncomment = "the canonical name → object picture"\n\n[[example_figure_scores]]\nslug = "mutability"\nscore = 9.5\ncomment = "three-state small multiple of aliased mutation"\n\n[[example_figure_scores]]\nslug = "copying-collections"\nscore = 9.5\ncomment = "same picture as mutability, perfect match"\n\n[[example_figure_scores]]\nslug = "hello-world"\nscore = 9.0\ncomment = "program → output, smallest mechanism"\n\n[[example_figure_scores]]\nslug = "numbers"\nscore = 9.0\ncomment = "int unbounded vs float thinning, both registers"\n\n[[example_figure_scores]]\nslug = "operators"\nscore = 9.0\ncomment = "expression tree mechanism"\n\n[[example_figure_scores]]\nslug = "none"\nscore = 9.0\ncomment = "three names converging on one None"\n\n[[example_figure_scores]]\nslug = "equality-and-identity"\nscore = 9.0\ncomment = "shared vs separate object, side-by-side"\n\n[[example_figure_scores]]\nslug = "strings"\nscore = 9.0\ncomment = "codepoints + bytes registers"\n\n[[example_figure_scores]]\nslug = "for-loops"\nscore = 9.0\ncomment = "4-row caret advance"\n\n[[example_figure_scores]]\nslug = "sorting"\nscore = 9.0\ncomment = "stability ribbons preserved across keys"\n\n[[example_figure_scores]]\nslug = "keyword-only-arguments"\nscore = 9.0\ncomment = "signature with explicit `*` separator"\n\n[[example_figure_scores]]\nslug = "positional-only-parameters"\nscore = 9.0\ncomment = "signature with explicit `/` separator"\n\n[[example_figure_scores]]\nslug = "closures"\nscore = 9.5\ncomment = "environment diagram: ghosted returned frame, heap function object, one live __closure__ reference; 1.5/1/0.75/1/1 · 1/1/1 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "scope-global-nonlocal"\nscore = 9.0\ncomment = "LEGB nested rings"\n\n[[example_figure_scores]]\nslug = "recursion"\nscore = 9.0\ncomment = "the example\'s own tree at its deepest frame, return values unwinding; earns-place 0.75, the cell\'s output already gives 10; 1.5/0.75/1/1/1 · 1/1/1 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "lists"\nscore = 9.0\ncomment = "cells with append mechanism"\n\n[[example_figure_scores]]\nslug = "dicts"\nscore = 9.0\ncomment = "the cell\'s own keys hashed to slots, the insert of \\"year\\" accented; earns-place 0.75, one-move 0.75 since insert and lookup share the caption; 1.5/0.75/0.75/1/1 · 1/1/1 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "slices"\nscore = 9.0\ncomment = "ruler with bracket overlay"\n\n[[example_figure_scores]]\nslug = "comprehensions"\nscore = 9.0\ncomment = "comprehension over equivalent for-loop"\n\n[[example_figure_scores]]\nslug = "type-hints"\nscore = 9.0\ncomment = "ghost annotations over runtime values"\n\n[[example_figure_scores]]\nslug = "generators"\nscore = 9.5\ncomment = "the cell\'s two next() ribbons on countdown(3), local n shown surviving; earns-place 0.75, the prose says the same; 1.5/0.75/1/1/1 · 1/1/1 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "exceptions"\nscore = 9.0\ncomment = "try/except/else/finally lanes with traced path"\n\n[[example_figure_scores]]\nslug = "context-managers"\nscore = 9.0\ncomment = "enter / body / exit bowtie"\n\n[[example_figure_scores]]\nslug = "async-await"\nscore = 9.0\ncomment = "loop/coro swimlane with await handoffs"\n\n[[example_figure_scores]]\nslug = "classes"\nscore = 9.0\ncomment = "instance/class/type triangle"\n\n[[example_figure_scores]]\nslug = "inheritance-and-super"\nscore = 9.0\ncomment = "MRO chain with diamond ghost"\n\n[[example_figure_scores]]\nslug = "dataclasses"\nscore = 9.0\ncomment = "fields → generated __init__ signature"\n\n[[example_figure_scores]]\nslug = "decorators"\nscore = 9.0\ncomment = "before/after rebinding through cell"\n\n[[example_figure_scores]]\nslug = "special-methods"\nscore = 9.0\ncomment = "syntax → method dispatch"\n\n[[example_figure_scores]]\nslug = "unpacking"\nscore = 9.0\ncomment = "binding-line mechanism with *rest"\n\n[[example_figure_scores]]\nslug = "exception-chaining"\nscore = 9.0\ncomment = "__cause__ vs __context__ distinguished"\n\n[[example_figure_scores]]\nslug = "iterating-over-iterables"\nscore = 9.0\ncomment = "iter() exposes the iterator"\n\n[[example_figure_scores]]\nslug = "iterators"\nscore = 9.0\ncomment = "three-state machine"\n\n[[example_figure_scores]]\nslug = "iterator-vs-iterable"\nscore = 9.0\ncomment = "the protocol exposed"\n\n[[example_figure_scores]]\nslug = "container-protocols"\nscore = 9.0\ncomment = "syntax routes to __setitem__, __contains__, __getitem__"\n\n[[example_figure_scores]]\nslug = "operator-overloading"\nscore = 9.0\ncomment = "dispatch arrow"\n\n[[example_figure_scores]]\nslug = "union-and-optional-types"\nscore = 9.0\ncomment = "type fork to several shapes"\n\n[[example_figure_scores]]\nslug = "abstract-base-classes"\nscore = 9.0\ncomment = "same triangle as concrete classes"\n\n[[example_figure_scores]]\nslug = "conditionals"\nscore = 9.0\ncomment = "predicate forks value to branch"\n\n[[example_figure_scores]]\nslug = "match-statements"\nscore = 9.0\ncomment = "dispatch ladder; first match wins"\n\n[[example_figure_scores]]\nslug = "advanced-match-patterns"\nscore = 9.0\ncomment = "four pattern variants"\n\n[[example_figure_scores]]\nslug = "loop-else"\nscore = 9.0\ncomment = "fell-through vs broke, two outcomes"\n\n[[example_figure_scores]]\nslug = "while-loops"\nscore = 9.0\ncomment = "back-edge mechanism plus the three stopping rules"\n\n[[example_figure_scores]]\nslug = "type-aliases"\nscore = 9.0\ncomment = "complex annotation collapses to a name"\n\n[[example_figure_scores]]\nslug = "typed-dicts"\nscore = 9.0\ncomment = "keys with declared value types"\n\n[[example_figure_scores]]\nslug = "comprehension-patterns"\nscore = 9.0\ncomment = "nested clauses compose"\n\n[[example_figure_scores]]\nslug = "lambdas"\nscore = 9.0\ncomment = "function literal: params / expression"\n\n[[example_figure_scores]]\nslug = "string-formatting"\nscore = 9.0\ncomment = "railroad tracing the cell\'s 05.1f; one-move 0.75, restraint 0.75 and fit 0.75: still the densest figure in the set at the banner ceiling; 1.5/1/0.75/1/1 · 1/1/0.75 · 0.75/0.5"\n\n[[example_figure_scores]]\nslug = "regular-expressions"\nscore = 9.0\ncomment = "the cell\'s pattern with both capture groups dropped onto Ada: 10; one-move 0.75 and restraint 0.75 for two rows plus two drops; 1.5/1/0.75/1/1 · 1/1/0.75 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "json"\nscore = 9.0\ncomment = "two-column type mapping"\n\n[[example_figure_scores]]\nslug = "metaclasses"\nscore = 9.0\ncomment = "extended triangle to metaclass"\n\n[[example_figure_scores]]\nslug = "datetime"\nscore = 9.0\ncomment = "one instant, two clock offsets"\n\n[[example_figure_scores]]\nslug = "booleans"\nscore = 9.0\ncomment = "2×2 truth table"\n\n[[example_figure_scores]]\nslug = "sets"\nscore = 9.0\ncomment = "hash buckets without values"\n\n[[example_figure_scores]]\nslug = "yield-from"\nscore = 9.0\ncomment = "stitched ribbons; delegation"\n\n[[example_figure_scores]]\nslug = "generator-expressions"\nscore = 9.0\ncomment = "lazy filter→map pipeline"\n\n[[example_figure_scores]]\nslug = "async-iteration-and-context"\nscore = 9.0\ncomment = "loop/coro lanes with await yields"\n\n[[example_figure_scores]]\nslug = "assignment-expressions"\nscore = 9.0\ncomment = "walrus binds while comparing"\n\n[[example_figure_scores]]\nslug = "break-and-continue"\nscore = 9.0\ncomment = "early exit at first match"\n\n[[example_figure_scores]]\nslug = "delete-statements"\nscore = 9.0\ncomment = "name erased; object survives if referenced"\n\n[[example_figure_scores]]\nslug = "exception-groups"\nscore = 9.0\ncomment = "except* peels matching leaves"\n\n[[example_figure_scores]]\nslug = "custom-exceptions"\nscore = 9.0\ncomment = "subclass chain to a domain name"\n\n[[example_figure_scores]]\nslug = "modules"\nscore = 9.0\ncomment = "sys.path resolution; first hit wins"\n\n[[example_figure_scores]]\nslug = "protocols"\nscore = 9.0\ncomment = "structural duck check"\n\n[[example_figure_scores]]\nslug = "enums"\nscore = 9.0\ncomment = "closed set of symbolic values"\n\n[[example_figure_scores]]\nslug = "functions"\nscore = 9.0\ncomment = "specific call: greet(\'Ada\') → \'Hello, Ada\'"\n\n[[example_figure_scores]]\nslug = "constants"\nscore = 9.0\ncomment = "name binding with the cell\'s own MAX_RETRIES → 3; earns-place 0.5, the prose already says it is an ordinary binding; 1.5/0.5/1/1/1 · 1/1/1 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "values"\nscore = 9.0\ncomment = "text → str binding plus the type() hop to where upper() lives; earns-place 0.75 since the cell prints type(text), one-move 0.75; 1.5/0.75/0.75/1/1 · 1/1/1 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "literals"\nscore = 8.5\ncomment = "literal spellings per type; a reference table, kept until a mechanism figure replaces it"\n\n[[example_figure_scores]]\nslug = "logging"\nscore = 9.5\ncomment = "the cell\'s three records crossing the handler\'s INFO gate, debug dropped; earns-place 0.75 since the output already shows the drop; 1.5/0.75/1/1/1 · 1/1/1 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "collections-module"\nscore = 8.5\ncomment = "deque / Counter / defaultdict / namedtuple; a catalogue, kept until the page is split"\n\n[[example_figure_scores]]\nslug = "import-aliases"\nscore = 9.0\ncomment = "two names bind to the same module"\n\n[[example_figure_scores]]\nslug = "number-parsing"\nscore = 9.0\ncomment = "int() success path vs ValueError"\n\n[[example_figure_scores]]\nslug = "tuples"\nscore = 9.0\ncomment = "frozen sequence with struck-through .append"\n\n[[example_figure_scores]]\nslug = "truthiness"\nscore = 9.0\ncomment = "bool(x) with the falsy set as a strip"\n\n[[example_figure_scores]]\nslug = "itertools"\nscore = 9.0\ncomment = "chain joins two iterables into one stream"\n\n[[example_figure_scores]]\nslug = "assertions"\nscore = 9.0\ncomment = "True passes, False raises"\n\n[[example_figure_scores]]\nslug = "descriptors"\nscore = 9.0\ncomment = "get/set/delete protocol routed through descriptor"\n\n[[example_figure_scores]]\nslug = "attribute-access"\nscore = 9.0\ncomment = "instance __dict__ → class __dict__ → __getattr__"\n\n[[example_figure_scores]]\nslug = "bound-and-unbound-methods"\nscore = 9.0\ncomment = "instance.method bound vs Class.method unbound"\n\n[[example_figure_scores]]\nslug = "classmethods-and-staticmethods"\nscore = 9.0\ncomment = "three method kinds, three first-arg conventions"\n\n[[example_figure_scores]]\nslug = "callable-objects"\nscore = 9.0\ncomment = "__call__ makes any object callable"\n\n[[example_figure_scores]]\nslug = "generics-and-typevar"\nscore = 9.0\ncomment = "the same T flows in and out"\n\n[[example_figure_scores]]\nslug = "truth-and-size"\nscore = 9.0\ncomment = "__bool__ → __len__ → True fallback chain"\n\n[[example_figure_scores]]\nslug = "bytes-and-bytearray"\nscore = 9.5\ncomment = "the example\'s two bytes as integer slots, packet[0] rewritten in place, anchored to the mutating cell; 1.5/0.75/1/1/1 · 1/1/1 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "sentinel-iteration"\nscore = 9.0\ncomment = "the cell\'s read_chunk and chunks; the empty string ghosted as the sentinel; earns-place 0.75, the output already omits it; 1.5/0.75/1/1/1 · 1/1/1 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "partial-functions"\nscore = 9.0\ncomment = "f → partial(f, 1) → g"\n\n[[example_figure_scores]]\nslug = "guard-clauses"\nscore = 9.0\ncomment = "early returns, main body at the tail"\n\n[[example_figure_scores]]\nslug = "packages"\nscore = 9.0\ncomment = "__init__.py + nested submodules"\n\n[[example_figure_scores]]\nslug = "virtual-environments"\nscore = 9.0\ncomment = "project / venv boundary"\n\n[[example_figure_scores]]\nslug = "subprocesses"\nscore = 9.0\ncomment = "spawn → child → captured output"\n\n[[example_figure_scores]]\nslug = "testing"\nscore = 9.0\ncomment = "arrange-act-assert three-row pattern"\n\n[[example_figure_scores]]\nslug = "networking"\nscore = 9.0\ncomment = "text ↔ bytes across the socket boundary"\n\n[[example_figure_scores]]\nslug = "casts-and-any"\nscore = 9.0\ncomment = "Any → cast(T, x) → T, runtime unchanged"\n\n[[example_figure_scores]]\nslug = "newtype"\nscore = 9.0\ncomment = "same runtime, distinct static identity"\n\n[[example_figure_scores]]\nslug = "paramspec"\nscore = 9.0\ncomment = "P preserved through decorator"\n\n[[example_figure_scores]]\nslug = "literal-and-final"\nscore = 9.0\ncomment = "slot narrows to a fixed set"\n\n[[example_figure_scores]]\nslug = "runtime-type-checks"\nscore = 9.0\ncomment = "isinstance returns bool"\n\n[[example_figure_scores]]\nslug = "structured-data-shapes"\nscore = 9.0\ncomment = "dataclass vs NamedTuple vs TypedDict runtime trade-offs"\n\n[[example_figure_scores]]\nslug = "csv-data"\nscore = 9.0\ncomment = "rows × columns; same shape per line"\n\n[[example_figure_scores]]\nslug = "warnings"\nscore = 9.0\ncomment = "soft signal; execution continues"\n\n[[example_figure_scores]]\nslug = "object-lifecycle"\nscore = 9.0\ncomment = "names keep object reachable until last reference disappears"\n\n[[example_figure_scores]]\nslug = "args-and-kwargs"\nscore = 9.0\ncomment = "*args tuple, **kwargs dict regions"\n\n[[example_figure_scores]]\nslug = "multiple-return-values"\nscore = 9.0\ncomment = "function returns tuple; caller unpacks"\n\n[[example_figure_scores]]\nslug = "properties"\nscore = 9.0\ncomment = "obj.x routes through fget instead of __dict__"\n\n[[example_figure_scores]]\nslug = "overloads"\nscore = 9.0\ncomment = "static overload signatures contrasted with one runtime body"\n\n[[example_figure_scores]]\nslug = "callable-types"\nscore = 9.0\ncomment = "callback slot shows argument list and return type"\n\n[[example_figure_scores]]\nslug = "threads-and-processes"\nscore = 9.0\ncomment = "thread GIL sharing contrasted with process isolation"\n\n# Curated scores for journey-section figures.\n[[journey_section_figure_scores]]\nsection = "Start with executable evidence."\nscore = 9.0\ncomment = "journey-native source/run/output evidence loop"\n\n[[journey_section_figure_scores]]\nsection = "Separate value, identity, and absence."\nscore = 9.0\ncomment = "three runtime questions separated"\n\n[[journey_section_figure_scores]]\nsection = "Read expressions as object operations."\nscore = 9.0\ncomment = "syntax enters the data-model method surface"\n\n[[journey_section_figure_scores]]\nsection = "Choose between paths."\nscore = 9.0\ncomment = "branch map independent of one if-statement example"\n\n[[journey_section_figure_scores]]\nsection = "Name and shape decisions."\nscore = 9.0\ncomment = "name-vs-shape decision map"\n\n[[journey_section_figure_scores]]\nsection = "Stop as soon as the answer is known."\nscore = 9.0\ncomment = "early boundary leaves tail unread"\n\n[[journey_section_figure_scores]]\nsection = "Choose the right loop shape."\nscore = 9.0\ncomment = "loop choice by stopping rule"\n\n[[journey_section_figure_scores]]\nsection = "See the protocol behind `for`."\nscore = 9.5\ncomment = "for surface mapped to iter()/next()/StopIteration"\n\n[[journey_section_figure_scores]]\nsection = "Compose lazy value streams."\nscore = 9.0\ncomment = "consumer pull drives the lazy pipeline"\n\n[[journey_section_figure_scores]]\nsection = "Pick the container that matches the question."\nscore = 9.0\ncomment = "list/tuple/dict/set per question"\n\n[[journey_section_figure_scores]]\nsection = "Move between shapes deliberately."\nscore = 9.0\ncomment = "input → transform → result"\n\n[[journey_section_figure_scores]]\nsection = "Cross text and data boundaries."\nscore = 9.0\ncomment = "text in, structured value out"\n\n[[journey_section_figure_scores]]\nsection = "Start with functions as named behavior."\nscore = 9.0\ncomment = "concrete call, named body, and return boundary"\n\n[[journey_section_figure_scores]]\nsection = "Use functions as values."\nscore = 9.0\ncomment = "second name binds same function"\n\n[[journey_section_figure_scores]]\nsection = "Bundle behavior with state."\nscore = 9.0\ncomment = "class groups state + methods"\n\n[[journey_section_figure_scores]]\nsection = "Keep runtime and static analysis separate."\nscore = 9.0\ncomment = "runtime track separated from static-tool track"\n\n[[journey_section_figure_scores]]\nsection = "Describe realistic data shapes."\nscore = 9.0\ncomment = "field, variant, and absence contracts in one map"\n\n[[journey_section_figure_scores]]\nsection = "Scale annotations for reusable libraries."\nscore = 9.0\ncomment = "caller contracts survive library API boundary"\n\n[[journey_section_figure_scores]]\nsection = "Make failure explicit."\nscore = 9.0\ncomment = "failure shapes mapped to explicit signals"\n\n[[journey_section_figure_scores]]\nsection = "Control resource and module boundaries."\nscore = 9.0\ncomment = "resource/module/env boundaries shown together"\n\n[[journey_section_figure_scores]]\nsection = "Handle operations that outlive one expression."\nscore = 9.0\ncomment = "operation boundary returns evidence later"\n\n# Curated example quality scores.\n[[example_quality_scores]]\nslug = "hello-world"\nscore = 7.1\ncomment = "waived: traditional smallest complete program"\n\n[[example_quality_scores]]\nslug = "values"\nscore = 9.0\ncomment = "object/type/operation map with prerequisite graph edges"\n\n[[example_quality_scores]]\nslug = "literals"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich, note-heavy, multi-cell"\n\n[[example_quality_scores]]\nslug = "numbers"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "booleans"\nscore = 9.0\ncomment = "truth operations, short-circuiting, bool-as-int footgun"\n\n[[example_quality_scores]]\nslug = "operators"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich, note-heavy, multi-cell"\n\n[[example_quality_scores]]\nslug = "none"\nscore = 9.0\ncomment = "None, mapping default, and exception absence boundaries"\n\n[[example_quality_scores]]\nslug = "variables"\nscore = 9.0\ncomment = "binding, rebinding, augmented-assignment, lifecycle graph"\n\n[[example_quality_scores]]\nslug = "constants"\nscore = 9.0\ncomment = "constant convention, Final boundary, runtime rebinding evidence"\n\n[[example_quality_scores]]\nslug = "truthiness"\nscore = 9.0\ncomment = "truth-value categories, explicit-comparison boundary, graph-linked"\n\n[[example_quality_scores]]\nslug = "equality-and-identity"\nscore = 9.0\ncomment = "== versus is, singleton check, identity-cache warning"\n\n[[example_quality_scores]]\nslug = "mutability"\nscore = 9.0\ncomment = "in-place mutation, rebinding, alias visibility"\n\n[[example_quality_scores]]\nslug = "object-lifecycle"\nscore = 9.0\ncomment = "references, rebinding, and last-reference boundary"\n\n[[example_quality_scores]]\nslug = "strings"\nscore = 9.0\ncomment = "Unicode text, immutability, encoding boundary"\n\n[[example_quality_scores]]\nslug = "bytes-and-bytearray"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "string-formatting"\nscore = 9.0\ncomment = "f-string expression, format spec, debug/repr boundary"\n\n[[example_quality_scores]]\nslug = "conditionals"\nscore = 9.0\ncomment = "branch ordering, truthiness, and ternary boundary"\n\n[[example_quality_scores]]\nslug = "guard-clauses"\nscore = 9.0\ncomment = "nested contrast plus flattened guard path"\n\n[[example_quality_scores]]\nslug = "assignment-expressions"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "for-loops"\nscore = 9.0\ncomment = "direct iteration, range, and enumerate progression"\n\n[[example_quality_scores]]\nslug = "break-and-continue"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "loop-else"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "iterating-over-iterables"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "iterators"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "iterator-vs-iterable"\nscore = 9.0\ncomment = "graph-rich"\n\n[[example_quality_scores]]\nslug = "sentinel-iteration"\nscore = 9.0\ncomment = "call-until-marker shape contrasted with manual while"\n\n[[example_quality_scores]]\nslug = "match-statements"\nscore = 9.0\ncomment = "shape dispatch and guarded pattern payoff"\n\n[[example_quality_scores]]\nslug = "advanced-match-patterns"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "while-loops"\nscore = 9.0\ncomment = "state-driven repetition contrasted with for loops"\n\n[[example_quality_scores]]\nslug = "lists"\nscore = 9.0\ncomment = "ordered mutable sequence operations plus tuple/set/copy boundaries"\n\n[[example_quality_scores]]\nslug = "tuples"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "unpacking"\nscore = 9.0\ncomment = "sequence, starred, and mapping unpacking shapes"\n\n[[example_quality_scores]]\nslug = "dicts"\nscore = 9.0\ncomment = "lookup/default/update/delete dictionary boundaries"\n\n[[example_quality_scores]]\nslug = "sets"\nscore = 9.0\ncomment = "uniqueness, membership, set algebra, ordering boundary"\n\n[[example_quality_scores]]\nslug = "slices"\nscore = 9.0\ncomment = "range bounds, step, reverse, and unchanged-source evidence"\n\n[[example_quality_scores]]\nslug = "comprehensions"\nscore = 9.0\ncomment = "loop-equivalent collection building with filter/projection boundaries"\n\n[[example_quality_scores]]\nslug = "comprehension-patterns"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "sorting"\nscore = 9.0\ncomment = "key functions, reverse order, sorted/list.sort boundary"\n\n[[example_quality_scores]]\nslug = "collections-module"\nscore = 9.0\ncomment = "Counter, defaultdict, deque, namedtuple mapped to data shapes"\n\n[[example_quality_scores]]\nslug = "copying-collections"\nscore = 9.0\ncomment = "alias, shallow copy, and deepcopy boundaries"\n\n[[example_quality_scores]]\nslug = "functions"\nscore = 9.0\ncomment = "definition/call/return/default-boundary walkthrough"\n\n[[example_quality_scores]]\nslug = "keyword-only-arguments"\nscore = 9.0\ncomment = "call-site readability and boolean flag boundary"\n\n[[example_quality_scores]]\nslug = "positional-only-parameters"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "args-and-kwargs"\nscore = 9.0\ncomment = "flexible argument collection plus forwarding/API-boundary graph"\n\n[[example_quality_scores]]\nslug = "multiple-return-values"\nscore = 9.0\ncomment = "tuple return plus unpacking boundary"\n\n[[example_quality_scores]]\nslug = "closures"\nscore = 9.0\ncomment = "closed-over state, factory payoff, late-binding boundary"\n\n[[example_quality_scores]]\nslug = "partial-functions"\nscore = 9.0\ncomment = "before/after callable adaptation and introspection"\n\n[[example_quality_scores]]\nslug = "scope-global-nonlocal"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "recursion"\nscore = 9.0\ncomment = "base case and recursive tree-shape payoff"\n\n[[example_quality_scores]]\nslug = "lambdas"\nscore = 9.0\ncomment = "expression callable use contrasted with named def reuse"\n\n[[example_quality_scores]]\nslug = "generators"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "yield-from"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "generator-expressions"\nscore = 9.0\ncomment = "eager list contrast, lazy one-pass consumption, reducer use"\n\n[[example_quality_scores]]\nslug = "itertools"\nscore = 9.0\ncomment = "lazy standard-library pipeline and iterator-composition payoff"\n\n[[example_quality_scores]]\nslug = "decorators"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "classes"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "inheritance-and-super"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "classmethods-and-staticmethods"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "dataclasses"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "properties"\nscore = 9.0\ncomment = "managed attribute API without caller syntax change"\n\n[[example_quality_scores]]\nslug = "special-methods"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich, note-heavy, multi-cell"\n\n[[example_quality_scores]]\nslug = "truth-and-size"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "container-protocols"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "callable-objects"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "operator-overloading"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "attribute-access"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "bound-and-unbound-methods"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "descriptors"\nscore = 9.0\ncomment = "descriptor lookup, __set_name__, and validation mechanics"\n\n[[example_quality_scores]]\nslug = "metaclasses"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "context-managers"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "delete-statements"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "exceptions"\nscore = 9.0\ncomment = "specific handling, else/finally cleanup, broad-catch boundary"\n\n[[example_quality_scores]]\nslug = "assertions"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "exception-chaining"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "exception-groups"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "warnings"\nscore = 9.0\ncomment = "capture and escalate soft failures with filters"\n\n[[example_quality_scores]]\nslug = "modules"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "import-aliases"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "packages"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "virtual-environments"\nscore = 9.0\ncomment = "standard venv workflow plus explicit Worker deployment boundary"\n\n[[example_quality_scores]]\nslug = "type-hints"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich, note-heavy, multi-cell"\n\n[[example_quality_scores]]\nslug = "runtime-type-checks"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "union-and-optional-types"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "type-aliases"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "typed-dicts"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "structured-data-shapes"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "literal-and-final"\nscore = 9.0\ncomment = "Literal value set, Final rebinding promise, runtime caveat"\n\n[[example_quality_scores]]\nslug = "callable-types"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "generics-and-typevar"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "paramspec"\nscore = 9.0\ncomment = "Callable erasure contrasted with ParamSpec-preserving decorator"\n\n[[example_quality_scores]]\nslug = "overloads"\nscore = 9.0\ncomment = "static overload stubs contrasted with one runtime implementation"\n\n[[example_quality_scores]]\nslug = "casts-and-any"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "newtype"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "protocols"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "abstract-base-classes"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "enums"\nscore = 9.0\ncomment = "closed symbolic choice set contrasted with raw strings"\n\n[[example_quality_scores]]\nslug = "regular-expressions"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich, note-heavy, multi-cell"\n\n[[example_quality_scores]]\nslug = "number-parsing"\nscore = 9.0\ncomment = "decimal, explicit base, and recoverable ValueError boundary"\n\n[[example_quality_scores]]\nslug = "custom-exceptions"\nscore = 9.0\ncomment = "domain error naming, raise point, recovery boundary"\n\n[[example_quality_scores]]\nslug = "json"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "logging"\nscore = 9.0\ncomment = "logger, handler, formatter, and threshold boundaries"\n\n[[example_quality_scores]]\nslug = "testing"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "subprocesses"\nscore = 9.0\ncomment = "standard subprocess contract plus explicit Worker boundary"\n\n[[example_quality_scores]]\nslug = "threads-and-processes"\nscore = 9.0\ncomment = "thread/process executor contrast plus explicit Worker boundary"\n\n[[example_quality_scores]]\nslug = "networking"\nscore = 9.0\ncomment = "protocol byte boundary plus explicit socket runtime caveat"\n\n[[example_quality_scores]]\nslug = "datetime"\nscore = 9.0\ncomment = "date/time/delta parsing with timezone scope made explicit"\n\n[[example_quality_scores]]\nslug = "csv-data"\nscore = 9.0\ncomment = "DictReader, conversion, and DictWriter row boundary"\n\n[[example_quality_scores]]\nslug = "async-await"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "async-iteration-and-context"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n' +REGISTRY_TOML = '# Quality and editorial registries.\n#\n# Source of truth for rubric checks, journey structure, edge labels,\n# figure attachments/captions, and curated scores. Executable paint\n# functions stay in `src/marginalia.py`; mutable editorial data lives here.\n\n[[confusable_pairs]]\nname = "__str__ vs __repr__"\nowner = "special-methods"\ntokens = ["__str__", "__repr__"]\n\n[[confusable_pairs]]\nname = "is vs =="\nowner = "equality-and-identity"\ntokens = [" is ", "=="]\n\n[[confusable_pairs]]\nname = "list vs tuple"\nowner = "tuples"\ntokens = ["list", "tuple"]\n\n[[confusable_pairs]]\nname = "classmethod vs staticmethod vs instance method"\nowner = "classmethods-and-staticmethods"\ntokens = ["@classmethod", "@staticmethod", "self"]\n\n[[confusable_pairs]]\nname = "isinstance vs type=="\nowner = "runtime-type-checks"\ntokens = ["isinstance(", "type("]\n\n[[confusable_pairs]]\nname = "generator vs class iterator"\nowner = "generators"\ntokens = ["yield", "__next__"]\n\n[[confusable_pairs]]\nname = "iterator vs iterable"\nowner = "iterator-vs-iterable"\ntokens = ["iterable", "iterator", "iter("]\n\n[[confusable_pairs]]\nname = "mutable vs immutable class attributes"\nowner = "classes"\ntokens = ["class attribute", "__init__"]\n\n[[confusable_pairs]]\nname = "eager vs lazy production"\nowner = "generators"\ntokens = ["return", "yield"]\n\n[[confusable_pairs]]\nname = "Protocol vs ABC"\nowner = "abstract-base-classes"\ntokens = ["Protocol", "ABC"]\n\n[[confusable_pairs]]\nname = "dataclass vs NamedTuple vs TypedDict"\nowner = "structured-data-shapes"\ntokens = ["@dataclass", "NamedTuple", "TypedDict"]\n\n[[confusable_pairs]]\nname = "bound vs unbound methods"\nowner = "bound-and-unbound-methods"\ntokens = ["bound method", "Class.method"]\n\n[[confusable_pairs]]\nname = "yield vs return"\nowner = "generators"\ntokens = ["yield", "return"]\n\n[[confusable_pairs]]\nname = "shallow vs deep copy"\nowner = "copying-collections"\ntokens = ["copy(", "deepcopy("]\n\n[[confusable_pairs]]\nname = "sync vs async functions"\nowner = "async-await"\ntokens = ["async def", "def "]\n\n[broad_surface_tours]\n\n[broad_surface_tours.special-methods]\nrequired_tokens = [\n "__init__", "__repr__", "__str__", "__eq__", "__hash__", "__lt__",\n "__len__", "__iter__", "__contains__", "__getitem__", "__setitem__",\n "__call__", "__enter__", "__exit__", "__bool__",\n]\n\n[broad_surface_tours.operators]\nrequired_tokens = ["+", "==", " is ", " in ", "and", "or", "&", ":="]\n\n[broad_surface_tours.type-hints]\nrequired_tokens = ["list[", " | ", "Optional", "TypeAlias"]\n\n[broad_surface_tours.testing]\nrequired_tokens = ["TestCase", "assertEqual", "assertRaises", "setUp"]\n\n[broad_surface_tours.async-await]\nrequired_tokens = ["async def", "await", "asyncio.run", "asyncio.gather", "async for", "async with"]\n\n[broad_surface_tours.packages]\nrequired_tokens = ["__init__.py", "from .", "__all__"]\n\n[broad_surface_tours.regular-expressions]\nrequired_tokens = ["re.match", "re.search", "re.findall", "re.compile", "re.IGNORECASE", "re.sub"]\n\n[broad_surface_tours.literals]\nrequired_tokens = ["0x", "0b", "_", "f\\"", "True", "None"]\n\n[[footguns]]\nname = "Mutable default class attribute"\nowner = "classes"\nbroken_tokens = ["items = []"]\nfixed_tokens = ["self.items = []"]\n\n[[footguns]]\nname = "Mutable default function argument"\nowner = "functions"\nbroken_tokens = ["items=[]", "append_broken"]\nfixed_tokens = ["items=None", "append_fixed"]\n\n[[footguns]]\nname = "Late-binding closure in a loop"\nowner = "closures"\nbroken_tokens = ["lambda: i", "[2, 2, 2]"]\nfixed_tokens = ["lambda i=i", "[0, 1, 2]"]\n\n[[footguns]]\nname = "Integer identity caching"\nowner = "equality-and-identity"\nbroken_tokens = ["small_a is small_b", "big_a is big_b"]\nfixed_tokens = ["big_a == big_b", "small-integer cache"]\n\n[[footguns]]\nname = "Shallow vs deep copy"\nowner = "copying-collections"\nbroken_tokens = ["copy("]\nfixed_tokens = ["deepcopy("]\n\n[[footguns]]\nname = "Generator one-pass exhaustion"\nowner = "generators"\nbroken_tokens = ["yield"]\nfixed_tokens = ["list("]\n\n[[footguns]]\nname = "Dictionary mutation during iteration"\nowner = "dicts"\nbroken_tokens = ["for ", "del "]\nfixed_tokens = ["list(", ".keys("]\n\n[[footguns]]\nname = "Floating-point equality"\nowner = "numbers"\nbroken_tokens = ["0.1", "0.2"]\nfixed_tokens = ["isclose", "math"]\n\n[[footguns]]\nname = "bool as a subclass of int"\nowner = "booleans"\nbroken_tokens = ["isinstance(True, int)", "True + True"]\nfixed_tokens = ["not isinstance(value, bool)", "is_strict_int"]\n\n[[footguns]]\nname = "Bare except swallowing KeyboardInterrupt"\nowner = "exceptions"\nbroken_tokens = ["except Exception"]\nfixed_tokens = ["except ValueError"]\n\n[paired_pages]\n# Pages whose titles differ only by a suffix or modifier; at least one\n# member of each pair must demonstrate the relationship in a cell.\npairs = [\n ["iterators", "iterating-over-iterables"],\n ["iterators", "iterator-vs-iterable"],\n ["generators", "generator-expressions"],\n ["comprehensions", "comprehension-patterns"],\n]\n\n[paired_pages.cell_tokens]\n"iterators|iterating-over-iterables" = ["iterable", "iterator"]\n"iterators|iterator-vs-iterable" = ["iterable", "iterator", "iter("]\n"generators|generator-expressions" = ["generator", "expression"]\n"comprehensions|comprehension-patterns" = ["nested loops", "explicit loop"]\n\n[quality_gates]\nexample_target = 9.0\nexample_hard_min = 8.5\njourney_section_min = 8.5\njourney_average_min = 8.8\n\n# A waiver is time-boxed with `expires = "YYYY-MM-DD"`. Use `permanent = true`\n# (and no `expires`) only when the reason can never stop being true.\n[quality_waivers.hello-world]\naccepted_min = 7.0\nreason = "Traditional first example is intentionally tiny: program -> output is the goal, not a full concept tour."\npermanent = true\n\n[no_figure_rationales]\n# Slugs may be added here only when the page is constraint-shaped,\n# infrastructure-shaped, or aggregator-shaped and a single mechanism\n# figure would distort the lesson. A weak figure is redrawn, not removed:\n# a page that had a figure keeps one. Current production attaches\n# figures to every example, so this registry is intentionally empty.\n\n[journey_outcomes]\n\n[journey_outcomes."runtime::Start with executable evidence."]\njourney = "runtime"\nsection = "Start with executable evidence."\nsupport = [\n "hello-world",\n "values",\n "literals",\n "variables",\n "constants",\n]\noutcomes = [\n "start with a complete program and its output",\n "see that Python programs manipulate runtime objects",\n "write small values directly in source code",\n "understand that names bind to objects rather than storing values themselves",\n]\n\n[journey_outcomes."runtime::Separate value, identity, and absence."]\njourney = "runtime"\nsection = "Separate value, identity, and absence."\nsupport = [\n "none",\n "booleans",\n "truthiness",\n "equality-and-identity",\n "mutability",\n "object-lifecycle",\n]\noutcomes = [\n "represent expected absence with a singleton object",\n "combine facts with boolean operators",\n "predict how objects behave in boolean contexts",\n "distinguish value equality from object identity",\n]\n\n[journey_outcomes."runtime::Read expressions as object operations."]\njourney = "runtime"\nsection = "Read expressions as object operations."\nsupport = [\n "numbers",\n "operators",\n "strings",\n "string-formatting",\n "bytes-and-bytearray",\n]\noutcomes = [\n "use numeric objects and arithmetic operators",\n "combine, compare, and test values with expression syntax",\n "treat text as Unicode rather than raw bytes",\n "turn objects into readable text at output boundaries",\n]\n\n[journey_outcomes."control-flow::Choose between paths."]\njourney = "control-flow"\nsection = "Choose between paths."\nsupport = [\n "booleans",\n "truthiness",\n "operators",\n "conditionals",\n]\noutcomes = [\n "combine facts into readable conditions",\n "use object truth values without hiding intent",\n "build comparisons and boolean expressions for conditions",\n "choose between branches with clear predicates",\n]\n\n[journey_outcomes."control-flow::Name and shape decisions."]\njourney = "control-flow"\nsection = "Name and shape decisions."\nsupport = [\n "assignment-expressions",\n "match-statements",\n "advanced-match-patterns",\n]\noutcomes = [\n "name an intermediate value inside a condition when it improves clarity",\n "dispatch on the shape of data rather than only on boolean tests",\n "combine destructuring, alternatives, and guards in pattern matching",\n]\n\n[journey_outcomes."control-flow::Stop as soon as the answer is known."]\njourney = "control-flow"\nsection = "Stop as soon as the answer is known."\nsupport = [\n "guard-clauses",\n "assertions",\n "exceptions",\n]\noutcomes = [\n "show how early returns reduce nested conditional code",\n "state assumptions that should fail loudly while developing",\n "leave the current path when ordinary return values are not enough",\n]\n\n[journey_outcomes."iteration::Choose the right loop shape."]\njourney = "iteration"\nsection = "Choose the right loop shape."\nsupport = [\n "for-loops",\n "while-loops",\n "break-and-continue",\n "loop-else",\n "sentinel-iteration",\n]\noutcomes = [\n "consume values from an iterable",\n "repeat while a condition must be rechecked",\n "interrupt or skip loop work intentionally",\n "attach completion logic to loops that did not break",\n]\n\n[journey_outcomes."iteration::See the protocol behind `for`."]\njourney = "iteration"\nsection = "See the protocol behind `for`."\nsupport = [\n "iterating-over-iterables",\n "iterator-vs-iterable",\n "iterators",\n "generators",\n]\noutcomes = [\n "separate value producers from value consumers",\n "use `iter()` and `next()` to expose the protocol behind `for`",\n "write functions that produce values lazily",\n]\n\n[journey_outcomes."iteration::Compose lazy value streams."]\njourney = "iteration"\nsection = "Compose lazy value streams."\nsupport = [\n "generator-expressions",\n "itertools",\n "yield-from",\n]\noutcomes = [\n "create lazy one-pass streams with expression syntax",\n "compose iterator streams without materializing every value",\n "delegate part of a generator to another iterable",\n]\n\n[journey_outcomes."shapes::Pick the container that matches the question."]\njourney = "shapes"\nsection = "Pick the container that matches the question."\nsupport = [\n "lists",\n "tuples",\n "dicts",\n "sets",\n "collections-module",\n]\noutcomes = [\n "store ordered mutable data",\n "group fixed-position values",\n "look up values by key",\n "model uniqueness and membership",\n]\n\n[journey_outcomes."shapes::Move between shapes deliberately."]\njourney = "shapes"\nsection = "Move between shapes deliberately."\nsupport = [\n "unpacking",\n "slices",\n "comprehensions",\n "comprehension-patterns",\n "sorting",\n "copying-collections",\n]\noutcomes = [\n "bind names from structured values",\n "select ranges from sequences",\n "build concrete collections from compact loops",\n "compose filters and nested transformations",\n]\n\n[journey_outcomes."shapes::Cross text and data boundaries."]\njourney = "shapes"\nsection = "Cross text and data boundaries."\nsupport = [\n "number-parsing",\n "files-and-pathlib",\n "json",\n "regular-expressions",\n "datetime",\n "csv-data",\n]\noutcomes = [\n "turn text into numbers safely",\n "move structured data across a text boundary",\n "extract structure from text patterns",\n "represent dates, times, and durations as typed values",\n]\n\n[journey_outcomes."interfaces::Start with functions as named behavior."]\njourney = "interfaces"\nsection = "Start with functions as named behavior."\nsupport = [\n "functions",\n "keyword-only-arguments",\n "positional-only-parameters",\n "args-and-kwargs",\n "multiple-return-values",\n]\noutcomes = [\n "package behavior behind a name",\n "make important call-site choices explicit",\n "hide parameter names that should remain implementation details",\n "accept flexible call shapes when forwarding or adapting APIs",\n]\n\n[journey_outcomes."interfaces::Use functions as values."]\njourney = "interfaces"\nsection = "Use functions as values."\nsupport = [\n "scope-global-nonlocal",\n "closures",\n "recursion",\n "lambdas",\n "decorators",\n "partial-functions",\n]\noutcomes = [\n "control where assignment happens",\n "capture state in nested functions",\n "solve self-similar problems with a base case",\n "write small unnamed functions for expression positions",\n]\n\n[journey_outcomes."interfaces::Bundle behavior with state."]\njourney = "interfaces"\nsection = "Bundle behavior with state."\nsupport = [\n "classes",\n "inheritance-and-super",\n "dataclasses",\n "properties",\n "classmethods-and-staticmethods",\n "special-methods",\n "truth-and-size",\n "container-protocols",\n "callable-objects",\n "operator-overloading",\n "attribute-access",\n "bound-and-unbound-methods",\n "descriptors",\n "metaclasses",\n]\noutcomes = [\n "bundle state and behavior into a new object type",\n "reuse and extend behavior through parent classes",\n "generate common methods for data containers",\n "keep attribute syntax while adding computation or validation",\n]\n\n[journey_outcomes."types::Keep runtime and static analysis separate."]\njourney = "types"\nsection = "Keep runtime and static analysis separate."\nsupport = [\n "type-hints",\n "protocols",\n "abstract-base-classes",\n "enums",\n "runtime-type-checks",\n]\noutcomes = [\n "document expected types and feed type checkers",\n "describe required behavior by structural shape",\n "name a fixed set of symbolic values",\n "show `type()`, `isinstance()`, and `issubclass()` without turning Python into Java",\n]\n\n[journey_outcomes."types::Describe realistic data shapes."]\njourney = "types"\nsection = "Describe realistic data shapes."\nsupport = [\n "union-and-optional-types",\n "type-aliases",\n "typed-dicts",\n "structured-data-shapes",\n "literal-and-final",\n "callable-types",\n]\noutcomes = [\n "show `X | Y` and `None`-aware APIs",\n "name complex types with `type` statements or aliases",\n "type dictionary records that come from JSON",\n "express constrained values and names that should not be rebound",\n]\n\n[journey_outcomes."types::Scale annotations for reusable libraries."]\njourney = "types"\nsection = "Scale annotations for reusable libraries."\nsupport = [\n "generics-and-typevar",\n "paramspec",\n "overloads",\n "casts-and-any",\n "newtype",\n]\noutcomes = [\n "write reusable typed containers and functions",\n "preserve callable signatures through decorators",\n "describe APIs whose return type depends on the input shape",\n "show escape hatches and their tradeoffs",\n]\n\n[journey_outcomes."reliability::Make failure explicit."]\njourney = "reliability"\nsection = "Make failure explicit."\nsupport = [\n "exceptions",\n "assertions",\n "exception-chaining",\n "exception-groups",\n "custom-exceptions",\n "warnings",\n]\noutcomes = [\n "signal and recover from errors",\n "state internal assumptions",\n "preserve the cause while translating an error",\n "handle multiple failures together",\n]\n\n[journey_outcomes."reliability::Control resource and module boundaries."]\njourney = "reliability"\nsection = "Control resource and module boundaries."\nsupport = [\n "context-managers",\n "delete-statements",\n "modules",\n "import-aliases",\n "packages",\n "virtual-environments",\n]\noutcomes = [\n "pair setup with reliable cleanup",\n "remove names, attributes, and items intentionally",\n "split code into importable files",\n "make imported names clear at use sites",\n]\n\n[journey_outcomes."reliability::Handle operations that outlive one expression."]\njourney = "reliability"\nsection = "Handle operations that outlive one expression."\nsupport = [\n "async-await",\n "async-iteration-and-context",\n "logging",\n "testing",\n "subprocesses",\n "threads-and-processes",\n "networking",\n]\noutcomes = [\n "await concurrent I/O-shaped work",\n "consume async streams and cleanup protocols",\n "record operational events without using `print()`",\n "write deterministic tests with `unittest` or `pytest`",\n]\n\n[score_model]\n# Criterion weights mirror docs/example-quality-rubric.md. The registry\n# makes the scoring model inspectable even before every example is broken\n# down into per-criterion subscores.\nconceptual_payoff = 1.0\nrationale = 0.75\nalternatives_and_boundaries = 0.75\nexecutable_determinism = 1.0\npython_idiom_and_accuracy = 1.0\nliterate_fit = 0.75\nsource_result_pairing = 0.75\nconcept_decomposition = 0.75\nprogressive_walkthrough = 0.75\nrepresentative_coverage = 0.75\npractical_usefulness = 0.75\neditorial_progression = 1.0\n\n# Editorial registries loaded by the site at runtime.\n# Keep prose, captions, scores, journey ordering, and edge labels here;\n# keep executable paint functions in src/marginalia.py.\n\n[[journeys]]\nslug = "runtime"\ntitle = "Runtime"\nsummary = "This journey builds the smallest coherent model of Python at runtime: programs run statements, names refer to objects, objects have types, and operations ask those objects to do work."\n\n[[journeys.sections]]\ntitle = "Start with executable evidence."\nsummary = "Learners first need to see that every page is a runnable program with visible output."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "hello-world"\ndescription = "start with a complete program and its output"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "values"\ndescription = "see that Python programs manipulate runtime objects"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "literals"\ndescription = "write small values directly in source code"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "variables"\ndescription = "understand that names bind to objects rather than storing values themselves"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "constants"\ndescription = "learn the convention Python uses for values that should not change"\n\n[[journeys.sections]]\ntitle = "Separate value, identity, and absence."\nsummary = "This section prevents early confusion about equality, object identity, missing values, and truth tests."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "none"\ndescription = "represent expected absence with a singleton object"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "booleans"\ndescription = "combine facts with boolean operators"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "truthiness"\ndescription = "predict how objects behave in boolean contexts"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "equality-and-identity"\ndescription = "distinguish value equality from object identity"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "mutability"\ndescription = "predict when operations change an object in place"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "object-lifecycle"\ndescription = "explain references, garbage collection, and why identity can outlive a single name"\n\n[[journeys.sections]]\ntitle = "Read expressions as object operations."\nsummary = "This section connects operators, text, and formatting to Python\'s data model."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "numbers"\ndescription = "use numeric objects and arithmetic operators"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "operators"\ndescription = "combine, compare, and test values with expression syntax"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "strings"\ndescription = "treat text as Unicode rather than raw bytes"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "string-formatting"\ndescription = "turn objects into readable text at output boundaries"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "bytes-and-bytearray"\ndescription = "contrast text with binary data and explicit decoding"\n\n[[journeys]]\nslug = "control-flow"\ntitle = "Control Flow"\nsummary = "This journey follows how a Python program chooses which path runs, names facts at decision points, and exits early when the remaining work no longer applies."\n\n[[journeys.sections]]\ntitle = "Choose between paths."\nsummary = "Start with ordinary branching and boolean predicates before reaching for more compact forms."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "booleans"\ndescription = "combine facts into readable conditions"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "truthiness"\ndescription = "use object truth values without hiding intent"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "operators"\ndescription = "build comparisons and boolean expressions for conditions"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "conditionals"\ndescription = "choose between branches with clear predicates"\n\n[[journeys.sections]]\ntitle = "Name and shape decisions."\nsummary = "Some branches become clearer when the code names an intermediate value or dispatches on data shape."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "assignment-expressions"\ndescription = "name an intermediate value inside a condition when it improves clarity"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "match-statements"\ndescription = "dispatch on the shape of data rather than only on boolean tests"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "advanced-match-patterns"\ndescription = "combine destructuring, alternatives, and guards in pattern matching"\n\n[[journeys.sections]]\ntitle = "Stop as soon as the answer is known."\nsummary = "Early exits make the successful path easier to read by moving exceptional or completed cases out of the way."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "guard-clauses"\ndescription = "show how early returns reduce nested conditional code"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "assertions"\ndescription = "state assumptions that should fail loudly while developing"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "exceptions"\ndescription = "leave the current path when ordinary return values are not enough"\n\n[[journeys]]\nslug = "iteration"\ntitle = "Iteration"\nsummary = "This journey follows repeated work from ordinary loops to the iterator protocol: consume values, stop deliberately, and produce lazy streams only when they help."\n\n[[journeys.sections]]\ntitle = "Choose the right loop shape."\nsummary = "Loops differ by what they consume, when they stop, and whether completion itself carries meaning."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "for-loops"\ndescription = "consume values from an iterable"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "while-loops"\ndescription = "repeat while a condition must be rechecked"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "break-and-continue"\ndescription = "interrupt or skip loop work intentionally"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "loop-else"\ndescription = "attach completion logic to loops that did not break"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "sentinel-iteration"\ndescription = "show `iter(callable, sentinel)` for repeated reads until a marker appears"\n\n[[journeys.sections]]\ntitle = "See the protocol behind `for`."\nsummary = "The important mental shift is that loops consume producers through a protocol rather than special-casing lists."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "iterating-over-iterables"\ndescription = "separate value producers from value consumers"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "iterator-vs-iterable"\ndescription = "distinguish re-iterable collections from one-pass iterators"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "iterators"\ndescription = "use `iter()` and `next()` to expose the protocol behind `for`"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "generators"\ndescription = "write functions that produce values lazily"\n\n[[journeys.sections]]\ntitle = "Compose lazy value streams."\nsummary = "Iterator pipelines are useful when code can transform values one at a time instead of materializing every intermediate result."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "generator-expressions"\ndescription = "create lazy one-pass streams with expression syntax"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "itertools"\ndescription = "compose iterator streams without materializing every value"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "yield-from"\ndescription = "delegate part of a generator to another iterable"\n\n[[journeys]]\nslug = "shapes"\ntitle = "Shapes"\nsummary = "This journey teaches the core Python habit of choosing a data shape, transforming it directly, and making the result visible."\n\n[[journeys.sections]]\ntitle = "Pick the container that matches the question."\nsummary = "Lists, tuples, dictionaries, and sets answer different questions about order, position, lookup, and uniqueness."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "lists"\ndescription = "store ordered mutable data"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "tuples"\ndescription = "group fixed-position values"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "dicts"\ndescription = "look up values by key"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "sets"\ndescription = "model uniqueness and membership"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "collections-module"\ndescription = "show `deque`, `Counter`, `defaultdict`, and `namedtuple` as specialized shapes"\n\n[[journeys.sections]]\ntitle = "Move between shapes deliberately."\nsummary = "Most everyday Python code is data reshaping, so learners need the idioms for selecting, unpacking, and rebuilding values."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "unpacking"\ndescription = "bind names from structured values"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "slices"\ndescription = "select ranges from sequences"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "comprehensions"\ndescription = "build concrete collections from compact loops"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "comprehension-patterns"\ndescription = "compose filters and nested transformations"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "sorting"\ndescription = "order records with key functions"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "copying-collections"\ndescription = "contrast shallow copies, deep copies, and shared nested data"\n\n[[journeys.sections]]\ntitle = "Cross text and data boundaries."\nsummary = "Programs often receive text and produce structured data, so parsing and serialization belong in the data journey."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "number-parsing"\ndescription = "turn text into numbers safely"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "files-and-pathlib"\ndescription = "read and write text files through `Path` objects"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "json"\ndescription = "move structured data across a text boundary"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "regular-expressions"\ndescription = "extract structure from text patterns"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "datetime"\ndescription = "represent dates, times, and durations as typed values"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "csv-data"\ndescription = "show row-shaped text data and dictionary records"\n\n[[journeys]]\nslug = "interfaces"\ntitle = "Interfaces"\nsummary = "This journey shows how Python grows from simple functions to callable APIs, object interfaces, protocols, and metaclasses."\n\n[[journeys.sections]]\ntitle = "Start with functions as named behavior."\nsummary = "Functions are the first abstraction boundary because they name behavior and control how callers provide information."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "functions"\ndescription = "package behavior behind a name"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "keyword-only-arguments"\ndescription = "make important call-site choices explicit"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "positional-only-parameters"\ndescription = "hide parameter names that should remain implementation details"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "args-and-kwargs"\ndescription = "accept flexible call shapes when forwarding or adapting APIs"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "multiple-return-values"\ndescription = "return multiple related values as a tuple"\n\n[[journeys.sections]]\ntitle = "Use functions as values."\nsummary = "Python functions can capture state, be passed around, and wrap other functions."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "scope-global-nonlocal"\ndescription = "control where assignment happens"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "closures"\ndescription = "capture state in nested functions"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "recursion"\ndescription = "solve self-similar problems with a base case"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "lambdas"\ndescription = "write small unnamed functions for expression positions"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "decorators"\ndescription = "wrap behavior without changing call sites"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "partial-functions"\ndescription = "show how to pre-fill arguments with `functools.partial`"\n\n[[journeys.sections]]\ntitle = "Bundle behavior with state."\nsummary = "Classes become useful when data and behavior need to move together behind a stable interface."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "classes"\ndescription = "bundle state and behavior into a new object type"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "inheritance-and-super"\ndescription = "reuse and extend behavior through parent classes"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "dataclasses"\ndescription = "generate common methods for data containers"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "properties"\ndescription = "keep attribute syntax while adding computation or validation"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "classmethods-and-staticmethods"\ndescription = "choose between instance, class, and static behavior on a class"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "special-methods"\ndescription = "connect objects to Python syntax and built-ins"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "truth-and-size"\ndescription = "make objects work with truth tests and `len()`"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "container-protocols"\ndescription = "support membership, lookup, and assignment syntax"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "callable-objects"\ndescription = "make stateful instances callable like functions"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "operator-overloading"\ndescription = "define operators only when the operation is unsurprising"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "attribute-access"\ndescription = "customize fallback lookup and assignment carefully"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "bound-and-unbound-methods"\ndescription = "explain how attribute access turns a function into a bound method"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "descriptors"\ndescription = "explain the protocol behind methods, properties, and managed attributes"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "metaclasses"\ndescription = "customize class creation when ordinary class tools are not enough"\n\n[[journeys]]\nslug = "types"\ntitle = "Types"\nsummary = "This journey maps Python\'s runtime object model to optional static annotations so learners know what types can and cannot promise."\n\n[[journeys.sections]]\ntitle = "Keep runtime and static analysis separate."\nsummary = "The first lesson is that annotations describe expectations for tools while ordinary Python objects still run the program."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "type-hints"\ndescription = "document expected types and feed type checkers"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "protocols"\ndescription = "describe required behavior by structural shape"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "abstract-base-classes"\ndescription = "contrast runtime-enforced nominal interfaces with structural protocols"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "enums"\ndescription = "name a fixed set of symbolic values"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "runtime-type-checks"\ndescription = "show `type()`, `isinstance()`, and `issubclass()` without turning Python into Java"\n\n[[journeys.sections]]\ntitle = "Describe realistic data shapes."\nsummary = "Typed Python becomes useful when annotations explain optional values, unions, callables, and JSON-like records."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "union-and-optional-types"\ndescription = "show `X | Y` and `None`-aware APIs"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "type-aliases"\ndescription = "name complex types with `type` statements or aliases"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "typed-dicts"\ndescription = "type dictionary records that come from JSON"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "structured-data-shapes"\ndescription = "choose between dataclass, NamedTuple, and TypedDict for records"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "literal-and-final"\ndescription = "express constrained values and names that should not be rebound"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "callable-types"\ndescription = "type functions that are passed as arguments"\n\n[[journeys.sections]]\ntitle = "Scale annotations for reusable libraries."\nsummary = "Advanced typing exists to preserve information across reusable functions, containers, and decorators."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "generics-and-typevar"\ndescription = "write reusable typed containers and functions"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "paramspec"\ndescription = "preserve callable signatures through decorators"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "overloads"\ndescription = "describe APIs whose return type depends on the input shape"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "casts-and-any"\ndescription = "show escape hatches and their tradeoffs"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "newtype"\ndescription = "create distinct static identities for runtime-compatible values"\n\n[[journeys]]\nslug = "reliability"\ntitle = "Reliability"\nsummary = "This journey follows the boundaries where programs fail, clean up, split into modules, communicate with the outside world, and run concurrent work."\n\n[[journeys.sections]]\ntitle = "Make failure explicit."\nsummary = "Robust Python code distinguishes expected absence, broken assumptions, recoverable errors, and domain-specific failures."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "exceptions"\ndescription = "signal and recover from errors"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "assertions"\ndescription = "state internal assumptions"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "exception-chaining"\ndescription = "preserve the cause while translating an error"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "exception-groups"\ndescription = "handle multiple failures together"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "custom-exceptions"\ndescription = "name failures in the language of the problem domain"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "warnings"\ndescription = "signal soft problems and deprecations"\n\n[[journeys.sections]]\ntitle = "Control resource and module boundaries."\nsummary = "Cleanup, deletion, imports, and modules define where responsibilities begin and end."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "context-managers"\ndescription = "pair setup with reliable cleanup"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "delete-statements"\ndescription = "remove names, attributes, and items intentionally"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "modules"\ndescription = "split code into importable files"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "import-aliases"\ndescription = "make imported names clear at use sites"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "packages"\ndescription = "show package directories, `__init__.py`, and public module boundaries"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "virtual-environments"\ndescription = "isolate dependencies for a project"\n\n[[journeys.sections]]\ntitle = "Handle operations that outlive one expression."\nsummary = "I/O, testing, logging, subprocesses, and concurrency require different control boundaries from ordinary expressions."\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "async-await"\ndescription = "await concurrent I/O-shaped work"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "async-iteration-and-context"\ndescription = "consume async streams and cleanup protocols"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "logging"\ndescription = "record operational events without using `print()`"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "testing"\ndescription = "write deterministic tests with `unittest` or `pytest`"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "subprocesses"\ndescription = "run external commands safely"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "threads-and-processes"\ndescription = "contrast concurrency choices beyond `asyncio`"\n\n[[journeys.sections.items]]\nkind = "example"\nvalue = "networking"\ndescription = "make HTTP or socket boundaries explicit"\n\n# Explicit see_also edge labels; default labels are inferred in src/app.py.\n[[see_also_edge_labels]]\nsource = "break-and-continue"\ntarget = "loop-else"\nlabel = "contrast"\n\n[[see_also_edge_labels]]\nsource = "assignment-expressions"\ntarget = "conditionals"\nlabel = "contrast"\n\n[[see_also_edge_labels]]\nsource = "yield-from"\ntarget = "generators"\nlabel = "prerequisite"\n\n[[see_also_edge_labels]]\nsource = "async-iteration-and-context"\ntarget = "async-await"\nlabel = "prerequisite"\n\n[[see_also_edge_labels]]\nsource = "delete-statements"\ntarget = "mutability"\nlabel = "shared mechanism"\n\n[[see_also_edge_labels]]\nsource = "positional-only-parameters"\ntarget = "keyword-only-arguments"\nlabel = "contrast"\n\n[[see_also_edge_labels]]\nsource = "assertions"\ntarget = "exceptions"\nlabel = "alternative"\n\n[[see_also_edge_labels]]\nsource = "exception-chaining"\ntarget = "exceptions"\nlabel = "builds on"\n\n[[see_also_edge_labels]]\nsource = "exception-groups"\ntarget = "exceptions"\nlabel = "alternative"\n\n[[see_also_edge_labels]]\nsource = "operators"\ntarget = "numbers"\nlabel = "related syntax"\n\n[[see_also_edge_labels]]\nsource = "operators"\ntarget = "booleans"\nlabel = "condition building"\n\n[[see_also_edge_labels]]\nsource = "operators"\ntarget = "assignment-expressions"\nlabel = "specialized expression"\n\n[[see_also_edge_labels]]\nsource = "literals"\ntarget = "values"\nlabel = "value surface"\n\n[[see_also_edge_labels]]\nsource = "literals"\ntarget = "strings"\nlabel = "text literal"\n\n[[see_also_edge_labels]]\nsource = "literals"\ntarget = "sets"\nlabel = "container literal"\n\n# Example-cell figure attachments. figure names refer to FIGURES paint functions.\n[[figure_attachments]]\nslug = "mutability"\nanchor = "cell-0"\nfigure = "aliasing-mutation"\ncaption = "Two names share one mutable list — appending through one name changes the object visible through both."\n\n[[figure_attachments]]\nslug = "mutability"\nanchor = "cell-0"\nfigure = "tuple-no-mutation"\ncaption = "By contrast, a tuple is frozen — its contents cannot change in place, so aliasing carries no mutation hazard."\n\n[[figure_attachments]]\nslug = "variables"\nanchor = "cell-0"\nfigure = "variables-bind"\ncaption = "A name is a label that points at an object. Assignment binds the label; the object exists independently."\n\n[[figure_attachments]]\nslug = "lists"\nanchor = "cell-0"\nfigure = "list-append"\ncaption = "Lists are mutable sequences. `.append` extends the same list object — no new list is created."\n\n[[figure_attachments]]\nslug = "dicts"\nanchor = "cell-0"\nfigure = "dict-buckets"\ncaption = "hash(key) picks the slot: \\"year\\" lands in an empty one, and profile[\\"name\\"] goes straight to its slot without scanning the other entries."\n\n[[figure_attachments]]\nslug = "unpacking"\nanchor = "cell-0"\nfigure = "unpacking-bind"\ncaption = "Left-side names bind to right-side positions; `*rest` gathers the middle into a list."\n\n[[figure_attachments]]\nslug = "comprehensions"\nanchor = "cell-0"\nfigure = "comprehension-equivalence"\ncaption = "A comprehension is a compact spelling of the equivalent for-loop with append, made into one expression."\n\n[[figure_attachments]]\nslug = "classes"\nanchor = "cell-0"\nfigure = "class-triangle"\ncaption = "Every Python value sits on the instance → class → type triangle; the metaclass is the type of the class."\n\n[[figure_attachments]]\nslug = "inheritance-and-super"\nanchor = "cell-0"\nfigure = "mro-chain"\ncaption = "Multiple inheritance forms a graph; C3 linearisation flattens it into the MRO Python uses for attribute lookup."\n\n[[figure_attachments]]\nslug = "dataclasses"\nanchor = "cell-0"\nfigure = "dataclass-fields"\ncaption = "Field declarations become the generated __init__ signature: declaration is the constructor."\n\n[[figure_attachments]]\nslug = "special-methods"\nanchor = "cell-0"\nfigure = "operator-dispatch"\ncaption = "Operators are method calls. `a + b` dispatches to `a.__add__(b)`; the data model exposes the syntax."\n\n[[figure_attachments]]\nslug = "decorators"\nanchor = "cell-0"\nfigure = "decorator-rebind"\ncaption = "@dec rebinds the name to wrapper(f₀); the original function survives only in the wrapper\'s closure cell."\n\n[[figure_attachments]]\nslug = "recursion"\nanchor = "cell-1"\nfigure = "call-stack"\ncaption = "At the leaf with value 4, three frames of total are stacked, each waiting on the one below; unwinding returns 4, then 3 + 4 = 7, then 1 + 2 + 7 = 10."\n\n[[figure_attachments]]\nslug = "exception-chaining"\nanchor = "cell-0"\nfigure = "exception-cause-context"\ncaption = "`raise X from Y` sets `__cause__` (explicit); raising during except sets `__context__` (implicit)."\n\n[[figure_attachments]]\nslug = "hello-world"\nanchor = "cell-0"\nfigure = "program-output"\ncaption = "Every Python program starts as source and produces text on standard output. The smallest mental model."\n\n[[figure_attachments]]\nslug = "numbers"\nanchor = "cell-0"\nfigure = "number-lines"\ncaption = "Ints have unbounded precision; floats use IEEE doubles whose representable values thin out near the extremes."\n\n[[figure_attachments]]\nslug = "operators"\nanchor = "cell-0"\nfigure = "expression-tree"\ncaption = "An expression like `(2 + 3) * 4` parses as a tree; operator precedence and parentheses determine its shape."\n\n[[figure_attachments]]\nslug = "none"\nanchor = "cell-0"\nfigure = "none-singleton"\ncaption = "`None` is a single object: every name that points at None points at the same object."\n\n[[figure_attachments]]\nslug = "equality-and-identity"\nanchor = "cell-0"\nfigure = "identity-and-equality"\ncaption = "Two names can share one object (`is` and `==` both true) or hold two equal-but-distinct objects (only `==` true)."\n\n[[figure_attachments]]\nslug = "strings"\nanchor = "cell-0"\nfigure = "codepoints-bytes"\ncaption = "Strings are sequences of Unicode codepoints. UTF-8 encoding turns them into bytes; `é` takes two bytes, `c` takes one."\n\n[[figure_attachments]]\nslug = "for-loops"\nanchor = "cell-1"\nfigure = "iterator-unroll"\ncaption = "Each call to next() advances the caret one cell along the iterable — the same shape behind range(), strings, and any sequence."\n\n[[figure_attachments]]\nslug = "sorting"\nanchor = "cell-1"\nfigure = "sort-stability"\ncaption = "Python\'s sort is stable: items with equal keys keep their original order, so chained sorts compose predictably."\n\n[[figure_attachments]]\nslug = "keyword-only-arguments"\nanchor = "cell-0"\nfigure = "kw-only-separator"\ncaption = "A bare `*` divides positional or keyword arguments from keyword-only ones; callers must pass `c` and `d` by name."\n\n[[figure_attachments]]\nslug = "positional-only-parameters"\nanchor = "cell-0"\nfigure = "positional-only-separator"\ncaption = "A bare `/` divides positional-only arguments from positional-or-keyword ones; callers cannot name `a` or `b`."\n\n[[figure_attachments]]\nslug = "positional-only-parameters"\nanchor = "cell-0"\nfigure = "kw-only-separator"\ncaption = "In the same signature, the bare `*` works the other way: parameters after it, such as `clamp`, must be named at the call site."\n\n[[figure_attachments]]\nslug = "closures"\nanchor = "cell-0"\nfigure = "closure-cell"\ncaption = "make_multiplier(2) has returned, but the function object double names still points into that frame\'s cell, so the captured factor outlives the call."\n\n[[figure_attachments]]\nslug = "scope-global-nonlocal"\nanchor = "cell-0"\nfigure = "scope-rings"\ncaption = "Name lookup walks LEGB — local, enclosing, global, built-in — outward, returning the first binding it finds."\n\n[[figure_attachments]]\nslug = "generators"\nanchor = "cell-0"\nfigure = "generator-resume"\ncaption = "The cell\'s two next() calls on countdown(3), one timeline each: every call resumes the body to the next yield gate, and the local n survives the pause."\n\n[[figure_attachments]]\nslug = "type-hints"\nanchor = "cell-0"\nfigure = "annotation-ghost"\ncaption = "Annotations describe expected types for tools; the runtime accepts any object regardless."\n\n[[figure_attachments]]\nslug = "exceptions"\nanchor = "cell-0"\nfigure = "exception-lanes"\ncaption = "try, except, else, and finally as parallel lanes; a single coral path traces what actually runs."\n\n[[figure_attachments]]\nslug = "context-managers"\nanchor = "cell-0"\nfigure = "context-bowtie"\ncaption = "A context manager pairs setup with reliable cleanup; the raise path still routes through __exit__."\n\n[[figure_attachments]]\nslug = "async-await"\nanchor = "cell-1"\nfigure = "async-swimlane"\ncaption = "On await, the coroutine yields to the loop; the loop runs other work and resumes when the awaitable is ready."\n\n[[figure_attachments]]\nslug = "iterators"\nanchor = "cell-0"\nfigure = "iter-protocol"\ncaption = "iter() exposes the iterator behind for; next() pulls one value at a time until exhausted."\n\n[[figure_attachments]]\nslug = "slices"\nanchor = "cell-0"\nfigure = "slice-ruler"\ncaption = "Slice indices sit between cells; [:3] and [3:] partition the sequence at index 3, never overlapping or losing an item."\n\n[[figure_attachments]]\nslug = "operator-overloading"\nanchor = "cell-0"\nfigure = "operator-dispatch"\ncaption = "Defining `__add__` on a class lets `+` dispatch into the class\'s own behavior."\n\n[[figure_attachments]]\nslug = "iterator-vs-iterable"\nanchor = "cell-0"\nfigure = "iter-protocol"\ncaption = "An iterable knows how to produce an iterator (via iter()); the iterator knows how to produce values (via next())."\n\n[[figure_attachments]]\nslug = "iterator-vs-iterable"\nanchor = "cell-1"\nfigure = "iterator-unroll"\ncaption = "The iterator\'s caret only moves forward — after the first `list(stream)` drains it, nothing is left for the second."\n\n[[figure_attachments]]\nslug = "type-aliases"\nanchor = "cell-0"\nfigure = "type-alias-name"\ncaption = "A type alias names a complex annotation once so call sites read as the domain meaning, not the type composition."\n\n[[figure_attachments]]\nslug = "typed-dicts"\nanchor = "cell-0"\nfigure = "typed-dict-shape"\ncaption = "TypedDict gives each key a typed value, so `obj[\'x\']` is checked against the declared shape."\n\n[[figure_attachments]]\nslug = "union-and-optional-types"\nanchor = "cell-0"\nfigure = "union-types"\ncaption = "`int | str | None` says one slot may hold any of three shapes — including expected absence."\n\n[[figure_attachments]]\nslug = "generics-and-typevar"\nanchor = "cell-0"\nfigure = "generic-preservation"\ncaption = "A generic preserves the input type through the call: the same T flows in and out of fn[T]."\n\n[[figure_attachments]]\nslug = "abstract-base-classes"\nanchor = "cell-0"\nfigure = "class-triangle"\ncaption = "An ABC sits on the same triangle as concrete classes; subclasses inherit the abstract methods they must implement."\n\n[[figure_attachments]]\nslug = "copying-collections"\nanchor = "cell-0"\nfigure = "aliasing-mutation"\ncaption = "Without copy() two names share the same object; mutating through one is visible through the other."\n\n[[figure_attachments]]\nslug = "truth-and-size"\nanchor = "cell-0"\nfigure = "truth-and-size"\ncaption = "bool(x) calls __bool__ first; if absent, __len__() != 0; if neither, defaults to True."\n\n[[figure_attachments]]\nslug = "descriptors"\nanchor = "cell-0"\nfigure = "descriptor-protocol"\ncaption = "Attribute access on an instance routes through the descriptor\'s __get__/__set__/__delete__ when the attribute is a descriptor."\n\n[[figure_attachments]]\nslug = "bound-and-unbound-methods"\nanchor = "cell-0"\nfigure = "bound-unbound"\ncaption = "Accessing a method via an instance binds self; accessing it via the class returns the underlying function."\n\n[[figure_attachments]]\nslug = "classmethods-and-staticmethods"\nanchor = "cell-0"\nfigure = "method-kinds"\ncaption = "Three method kinds, three first-argument conventions: classmethod gets the class, staticmethod gets nothing, instance gets self."\n\n[[figure_attachments]]\nslug = "callable-objects"\nanchor = "cell-0"\nfigure = "callable-objects"\ncaption = "Defining __call__ makes any object callable; functions are just one shape that satisfies this protocol."\n\n[[figure_attachments]]\nslug = "attribute-access"\nanchor = "cell-0"\nfigure = "attribute-lookup"\ncaption = "obj.x checks instance __dict__, then class __dict__, then __getattr__; the first hit wins."\n\n[[figure_attachments]]\nslug = "guard-clauses"\nanchor = "cell-0"\nfigure = "guard-clauses"\ncaption = "Early returns handle the exceptional cases first so the main work is the body of the function, not its tail."\n\n[[figure_attachments]]\nslug = "bytes-and-bytearray"\nanchor = "cell-3"\nfigure = "bytes-vs-bytearray"\ncaption = "Both objects hold the same two bytes as integers; b\\"py\\" cannot change, while packet[0] = ord(\\"P\\") rewrites the first slot of the bytearray in place."\n\n[[figure_attachments]]\nslug = "sentinel-iteration"\nanchor = "cell-0"\nfigure = "sentinel-iteration"\ncaption = "iter(queue.popleft, \\"\\") keeps calling queue.popleft and yields \\"py\\" and \\"thon\\"; the empty string is the sentinel, so it stops the loop and is never yielded."\n\n[[figure_attachments]]\nslug = "partial-functions"\nanchor = "cell-0"\nfigure = "partial-functions"\ncaption = "`functools.partial(f, 1)` pre-fills `a=1`, returning a thinner callable `g(b, c)` that only needs the rest."\n\n[[figure_attachments]]\nslug = "args-and-kwargs"\nanchor = "cell-0"\nfigure = "args-kwargs"\ncaption = "*args captures the extra positionals as a tuple; **kwargs captures the extra keywords as a dict."\n\n[[figure_attachments]]\nslug = "multiple-return-values"\nanchor = "cell-0"\nfigure = "multiple-return"\ncaption = "A function returning multiple values really returns one tuple; the caller unpacks it into named bindings."\n\n[[figure_attachments]]\nslug = "lambdas"\nanchor = "cell-0"\nfigure = "lambda-expression"\ncaption = "A lambda is a function literal: parameters before the colon, a single expression after, no statement body."\n\n[[figure_attachments]]\nslug = "properties"\nanchor = "cell-0"\nfigure = "property-fork"\ncaption = "When x is a property, attribute access routes through fget/fset instead of touching __dict__."\n\n[[figure_attachments]]\nslug = "metaclasses"\nanchor = "cell-0"\nfigure = "metaclass-triangle"\ncaption = "A metaclass is the type of a class, just as a class is the type of its instances; type is the default metaclass."\n\n[[figure_attachments]]\nslug = "metaclasses"\nanchor = "cell-0"\nfigure = "class-triangle"\ncaption = "The class makes instances — the same triangle one level down, with type as the default apex."\n\n[[figure_attachments]]\nslug = "modules"\nanchor = "cell-0"\nfigure = "sys-path-resolution"\ncaption = "An import walks sys.path entry by entry; the first directory containing the module wins."\n\n[[figure_attachments]]\nslug = "import-aliases"\nanchor = "cell-0"\nfigure = "import-alias"\ncaption = "`import x as y` binds the name y to the same module object x would have."\n\n[[figure_attachments]]\nslug = "protocols"\nanchor = "cell-0"\nfigure = "protocol-check"\ncaption = "An object satisfies a protocol structurally — by having the required methods — not by inheriting it."\n\n[[figure_attachments]]\nslug = "enums"\nanchor = "cell-0"\nfigure = "enum-members"\ncaption = "An enum names a fixed set of symbolic values; no new members appear at runtime."\n\n[[figure_attachments]]\nslug = "datetime"\nanchor = "cell-0"\nfigure = "datetime-instant"\ncaption = "An aware datetime carries a UTC offset; one instant in time reads differently on two clocks."\n\n[[figure_attachments]]\nslug = "files-and-pathlib"\nanchor = "cell-0"\nfigure = "path-tree"\ncaption = "Each `Path` names one place in the directory tree; `/` steps down one level per name."\n\n[[figure_attachments]]\nslug = "json"\nanchor = "cell-0"\nfigure = "json-python-mapping"\ncaption = "Six type pairs bridge the JSON text boundary; each json value maps to one Python type."\n\n[[figure_attachments]]\nslug = "regular-expressions"\nanchor = "cell-0"\nfigure = "regex-groups"\ncaption = "findall returns only what the parentheses capture: `([A-Za-z]+)` takes the name and `(\\\\d+)` the score, one (name, score) pair per record."\n\n[[figure_attachments]]\nslug = "number-parsing"\nanchor = "cell-0"\nfigure = "number-parse"\ncaption = "int() turns text into a typed number; malformed input raises ValueError instead of guessing."\n\n[[figure_attachments]]\nslug = "string-formatting"\nanchor = "cell-1"\nfigure = "format-spec"\ncaption = "The format spec is a railroad of optional stations in a fixed order; this cell\'s 05.1f visits zero-pad, width, precision and type and bypasses the rest."\n\n[[figure_attachments]]\nslug = "truthiness"\nanchor = "cell-0"\nfigure = "truthy-check"\ncaption = "bool(x) is True except for a small fixed set: 0, 0.0, \\"\\", [], {}, None, False."\n\n[[figure_attachments]]\nslug = "booleans"\nanchor = "cell-0"\nfigure = "boolean-truth-table"\ncaption = "`a and b` returns True only when both are True; otherwise it returns the first falsy value."\n\n[[figure_attachments]]\nslug = "sets"\nanchor = "cell-0"\nfigure = "set-buckets"\ncaption = "Sets are hash buckets without values; `x in s` averages O(1) regardless of size."\n\n[[figure_attachments]]\nslug = "tuples"\nanchor = "cell-3"\nfigure = "tuple-frozen"\ncaption = "Tuples are ordered, immutable sequences; positions matter, contents do not change once constructed."\n\n[[figure_attachments]]\nslug = "tuples"\nanchor = "cell-3"\nfigure = "list-append"\ncaption = "A list is the other intent: a variable number of similar items, growing in place with `.append`."\n\n[[figure_attachments]]\nslug = "yield-from"\nanchor = "cell-0"\nfigure = "yield-delegation"\ncaption = "`yield from inner` delegates iteration to an inner generator; its yields surface here unchanged."\n\n[[figure_attachments]]\nslug = "itertools"\nanchor = "cell-0"\nfigure = "itertools-chain"\ncaption = "chain stitches two iterables into one stream without materialising either: values arrive lazily."\n\n[[figure_attachments]]\nslug = "assertions"\nanchor = "cell-0"\nfigure = "assertion-check"\ncaption = "assert tests a condition; True passes silently, False raises AssertionError with the optional message."\n\n[[figure_attachments]]\nslug = "custom-exceptions"\nanchor = "cell-0"\nfigure = "custom-exception-chain"\ncaption = "Subclassing an existing exception gains a domain name without changing semantics."\n\n[[figure_attachments]]\nslug = "exception-groups"\nanchor = "cell-0"\nfigure = "exception-group-peel"\ncaption = "except* peels matched leaves out of an ExceptionGroup; survivors regroup and propagate."\n\n[[figure_attachments]]\nslug = "delete-statements"\nanchor = "cell-0"\nfigure = "delete-name-erased"\ncaption = "`del x` removes the name; the object survives if any other reference holds it, otherwise gets collected."\n\n[[figure_attachments]]\nslug = "conditionals"\nanchor = "cell-0"\nfigure = "branch-fork"\ncaption = "A predicate sorts a value into one of several branches; if/elif/else is the explicit spelling."\n\n[[figure_attachments]]\nslug = "match-statements"\nanchor = "cell-0"\nfigure = "match-dispatch-ladder"\ncaption = "match dispatches by pattern shape; the value flows down the patterns and the first match wins."\n\n[[figure_attachments]]\nslug = "assignment-expressions"\nanchor = "cell-0"\nfigure = "naming-decisions"\ncaption = "The walrus binds a name during the surrounding expression; one expression, two outputs."\n\n[[figure_attachments]]\nslug = "iterating-over-iterables"\nanchor = "cell-0"\nfigure = "iter-protocol"\ncaption = "`for` desugars to iter()+next(): one iter() call, then next() until StopIteration ends the loop."\n\n[[figure_attachments]]\nslug = "generator-expressions"\nanchor = "cell-1"\nfigure = "lazy-stream"\ncaption = "A generator expression composes filter and map lazily; values flow only when next() pulls them."\n\n[[figure_attachments]]\nslug = "async-iteration-and-context"\nanchor = "cell-0"\nfigure = "async-swimlane"\ncaption = "async iteration and async with both rest on the same loop-vs-coroutine handoff as await."\n\n[[figure_attachments]]\nslug = "loop-else"\nanchor = "cell-0"\nfigure = "loop-else-gate"\ncaption = "The loop\'s else branch runs only when the loop falls through naturally; break skips it."\n\n[[figure_attachments]]\nslug = "break-and-continue"\nanchor = "cell-0"\nfigure = "early-exit"\ncaption = "break exits the loop; continue skips to the next iteration. Both interrupt the natural fall-through."\n\n[[figure_attachments]]\nslug = "comprehension-patterns"\nanchor = "cell-0"\nfigure = "comprehension-equivalence"\ncaption = "Nested clauses compose left to right; the comprehension is still equivalent to a for-loop with append."\n\n[[figure_attachments]]\nslug = "container-protocols"\nanchor = "cell-0"\nfigure = "container-methods"\ncaption = "Container syntax routes to narrow protocol methods: assignment to __setitem__, membership to __contains__, lookup to __getitem__."\n\n[[figure_attachments]]\nslug = "functions"\nanchor = "cell-0"\nfigure = "function-with-body"\ncaption = "A function takes inputs, evaluates a body, and returns a value: `greet(\'Ada\')` produces `\'Hello, Ada\'`."\n\n[[figure_attachments]]\nslug = "constants"\nanchor = "cell-0"\nfigure = "constants-bind"\ncaption = "UPPER_CASE is a naming convention, not a language constraint; the binding behaves like any other variable."\n\n[[figure_attachments]]\nslug = "values"\nanchor = "cell-0"\nfigure = "value-type-lookup"\ncaption = "text names a str object, and type(text) is str: the type carries upper() and the rest of the behaviour, not the name."\n\n[[figure_attachments]]\nslug = "literals"\nanchor = "cell-0"\nfigure = "literal-forms"\ncaption = "Each Python type has its own literal spellings; ints accept decimal, hex, and binary; strings accept either quote."\n\n[[figure_attachments]]\nslug = "logging"\nanchor = "cell-0"\nfigure = "logging-threshold"\ncaption = "The handler\'s level is a gate: debug is below INFO and never reaches stdout, while info and warning pass through unchanged."\n\n[[figure_attachments]]\nslug = "collections-module"\nanchor = "cell-0"\nfigure = "collections-containers"\ncaption = "Four specialised containers for shapes the built-in types don\'t cover well: deque, Counter, defaultdict, namedtuple."\n\n[[figure_attachments]]\nslug = "while-loops"\nanchor = "cell-0"\nfigure = "while-backedge"\ncaption = "`while` repeats the body while the test stays true; the back-edge returns control to the test before each pass."\n\n[[figure_attachments]]\nslug = "while-loops"\nanchor = "cell-0"\nfigure = "loop-repetition"\ncaption = "Each loop shape has its own stopping rule: `for` ends when the iterable is exhausted, `while` when the condition turns false, sentinel iteration when the marker value appears."\n\n[[figure_attachments]]\nslug = "advanced-match-patterns"\nanchor = "cell-0"\nfigure = "match-pattern-variants"\ncaption = "Capture, alternative, guard, and class patterns each name a different way a value can match a case."\n\n[[figure_attachments]]\nslug = "packages"\nanchor = "cell-0"\nfigure = "package-tree"\ncaption = "A directory with __init__.py becomes an importable package; submodules and subpackages nest beneath it."\n\n[[figure_attachments]]\nslug = "virtual-environments"\nanchor = "cell-0"\nfigure = "venv-boundary"\ncaption = "A venv carries its own interpreter and site-packages, isolating a project\'s dependencies from the system."\n\n[[figure_attachments]]\nslug = "subprocesses"\nanchor = "cell-0"\nfigure = "subprocess-spawn"\ncaption = "subprocess.run spawns a child process and captures its stdout, stderr, and exit code as portable evidence."\n\n[[figure_attachments]]\nslug = "testing"\nanchor = "cell-0"\nfigure = "aaa-pattern"\ncaption = "arrange-act-assert: set up the state, perform the behavior under test, compare the result to expectations."\n\n[[figure_attachments]]\nslug = "networking"\nanchor = "cell-0"\nfigure = "socket-byte-boundary"\ncaption = "Text crosses the socket as bytes — `encode` marks the python → wire boundary, `decode` brings the bytes back to a Python `str`."\n\n[[figure_attachments]]\nslug = "threads-and-processes"\nanchor = "cell-0"\nfigure = "gil-lanes"\ncaption = "Threads share memory but the GIL serialises Python bytecode; processes run in parallel with isolated memory."\n\n[[figure_attachments]]\nslug = "casts-and-any"\nanchor = "cell-0"\nfigure = "cast-escape"\ncaption = "cast(T, x) tells the type checker to treat x as T; the runtime is unaffected."\n\n[[figure_attachments]]\nslug = "newtype"\nanchor = "cell-0"\nfigure = "newtype-phantom"\ncaption = "NewType creates a distinct static identity backed by the same runtime type — UserId is int with a name."\n\n[[figure_attachments]]\nslug = "overloads"\nanchor = "cell-0"\nfigure = "overload-signatures"\ncaption = "@overload declares static call signatures for double(int) and double(str); one runtime implementation handles both."\n\n[[figure_attachments]]\nslug = "paramspec"\nanchor = "cell-0"\nfigure = "paramspec-preserve"\ncaption = "ParamSpec preserves the wrapped function\'s signature through a decorator, parameter for parameter."\n\n[[figure_attachments]]\nslug = "literal-and-final"\nanchor = "cell-0"\nfigure = "literal-constrained"\ncaption = "Literal narrows a slot to a fixed set of constant values; Final says the binding will not change."\n\n[[figure_attachments]]\nslug = "callable-types"\nanchor = "cell-0"\nfigure = "callable-type"\ncaption = "A Callable annotation describes the callback slot: this argument list must produce this return type."\n\n[[figure_attachments]]\nslug = "runtime-type-checks"\nanchor = "cell-0"\nfigure = "isinstance-check"\ncaption = "isinstance and issubclass ask the runtime; the answer is a bool, not a static type refinement."\n\n[[figure_attachments]]\nslug = "structured-data-shapes"\nanchor = "cell-0"\nfigure = "structured-shapes"\ncaption = "The same record can be a mutable dataclass, an immutable NamedTuple, or a runtime dict described by TypedDict."\n\n[[figure_attachments]]\nslug = "csv-data"\nanchor = "cell-0"\nfigure = "csv-records"\ncaption = "CSV files are rows of records; each line has the same columns in the same order."\n\n[[figure_attachments]]\nslug = "warnings"\nanchor = "cell-0"\nfigure = "warning-signal"\ncaption = "A warning is a soft signal: the message is reported, but execution continues unless filters elevate it."\n\n[[figure_attachments]]\nslug = "object-lifecycle"\nanchor = "cell-0"\nfigure = "object-lifecycle"\ncaption = "Names keep the same object reachable; deleting one name matters only when it removes the last reference."\n\n# Journey-section figures keyed by the visible section title.\n[[journey_section_figures]]\nsection = "Start with executable evidence."\nfigure = "runtime-evidence-loop"\ncaption = "Examples are evidence loops: source, a run step, and visible output stay together."\n\n[[journey_section_figures]]\nsection = "Separate value, identity, and absence."\nfigure = "runtime-object-axes"\ncaption = "Runtime objects answer separate questions: equal value, same identity, or the singleton that marks absence."\n\n[[journey_section_figures]]\nsection = "Read expressions as object operations."\nfigure = "runtime-expression-model"\ncaption = "Expression syntax enters the data model; object methods produce the result."\n\n[[journey_section_figures]]\nsection = "Choose between paths."\nfigure = "control-decision-map"\ncaption = "Facts flow into one decision point; exactly one branch owns the next step."\n\n[[journey_section_figures]]\nsection = "Name and shape decisions."\nfigure = "control-fact-shape"\ncaption = "Name a fact when a condition needs it; match shape when the data structure is the decision."\n\n[[journey_section_figures]]\nsection = "Stop as soon as the answer is known."\nfigure = "control-stop-boundary"\ncaption = "Early exits draw a boundary: once the answer is found, the tail stays unread."\n\n[[journey_section_figures]]\nsection = "Choose the right loop shape."\nfigure = "iteration-loop-selector"\ncaption = "Choose the loop from its stopping rule: exhaustion, condition, or sentinel marker."\n\n[[journey_section_figures]]\nsection = "See the protocol behind `for`."\nfigure = "iteration-protocol-map"\ncaption = "for is surface syntax; iter() creates an iterator and next() pulls values until StopIteration."\n\n[[journey_section_figures]]\nsection = "Compose lazy value streams."\nfigure = "iteration-lazy-pull"\ncaption = "Lazy pipelines run from the consumer\'s pull: next() requests one value through each stage."\n\n[[journey_section_figures]]\nsection = "Pick the container that matches the question."\nfigure = "container-questions"\ncaption = "Each container answers a different question: ordered, fixed, lookup, unique."\n\n[[journey_section_figures]]\nsection = "Move between shapes deliberately."\nfigure = "reshape-pipeline"\ncaption = "Most everyday code reshapes data: one input, one transform, one new value."\n\n[[journey_section_figures]]\nsection = "Cross text and data boundaries."\nfigure = "text-data-boundary"\ncaption = "Programs receive text and produce structured data; parsing makes the boundary explicit."\n\n[[journey_section_figures]]\nsection = "Start with functions as named behavior."\nfigure = "function-signature"\ncaption = "A function is the first abstraction boundary: arguments in, body, return value out."\n\n[[journey_section_figures]]\nsection = "Use functions as values."\nfigure = "function-as-value"\ncaption = "Functions are first-class values. A second name binds to the same function object."\n\n[[journey_section_figures]]\nsection = "Bundle behavior with state."\nfigure = "class-with-state"\ncaption = "Classes group fields and methods so data and behavior move together behind one interface."\n\n[[journey_section_figures]]\nsection = "Keep runtime and static analysis separate."\nfigure = "type-runtime-static-split"\ncaption = "Runtime values run the program; static tools inspect separate annotations and report before execution."\n\n[[journey_section_figures]]\nsection = "Describe realistic data shapes."\nfigure = "type-shape-catalog"\ncaption = "Real data contracts combine fields, variants, and expected absence instead of one scalar type."\n\n[[journey_section_figures]]\nsection = "Scale annotations for reusable libraries."\nfigure = "type-library-contract"\ncaption = "Reusable APIs carry caller contracts through the library boundary with generics, parameters, and overloads."\n\n[[journey_section_figures]]\nsection = "Make failure explicit."\nfigure = "reliability-signal-map"\ncaption = "Different failure shapes need explicit signals: assertions, recovery, chained causes, or warnings."\n\n[[journey_section_figures]]\nsection = "Control resource and module boundaries."\nfigure = "reliability-boundary-map"\ncaption = "Reliable programs name their boundaries: resources clean up, modules import, environments constrain runtime."\n\n[[journey_section_figures]]\nsection = "Handle operations that outlive one expression."\nfigure = "reliability-operation-boundary"\ncaption = "Async, threaded, test, and logging work cross an operation boundary before evidence comes back."\n\n# Curated scores for example-cell figures.\n[[example_figure_scores]]\nslug = "variables"\nscore = 9.5\ncomment = "the canonical name → object picture"\n\n[[example_figure_scores]]\nslug = "mutability"\nscore = 9.5\ncomment = "three-state small multiple of aliased mutation"\n\n[[example_figure_scores]]\nslug = "copying-collections"\nscore = 9.5\ncomment = "same picture as mutability, perfect match"\n\n[[example_figure_scores]]\nslug = "hello-world"\nscore = 9.0\ncomment = "program → output, smallest mechanism"\n\n[[example_figure_scores]]\nslug = "numbers"\nscore = 9.0\ncomment = "int unbounded vs float thinning, both registers"\n\n[[example_figure_scores]]\nslug = "operators"\nscore = 9.0\ncomment = "expression tree mechanism"\n\n[[example_figure_scores]]\nslug = "none"\nscore = 9.0\ncomment = "three names converging on one None"\n\n[[example_figure_scores]]\nslug = "equality-and-identity"\nscore = 9.0\ncomment = "shared vs separate object, side-by-side"\n\n[[example_figure_scores]]\nslug = "strings"\nscore = 9.0\ncomment = "codepoints + bytes registers"\n\n[[example_figure_scores]]\nslug = "for-loops"\nscore = 9.0\ncomment = "4-row caret advance"\n\n[[example_figure_scores]]\nslug = "sorting"\nscore = 9.0\ncomment = "stability ribbons preserved across keys"\n\n[[example_figure_scores]]\nslug = "keyword-only-arguments"\nscore = 9.0\ncomment = "signature with explicit `*` separator"\n\n[[example_figure_scores]]\nslug = "positional-only-parameters"\nscore = 9.0\ncomment = "signature with explicit `/` separator"\n\n[[example_figure_scores]]\nslug = "closures"\nscore = 9.5\ncomment = "environment diagram: ghosted returned frame, heap function object, one live __closure__ reference; 1.5/1/0.75/1/1 · 1/1/1 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "scope-global-nonlocal"\nscore = 9.0\ncomment = "LEGB nested rings"\n\n[[example_figure_scores]]\nslug = "recursion"\nscore = 9.0\ncomment = "the example\'s own tree at its deepest frame, return values unwinding; earns-place 0.75, the cell\'s output already gives 10; 1.5/0.75/1/1/1 · 1/1/1 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "lists"\nscore = 9.0\ncomment = "cells with append mechanism"\n\n[[example_figure_scores]]\nslug = "dicts"\nscore = 9.0\ncomment = "the cell\'s own keys hashed to slots, the insert of \\"year\\" accented; earns-place 0.75, one-move 0.75 since insert and lookup share the caption; 1.5/0.75/0.75/1/1 · 1/1/1 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "slices"\nscore = 9.0\ncomment = "ruler with bracket overlay"\n\n[[example_figure_scores]]\nslug = "comprehensions"\nscore = 9.0\ncomment = "comprehension over equivalent for-loop"\n\n[[example_figure_scores]]\nslug = "type-hints"\nscore = 9.0\ncomment = "ghost annotations over runtime values"\n\n[[example_figure_scores]]\nslug = "generators"\nscore = 9.5\ncomment = "the cell\'s two next() ribbons on countdown(3), local n shown surviving; earns-place 0.75, the prose says the same; 1.5/0.75/1/1/1 · 1/1/1 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "exceptions"\nscore = 9.0\ncomment = "try/except/else/finally lanes with traced path"\n\n[[example_figure_scores]]\nslug = "context-managers"\nscore = 9.0\ncomment = "enter / body / exit bowtie"\n\n[[example_figure_scores]]\nslug = "async-await"\nscore = 9.0\ncomment = "loop/coro swimlane with await handoffs"\n\n[[example_figure_scores]]\nslug = "classes"\nscore = 9.0\ncomment = "instance/class/type triangle"\n\n[[example_figure_scores]]\nslug = "inheritance-and-super"\nscore = 9.0\ncomment = "MRO chain with diamond ghost"\n\n[[example_figure_scores]]\nslug = "dataclasses"\nscore = 9.0\ncomment = "fields → generated __init__ signature"\n\n[[example_figure_scores]]\nslug = "decorators"\nscore = 9.0\ncomment = "before/after rebinding through cell"\n\n[[example_figure_scores]]\nslug = "special-methods"\nscore = 9.0\ncomment = "syntax → method dispatch"\n\n[[example_figure_scores]]\nslug = "unpacking"\nscore = 9.0\ncomment = "binding-line mechanism with *rest"\n\n[[example_figure_scores]]\nslug = "exception-chaining"\nscore = 9.0\ncomment = "__cause__ vs __context__ distinguished"\n\n[[example_figure_scores]]\nslug = "iterating-over-iterables"\nscore = 9.0\ncomment = "iter() exposes the iterator"\n\n[[example_figure_scores]]\nslug = "iterators"\nscore = 9.0\ncomment = "three-state machine"\n\n[[example_figure_scores]]\nslug = "iterator-vs-iterable"\nscore = 9.0\ncomment = "the protocol exposed"\n\n[[example_figure_scores]]\nslug = "container-protocols"\nscore = 9.0\ncomment = "syntax routes to __setitem__, __contains__, __getitem__"\n\n[[example_figure_scores]]\nslug = "operator-overloading"\nscore = 9.0\ncomment = "dispatch arrow"\n\n[[example_figure_scores]]\nslug = "union-and-optional-types"\nscore = 9.0\ncomment = "type fork to several shapes"\n\n[[example_figure_scores]]\nslug = "abstract-base-classes"\nscore = 9.0\ncomment = "same triangle as concrete classes"\n\n[[example_figure_scores]]\nslug = "conditionals"\nscore = 9.0\ncomment = "predicate forks value to branch"\n\n[[example_figure_scores]]\nslug = "match-statements"\nscore = 9.0\ncomment = "dispatch ladder; first match wins"\n\n[[example_figure_scores]]\nslug = "advanced-match-patterns"\nscore = 9.0\ncomment = "four pattern variants"\n\n[[example_figure_scores]]\nslug = "loop-else"\nscore = 9.0\ncomment = "fell-through vs broke, two outcomes"\n\n[[example_figure_scores]]\nslug = "while-loops"\nscore = 9.0\ncomment = "back-edge mechanism plus the three stopping rules"\n\n[[example_figure_scores]]\nslug = "type-aliases"\nscore = 9.0\ncomment = "complex annotation collapses to a name"\n\n[[example_figure_scores]]\nslug = "typed-dicts"\nscore = 9.0\ncomment = "keys with declared value types"\n\n[[example_figure_scores]]\nslug = "comprehension-patterns"\nscore = 9.0\ncomment = "nested clauses compose"\n\n[[example_figure_scores]]\nslug = "lambdas"\nscore = 9.0\ncomment = "function literal: params / expression"\n\n[[example_figure_scores]]\nslug = "string-formatting"\nscore = 9.0\ncomment = "railroad tracing the cell\'s 05.1f; one-move 0.75, restraint 0.75 and fit 0.75: still the densest figure in the set at the banner ceiling; 1.5/1/0.75/1/1 · 1/1/0.75 · 0.75/0.5"\n\n[[example_figure_scores]]\nslug = "regular-expressions"\nscore = 9.0\ncomment = "the cell\'s pattern with both capture groups dropped onto Ada: 10; one-move 0.75 and restraint 0.75 for two rows plus two drops; 1.5/1/0.75/1/1 · 1/1/0.75 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "files-and-pathlib"\nscore = 9.0\ncomment = "the page\'s own tree with the two paths the cells build; containment hairlines, dashed path-to-place links, no accent"\n\n[[example_figure_scores]]\nslug = "json"\nscore = 9.0\ncomment = "two-column type mapping"\n\n[[example_figure_scores]]\nslug = "metaclasses"\nscore = 9.0\ncomment = "extended triangle to metaclass"\n\n[[example_figure_scores]]\nslug = "datetime"\nscore = 9.0\ncomment = "one instant, two clock offsets"\n\n[[example_figure_scores]]\nslug = "booleans"\nscore = 9.0\ncomment = "2×2 truth table"\n\n[[example_figure_scores]]\nslug = "sets"\nscore = 9.0\ncomment = "hash buckets without values"\n\n[[example_figure_scores]]\nslug = "yield-from"\nscore = 9.0\ncomment = "stitched ribbons; delegation"\n\n[[example_figure_scores]]\nslug = "generator-expressions"\nscore = 9.0\ncomment = "lazy filter→map pipeline"\n\n[[example_figure_scores]]\nslug = "async-iteration-and-context"\nscore = 9.0\ncomment = "loop/coro lanes with await yields"\n\n[[example_figure_scores]]\nslug = "assignment-expressions"\nscore = 9.0\ncomment = "walrus binds while comparing"\n\n[[example_figure_scores]]\nslug = "break-and-continue"\nscore = 9.0\ncomment = "early exit at first match"\n\n[[example_figure_scores]]\nslug = "delete-statements"\nscore = 9.0\ncomment = "name erased; object survives if referenced"\n\n[[example_figure_scores]]\nslug = "exception-groups"\nscore = 9.0\ncomment = "except* peels matching leaves"\n\n[[example_figure_scores]]\nslug = "custom-exceptions"\nscore = 9.0\ncomment = "subclass chain to a domain name"\n\n[[example_figure_scores]]\nslug = "modules"\nscore = 9.0\ncomment = "sys.path resolution; first hit wins"\n\n[[example_figure_scores]]\nslug = "protocols"\nscore = 9.0\ncomment = "structural duck check"\n\n[[example_figure_scores]]\nslug = "enums"\nscore = 9.0\ncomment = "closed set of symbolic values"\n\n[[example_figure_scores]]\nslug = "functions"\nscore = 9.0\ncomment = "specific call: greet(\'Ada\') → \'Hello, Ada\'"\n\n[[example_figure_scores]]\nslug = "constants"\nscore = 9.0\ncomment = "name binding with the cell\'s own MAX_RETRIES → 3; earns-place 0.5, the prose already says it is an ordinary binding; 1.5/0.5/1/1/1 · 1/1/1 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "values"\nscore = 9.0\ncomment = "text → str binding plus the type() hop to where upper() lives; earns-place 0.75 since the cell prints type(text), one-move 0.75; 1.5/0.75/0.75/1/1 · 1/1/1 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "literals"\nscore = 8.5\ncomment = "literal spellings per type; a reference table, kept until a mechanism figure replaces it"\n\n[[example_figure_scores]]\nslug = "logging"\nscore = 9.5\ncomment = "the cell\'s three records crossing the handler\'s INFO gate, debug dropped; earns-place 0.75 since the output already shows the drop; 1.5/0.75/1/1/1 · 1/1/1 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "collections-module"\nscore = 8.5\ncomment = "deque / Counter / defaultdict / namedtuple; a catalogue, kept until the page is split"\n\n[[example_figure_scores]]\nslug = "import-aliases"\nscore = 9.0\ncomment = "two names bind to the same module"\n\n[[example_figure_scores]]\nslug = "number-parsing"\nscore = 9.0\ncomment = "int() success path vs ValueError"\n\n[[example_figure_scores]]\nslug = "tuples"\nscore = 9.0\ncomment = "frozen sequence with struck-through .append"\n\n[[example_figure_scores]]\nslug = "truthiness"\nscore = 9.0\ncomment = "bool(x) with the falsy set as a strip"\n\n[[example_figure_scores]]\nslug = "itertools"\nscore = 9.0\ncomment = "chain joins two iterables into one stream"\n\n[[example_figure_scores]]\nslug = "assertions"\nscore = 9.0\ncomment = "True passes, False raises"\n\n[[example_figure_scores]]\nslug = "descriptors"\nscore = 9.0\ncomment = "get/set/delete protocol routed through descriptor"\n\n[[example_figure_scores]]\nslug = "attribute-access"\nscore = 9.0\ncomment = "instance __dict__ → class __dict__ → __getattr__"\n\n[[example_figure_scores]]\nslug = "bound-and-unbound-methods"\nscore = 9.0\ncomment = "instance.method bound vs Class.method unbound"\n\n[[example_figure_scores]]\nslug = "classmethods-and-staticmethods"\nscore = 9.0\ncomment = "three method kinds, three first-arg conventions"\n\n[[example_figure_scores]]\nslug = "callable-objects"\nscore = 9.0\ncomment = "__call__ makes any object callable"\n\n[[example_figure_scores]]\nslug = "generics-and-typevar"\nscore = 9.0\ncomment = "the same T flows in and out"\n\n[[example_figure_scores]]\nslug = "truth-and-size"\nscore = 9.0\ncomment = "__bool__ → __len__ → True fallback chain"\n\n[[example_figure_scores]]\nslug = "bytes-and-bytearray"\nscore = 9.5\ncomment = "the example\'s two bytes as integer slots, packet[0] rewritten in place, anchored to the mutating cell; 1.5/0.75/1/1/1 · 1/1/1 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "sentinel-iteration"\nscore = 9.0\ncomment = "the cell\'s queue.popleft call and queued chunks; the empty string ghosted as the sentinel; earns-place 0.75, the output already omits it; 1.5/0.75/1/1/1 · 1/1/1 · 1/0.5"\n\n[[example_figure_scores]]\nslug = "partial-functions"\nscore = 9.0\ncomment = "f → partial(f, 1) → g"\n\n[[example_figure_scores]]\nslug = "guard-clauses"\nscore = 9.0\ncomment = "early returns, main body at the tail"\n\n[[example_figure_scores]]\nslug = "packages"\nscore = 9.0\ncomment = "__init__.py + nested submodules"\n\n[[example_figure_scores]]\nslug = "virtual-environments"\nscore = 9.0\ncomment = "project / venv boundary"\n\n[[example_figure_scores]]\nslug = "subprocesses"\nscore = 9.0\ncomment = "spawn → child → captured output"\n\n[[example_figure_scores]]\nslug = "testing"\nscore = 9.0\ncomment = "arrange-act-assert three-row pattern"\n\n[[example_figure_scores]]\nslug = "networking"\nscore = 9.0\ncomment = "text ↔ bytes across the socket boundary"\n\n[[example_figure_scores]]\nslug = "casts-and-any"\nscore = 9.0\ncomment = "Any → cast(T, x) → T, runtime unchanged"\n\n[[example_figure_scores]]\nslug = "newtype"\nscore = 9.0\ncomment = "same runtime, distinct static identity"\n\n[[example_figure_scores]]\nslug = "paramspec"\nscore = 9.0\ncomment = "P preserved through decorator"\n\n[[example_figure_scores]]\nslug = "literal-and-final"\nscore = 9.0\ncomment = "slot narrows to a fixed set"\n\n[[example_figure_scores]]\nslug = "runtime-type-checks"\nscore = 9.0\ncomment = "isinstance returns bool"\n\n[[example_figure_scores]]\nslug = "structured-data-shapes"\nscore = 9.0\ncomment = "dataclass vs NamedTuple vs TypedDict runtime trade-offs"\n\n[[example_figure_scores]]\nslug = "csv-data"\nscore = 9.0\ncomment = "rows × columns; same shape per line"\n\n[[example_figure_scores]]\nslug = "warnings"\nscore = 9.0\ncomment = "soft signal; execution continues"\n\n[[example_figure_scores]]\nslug = "object-lifecycle"\nscore = 9.0\ncomment = "names keep object reachable until last reference disappears"\n\n[[example_figure_scores]]\nslug = "args-and-kwargs"\nscore = 9.0\ncomment = "*args tuple, **kwargs dict regions"\n\n[[example_figure_scores]]\nslug = "multiple-return-values"\nscore = 9.0\ncomment = "function returns tuple; caller unpacks"\n\n[[example_figure_scores]]\nslug = "properties"\nscore = 9.0\ncomment = "obj.x routes through fget instead of __dict__"\n\n[[example_figure_scores]]\nslug = "overloads"\nscore = 9.0\ncomment = "static overload signatures contrasted with one runtime body"\n\n[[example_figure_scores]]\nslug = "callable-types"\nscore = 9.0\ncomment = "callback slot shows argument list and return type"\n\n[[example_figure_scores]]\nslug = "threads-and-processes"\nscore = 9.0\ncomment = "thread GIL sharing contrasted with process isolation"\n\n# Curated scores for journey-section figures.\n[[journey_section_figure_scores]]\nsection = "Start with executable evidence."\nscore = 9.0\ncomment = "journey-native source/run/output evidence loop"\n\n[[journey_section_figure_scores]]\nsection = "Separate value, identity, and absence."\nscore = 9.0\ncomment = "three runtime questions separated"\n\n[[journey_section_figure_scores]]\nsection = "Read expressions as object operations."\nscore = 9.0\ncomment = "syntax enters the data-model method surface"\n\n[[journey_section_figure_scores]]\nsection = "Choose between paths."\nscore = 9.0\ncomment = "branch map independent of one if-statement example"\n\n[[journey_section_figure_scores]]\nsection = "Name and shape decisions."\nscore = 9.0\ncomment = "name-vs-shape decision map"\n\n[[journey_section_figure_scores]]\nsection = "Stop as soon as the answer is known."\nscore = 9.0\ncomment = "early boundary leaves tail unread"\n\n[[journey_section_figure_scores]]\nsection = "Choose the right loop shape."\nscore = 9.0\ncomment = "loop choice by stopping rule"\n\n[[journey_section_figure_scores]]\nsection = "See the protocol behind `for`."\nscore = 9.5\ncomment = "for surface mapped to iter()/next()/StopIteration"\n\n[[journey_section_figure_scores]]\nsection = "Compose lazy value streams."\nscore = 9.0\ncomment = "consumer pull drives the lazy pipeline"\n\n[[journey_section_figure_scores]]\nsection = "Pick the container that matches the question."\nscore = 9.0\ncomment = "list/tuple/dict/set per question"\n\n[[journey_section_figure_scores]]\nsection = "Move between shapes deliberately."\nscore = 9.0\ncomment = "input → transform → result"\n\n[[journey_section_figure_scores]]\nsection = "Cross text and data boundaries."\nscore = 9.0\ncomment = "text in, structured value out"\n\n[[journey_section_figure_scores]]\nsection = "Start with functions as named behavior."\nscore = 9.0\ncomment = "concrete call, named body, and return boundary"\n\n[[journey_section_figure_scores]]\nsection = "Use functions as values."\nscore = 9.0\ncomment = "second name binds same function"\n\n[[journey_section_figure_scores]]\nsection = "Bundle behavior with state."\nscore = 9.0\ncomment = "class groups state + methods"\n\n[[journey_section_figure_scores]]\nsection = "Keep runtime and static analysis separate."\nscore = 9.0\ncomment = "runtime track separated from static-tool track"\n\n[[journey_section_figure_scores]]\nsection = "Describe realistic data shapes."\nscore = 9.0\ncomment = "field, variant, and absence contracts in one map"\n\n[[journey_section_figure_scores]]\nsection = "Scale annotations for reusable libraries."\nscore = 9.0\ncomment = "caller contracts survive library API boundary"\n\n[[journey_section_figure_scores]]\nsection = "Make failure explicit."\nscore = 9.0\ncomment = "failure shapes mapped to explicit signals"\n\n[[journey_section_figure_scores]]\nsection = "Control resource and module boundaries."\nscore = 9.0\ncomment = "resource/module/env boundaries shown together"\n\n[[journey_section_figure_scores]]\nsection = "Handle operations that outlive one expression."\nscore = 9.0\ncomment = "operation boundary returns evidence later"\n\n# Curated example quality scores.\n[[example_quality_scores]]\nslug = "hello-world"\nscore = 7.1\ncomment = "waived: traditional smallest complete program"\n\n[[example_quality_scores]]\nslug = "values"\nscore = 9.0\ncomment = "object/type/operation map with prerequisite graph edges"\n\n[[example_quality_scores]]\nslug = "literals"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich, note-heavy, multi-cell"\n\n[[example_quality_scores]]\nslug = "numbers"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "booleans"\nscore = 9.0\ncomment = "truth operations, short-circuiting, bool-as-int footgun"\n\n[[example_quality_scores]]\nslug = "operators"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich, note-heavy, multi-cell"\n\n[[example_quality_scores]]\nslug = "none"\nscore = 9.0\ncomment = "None, mapping default, and exception absence boundaries"\n\n[[example_quality_scores]]\nslug = "variables"\nscore = 9.0\ncomment = "binding, rebinding, augmented-assignment, lifecycle graph"\n\n[[example_quality_scores]]\nslug = "constants"\nscore = 9.0\ncomment = "constant convention, Final boundary, runtime rebinding evidence"\n\n[[example_quality_scores]]\nslug = "truthiness"\nscore = 9.0\ncomment = "truth-value categories, explicit-comparison boundary, graph-linked"\n\n[[example_quality_scores]]\nslug = "equality-and-identity"\nscore = 9.0\ncomment = "== versus is, singleton check, identity-cache warning"\n\n[[example_quality_scores]]\nslug = "mutability"\nscore = 9.0\ncomment = "in-place mutation, rebinding, alias visibility"\n\n[[example_quality_scores]]\nslug = "object-lifecycle"\nscore = 9.0\ncomment = "references, rebinding, and last-reference boundary"\n\n[[example_quality_scores]]\nslug = "strings"\nscore = 9.0\ncomment = "Unicode text, immutability, encoding boundary"\n\n[[example_quality_scores]]\nslug = "bytes-and-bytearray"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "string-formatting"\nscore = 9.0\ncomment = "f-string expression, format spec, debug/repr boundary"\n\n[[example_quality_scores]]\nslug = "conditionals"\nscore = 9.0\ncomment = "branch ordering, truthiness, and ternary boundary"\n\n[[example_quality_scores]]\nslug = "guard-clauses"\nscore = 9.0\ncomment = "nested contrast plus flattened guard path"\n\n[[example_quality_scores]]\nslug = "assignment-expressions"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "for-loops"\nscore = 9.0\ncomment = "direct iteration, range, and enumerate progression"\n\n[[example_quality_scores]]\nslug = "break-and-continue"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "loop-else"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "iterating-over-iterables"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "iterators"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "iterator-vs-iterable"\nscore = 9.0\ncomment = "graph-rich"\n\n[[example_quality_scores]]\nslug = "sentinel-iteration"\nscore = 9.0\ncomment = "call-until-marker shape contrasted with manual while"\n\n[[example_quality_scores]]\nslug = "match-statements"\nscore = 9.0\ncomment = "shape dispatch and guarded pattern payoff"\n\n[[example_quality_scores]]\nslug = "advanced-match-patterns"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "while-loops"\nscore = 9.0\ncomment = "state-driven repetition contrasted with for loops"\n\n[[example_quality_scores]]\nslug = "lists"\nscore = 9.0\ncomment = "ordered mutable sequence operations plus tuple/set/copy boundaries"\n\n[[example_quality_scores]]\nslug = "tuples"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "unpacking"\nscore = 9.0\ncomment = "sequence, starred, and mapping unpacking shapes"\n\n[[example_quality_scores]]\nslug = "dicts"\nscore = 9.0\ncomment = "lookup/default/update/delete dictionary boundaries"\n\n[[example_quality_scores]]\nslug = "sets"\nscore = 9.0\ncomment = "uniqueness, membership, set algebra, ordering boundary"\n\n[[example_quality_scores]]\nslug = "slices"\nscore = 9.0\ncomment = "range bounds, step, reverse, and unchanged-source evidence"\n\n[[example_quality_scores]]\nslug = "comprehensions"\nscore = 9.0\ncomment = "loop-equivalent collection building with filter/projection boundaries"\n\n[[example_quality_scores]]\nslug = "comprehension-patterns"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "sorting"\nscore = 9.0\ncomment = "key functions, reverse order, sorted/list.sort boundary"\n\n[[example_quality_scores]]\nslug = "collections-module"\nscore = 9.0\ncomment = "Counter, defaultdict, deque, namedtuple mapped to data shapes"\n\n[[example_quality_scores]]\nslug = "copying-collections"\nscore = 9.0\ncomment = "alias, shallow copy, and deepcopy boundaries"\n\n[[example_quality_scores]]\nslug = "functions"\nscore = 9.0\ncomment = "definition/call/return/default-boundary walkthrough"\n\n[[example_quality_scores]]\nslug = "keyword-only-arguments"\nscore = 9.0\ncomment = "call-site readability and boolean flag boundary"\n\n[[example_quality_scores]]\nslug = "positional-only-parameters"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "args-and-kwargs"\nscore = 9.0\ncomment = "flexible argument collection plus forwarding/API-boundary graph"\n\n[[example_quality_scores]]\nslug = "multiple-return-values"\nscore = 9.0\ncomment = "tuple return plus unpacking boundary"\n\n[[example_quality_scores]]\nslug = "closures"\nscore = 9.0\ncomment = "closed-over state, factory payoff, late-binding boundary"\n\n[[example_quality_scores]]\nslug = "partial-functions"\nscore = 9.0\ncomment = "before/after callable adaptation and introspection"\n\n[[example_quality_scores]]\nslug = "scope-global-nonlocal"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "recursion"\nscore = 9.0\ncomment = "base case and recursive tree-shape payoff"\n\n[[example_quality_scores]]\nslug = "lambdas"\nscore = 9.0\ncomment = "expression callable use contrasted with named def reuse"\n\n[[example_quality_scores]]\nslug = "generators"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "yield-from"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "generator-expressions"\nscore = 9.0\ncomment = "eager list contrast, lazy one-pass consumption, reducer use"\n\n[[example_quality_scores]]\nslug = "itertools"\nscore = 9.0\ncomment = "lazy standard-library pipeline and iterator-composition payoff"\n\n[[example_quality_scores]]\nslug = "decorators"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "classes"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "inheritance-and-super"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "classmethods-and-staticmethods"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "dataclasses"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "properties"\nscore = 9.0\ncomment = "managed attribute API without caller syntax change"\n\n[[example_quality_scores]]\nslug = "special-methods"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich, note-heavy, multi-cell"\n\n[[example_quality_scores]]\nslug = "truth-and-size"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "container-protocols"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "callable-objects"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "operator-overloading"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "attribute-access"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "bound-and-unbound-methods"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "descriptors"\nscore = 9.0\ncomment = "descriptor lookup, __set_name__, and validation mechanics"\n\n[[example_quality_scores]]\nslug = "metaclasses"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "context-managers"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "delete-statements"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "exceptions"\nscore = 9.0\ncomment = "specific handling, else/finally cleanup, broad-catch boundary"\n\n[[example_quality_scores]]\nslug = "assertions"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "exception-chaining"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "exception-groups"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "warnings"\nscore = 9.0\ncomment = "capture and escalate soft failures with filters"\n\n[[example_quality_scores]]\nslug = "modules"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "import-aliases"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "packages"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "virtual-environments"\nscore = 9.0\ncomment = "standard venv workflow plus explicit Worker deployment boundary"\n\n[[example_quality_scores]]\nslug = "type-hints"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich, note-heavy, multi-cell"\n\n[[example_quality_scores]]\nslug = "runtime-type-checks"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "union-and-optional-types"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "type-aliases"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "typed-dicts"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "structured-data-shapes"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "literal-and-final"\nscore = 9.0\ncomment = "Literal value set, Final rebinding promise, runtime caveat"\n\n[[example_quality_scores]]\nslug = "callable-types"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "generics-and-typevar"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "paramspec"\nscore = 9.0\ncomment = "Callable erasure contrasted with ParamSpec-preserving decorator"\n\n[[example_quality_scores]]\nslug = "overloads"\nscore = 9.0\ncomment = "static overload stubs contrasted with one runtime implementation"\n\n[[example_quality_scores]]\nslug = "casts-and-any"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "newtype"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "protocols"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "abstract-base-classes"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "enums"\nscore = 9.0\ncomment = "closed symbolic choice set contrasted with raw strings"\n\n[[example_quality_scores]]\nslug = "regular-expressions"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich, note-heavy, multi-cell"\n\n[[example_quality_scores]]\nslug = "number-parsing"\nscore = 9.0\ncomment = "decimal, explicit base, and recoverable ValueError boundary"\n\n[[example_quality_scores]]\nslug = "custom-exceptions"\nscore = 9.0\ncomment = "domain error naming, raise point, recovery boundary"\n\n[[example_quality_scores]]\nslug = "files-and-pathlib"\nscore = 9.0\ncomment = "path vs file distinction, whole-file and line-by-line reading, directory listing, missing-file boundary; all cells run in the sandbox"\n\n[[example_quality_scores]]\nslug = "json"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "logging"\nscore = 9.0\ncomment = "logger, handler, formatter, and threshold boundaries"\n\n[[example_quality_scores]]\nslug = "testing"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n\n[[example_quality_scores]]\nslug = "subprocesses"\nscore = 9.0\ncomment = "standard subprocess contract plus explicit Worker boundary"\n\n[[example_quality_scores]]\nslug = "threads-and-processes"\nscore = 9.0\ncomment = "thread/process executor contrast plus explicit Worker boundary"\n\n[[example_quality_scores]]\nslug = "networking"\nscore = 9.0\ncomment = "protocol byte boundary plus explicit socket runtime caveat"\n\n[[example_quality_scores]]\nslug = "datetime"\nscore = 9.0\ncomment = "date/time/delta parsing with timezone scope made explicit"\n\n[[example_quality_scores]]\nslug = "csv-data"\nscore = 9.0\ncomment = "DictReader, conversion, and DictWriter row boundary"\n\n[[example_quality_scores]]\nslug = "async-await"\nscore = 9.0\ncomment = "graph-rich, note-heavy"\n\n[[example_quality_scores]]\nslug = "async-iteration-and-context"\nscore = 9.0\ncomment = "criterion-level pass: graph-rich"\n' diff --git a/src/example_loader.py b/src/example_loader.py index abf8cb6..15c2d06 100644 --- a/src/example_loader.py +++ b/src/example_loader.py @@ -167,6 +167,9 @@ def example_to_dict(filename: str, catalog: ExampleCatalog) -> dict[str, Any]: "min_python": frontmatter.get("min_python"), "version_sensitive": bool(frontmatter.get("version_sensitive", False)), "version_notes": frontmatter.get("version_notes"), + # Names what the in-browser sandbox lacks on pages that teach it + # anyway (child processes, threads, sockets); Run explains the limit. + "sandbox_limit": frontmatter.get("sandbox_limit"), } diff --git a/src/example_sources/advanced-match-patterns.md b/src/example_sources/advanced-match-patterns.md index c425ab2..3588dd9 100644 --- a/src/example_sources/advanced-match-patterns.md +++ b/src/example_sources/advanced-match-patterns.md @@ -19,21 +19,23 @@ The wildcard `_` catches everything not matched earlier. :::program ```python -def describe(command): +commands = [ + ["move", 2, 3], + ["exit"], + ["echo", "hello", "python"], + ["move", -1, 3], +] + +for command in commands: match command: case ["move", x, y] if x >= 0 and y >= 0: - return f"move to {x},{y}" + print(f"move to {x},{y}") case ["quit" | "exit"]: - return "stop" + print("stop") case ["echo", *words]: - return " ".join(words) + print(" ".join(words)) case _: - return "unknown" - -print(describe(["move", 2, 3])) -print(describe(["exit"])) -print(describe(["echo", "hello", "python"])) -print(describe(["move", -1, 3])) + print("unknown") ``` ::: @@ -41,18 +43,13 @@ print(describe(["move", -1, 3])) Sequence patterns match by position. A guard after `if` adds a condition that must also be true. ```python -def describe(command): - match command: - case ["move", x, y] if x >= 0 and y >= 0: - return f"move to {x},{y}" - case ["quit" | "exit"]: - return "stop" - case ["echo", *words]: - return " ".join(words) - case _: - return "unknown" +command = ["move", 2, 3] -print(describe(["move", 2, 3])) +match command: + case ["move", x, y] if x >= 0 and y >= 0: + print(f"move to {x},{y}") + case _: + print("unknown") ``` ```output @@ -64,8 +61,12 @@ move to 2,3 An OR pattern accepts several alternatives in one case. A star pattern captures the rest of a sequence. ```python -print(describe(["exit"])) -print(describe(["echo", "hello", "python"])) +for command in [["exit"], ["echo", "hello", "python"]]: + match command: + case ["quit" | "exit"]: + print("stop") + case ["echo", *words]: + print(" ".join(words)) ``` ```output @@ -75,10 +76,16 @@ hello python ::: :::cell -The wildcard `_` catches values that did not match earlier cases. Here the guard rejects the negative coordinate. +The wildcard `_` catches values that did not match earlier cases. Here the guard rejects the negative coordinate, so the same `match` that accepted `["move", 2, 3]` falls through to the fallback. ```python -print(describe(["move", -1, 3])) +command = ["move", -1, 3] + +match command: + case ["move", x, y] if x >= 0 and y >= 0: + print(f"move to {x},{y}") + case _: + print("unknown") ``` ```output diff --git a/src/example_sources/assignment-expressions.md b/src/example_sources/assignment-expressions.md index d97156a..460a34d 100644 --- a/src/example_sources/assignment-expressions.md +++ b/src/example_sources/assignment-expressions.md @@ -50,7 +50,7 @@ python 6 ::: :::cell -The same idea works in loops that read state until a sentinel appears. The assignment and comparison stay together. +The same idea works in [while loops](/examples/while-loops) that read state until a sentinel appears. The assignment and comparison stay together. ```python queue = ["retry", "ok"] diff --git a/src/example_sources/booleans.md b/src/example_sources/booleans.md index 785e23e..05780a5 100644 --- a/src/example_sources/booleans.md +++ b/src/example_sources/booleans.md @@ -33,11 +33,13 @@ print(isinstance(True, int)) print(True + True) print(sum([True, True, False, True])) -def is_strict_int(value): - return isinstance(value, int) and not isinstance(value, bool) +value = True +is_strict_int = isinstance(value, int) and not isinstance(value, bool) +print(is_strict_int) -print(is_strict_int(True)) -print(is_strict_int(1)) +value = 1 +is_strict_int = isinstance(value, int) and not isinstance(value, bool) +print(is_strict_int) ``` ::: @@ -76,18 +78,20 @@ True ::: :::cell -`bool` is a subclass of `int`, which is occasionally a footgun. `True` behaves as `1` and `False` as `0` in arithmetic, and `isinstance(True, int)` is `True`. When a function must reject booleans, exclude them explicitly with `isinstance(value, int) and not isinstance(value, bool)`. +`bool` is a subclass of `int`, which is occasionally a footgun. `True` behaves as `1` and `False` as `0` in arithmetic, and `isinstance(True, int)` is `True`. When a check must reject booleans, exclude them explicitly with `isinstance(value, int) and not isinstance(value, bool)`: the combined test is false for `True` and true for `1`. ```python print(isinstance(True, int)) print(True + True) print(sum([True, True, False, True])) -def is_strict_int(value): - return isinstance(value, int) and not isinstance(value, bool) +value = True +is_strict_int = isinstance(value, int) and not isinstance(value, bool) +print(is_strict_int) -print(is_strict_int(True)) -print(is_strict_int(1)) +value = 1 +is_strict_int = isinstance(value, int) and not isinstance(value, bool) +print(is_strict_int) ``` ```output diff --git a/src/example_sources/closures.md b/src/example_sources/closures.md index 9857794..e920575 100644 --- a/src/example_sources/closures.md +++ b/src/example_sources/closures.md @@ -75,7 +75,7 @@ print(triple(5)) ::: :::cell -Closures bind names, not values. Lambdas defined in a loop all reference the same loop variable, so calling them later sees its final value. Capture the value at definition time by binding it as a default argument — `lambda i=i: i` — so each closure remembers its own `i`. +Closures bind names, not values. [Lambdas](/examples/lambdas) (one-expression functions) defined in a loop all reference the same loop variable, so calling them later sees its final value. Capture the value at definition time by binding it as a default argument — `lambda i=i: i` — so each closure remembers its own `i`. ```python late = [] diff --git a/src/example_sources/constants.md b/src/example_sources/constants.md index f7ca3de..f44601c 100644 --- a/src/example_sources/constants.md +++ b/src/example_sources/constants.md @@ -24,8 +24,10 @@ from typing import Final MAX_RETRIES: Final = 3 API_VERSION = "2026-05" -for attempt in range(1, MAX_RETRIES + 1): - print(f"attempt {attempt} of {MAX_RETRIES}") +attempts = 2 +print(attempts < MAX_RETRIES) +attempts = 3 +print(attempts < MAX_RETRIES) print(API_VERSION) @@ -35,19 +37,20 @@ print(MAX_RETRIES) ::: :::cell -All-caps names communicate design intent: this value is configuration that callers should treat as fixed. +All-caps names communicate design intent: this value is configuration that callers should treat as fixed. Comparing against `MAX_RETRIES` instead of a bare `3` keeps the meaning beside the check, and gives the limit one place to change. ```python MAX_RETRIES = 3 -for attempt in range(1, MAX_RETRIES + 1): - print(f"attempt {attempt} of {MAX_RETRIES}") +attempts = 2 +print(attempts < MAX_RETRIES) +attempts = 3 +print(attempts < MAX_RETRIES) ``` ```output -attempt 1 of 3 -attempt 2 of 3 -attempt 3 of 3 +True +False ``` ::: diff --git a/src/example_sources/dataclasses.md b/src/example_sources/dataclasses.md index 9b53304..930c6d9 100644 --- a/src/example_sources/dataclasses.md +++ b/src/example_sources/dataclasses.md @@ -9,6 +9,8 @@ see_also = [ "classes", "type-hints", ] +min_python = "3.13" +version_notes = "copy.replace() was added in Python 3.13; dataclasses.replace() is the earlier equivalent." +++ `dataclass` is a standard-library decorator for classes that mainly store data. It generates methods such as `__init__` and `__repr__` from type-annotated fields. @@ -19,6 +21,7 @@ Type annotations define fields. Defaults work like normal class attributes and a :::program ```python +import copy from dataclasses import dataclass @dataclass @@ -33,6 +36,10 @@ print(user.name) inactive = User("Guido", active=False) print(inactive) print(inactive.active) + +paused = copy.replace(user, active=False) +print(paused) +print(user) ``` ::: @@ -83,8 +90,26 @@ False ``` ::: +:::cell +`copy.replace()` builds a new instance with some fields changed and leaves the original alone. It was added in Python 3.13 as the general form of `dataclasses.replace()`, and it also works on named tuples and dates. + +```python +import copy + +paused = copy.replace(user, active=False) +print(paused) +print(user) +``` + +```output +User(name='Ada', active=False) +User(name='Ada', active=True) +``` +::: + :::note - Type annotations define dataclass fields. +- `copy.replace(obj, field=value)` copies with changes; before Python 3.13, use `dataclasses.replace()`. - Dataclasses generate methods but remain normal Python classes. - Use `field()` for advanced defaults such as per-instance lists or dictionaries. ::: diff --git a/src/example_sources/files-and-pathlib.md b/src/example_sources/files-and-pathlib.md new file mode 100644 index 0000000..a862e00 --- /dev/null +++ b/src/example_sources/files-and-pathlib.md @@ -0,0 +1,165 @@ ++++ +slug = "files-and-pathlib" +title = "Files and pathlib" +section = "Standard Library" +summary = "pathlib names files and directories, and open() reads and writes their text." +doc_path = "/library/pathlib.html" +see_also = [ + "context-managers", + "exceptions", + "csv-data", + "json", +] ++++ + +A `Path` object names a place in the file system. It does not open anything by itself: it knows how to join names with `/`, take a path apart, and ask the file system questions such as whether the file exists. + +Reading and writing are separate steps. `Path.read_text()` and `Path.write_text()` handle a whole small file in one call, while `open()` gives a file object that a `with` block closes for you and that you can loop over line by line. + +This page works inside a temporary directory so it leaves nothing behind. Real programs use the same calls on paths they were given, and should always name the text encoding rather than rely on the platform default. + +:::program +```python +import shutil +import tempfile +from pathlib import Path + +root = Path(tempfile.mkdtemp()) +notes = root / "notes.txt" +print(notes.name) +print(notes.suffix) +print(notes.exists()) + +notes.write_text("first line\nsecond line\n", encoding="utf-8") +print(notes.exists()) +text = notes.read_text(encoding="utf-8") +print(text.splitlines()) + +with open(notes, "a", encoding="utf-8") as handle: + handle.write("third line\n") + +with open(notes, encoding="utf-8") as handle: + for number, line in enumerate(handle, start=1): + print(number, line.rstrip()) + +reports = root / "reports" +reports.mkdir() +(reports / "summary.csv").write_text("total\n3\n", encoding="utf-8") +print(sorted(path.name for path in root.iterdir())) +print([path.relative_to(root).as_posix() for path in root.rglob("*.csv")]) +print(reports.is_dir()) + +missing = root / "missing.txt" +try: + missing.read_text(encoding="utf-8") +except FileNotFoundError as error: + print(type(error).__name__) + +shutil.rmtree(root) +print(root.exists()) +``` +::: + +:::cell +The `/` operator joins a directory path and a name into a new `Path`. Building a path touches nothing on disk, so `notes` can be taken apart with `.name` and `.suffix` before any file exists. + +```python +import shutil +import tempfile +from pathlib import Path + +root = Path(tempfile.mkdtemp()) +notes = root / "notes.txt" +print(notes.name) +print(notes.suffix) +print(notes.exists()) +``` + +```output +notes.txt +.txt +False +``` +::: + +:::cell +`write_text()` creates the file, writes the string, and closes it. `read_text()` returns the whole file as one string, which suits small files. Passing `encoding="utf-8"` makes the bytes on disk the same on every machine. + +```python +notes.write_text("first line\nsecond line\n", encoding="utf-8") +print(notes.exists()) +text = notes.read_text(encoding="utf-8") +print(text.splitlines()) +``` + +```output +True +['first line', 'second line'] +``` +::: + +:::cell +`open()` returns a file object, and the `with` block closes it even if the body raises. Mode `"a"` appends instead of replacing. A file opened for reading is an iterator of lines, each still ending in its newline, so large files can be processed without loading them whole. + +```python +with open(notes, "a", encoding="utf-8") as handle: + handle.write("third line\n") + +with open(notes, encoding="utf-8") as handle: + for number, line in enumerate(handle, start=1): + print(number, line.rstrip()) +``` + +```output +1 first line +2 second line +3 third line +``` +::: + +:::cell +Directories are paths too. `mkdir()` creates one, `iterdir()` lists the entries directly inside a directory, and `rglob()` searches every level below it for names matching a pattern. Listing order is up to the file system, so sort when the order matters. + +```python +reports = root / "reports" +reports.mkdir() +(reports / "summary.csv").write_text("total\n3\n", encoding="utf-8") +print(sorted(path.name for path in root.iterdir())) +print([path.relative_to(root).as_posix() for path in root.rglob("*.csv")]) +print(reports.is_dir()) +``` + +```output +['notes.txt', 'reports'] +['reports/summary.csv'] +True +``` +::: + +:::cell +Opening a file that is not there raises `FileNotFoundError`. Catching it is usually better than checking `exists()` first, because the file can appear or vanish between the check and the read. `shutil.rmtree()` removes the temporary directory and everything in it. + +```python +missing = root / "missing.txt" +try: + missing.read_text(encoding="utf-8") +except FileNotFoundError as error: + print(type(error).__name__) + +shutil.rmtree(root) +print(root.exists()) +``` + +```output +FileNotFoundError +False +``` +::: + +:::note +- A `Path` is a name for a place; building one with `/` does not create or open a file. +- Pass `encoding="utf-8"` to `open()`, `read_text()`, and `write_text()` so text means the same bytes everywhere. +- Use `with open(...)` so the file is closed when the block ends, and loop over the file object to read line by line. +- `iterdir()` lists one directory and `rglob()` searches below it; sort the results when order matters. +- Catch `FileNotFoundError` at the read instead of trusting an earlier `exists()` check. +::: diff --git a/src/example_sources/generators.md b/src/example_sources/generators.md index bc2f2ab..4e8b915 100644 --- a/src/example_sources/generators.md +++ b/src/example_sources/generators.md @@ -128,7 +128,7 @@ print(list(stream)) ::: :::cell -Every generator is an iterator. The same countdown written by hand needs `__iter__` and `__next__` and an explicit `StopIteration`. The generator function expresses the same protocol with one `yield`. +Every generator is an iterator. The same countdown written by hand is a [class](/examples/classes) that needs `__iter__` and `__next__` and an explicit `StopIteration`. The generator function expresses the same protocol with one `yield`. ```python class Countdown: diff --git a/src/example_sources/generics-and-typevar.md b/src/example_sources/generics-and-typevar.md index 0420311..7a5025f 100644 --- a/src/example_sources/generics-and-typevar.md +++ b/src/example_sources/generics-and-typevar.md @@ -9,45 +9,65 @@ see_also = [ "collections-module", "casts-and-any", ] +min_python = "3.13" +version_notes = "Type parameter syntax needs Python 3.12; type parameter defaults and __default__ need Python 3.13." +++ Generics connect types across an API. A plain function that returns `object` loses information; a generic function can say that the returned value has the same type as the input element. -A `TypeVar` stands for a type chosen by the caller. In `list[T] -> T`, the same `T` says that a list of strings produces a string and a list of integers produces an integer. +A type parameter stands for a type chosen by the caller. In `def first[T](items: list[T]) -> T`, the brackets after the function name declare `T`, and the same `T` says that a list of strings produces a string and a list of integers produces an integer. -Use generics when a function or class is reusable but still preserves a relationship between input and output types. +Use generics when a function or class is reusable but still preserves a relationship between input and output types. Older code declares the same variable with `typing.TypeVar`; both spellings mean the same thing to a type checker. :::program ```python from typing import TypeVar -T = TypeVar("T") - -def first(items: list[T]) -> T: +def first[T](items: list[T]) -> T: return items[0] -def pair(left: T, right: T) -> tuple[T, T]: +def pair[T](left: T, right: T) -> tuple[T, T]: return (left, right) + +class Box[T]: + def __init__(self, item: T) -> None: + self.item = item + + def get(self) -> T: + return self.item + + +class Setting[T = str]: + def __init__(self, value: T) -> None: + self.value = value + + +Item = TypeVar("Item") + + +def last(items: list[Item]) -> Item: + return items[-1] + print(first([1, 2, 3])) print(first(["Ada", "Grace"])) print(pair("x", "y")) -print(T.__name__) +print(Box(3).get()) +print(Box.__type_params__) +print(Setting.__type_params__[0].__default__) +print(last([1, 2, 3])) +print(first.__annotations__) +print(last.__annotations__) ``` ::: :::cell -A `TypeVar` stands for a type chosen by the caller. The return type follows the list element type. +Square brackets after the function name declare a type parameter. `T` stands for a type chosen by the caller, so the return type follows the list element type. ```python -from typing import TypeVar - -T = TypeVar("T") - - -def first(items: list[T]) -> T: +def first[T](items: list[T]) -> T: return items[0] print(first([1, 2, 3])) @@ -61,10 +81,10 @@ Ada ::: :::cell -Reusing the same `TypeVar` expresses a relationship between parameters and results. +Reusing the same type parameter expresses a relationship between parameters and results. Each function declares its own `T`; the name is scoped to that definition. ```python -def pair(left: T, right: T) -> tuple[T, T]: +def pair[T](left: T, right: T) -> tuple[T, T]: return (left, right) print(pair("x", "y")) @@ -76,22 +96,70 @@ print(pair("x", "y")) ::: :::cell -`TypeVar` is visible at runtime, but the relationship is mainly for type checkers. +A class takes type parameters the same way. `Box[T]` says that whatever type goes in through `__init__` is the type that `get()` hands back. The parameters are recorded on the class, but nothing checks them at runtime. ```python -print(T.__name__) +class Box[T]: + def __init__(self, item: T) -> None: + self.item = item + + def get(self) -> T: + return self.item + +print(Box(3).get()) +print(Box.__type_params__) +``` + +```output +3 +(T,) +``` +::: + +:::cell +Python 3.13 lets a type parameter name a default. A type checker reads a bare `Setting` as `Setting[str]`, while `Setting[int]` still overrides it. The default is stored on the parameter object. + +```python +class Setting[T = str]: + def __init__(self, value: T) -> None: + self.value = value + +print(Setting.__type_params__[0].__default__) +``` + +```output + +``` +::: + +:::cell +Before Python 3.12 the variable had to be created separately with `TypeVar` and then used by name. This legacy spelling still works and is common in existing code; the annotations show it as `~Item` rather than a scoped `T`. + +```python +from typing import TypeVar + +Item = TypeVar("Item") + + +def last(items: list[Item]) -> Item: + return items[-1] + +print(last([1, 2, 3])) print(first.__annotations__) +print(last.__annotations__) ``` ```output -T -{'items': list[~T], 'return': ~T} +3 +{'items': list[T], 'return': T} +{'items': list[~Item], 'return': ~Item} ``` ::: :::note -- A `TypeVar` stands for a type chosen by the caller. -- Python 3.12+ also accepts the inline PEP 695 spelling `def first[T](items: list[T]) -> T`, which declares the variable without a separate `TypeVar` line; the explicit form shown here works everywhere and reads the same way. +- `def first[T](...)` and `class Box[T]` declare type parameters inline; this syntax needs Python 3.12 or later. +- `[T = str]` gives a type parameter a default; that needs Python 3.13. +- `T = TypeVar("T")` is the legacy spelling of the same idea and is still what older codebases use. - Generic functions avoid losing information to `object` or `Any`. - Use generics when input and output types are connected. ::: diff --git a/src/example_sources/iterator-vs-iterable.md b/src/example_sources/iterator-vs-iterable.md index 66aed45..d224351 100644 --- a/src/example_sources/iterator-vs-iterable.md +++ b/src/example_sources/iterator-vs-iterable.md @@ -13,7 +13,7 @@ see_also = [ An iterable can produce values when asked. An iterator is the object that remembers where the production currently is. The distinction matters because iterables can be traversed many times, while many iterators can be traversed only once. -`iter(iterable)` returns a fresh iterator each call. `iter(iterator)` returns the iterator itself. That self-iteration property is how `for` loops can accept either kind, and it is also why a function that loops over its argument twice silently breaks when called with a generator instead of a list. +`iter(iterable)` returns a fresh iterator each call. `iter(iterator)` returns the iterator itself. That self-iteration property is how `for` loops can accept either kind, and it is also why code that loops over its input twice silently breaks when handed an iterator instead of a list. The takeaway for API design: receive iterables when the caller may want a second pass, and materialize once at the boundary if you must. @@ -33,22 +33,14 @@ second = iter(names) print(first is second) print(iter(first) is first) -def total_and_count(numbers): - total = sum(numbers) - count = sum(1 for _ in numbers) - return total, count +numbers = [10, 9, 8] +print(sum(numbers), len(list(numbers))) -def values(): - yield from [10, 9, 8] +stream = iter([10, 9, 8]) +print(sum(stream), len(list(stream))) -print(total_and_count([10, 9, 8])) -print(total_and_count(values())) - -def total_and_count_safe(numbers): - items = list(numbers) - return sum(items), len(items) - -print(total_and_count_safe(values())) +items = list(iter([10, 9, 8])) +print(sum(items), len(items)) ``` ::: @@ -99,36 +91,28 @@ True ::: :::cell -The distinction shows up at API boundaries. A function that loops over its argument twice works for an iterable but silently produces wrong answers for an iterator, because the second pass finds the iterator already exhausted. Materialize once at the boundary when both passes matter. +The distinction shows up whenever code makes two passes over the same input. Summing and then counting works for an iterable, but silently produces a wrong answer for an iterator, because the second pass finds the iterator already exhausted. Materialize once with `list()` when both passes matter. ```python -def total_and_count(numbers): - total = sum(numbers) - count = sum(1 for _ in numbers) - return total, count - -def values(): - yield from [10, 9, 8] - -print(total_and_count([10, 9, 8])) -print(total_and_count(values())) +numbers = [10, 9, 8] +print(sum(numbers), len(list(numbers))) -def total_and_count_safe(numbers): - items = list(numbers) - return sum(items), len(items) +stream = iter([10, 9, 8]) +print(sum(stream), len(list(stream))) -print(total_and_count_safe(values())) +items = list(iter([10, 9, 8])) +print(sum(items), len(items)) ``` ```output -(27, 3) -(27, 0) -(27, 3) +27 3 +27 0 +27 3 ``` ::: :::note - An iterable produces an iterator each time `iter()` is called on it; an iterator produces values until it is exhausted. - `iter(iterable)` returns a fresh iterator; `iter(iterator)` returns the same iterator. -- Functions that traverse their input more than once must accept an iterable or materialize the input at the boundary. +- Code that traverses its input more than once must receive an iterable or materialize the input first; this matters most for [functions](/examples/functions) that cannot know what callers will pass. ::: diff --git a/src/example_sources/manifest.toml b/src/example_sources/manifest.toml index ea03446..c33abc6 100644 --- a/src/example_sources/manifest.toml +++ b/src/example_sources/manifest.toml @@ -19,18 +19,17 @@ order = [ "bytes-and-bytearray", "string-formatting", "conditionals", - "guard-clauses", - "assignment-expressions", "for-loops", "break-and-continue", "loop-else", "iterating-over-iterables", "iterators", "iterator-vs-iterable", - "sentinel-iteration", "match-statements", "advanced-match-patterns", "while-loops", + "assignment-expressions", + "sentinel-iteration", "lists", "tuples", "unpacking", @@ -43,6 +42,8 @@ order = [ "collections-module", "copying-collections", "functions", + "guard-clauses", + "exceptions", "keyword-only-arguments", "positional-only-parameters", "args-and-kwargs", @@ -73,7 +74,6 @@ order = [ "metaclasses", "context-managers", "delete-statements", - "exceptions", "assertions", "exception-chaining", "exception-groups", @@ -101,6 +101,7 @@ order = [ "regular-expressions", "number-parsing", "custom-exceptions", + "files-and-pathlib", "json", "logging", "testing", diff --git a/src/example_sources/networking.md b/src/example_sources/networking.md index a361d29..564e452 100644 --- a/src/example_sources/networking.md +++ b/src/example_sources/networking.md @@ -10,6 +10,7 @@ see_also = [ "async-await", ] expected_output = "b'ping'\nping\n" +sandbox_limit = "sockets" +++ Networking code sends and receives bytes across protocol boundaries. Higher-level HTTP clients hide many details, but the core rule remains: text is encoded before it leaves the process and decoded after bytes come back. diff --git a/src/example_sources/none.md b/src/example_sources/none.md index b46c505..d75ac96 100644 --- a/src/example_sources/none.md +++ b/src/example_sources/none.md @@ -12,32 +12,26 @@ see_also = [ ] +++ -`None` represents the absence of a value. It is the usual sentinel when a function has no result to return but the absence itself is meaningful. +`None` represents the absence of a value. It is the usual result when a call has nothing to hand back but the absence itself is meaningful. Because `None` is a singleton, idiomatic Python checks it with `is None` or `is not None`. This avoids confusing identity with value equality. -Absence has several nearby shapes in Python. A function can return `None`, a dictionary lookup can supply a default for a missing key, and an invalid operation can raise an exception. +Absence has several nearby shapes in Python. A call can return `None`, a dictionary lookup can supply a default for a missing key, and an invalid operation can raise an exception instead of returning anything. :::program ```python result = None print(result is None) -def find_score(name): - if name == "Ada": - return 10 - return None - -score = find_score("Grace") -print(score is None) +names = ["Grace", "Ada"] +result = names.sort() +print(result is None) +print(names) profile = {"name": "Ada"} +timezone = profile.get("timezone") +print(timezone is None) print(profile.get("timezone", "UTC")) - -try: - int("python") -except ValueError: - print("invalid number") ``` ::: @@ -55,44 +49,40 @@ True ::: :::cell -Functions often return `None` when absence is expected and callers can continue. The function name and surrounding code should make that possibility clear. +A call that does its work without producing a result returns `None`. `list.sort()` reorders the list in place, so the value it hands back is `None` and the sorted data is in `names`. Assigning that result to a name is a common slip; the same rule applies to every [function](/examples/functions) that finishes without a `return` value. ```python -def find_score(name): - if name == "Ada": - return 10 - return None - -score = find_score("Grace") -print(score is None) +names = ["Grace", "Ada"] +result = names.sort() +print(result is None) +print(names) ``` ```output True +['Ada', 'Grace'] ``` ::: :::cell -A missing dictionary key is another absence boundary. Use `get()` when the mapping can supply a default, and use exceptions for invalid operations that cannot produce a value. +A missing dictionary key is another absence boundary. `get()` returns `None` when the key is missing, or a default when the mapping can supply one. Indexing with `profile["timezone"]` would not return `None`: it raises `KeyError`, because Python reports invalid operations with [exceptions](/examples/exceptions) rather than with a value. ```python profile = {"name": "Ada"} +timezone = profile.get("timezone") +print(timezone is None) print(profile.get("timezone", "UTC")) - -try: - int("python") -except ValueError: - print("invalid number") ``` ```output +True UTC -invalid number ``` ::: :::note - Use `is None` rather than `== None`; `None` is a singleton identity value. - Use `None` for expected absence that callers can test. +- Calls that only change something in place, such as `list.sort()`, return `None`. - Use dictionary defaults for missing mapping keys and exceptions for invalid operations. ::: diff --git a/src/example_sources/object-lifecycle.md b/src/example_sources/object-lifecycle.md index 3587055..5884df3 100644 --- a/src/example_sources/object-lifecycle.md +++ b/src/example_sources/object-lifecycle.md @@ -15,23 +15,19 @@ Python objects live independently from the names that refer to them. Assignment Most programs do not manually destroy objects. They control lifetime by controlling which containers, local variables, and object attributes still hold references. -This example uses a small class so the object has visible state. The important evidence is that deleting one name does not destroy the object while another name still refers to it. +This example uses a one-item list so the object has visible state. The important evidence is that rebinding or deleting one name does not destroy the object while another name still refers to it. :::program ```python -class Box: - def __init__(self, label): - self.label = label - -box = Box("draft") +box = ["draft"] alias = box print(box is alias) -print(alias.label) +print(alias) -box = Box("published") -print(alias.label) -print(box.label) +box = ["published"] +print(alias) +print(box) del alias print("old object unreachable") @@ -42,38 +38,34 @@ print("old object unreachable") Two names can refer to the same object. Mutating through one name would affect the object seen through the other. ```python -class Box: - def __init__(self, label): - self.label = label - -box = Box("draft") +box = ["draft"] alias = box print(box is alias) -print(alias.label) +print(alias) ``` ```output True -draft +['draft'] ``` ::: :::cell -Rebinding `box` does not change the original object. `alias` still reaches the first `Box` until that reference is removed too. +Rebinding `box` does not change the original object. `alias` still reaches the first list until that reference is removed too. ```python -box = Box("published") -print(alias.label) -print(box.label) +box = ["published"] +print(alias) +print(box) del alias print("old object unreachable") ``` ```output -draft -published +['draft'] +['published'] old object unreachable ``` ::: diff --git a/src/example_sources/operator-overloading.md b/src/example_sources/operator-overloading.md index 80b74c0..c077721 100644 --- a/src/example_sources/operator-overloading.md +++ b/src/example_sources/operator-overloading.md @@ -34,12 +34,18 @@ class Vector: return NotImplemented return (self.x, self.y) == (other.x, other.y) + def __matmul__(self, other): + if not isinstance(other, Vector): + return NotImplemented + return self.x * other.x + self.y * other.y + def __repr__(self): return f"Vector({self.x}, {self.y})" print(Vector(2, 3) + Vector(4, 5)) print(Vector(1, 1) == Vector(1, 1)) print(Vector(1, 1) == 5) +print(Vector(2, 3) @ Vector(4, 5)) ``` ::: @@ -92,6 +98,28 @@ False ``` ::: +:::cell +`__matmul__` defines the `@` operator, which Python reserves for matrix-style multiplication. No built-in type implements it, so it only works on classes that opt in — here as the dot product of two vectors. + +```python +class Vector: + def __init__(self, x, y): + self.x = x + self.y = y + + def __matmul__(self, other): + if not isinstance(other, Vector): + return NotImplemented + return self.x * other.x + self.y * other.y + +print(Vector(2, 3) @ Vector(4, 5)) +``` + +```output +23 +``` +::: + :::cell A useful `__repr__` makes operator results inspectable while debugging. diff --git a/src/example_sources/operators.md b/src/example_sources/operators.md index cf9d9f1..dc7d7fe 100644 --- a/src/example_sources/operators.md +++ b/src/example_sources/operators.md @@ -37,26 +37,14 @@ print(flags | 0b0100) print(flags ^ 0b0101) print(flags << 1) -class Scale: - def __init__(self, value): - self.value = value - - def __matmul__(self, other): - return self.value * other.value - -print(Scale(2) @ Scale(3)) - items = ["a", "b"] -if (size := len(items)) > 0: - print(size) +print((size := len(items)) > 0) +print(size) -def loud(): - print("ran") - return True - -print(False and loud()) -print(True or loud()) -print(True and loud()) +count = 0 +print(count != 0 and 10 / count) +print(count == 0 or 10 / count) +print(count == 0 and "empty") ``` ::: @@ -116,56 +104,34 @@ print(flags << 1) ::: :::cell -The `@` operator is reserved for matrix-like multiplication and custom types that define `__matmul__`. - -```python -class Scale: - def __init__(self, value): - self.value = value - - def __matmul__(self, other): - return self.value * other.value - -print(Scale(2) @ Scale(3)) -``` - -```output -6 -``` -::: - -:::cell -The walrus operator `:=` assigns inside an expression. Use it when naming a value avoids repeating work in a condition. +The walrus operator `:=` assigns inside an expression: the parenthesized part both names the length and passes it on to the comparison. [Assignment expressions](/examples/assignment-expressions) shows where that earns its place. ```python items = ["a", "b"] -if (size := len(items)) > 0: - print(size) +print((size := len(items)) > 0) +print(size) ``` ```output +True 2 ``` ::: :::cell -`and` and `or` short-circuit: the right side runs only when the left side cannot already determine the result. That makes them safe for guard expressions like `obj and obj.value` where the right side would fail on `None`. +`and` and `or` short-circuit: the right side runs only when the left side cannot already determine the result. Here `10 / count` would fail with a division-by-zero error if it ran, but the left side settles both answers first. The result is the last operand evaluated, so `count == 0 and "empty"` produces `"empty"`. ```python -def loud(): - print("ran") - return True - -print(False and loud()) -print(True or loud()) -print(True and loud()) +count = 0 +print(count != 0 and 10 / count) +print(count == 0 or 10 / count) +print(count == 0 and "empty") ``` ```output False True -ran -True +empty ``` ::: @@ -173,5 +139,5 @@ True - Use the clearest operator for the question: arithmetic, comparison, boolean logic, membership, identity, or bitwise manipulation. - `and` and `or` short-circuit, so the right side may not run. - Operators have precedence; use parentheses when grouping would otherwise be hard to read. -- Custom operator behavior should make an object feel more natural, not more clever. +- `@` is the matrix-multiplication operator. No built-in type implements it; [operator overloading](/examples/operator-overloading) shows how a class gives `@`, `+`, or `==` its own meaning. ::: diff --git a/src/example_sources/sentinel-iteration.md b/src/example_sources/sentinel-iteration.md index 3680024..53dbfdc 100644 --- a/src/example_sources/sentinel-iteration.md +++ b/src/example_sources/sentinel-iteration.md @@ -15,22 +15,20 @@ see_also = [ This shape is useful for repeated reads: file blocks until `b""`, socket chunks until an empty response, queue items until a stop marker. It removes the common `while True` plus `break` scaffolding when the loop body is otherwise just "read, then process". -The callable must take no arguments. Wrap a parameterized reader in a `lambda`, `functools.partial`, or object method when the underlying API needs parameters. +The callable must take no arguments. A method taken from an object, such as `queue.popleft`, already fits. Wrap a parameterized reader in a `lambda` or `functools.partial` when the underlying API needs parameters. :::program ```python -chunks = iter(["py", "thon", ""]) +from collections import deque +queue = deque(["py", "thon", "", "ignored"]) +print(list(iter(queue.popleft, ""))) +print(queue) -def read_chunk(): - return next(chunks) - -print(list(iter(read_chunk, ""))) - -chunks = iter(["py", "thon", ""]) +queue = deque(["py", "thon", "", "ignored"]) word = "" while True: - chunk = next(chunks) + chunk = queue.popleft() if chunk == "": break word += chunk @@ -39,20 +37,19 @@ print(word) ::: :::cell -The two-argument form turns a polling callable into an iterator. The empty string stops the loop without appearing in the result. +The two-argument form turns a polling callable into an iterator. `queue.popleft` (no parentheses) is a zero-argument callable that removes and returns the next queued item each time it is called. The empty string stops the loop without appearing in the result, and anything queued after the sentinel is left unread. ```python -chunks = iter(["py", "thon", ""]) - - -def read_chunk(): - return next(chunks) +from collections import deque -print(list(iter(read_chunk, ""))) +queue = deque(["py", "thon", "", "ignored"]) +print(list(iter(queue.popleft, ""))) +print(queue) ``` ```output ['py', 'thon'] +deque(['ignored']) ``` ::: @@ -60,10 +57,10 @@ print(list(iter(read_chunk, ""))) The equivalent manual loop needs an explicit read, comparison, and `break`. Use this shape when the stop condition is more complicated than a single sentinel value. ```python -chunks = iter(["py", "thon", ""]) +queue = deque(["py", "thon", "", "ignored"]) word = "" while True: - chunk = next(chunks) + chunk = queue.popleft() if chunk == "": break word += chunk diff --git a/src/example_sources/sorting.md b/src/example_sources/sorting.md index ab2fa7e..b1d387a 100644 --- a/src/example_sources/sorting.md +++ b/src/example_sources/sorting.md @@ -52,7 +52,7 @@ print(names) ::: :::cell -A key function computes the value to compare. Here the records are sorted by score, highest first, and the output shows the resulting order. +A key function computes the value to compare. The `lambda user: user["score"]` expression is a small unnamed function that takes one record and returns its score ([lambdas](/examples/lambdas) covers the form). Here the records are sorted by score, highest first, and the output shows the resulting order. ```python users = [ diff --git a/src/example_sources/strings.md b/src/example_sources/strings.md index 69017d1..ca17e96 100644 --- a/src/example_sources/strings.md +++ b/src/example_sources/strings.md @@ -24,11 +24,12 @@ english = "hello" french = "café" thai = "สวัสดี" -for label, word in [("English", english), ("French", french), ("Thai", thai)]: - print(label, word, len(word), len(word.encode("utf-8"))) +print("English", english, len(english), len(english.encode("utf-8"))) +print("French", french, len(french), len(french.encode("utf-8"))) +print("Thai", thai, len(thai), len(thai.encode("utf-8"))) print(thai[0]) -print([hex(ord(char)) for char in thai[:2]]) +print(hex(ord(thai[0])), hex(ord(thai[1]))) text = " café " clean = text.strip() @@ -46,8 +47,9 @@ english = "hello" french = "café" thai = "สวัสดี" -for label, word in [("English", english), ("French", french), ("Thai", thai)]: - print(label, word, len(word), len(word.encode("utf-8"))) +print("English", english, len(english), len(english.encode("utf-8"))) +print("French", french, len(french), len(french.encode("utf-8"))) +print("Thai", thai, len(thai), len(thai.encode("utf-8"))) ``` ```output @@ -58,16 +60,16 @@ Thai สวัสดี 6 18 ::: :::cell -Indexing and iteration work with Unicode code points, not encoded bytes. `ord()` returns the integer code point, which is often displayed in hexadecimal when teaching text encoding. +Indexing works with Unicode code points, not encoded bytes: `thai[0]` is the first character, not its first byte. `ord()` returns the integer code point, which is often displayed in hexadecimal when teaching text encoding. ```python print(thai[0]) -print([hex(ord(char)) for char in thai[:2]]) +print(hex(ord(thai[0])), hex(ord(thai[1]))) ``` ```output ส -['0xe2a', '0xe27'] +0xe2a 0xe27 ``` ::: diff --git a/src/example_sources/subprocesses.md b/src/example_sources/subprocesses.md index 202ddb3..23511d0 100644 --- a/src/example_sources/subprocesses.md +++ b/src/example_sources/subprocesses.md @@ -10,6 +10,7 @@ see_also = [ "threads-and-processes", ] expected_output = "child process\n0\n" +sandbox_limit = "child processes" +++ `subprocess` is the standard boundary for running external commands. It starts another program, waits for it, and gives you a result object with the exit code and captured output. diff --git a/src/example_sources/threads-and-processes.md b/src/example_sources/threads-and-processes.md index e008c80..4432732 100644 --- a/src/example_sources/threads-and-processes.md +++ b/src/example_sources/threads-and-processes.md @@ -10,6 +10,7 @@ see_also = [ "networking", ] expected_output = "[1, 4, 9]\nProcessPoolExecutor\n" +sandbox_limit = "threads and processes" +++ Threads and processes are two ways to run work outside the current control path. Threads are useful for overlapping I/O-shaped waits, while processes are useful when CPU-bound work needs separate interpreter processes. diff --git a/src/example_sources/typed-dicts.md b/src/example_sources/typed-dicts.md index 8f59c9b..b1f483c 100644 --- a/src/example_sources/typed-dicts.md +++ b/src/example_sources/typed-dicts.md @@ -10,6 +10,8 @@ see_also = [ "dataclasses", "structured-data-shapes", ] +min_python = "3.13" +version_notes = "typing.ReadOnly and __readonly_keys__ were added in Python 3.13." +++ `TypedDict` describes dictionary records with known keys. It is useful for JSON-like data that should remain a dictionary instead of becoming a class instance. @@ -20,7 +22,7 @@ Use `TypedDict` for external records and `dataclass` when your own program wants :::program ```python -from typing import NotRequired, TypedDict +from typing import NotRequired, ReadOnly, TypedDict class User(TypedDict): name: str @@ -28,6 +30,11 @@ class User(TypedDict): nickname: NotRequired[str] +class Account(TypedDict): + id: ReadOnly[int] + name: str + + def describe(user: User) -> str: return f"{user['name']}: {user['score']}" @@ -35,6 +42,11 @@ record: User = {"name": "Ada", "score": 98} print(describe(record)) print(isinstance(record, dict)) print(record.get("nickname", "none")) + +account: Account = {"id": 7, "name": "Ada"} +account["name"] = "Grace" +print(account) +print(sorted(Account.__readonly_keys__)) ``` ::: @@ -95,8 +107,31 @@ none ``` ::: +:::cell +`ReadOnly`, added in Python 3.13, marks a key that type checkers should not allow code to reassign. Here a checker accepts the update to `name` and would reject `account["id"] = 8`. It is the same static-only boundary: the class records which keys are read-only, but the dictionary itself would still accept the write. + +```python +from typing import ReadOnly + +class Account(TypedDict): + id: ReadOnly[int] + name: str + +account: Account = {"id": 7, "name": "Ada"} +account["name"] = "Grace" +print(account) +print(sorted(Account.__readonly_keys__)) +``` + +```output +{'id': 7, 'name': 'Grace'} +['id'] +``` +::: + :::note - Use `TypedDict` for dictionary records from JSON or APIs. +- `ReadOnly[...]` (Python 3.13) tells type checkers a key must not be reassigned; it does not freeze the dictionary. - Type checkers understand required and optional keys. - Runtime behavior is still ordinary dictionary behavior. ::: diff --git a/src/example_sources/unpacking.md b/src/example_sources/unpacking.md index 58b4b62..7495528 100644 --- a/src/example_sources/unpacking.md +++ b/src/example_sources/unpacking.md @@ -16,7 +16,7 @@ Unpacking binds multiple names from one iterable or mapping. It makes the struct Starred unpacking handles variable-length sequences by collecting the middle or remaining values. This keeps common head-tail patterns readable. -Dictionary unpacking with ** connects structured data to function calls. It is widely used in configuration, adapters, and code that bridges APIs. +In a call, `*` spreads a sequence into positional arguments and `**` spreads a dictionary into keyword arguments, connecting structured data to function calls. It is widely used in configuration, adapters, and code that bridges APIs. :::program ```python @@ -27,11 +27,11 @@ print(x, y) first, *middle, last = [1, 2, 3, 4] print(first, middle, last) -def describe(name, language): - print(name, language) +print(*point) +print(*point, sep=", ") data = {"name": "Ada", "language": "Python"} -describe(**data) +print("{name} writes {language}".format(**data)) ``` ::: @@ -63,18 +63,20 @@ print(first, middle, last) ::: :::cell -`describe(**data)` spreads the dictionary's keys as keyword arguments, so the call site never repeats `name=` and `language=` by hand. This is the bridge between dict-shaped data (configuration, parsed JSON) and function signatures. +The same stars work in a call. `print(*point)` spreads the tuple into separate positional arguments, and `format(**data)` spreads the dictionary's keys as keyword arguments, so the call site never repeats `name=` and `language=` by hand. This is the bridge between collection-shaped data (configuration, parsed JSON) and call signatures; [args and kwargs](/examples/args-and-kwargs) shows the receiving side. ```python -def describe(name, language): - print(name, language) +print(*point) +print(*point, sep=", ") data = {"name": "Ada", "language": "Python"} -describe(**data) +print("{name} writes {language}".format(**data)) ``` ```output -Ada Python +3 4 +3, 4 +Ada writes Python ``` ::: diff --git a/src/example_sources/virtual-environments.md b/src/example_sources/virtual-environments.md index bb181a5..dd91e43 100644 --- a/src/example_sources/virtual-environments.md +++ b/src/example_sources/virtual-environments.md @@ -10,6 +10,7 @@ see_also = [ "import-aliases", ] expected_output = ".venv\nTrue\n" +sandbox_limit = "the venv module" +++ Virtual environments isolate a project's installed packages from the global Python installation and from other projects. The usual workflow is a command-line one: create `.venv`, activate it, then install project dependencies there. diff --git a/src/example_sources/warnings.md b/src/example_sources/warnings.md index 9c2aefd..d1a0820 100644 --- a/src/example_sources/warnings.md +++ b/src/example_sources/warnings.md @@ -9,6 +9,8 @@ see_also = [ "logging", "testing", ] +min_python = "3.13" +version_notes = "The warnings.deprecated decorator was added in Python 3.13." +++ A warning reports a problem that callers should know about, but it does not have to stop the current operation. Deprecations are the classic case: the old API can still return a value while telling users to migrate. @@ -38,6 +40,17 @@ with warnings.catch_warnings(): old_name() except DeprecationWarning: print("warning became error") + + +@warnings.deprecated("use new_name() instead") +def older_name(): + return "result" + +with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", DeprecationWarning) + print(older_name()) + print(str(caught[0].message)) +print(older_name.__deprecated__) ``` ::: @@ -83,8 +96,31 @@ warning became error ``` ::: +:::cell +Python 3.13 adds the `@warnings.deprecated` decorator, which states the deprecation once at the definition. Calling the function emits a `DeprecationWarning` aimed at the caller, the message is kept on `__deprecated__`, and type checkers flag uses of the function before the program runs. + +```python +@warnings.deprecated("use new_name() instead") +def older_name(): + return "result" + +with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", DeprecationWarning) + print(older_name()) + print(str(caught[0].message)) +print(older_name.__deprecated__) +``` + +```output +result +use new_name() instead +use new_name() instead +``` +::: + :::note - Use warnings for soft problems callers can act on later. - Use exceptions when the current operation cannot continue. - `stacklevel` should point the warning at the caller rather than inside the helper. +- On Python 3.13 and later, prefer `@warnings.deprecated(...)` for whole functions and classes; call `warnings.warn()` directly for narrower cases such as one deprecated argument. ::: diff --git a/src/example_sources_data.py b/src/example_sources_data.py index e8186c7..48e55c2 100644 --- a/src/example_sources_data.py +++ b/src/example_sources_data.py @@ -1,2 +1,2 @@ # Generated by scripts/embed_example_sources.py. Do not edit by hand. -EXAMPLE_SOURCE_FILES = {'manifest.toml': 'python_version = "3.13"\ndocs_base_url = "https://docs.python.org/3.13"\n\norder = [\n "hello-world",\n "values",\n "literals",\n "numbers",\n "booleans",\n "operators",\n "none",\n "variables",\n "constants",\n "truthiness",\n "equality-and-identity",\n "mutability",\n "object-lifecycle",\n "strings",\n "bytes-and-bytearray",\n "string-formatting",\n "conditionals",\n "guard-clauses",\n "assignment-expressions",\n "for-loops",\n "break-and-continue",\n "loop-else",\n "iterating-over-iterables",\n "iterators",\n "iterator-vs-iterable",\n "sentinel-iteration",\n "match-statements",\n "advanced-match-patterns",\n "while-loops",\n "lists",\n "tuples",\n "unpacking",\n "dicts",\n "sets",\n "slices",\n "comprehensions",\n "comprehension-patterns",\n "sorting",\n "collections-module",\n "copying-collections",\n "functions",\n "keyword-only-arguments",\n "positional-only-parameters",\n "args-and-kwargs",\n "multiple-return-values",\n "closures",\n "partial-functions",\n "scope-global-nonlocal",\n "recursion",\n "lambdas",\n "generators",\n "yield-from",\n "generator-expressions",\n "itertools",\n "decorators",\n "classes",\n "inheritance-and-super",\n "classmethods-and-staticmethods",\n "dataclasses",\n "properties",\n "special-methods",\n "truth-and-size",\n "container-protocols",\n "callable-objects",\n "operator-overloading",\n "attribute-access",\n "bound-and-unbound-methods",\n "descriptors",\n "metaclasses",\n "context-managers",\n "delete-statements",\n "exceptions",\n "assertions",\n "exception-chaining",\n "exception-groups",\n "warnings",\n "modules",\n "import-aliases",\n "packages",\n "virtual-environments",\n "type-hints",\n "runtime-type-checks",\n "union-and-optional-types",\n "type-aliases",\n "typed-dicts",\n "structured-data-shapes",\n "literal-and-final",\n "callable-types",\n "generics-and-typevar",\n "paramspec",\n "overloads",\n "casts-and-any",\n "newtype",\n "protocols",\n "abstract-base-classes",\n "enums",\n "regular-expressions",\n "number-parsing",\n "custom-exceptions",\n "json",\n "logging",\n "testing",\n "subprocesses",\n "threads-and-processes",\n "networking",\n "datetime",\n "csv-data",\n "async-await",\n "async-iteration-and-context",\n]\n', 'abstract-base-classes.md': '+++\nslug = "abstract-base-classes"\ntitle = "Abstract Base Classes"\nsection = "Classes"\nsummary = "ABC and abstractmethod enforce that subclasses implement required methods."\ndoc_path = "/library/abc.html"\nsee_also = [\n "protocols",\n "inheritance-and-super",\n "classes",\n]\n+++\n\n`ABC` and `@abstractmethod` describe an interface that subclasses must implement. The base class refuses to instantiate until a concrete subclass provides every abstract method, which catches "I forgot to implement this" at construction time rather than at the first method call.\n\nABCs are different from `Protocol`. An ABC is nominal: a class participates in the contract by inheriting from it. A `Protocol` is structural: any class with the right methods qualifies, no inheritance required. Reach for an ABC when you want shared implementation in the base class or you want `isinstance()` to mean "explicitly opted in"; reach for a `Protocol` when you only care about behavior at the API boundary.\n\nThe cost is a small amount of ceremony at the type level. The benefit is that a half-implemented subclass cannot be created by accident.\n\n:::program\n```python\nfrom abc import ABC, abstractmethod\nfrom typing import Protocol\n\nclass Shape(ABC):\n @abstractmethod\n def area(self) -> float:\n ...\n\n def describe(self) -> str:\n return f"shape with area {self.area()}"\n\ntry:\n Shape()\nexcept TypeError as error:\n print(error)\n\nclass Square(Shape):\n def __init__(self, side):\n self.side = side\n\n def area(self):\n return self.side ** 2\n\nprint(Square(3).area())\nprint(Square(3).describe())\n\nclass Incomplete(Shape):\n pass\n\ntry:\n Incomplete()\nexcept TypeError as error:\n print(error)\n\nclass HasArea(Protocol):\n def area(self) -> float:\n ...\n\nclass Triangle:\n def __init__(self, base, height):\n self.base = base\n self.height = height\n\n def area(self):\n return 0.5 * self.base * self.height\n\ndef total_area(shapes: list[HasArea]) -> float:\n return sum(shape.area() for shape in shapes)\n\nprint(total_area([Square(3), Triangle(4, 3)]))\nprint(isinstance(Triangle(4, 3), Shape))\nprint(isinstance(Square(3), Shape))\n```\n:::\n\n:::cell\n`ABC` plus `@abstractmethod` declares the contract. Trying to construct the base class itself fails because at least one method has no implementation. A concrete `describe()` lives alongside the abstract `area()` so subclasses inherit shared behavior for free.\n\n```python\nfrom abc import ABC, abstractmethod\n\nclass Shape(ABC):\n @abstractmethod\n def area(self) -> float:\n ...\n\n def describe(self) -> str:\n return f"shape with area {self.area()}"\n\ntry:\n Shape()\nexcept TypeError as error:\n print(error)\n```\n\n```output\nCan\'t instantiate abstract class Shape without an implementation for abstract method \'area\'\n```\n:::\n\n:::cell\nA subclass that implements every abstract method is concrete and can be instantiated. It also inherits the non-abstract methods from the base class.\n\n```python\nclass Square(Shape):\n def __init__(self, side):\n self.side = side\n\n def area(self):\n return self.side ** 2\n\nprint(Square(3).area())\nprint(Square(3).describe())\n```\n\n```output\n9\nshape with area 9\n```\n:::\n\n:::cell\nA subclass that forgets to implement an abstract method also cannot be instantiated — that is the value the ABC adds. The error fires at construction, not when something later tries to call the missing method.\n\n```python\nclass Incomplete(Shape):\n pass\n\ntry:\n Incomplete()\nexcept TypeError as error:\n print(error)\n```\n\n```output\nCan\'t instantiate abstract class Incomplete without an implementation for abstract method \'area\'\n```\n:::\n\n:::cell\nContrast with `Protocol`. A `HasArea` protocol accepts any class with an `area()` method, no inheritance required. `Triangle` does not inherit from `Shape`, so it satisfies the protocol but fails `isinstance(_, Shape)`. `Square` satisfies both because it explicitly inherited from the ABC.\n\n```python\nfrom typing import Protocol\n\nclass HasArea(Protocol):\n def area(self) -> float:\n ...\n\nclass Triangle:\n def __init__(self, base, height):\n self.base = base\n self.height = height\n\n def area(self):\n return 0.5 * self.base * self.height\n\ndef total_area(shapes: list[HasArea]) -> float:\n return sum(shape.area() for shape in shapes)\n\nprint(total_area([Square(3), Triangle(4, 3)]))\nprint(isinstance(Triangle(4, 3), Shape))\nprint(isinstance(Square(3), Shape))\n```\n\n```output\n15.0\nFalse\nTrue\n```\n:::\n\n:::note\n- `ABC` plus `@abstractmethod` blocks instantiation until every abstract method has an implementation.\n- ABCs are nominal — subclasses opt in by inheriting; `isinstance()` reflects that opt-in.\n- Protocols are structural — any class with the right shape qualifies, regardless of inheritance.\n- Prefer an ABC when shared implementation or explicit opt-in matters; prefer a Protocol when only behavior at the API boundary matters.\n:::\n', 'advanced-match-patterns.md': '+++\nslug = "advanced-match-patterns"\ntitle = "Advanced Match Patterns"\nsection = "Control Flow"\nsummary = "match patterns can destructure sequences, combine alternatives, and add guards."\ndoc_path = "/tutorial/controlflow.html#match-statements"\nsee_also = [\n "match-statements",\n "tuples",\n "classes",\n]\n+++\n\nStructural pattern matching is more than equality checks. Patterns can destructure sequences, match several alternatives, capture the rest of a sequence, and use guards.\n\nUse these forms when the shape of data is the decision. If the decision is only a single boolean condition, ordinary `if` statements are usually clearer.\n\nThe wildcard `_` catches everything not matched earlier.\n\n:::program\n```python\ndef describe(command):\n match command:\n case ["move", x, y] if x >= 0 and y >= 0:\n return f"move to {x},{y}"\n case ["quit" | "exit"]:\n return "stop"\n case ["echo", *words]:\n return " ".join(words)\n case _:\n return "unknown"\n\nprint(describe(["move", 2, 3]))\nprint(describe(["exit"]))\nprint(describe(["echo", "hello", "python"]))\nprint(describe(["move", -1, 3]))\n```\n:::\n\n:::cell\nSequence patterns match by position. A guard after `if` adds a condition that must also be true.\n\n```python\ndef describe(command):\n match command:\n case ["move", x, y] if x >= 0 and y >= 0:\n return f"move to {x},{y}"\n case ["quit" | "exit"]:\n return "stop"\n case ["echo", *words]:\n return " ".join(words)\n case _:\n return "unknown"\n\nprint(describe(["move", 2, 3]))\n```\n\n```output\nmove to 2,3\n```\n:::\n\n:::cell\nAn OR pattern accepts several alternatives in one case. A star pattern captures the rest of a sequence.\n\n```python\nprint(describe(["exit"]))\nprint(describe(["echo", "hello", "python"]))\n```\n\n```output\nstop\nhello python\n```\n:::\n\n:::cell\nThe wildcard `_` catches values that did not match earlier cases. Here the guard rejects the negative coordinate.\n\n```python\nprint(describe(["move", -1, 3]))\n```\n\n```output\nunknown\n```\n:::\n\n:::note\n- Use `case _` as a wildcard fallback.\n- Guards refine a pattern after the structure matches.\n- OR patterns and star patterns keep shape-based branches compact.\n:::\n', 'args-and-kwargs.md': '+++\nslug = "args-and-kwargs"\ntitle = "Args and Kwargs"\nsection = "Functions"\nsummary = "*args collects extra positional arguments and **kwargs collects named ones."\ndoc_path = "/tutorial/controlflow.html#arbitrary-argument-lists"\nsee_also = [\n "functions",\n "keyword-only-arguments",\n "partial-functions",\n "paramspec",\n]\n+++\n\n`*args` and `**kwargs` let a function accept flexible positional and keyword arguments. They are the function-definition counterpart to unpacking at a call site.\n\nThese parameters are useful for wrappers, decorators, logging helpers, and APIs that forward arguments to another function.\n\nThey should not replace clear signatures. If a function has a stable interface, explicit parameters document expectations better than a bag of arguments.\n\n:::program\n```python\ndef total(*numbers):\n return sum(numbers)\n\nprint(total(2, 3, 5))\n\n\ndef describe(**metadata):\n print(metadata)\n\ndescribe(owner="Ada", public=True)\n\n\ndef report(title, *items, **metadata):\n print(title)\n print(items)\n print(metadata)\n\nreport("scores", 10, 9, owner="Ada")\n```\n:::\n\n:::cell\n`*args` collects extra positional arguments into a tuple. This fits functions that naturally accept any number of similar values.\n\n```python\ndef total(*numbers):\n return sum(numbers)\n\nprint(total(2, 3, 5))\n```\n\n```output\n10\n```\n:::\n\n:::cell\n`**kwargs` collects named arguments into a dictionary. The names become string keys.\n\n```python\ndef describe(**metadata):\n print(metadata)\n\ndescribe(owner="Ada", public=True)\n```\n\n```output\n{\'owner\': \'Ada\', \'public\': True}\n```\n:::\n\n:::cell\nA function can combine explicit parameters, `*args`, and `**kwargs`. Put the flexible parts last so the fixed shape remains visible.\n\n```python\ndef report(title, *items, **metadata):\n print(title)\n print(items)\n print(metadata)\n\nreport("scores", 10, 9, owner="Ada")\n```\n\n```output\nscores\n(10, 9)\n{\'owner\': \'Ada\'}\n```\n:::\n\n:::note\n- Use these tools when a function naturally accepts a flexible shape.\n- Prefer explicit parameters when the accepted arguments are known and fixed.\n- `*args` is a tuple; `**kwargs` is a dictionary.\n:::\n', 'assertions.md': '+++\nslug = "assertions"\ntitle = "Assertions"\nsection = "Errors"\nsummary = "assert documents internal assumptions and fails loudly when they are false."\ndoc_path = "/reference/simple_stmts.html#the-assert-statement"\nsee_also = [\n "exceptions",\n "custom-exceptions",\n "type-hints",\n]\n+++\n\n`assert` checks an internal assumption. If the condition is false, Python raises `AssertionError` with an optional message.\n\nUse assertions for programmer assumptions, not for validating user input or external data. Input validation should raise ordinary exceptions that production code expects to handle.\n\nAssertions make invariants executable while keeping the successful path compact.\n\n:::program\n```python\ndef average(scores):\n assert scores, "scores must not be empty"\n return sum(scores) / len(scores)\n\nprint(average([8, 10]))\n\ntry:\n average([])\nexcept AssertionError as error:\n print(error)\n```\n:::\n\n:::cell\nWhen the assertion is true, execution continues normally. The assertion documents the function\'s internal expectation.\n\n```python\ndef average(scores):\n assert scores, "scores must not be empty"\n return sum(scores) / len(scores)\n\nprint(average([8, 10]))\n```\n\n```output\n9.0\n```\n:::\n\n:::cell\nWhen the assertion is false, Python raises `AssertionError`. This signals a broken assumption, not a normal recovery path.\n\n```python\ntry:\n average([])\nexcept AssertionError as error:\n print(error)\n```\n\n```output\nscores must not be empty\n```\n:::\n\n:::note\n- Use `assert` for internal invariants and debugging assumptions.\n- Use explicit exceptions for user input, files, network responses, and other expected failures.\n- Assertions can be disabled with Python optimization flags, so do not rely on them for security checks.\n:::\n', 'assignment-expressions.md': '+++\nslug = "assignment-expressions"\ntitle = "Assignment Expressions"\nsection = "Control Flow"\nsummary = "The walrus operator assigns a value inside an expression."\ndoc_path = "/reference/expressions.html#assignment-expressions"\nsee_also = [\n "conditionals",\n "while-loops",\n "variables",\n]\n+++\n\nThe assignment expression operator `:=` assigns a name while evaluating an expression. It is often called the walrus operator.\n\nUse it when computing a value and testing it are naturally one step. Avoid it when a separate assignment would make the code easier to read.\n\nThe boundary is readability: the walrus operator can remove duplication, but it should not hide important state changes.\n\n:::program\n```python\nmessages = ["hello", "", "python"]\n\nfor message in messages:\n if length := len(message):\n print(message, length)\n\nqueue = ["retry", "ok"]\nwhile (status := queue.pop(0)) != "ok":\n print(status)\nprint(status)\n```\n:::\n\n:::cell\nAn assignment expression can name a computed value while a condition tests it. Here empty strings are skipped because their length is zero.\n\n```python\nmessages = ["hello", "", "python"]\n\nfor message in messages:\n if length := len(message):\n print(message, length)\n```\n\n```output\nhello 5\npython 6\n```\n:::\n\n:::cell\nThe same idea works in loops that read state until a sentinel appears. The assignment and comparison stay together.\n\n```python\nqueue = ["retry", "ok"]\nwhile (status := queue.pop(0)) != "ok":\n print(status)\nprint(status)\n```\n\n```output\nretry\nok\n```\n:::\n\n:::note\n- `name := expression` assigns and evaluates to the assigned value.\n- Use it to avoid computing the same value twice.\n- Prefer a normal assignment when the expression becomes hard to scan.\n:::\n', 'async-await.md': '+++\nslug = "async-await"\ntitle = "Async Await"\nsection = "Async"\nsummary = "async def creates coroutines, and await pauses until awaitable work completes."\ndoc_path = "/library/asyncio-task.html"\nsee_also = [\n "async-iteration-and-context",\n "functions",\n "context-managers",\n]\n+++\n\n`async def` creates a coroutine function. Calling it creates a coroutine object; the body runs when an event loop awaits or schedules it.\n\n`await` pauses the current coroutine until another awaitable completes. This lets one event loop make progress on other work while a task waits for I/O.\n\nCloudflare Workers handlers are asynchronous, so understanding `await` is practical for fetch calls, bindings, and service interactions even when a small example uses `asyncio.sleep(0)` as a stand-in.\n\nThe alternative is ordinary `def` for work that completes immediately. Use async code for I/O-shaped waiting, not as a faster replacement for CPU-bound Python.\n\n:::program\n```python\nimport asyncio\n\ndef slug_to_title(slug):\n return slug.replace("-", " ").title()\n\nasync def fetch_title(slug):\n await asyncio.sleep(0)\n return slug_to_title(slug)\n\nasync def main():\n title = await fetch_title("async-await")\n print(title)\n titles = await asyncio.gather(fetch_title("json"), fetch_title("datetime"))\n print(titles)\n\nasyncio.run(main())\n\n\nclass Session:\n async def __aenter__(self):\n print("open")\n return self\n\n async def __aexit__(self, *_):\n print("close")\n return False\n\n\nasync def stream():\n for slug in ["json", "datetime"]:\n await asyncio.sleep(0)\n yield slug\n\n\nasync def driver():\n async with Session():\n async for slug in stream():\n print(slug)\n\nasyncio.run(driver())\n```\n:::\n\n:::cell\nAn ordinary `def` function computes its result immediately: calling it runs the body and hands the value straight back. This synchronous form is the baseline the rest of the page contrasts against.\n\n```python\ndef slug_to_title(slug):\n return slug.replace("-", " ").title()\n\nprint(slug_to_title("async-await"))\n```\n\n```output\nAsync Await\n```\n:::\n\n:::cell\nAn `async def` function returns a coroutine object when called. The function body has not produced its final result yet.\n\n```python\nimport asyncio\n\nasync def fetch_title(slug):\n await asyncio.sleep(0)\n return slug_to_title(slug)\n\ncoroutine = fetch_title("async-await")\nprint(coroutine.__class__.__name__)\ncoroutine.close()\n```\n\n```output\ncoroutine\n```\n:::\n\n:::cell\nUse `await` inside another coroutine to get the eventual result. `asyncio.run()` starts an event loop for the top-level coroutine.\n\n```python\nasync def main():\n title = await fetch_title("async-await")\n print(title)\n\nasyncio.run(main())\n```\n\n```output\nAsync Await\n```\n:::\n\n:::cell\n`asyncio.gather()` awaits several awaitables and returns their results in order. This is the shape used when independent I/O operations can progress together.\n\n```python\nasync def main():\n titles = await asyncio.gather(fetch_title("json"), fetch_title("datetime"))\n print(titles)\n\nasyncio.run(main())\n```\n\n```output\n[\'Json\', \'Datetime\']\n```\n:::\n\n:::cell\n`async with` and `async for` are the asynchronous forms of context managers and iteration. A class implements `__aenter__`/`__aexit__` to act as an async context manager; an `async def` function with `yield` becomes an async generator. The dedicated [async iteration and context](/examples/async-iteration-and-context) page explains the protocols in depth.\n\n```python\nclass Session:\n async def __aenter__(self):\n print("open")\n return self\n\n async def __aexit__(self, *_):\n print("close")\n return False\n\n\nasync def stream():\n for slug in ["json", "datetime"]:\n await asyncio.sleep(0)\n yield slug\n\n\nasync def driver():\n async with Session():\n async for slug in stream():\n print(slug)\n\nasyncio.run(driver())\n```\n\n```output\nopen\njson\ndatetime\nclose\n```\n:::\n\n:::note\n- Calling an async function creates a coroutine object.\n- `await` yields control until an awaitable completes.\n- Workers request handlers are async, so this pattern appears around fetches and bindings.\n- Prefer ordinary functions when there is no awaitable work to coordinate.\n:::\n', 'async-iteration-and-context.md': '+++\nslug = "async-iteration-and-context"\ntitle = "Async Iteration and Context"\nsection = "Async"\nsummary = "async for and async with consume asynchronous streams and cleanup protocols."\ndoc_path = "/reference/compound_stmts.html#async-for"\nsee_also = [\n "async-await",\n "iterators",\n "context-managers",\n]\n+++\n\n`async for` consumes an asynchronous iterator: a stream whose next value may require `await`. `async with` surrounds a block with asynchronous setup and cleanup.\n\nThese forms appear around network streams, database cursors, locks, and service clients where both iteration and cleanup may wait on I/O.\n\nUse ordinary `for` and `with` when producing the next value or cleaning up does not need to await anything.\n\nThe syntax mirrors `for` and `with`, but the protocol methods are asynchronous.\n\n:::program\n```python\nimport asyncio\n\nasync def titles():\n for slug in ["values", "async-await"]:\n await asyncio.sleep(0)\n yield slug.replace("-", " ").title()\n\nclass Session:\n async def __aenter__(self):\n print("open")\n return self\n\n async def __aexit__(self, exc_type, exc, tb):\n print("close")\n\nasync def main():\n async with Session():\n async for title in titles():\n print(title)\n\nasyncio.run(main())\n```\n:::\n\n:::cell\nAn async generator can `await` before yielding each value. `async for` consumes those values with the asynchronous iteration protocol.\n\n```python\nimport asyncio\n\nasync def titles():\n for slug in ["values", "async-await"]:\n await asyncio.sleep(0)\n yield slug.replace("-", " ").title()\n\nprint(titles.__name__)\n```\n\n```output\ntitles\n```\n:::\n\n:::cell\nAn async context manager defines `__aenter__` and `__aexit__`. `async with` awaits setup and cleanup around the block.\n\n```python\nclass Session:\n async def __aenter__(self):\n print("open")\n return self\n\n async def __aexit__(self, exc_type, exc, tb):\n print("close")\n\nprint(Session.__name__)\n```\n\n```output\nSession\n```\n:::\n\n:::cell\nThe top-level coroutine combines both protocols: open the async resource, then consume the async stream inside it.\n\n```python\nasync def main():\n async with Session():\n async for title in titles():\n print(title)\n\nasyncio.run(main())\n```\n\n```output\nopen\nValues\nAsync Await\nclose\n```\n:::\n\n:::note\n- `async for` consumes asynchronous iterators.\n- `async with` awaits asynchronous setup and cleanup.\n- These forms are common around I/O-shaped resources.\n:::\n', 'attribute-access.md': '+++\nslug = "attribute-access"\ntitle = "Attribute Access"\nsection = "Data Model"\nsummary = "Attribute hooks customize lookup, missing attributes, and assignment."\ndoc_path = "/reference/datamodel.html#customizing-attribute-access"\nsee_also = [\n "properties",\n "descriptors",\n "special-methods",\n "bound-and-unbound-methods",\n]\n+++\n\nAttribute access is usually simple: `obj.name` looks up an attribute. Python exposes hooks for the uncommon cases where lookup or assignment needs to be customized.\n\n`__getattr__` runs only when normal lookup fails, which makes it a safer hook for computed fallback attributes. `__setattr__` runs for every assignment, so it should be used sparingly and carefully.\n\nPrefer ordinary attributes and `@property` first. Reach for these hooks when an object is intentionally adapting another interface, validating all assignments, or exposing dynamic fields.\n\n:::program\n```python\nclass Settings:\n def __init__(self, values):\n self._values = dict(values)\n\n def __getattr__(self, name):\n try:\n return self._values[name]\n except KeyError as error:\n raise AttributeError(name) from error\n\n def __setattr__(self, name, value):\n if name.startswith("_"):\n object.__setattr__(self, name, value)\n else:\n self._values[name] = value\n\nsettings = Settings({"theme": "dark"})\nprint(settings.theme)\nsettings.volume = 7\nprint(settings._values["volume"])\n```\n:::\n\n:::cell\nThe starting point is ordinary: `__init__` stores one real attribute, the `_values` backing dictionary. The hooks in the next cells customize lookup and assignment around it.\n\n```python\nclass Settings:\n def __init__(self, values):\n self._values = dict(values)\n\nsettings = Settings({"theme": "dark"})\nprint(settings._values)\n```\n\n```output\n{\'theme\': \'dark\'}\n```\n:::\n\n:::cell\n`__getattr__` runs only for missing attributes, so it can provide fallback lookup.\n\n```python\nclass Settings:\n def __init__(self, values):\n self._values = dict(values)\n\n def __getattr__(self, name):\n try:\n return self._values[name]\n except KeyError as error:\n raise AttributeError(name) from error\n\nsettings = Settings({"theme": "dark"})\nprint(settings.theme)\n```\n\n```output\ndark\n```\n:::\n\n:::cell\n`__setattr__` intercepts every assignment, including the ones in `__init__`. Underscore names are stored as real attributes through `object.__setattr__`, which avoids recursing through your own hook; public names go to the backing dictionary.\n\n```python\nclass Settings:\n def __init__(self, values):\n self._values = dict(values)\n\n def __setattr__(self, name, value):\n if name.startswith("_"):\n object.__setattr__(self, name, value)\n else:\n self._values[name] = value\n\nsettings = Settings({"theme": "dark"})\nsettings.volume = 7\nprint(settings._values["volume"])\n```\n\n```output\n7\n```\n:::\n\n:::note\n- `__getattr__` is narrower than `__getattribute__` because it handles only missing attributes.\n- `__setattr__` affects every assignment on the instance.\n- Use `property` or descriptors when the behavior is attached to a known attribute name.\n:::\n', 'booleans.md': '+++\nslug = "booleans"\ntitle = "Booleans"\nsection = "Basics"\nsummary = "Booleans represent truth values and combine with logical operators."\ndoc_path = "/library/stdtypes.html#boolean-type-bool"\nsee_also = [\n "truthiness",\n "operators",\n "conditionals",\n]\n+++\n\nBooleans are the values `True` and `False`. They are produced by comparisons and combined with `and`, `or`, and `not`.\n\nPython\'s logical operators short-circuit. That means the right side is evaluated only when needed, which keeps guard checks efficient and safe.\n\nBooleans are also connected to truthiness: many objects can be tested in conditions even when they are not literally `True` or `False`.\n\n:::program\n```python\nlogged_in = True\nhas_permission = False\n\nprint(logged_in and has_permission)\nprint(logged_in or has_permission)\nprint(not has_permission)\n\nname = "Ada"\nprint(name == "Ada" and len(name) > 0)\n\nprint(isinstance(True, int))\nprint(True + True)\nprint(sum([True, True, False, True]))\n\ndef is_strict_int(value):\n return isinstance(value, int) and not isinstance(value, bool)\n\nprint(is_strict_int(True))\nprint(is_strict_int(1))\n```\n:::\n\n:::cell\nUse booleans for facts that are either true or false. Python spells the constants `True` and `False`.\n\nUse `and`, `or`, and `not` to combine truth values. These operators read like English and short-circuit when possible.\n\n```python\nlogged_in = True\nhas_permission = False\n\nprint(logged_in and has_permission)\nprint(logged_in or has_permission)\nprint(not has_permission)\n```\n\n```output\nFalse\nTrue\nTrue\n```\n:::\n\n:::cell\nComparisons produce booleans too, so they compose naturally with logical operators in conditions and validation checks.\n\n```python\nname = "Ada"\nprint(name == "Ada" and len(name) > 0)\n```\n\n```output\nTrue\n```\n:::\n\n:::cell\n`bool` is a subclass of `int`, which is occasionally a footgun. `True` behaves as `1` and `False` as `0` in arithmetic, and `isinstance(True, int)` is `True`. When a function must reject booleans, exclude them explicitly with `isinstance(value, int) and not isinstance(value, bool)`.\n\n```python\nprint(isinstance(True, int))\nprint(True + True)\nprint(sum([True, True, False, True]))\n\ndef is_strict_int(value):\n return isinstance(value, int) and not isinstance(value, bool)\n\nprint(is_strict_int(True))\nprint(is_strict_int(1))\n```\n\n```output\nTrue\n2\n3\nFalse\nTrue\n```\n:::\n\n:::note\n- Boolean constants are `True` and `False`, with capital letters.\n- `and` and `or` short-circuit: Python does not evaluate the right side if the left side already determines the result.\n- Prefer truthiness for containers and explicit comparisons when the exact boolean condition matters.\n- `bool` subclasses `int`; `isinstance(True, int)` is `True`. Exclude booleans explicitly when only "real" integers should pass.\n:::\n', 'bound-and-unbound-methods.md': '+++\nslug = "bound-and-unbound-methods"\ntitle = "Bound and Unbound Methods"\nsection = "Data Model"\nsummary = "instance.method binds self automatically; Class.method is a plain function."\ndoc_path = "/reference/datamodel.html#instance-methods"\nsee_also = [\n "classes",\n "attribute-access",\n "descriptors",\n "callable-objects",\n]\n+++\n\nWhen you write `instance.method`, Python returns a bound method — a callable that already remembers which instance to pass as `self`. When you write `Class.method`, you get the underlying function back, and calling it requires passing an instance yourself.\n\nThat distinction is why methods can be stored in collections, passed as callbacks, and called later without losing track of the object they belong to. Each bound method carries its own `__self__`, so two callables produced from two different instances stay independent even when their underlying function is the same.\n\nThe mechanism is the descriptor protocol: a function attached to a class implements `__get__`, and that hook turns attribute access on an instance into a bound method. The page does not need that detail to use methods, but it explains what is happening underneath.\n\n:::program\n```python\nclass Counter:\n def __init__(self, start=0):\n self.value = start\n\n def increment(self):\n self.value += 1\n return self.value\n\nbound_counter = Counter(10)\nm = bound_counter.increment\nprint(m.__self__ is bound_counter)\nprint(m())\nprint(m())\n\nunbound_counter = Counter(0)\nunbound = Counter.increment\nprint(type(unbound).__name__)\nprint(unbound(unbound_counter))\nprint(unbound(unbound_counter))\n\nhandlers = []\nfor _ in range(2):\n handlers.append(Counter().increment)\n\nprint(handlers[0]())\nprint(handlers[0]())\nprint(handlers[1]())\n\ndescriptor_counter = Counter(0)\nfunc = Counter.__dict__["increment"]\nprint(type(func).__name__)\nrebound = func.__get__(descriptor_counter, Counter)\nprint(type(rebound).__name__)\nprint(rebound.__self__ is descriptor_counter)\n```\n:::\n\n:::cell\n`instance.method` returns a bound method. The method already remembers the instance through `__self__`, so calling it does not require passing `self` again.\n\n```python\nclass Counter:\n def __init__(self, start=0):\n self.value = start\n\n def increment(self):\n self.value += 1\n return self.value\n\nbound_counter = Counter(10)\nm = bound_counter.increment\nprint(m.__self__ is bound_counter)\nprint(m())\nprint(m())\n```\n\n```output\nTrue\n11\n12\n```\n:::\n\n:::cell\n`Class.method` returns the underlying function — there is no `self` attached. Calling it requires passing the instance as the first argument explicitly. Using a fresh counter here makes the output independent of the previous cell.\n\n```python\nunbound_counter = Counter(0)\nunbound = Counter.increment\nprint(type(unbound).__name__)\nprint(unbound(unbound_counter))\nprint(unbound(unbound_counter))\n```\n\n```output\nfunction\n1\n2\n```\n:::\n\n:::cell\nBound methods are first-class values. They can be stored in lists, passed to other functions, and called later. Each bound method carries its own `__self__`, so two methods produced from two different instances stay independent.\n\n```python\nhandlers = []\nfor _ in range(2):\n handlers.append(Counter().increment)\n\nprint(handlers[0]())\nprint(handlers[0]())\nprint(handlers[1]())\n```\n\n```output\n1\n2\n1\n```\n:::\n\n:::cell\nThe binding is the descriptor protocol at work. The function lives on the class as a plain function; instance attribute access invokes `__get__`, which returns a bound method that knows the instance.\n\n```python\ndescriptor_counter = Counter(0)\nfunc = Counter.__dict__["increment"]\nprint(type(func).__name__)\nrebound = func.__get__(descriptor_counter, Counter)\nprint(type(rebound).__name__)\nprint(rebound.__self__ is descriptor_counter)\n```\n\n```output\nfunction\nmethod\nTrue\n```\n:::\n\n:::note\n- `instance.method` produces a bound method whose `__self__` is the instance.\n- `Class.method` produces the plain function and requires you to pass the instance.\n- "Unbound method" is the historical Python 2 term; since Python 3, `Class.method` is simply a function, which is what this page demonstrates.\n- Each bound method is its own object; storing one captures its instance.\n- The binding is implemented by the descriptor protocol on the function object.\n:::\n', 'break-and-continue.md': '+++\nslug = "break-and-continue"\ntitle = "Break and Continue"\nsection = "Control Flow"\nsummary = "break exits a loop early, while continue skips to the next iteration."\ndoc_path = "/tutorial/controlflow.html#break-and-continue-statements"\nsee_also = [\n "for-loops",\n "while-loops",\n "loop-else",\n]\n+++\n\n`break` and `continue` control the nearest enclosing loop. They exist for loops whose body discovers an early stop rule or an item-level skip rule.\n\nUse `continue` when the current item should not run the rest of the body. Use `break` when no later item should be processed.\n\nThe alternative is ordinary `if`/`else` nesting. Prefer `break` and `continue` when they keep the normal path flatter and easier to read.\n\n:::program\n```python\nnames = ["Ada", "", "Grace"]\nfor name in names:\n if not name:\n continue\n print(name)\n\ncommands = ["load", "save", "stop", "delete"]\nfor command in commands:\n if command == "stop":\n break\n print(command)\n```\n:::\n\n:::cell\n`continue` skips the rest of the current iteration. The empty name is ignored, and the loop moves on to the next value.\n\n```python\nnames = ["Ada", "", "Grace"]\nfor name in names:\n if not name:\n continue\n print(name)\n```\n\n```output\nAda\nGrace\n```\n:::\n\n:::cell\n`break` exits the loop immediately. The value after `stop` is never processed because the loop has already ended.\n\n```python\ncommands = ["load", "save", "stop", "delete"]\nfor command in commands:\n if command == "stop":\n break\n print(command)\n```\n\n```output\nload\nsave\n```\n:::\n\n:::note\n- `continue` skips to the next loop iteration.\n- `break` exits the nearest enclosing loop immediately.\n- Prefer plain `if`/`else` when the loop does not need early skip or early stop behavior.\n:::\n', 'bytes-and-bytearray.md': '+++\nslug = "bytes-and-bytearray"\ntitle = "Bytes and Bytearray"\nsection = "Text"\nsummary = "bytes and bytearray store binary data, not Unicode text."\ndoc_path = "/library/stdtypes.html#binary-sequence-types-bytes-bytearray-memoryview"\nsee_also = [\n "strings",\n "literals",\n "networking",\n]\n+++\n\n`str` stores Unicode text. `bytes` stores raw byte values. The boundary matters whenever text leaves Python for a file, network protocol, subprocess, or binary format.\n\nEncoding turns text into bytes with a named encoding such as UTF-8. Decoding turns bytes back into text. The lengths can differ because one Unicode character may require several bytes.\n\nUse immutable `bytes` for stable binary data and `bytearray` when the bytes must be changed in place.\n\n:::program\n```python\ntext = "café"\ndata = text.encode("utf-8")\n\nprint(data)\nprint(len(text), len(data))\nprint(data.decode("utf-8"))\nprint(data[0])\n\npacket = bytearray(b"py")\npacket[0] = ord("P")\nprint(packet)\n```\n:::\n\n:::cell\nEncode text when an external boundary needs bytes. UTF-8 uses one byte for ASCII characters and more than one byte for many other characters.\n\n```python\ntext = "café"\ndata = text.encode("utf-8")\nprint(data)\nprint(len(text), len(data))\n```\n\n```output\nb\'caf\\xc3\\xa9\'\n4 5\n```\n:::\n\n:::cell\nDecode bytes when the program needs text again. The decoder must match the encoding used at the boundary.\n\n```python\nprint(data.decode("utf-8"))\n```\n\n```output\ncafé\n```\n:::\n\n:::cell\nIndexing a `bytes` object returns an integer byte value, not a one-character `bytes` object.\n\n```python\nprint(data[0])\n```\n\n```output\n99\n```\n:::\n\n:::cell\n`bytes` is immutable. Use `bytearray` when binary data must be changed in place.\n\n```python\npacket = bytearray(b"py")\npacket[0] = ord("P")\nprint(packet)\n```\n\n```output\nbytearray(b\'Py\')\n```\n:::\n\n:::note\n- Encode text when an external boundary needs bytes.\n- Decode bytes when you want text again.\n- Indexing `bytes` returns integers from 0 to 255.\n- Use `bytearray` when binary data must be changed in place.\n:::\n', 'callable-objects.md': '+++\nslug = "callable-objects"\ntitle = "Callable Objects"\nsection = "Data Model"\nsummary = "__call__ lets an instance behave like a function while keeping state."\ndoc_path = "/reference/datamodel.html#object.__call__"\nsee_also = [\n "functions",\n "closures",\n "callable-types",\n "bound-and-unbound-methods",\n]\n+++\n\nFunctions are not the only callable objects in Python. Any instance can be called with parentheses when its class defines `__call__`.\n\nCallable objects are useful when behavior needs remembered configuration or evolving state. A closure can do this too; a class is often clearer when the state has multiple fields or needs named methods.\n\nThe tradeoff is ceremony. Use a function for simple behavior, a closure for small captured state, and a callable object when naming the state improves the interface.\n\n:::program\n```python\nclass Multiplier:\n def __init__(self, factor):\n self.factor = factor\n self.calls = 0\n\n def __call__(self, value):\n self.calls += 1\n return value * self.factor\n\ndouble = Multiplier(2)\nprint(double(5))\nprint(double(7))\nprint(double.calls)\n```\n:::\n\n:::cell\nA callable object starts as ordinary state stored on an instance.\n\n```python\nclass Multiplier:\n def __init__(self, factor):\n self.factor = factor\n self.calls = 0\n\ndouble = Multiplier(2)\nprint(double.factor)\n```\n\n```output\n2\n```\n:::\n\n:::cell\n`__call__` makes the instance usable with function-call syntax.\n\n```python\nclass Multiplier:\n def __init__(self, factor):\n self.factor = factor\n self.calls = 0\n\n def __call__(self, value):\n self.calls += 1\n return value * self.factor\n\ndouble = Multiplier(2)\nprint(double(5))\nprint(double(7))\n```\n\n```output\n10\n14\n```\n:::\n\n:::cell\nBecause the callable is still an object, it can remember state across calls.\n\n```python\nprint(double.calls)\n```\n\n```output\n2\n```\n:::\n\n:::note\n- `callable(obj)` checks whether an object can be called.\n- Callable objects are good for named, stateful behavior.\n- Prefer plain functions when no instance state is needed.\n:::\n', 'callable-types.md': '+++\nslug = "callable-types"\ntitle = "Callable Types"\nsection = "Types"\nsummary = "Callable annotations describe functions passed as values."\ndoc_path = "/library/typing.html#annotating-callable-objects"\nsee_also = [\n "functions",\n "callable-objects",\n "protocols",\n]\n+++\n\nCallable annotations describe values that can be called like functions. They are useful when a function accepts a callback, strategy, predicate, or transformation.\n\n`Callable[[int], int]` says how the callback will be called: one integer argument, integer result. The annotation helps tools and readers, while runtime still only needs an object that is actually callable.\n\nUse `Callable` for simple call shapes. Use a protocol when the callback needs named attributes, overloaded signatures, or a more descriptive interface.\n\n:::program\n```python\nfrom collections.abc import Callable\n\n\ndef apply_twice(value: int, func: Callable[[int], int]) -> int:\n return func(func(value))\n\n\ndef add_one(number: int) -> int:\n return number + 1\n\nclass Doubler:\n def __call__(self, number: int) -> int:\n return number * 2\n\nprint(apply_twice(3, add_one))\nprint(apply_twice(3, Doubler()))\nprint(callable(add_one), callable(Doubler()))\n```\n:::\n\n:::cell\nUse `Callable[[Arg], Return]` for function-shaped values. The callback is passed in and called by the receiving function.\n\n```python\nfrom collections.abc import Callable\n\n\ndef apply_twice(value: int, func: Callable[[int], int]) -> int:\n return func(func(value))\n\n\ndef add_one(number: int) -> int:\n return number + 1\n\nprint(apply_twice(3, add_one))\n```\n\n```output\n5\n```\n:::\n\n:::cell\nCallable annotations are structural: an object with `__call__` can also satisfy the shape.\n\n```python\nclass Doubler:\n def __call__(self, number: int) -> int:\n return number * 2\n\nprint(apply_twice(3, Doubler()))\n```\n\n```output\n12\n```\n:::\n\n:::cell\nRuntime callability is a separate question from static annotation. `callable()` checks whether Python can call the object.\n\n```python\nprint(callable(add_one), callable(Doubler()))\n```\n\n```output\nTrue True\n```\n:::\n\n:::note\n- Use `Callable[[Arg], Return]` for simple function-shaped values.\n- The annotation documents how the callback will be called.\n- For complex call signatures, protocols can be clearer.\n:::\n', 'casts-and-any.md': '+++\nslug = "casts-and-any"\ntitle = "Casts and Any"\nsection = "Types"\nsummary = "Any and cast are escape hatches for places static analysis cannot prove."\ndoc_path = "/library/typing.html#typing.cast"\nsee_also = [\n "type-hints",\n "runtime-type-checks",\n "typed-dicts",\n]\n+++\n\n`Any` and `cast()` are escape hatches. They are useful at messy boundaries where a type checker cannot prove what a value is, but they also remove protection when overused.\n\n`Any` tells static tools to stop checking most operations on a value. `cast(T, value)` tells the type checker to treat a value as `T`, but it returns the same runtime object unchanged.\n\nPrefer narrowing with runtime checks when possible. Use `cast()` when another invariant already proves the type and the checker cannot see that proof.\n\n:::program\n```python\nfrom typing import Any, cast\n\nraw: Any = {"score": "98"}\nscore_text = cast(dict[str, str], raw)["score"]\nscore = int(score_text)\n\nprint(score + 2)\nprint(cast(list[int], raw) is raw)\nprint(type(raw).__name__)\n\nvalue: object = {"score": "98"}\nif isinstance(value, dict):\n print(value["score"])\n```\n:::\n\n:::cell\n`Any` disables most static checking for a value. The runtime object is still whatever value was actually assigned.\n\n```python\nfrom typing import Any, cast\n\nraw: Any = {"score": "98"}\nscore_text = cast(dict[str, str], raw)["score"]\nscore = int(score_text)\nprint(score + 2)\n```\n\n```output\n100\n```\n:::\n\n:::cell\n`cast()` does not convert or validate the value. It returns the same object at runtime.\n\n```python\nprint(cast(list[int], raw) is raw)\nprint(type(raw).__name__)\n```\n\n```output\nTrue\ndict\n```\n:::\n\n:::cell\nA real runtime check narrows by inspecting the value. This is safer when the input is untrusted.\n\n```python\nvalue: object = {"score": "98"}\nif isinstance(value, dict):\n print(value["score"])\n```\n\n```output\n98\n```\n:::\n\n:::note\n- `Any` disables most static checking for a value.\n- `cast()` tells the type checker to trust you without changing the runtime object.\n- Prefer narrowing with checks when possible.\n:::\n', 'classes.md': '+++\nslug = "classes"\ntitle = "Classes"\nsection = "Classes"\nsummary = "Classes bundle data and behavior into new object types."\ndoc_path = "/tutorial/classes.html"\nsee_also = [\n "inheritance-and-super",\n "classmethods-and-staticmethods",\n "bound-and-unbound-methods",\n "dataclasses",\n]\n+++\n\nClasses define new object types by bundling data with behavior. They are useful when several values and operations belong together and should travel as one object.\n\nThe alternative is often a dictionary plus separate functions. That is fine for loose data, but a class gives the data a stable API and keeps behavior next to the state it changes.\n\n`__init__` initializes each instance, and methods receive the instance as `self`. Separate instances keep separate state because each object has its own attributes.\n\n:::program\n```python\nclass Counter:\n step = 1\n\n def __init__(self, start=0):\n self.value = start\n\n def increment(self, amount=1):\n self.value += amount\n return self.value\n\nfirst = Counter()\nsecond = Counter(10)\n\nprint(first.value)\nprint(second.value)\nprint(first.increment())\nprint(second.increment(5))\nprint(first.step)\nCounter.step = 5\nprint(second.step)\n\nclass Cart:\n items = []\n\n def add(self, item):\n self.items.append(item)\n\nshared_a = Cart()\nshared_b = Cart()\nshared_a.add("apple")\nprint(shared_b.items)\n\nclass FixedCart:\n def __init__(self):\n self.items = []\n\n def add(self, item):\n self.items.append(item)\n\nown_a = FixedCart()\nown_b = FixedCart()\nown_a.add("apple")\nprint(own_b.items)\n```\n:::\n\n:::cell\nDefine a class when data and behavior should travel together. The initializer gives each object its starting state.\n\n```python\nclass Counter:\n def __init__(self, start=0):\n self.value = start\n\nfirst = Counter()\nsecond = Counter(10)\nprint(first.value)\nprint(second.value)\n```\n\n```output\n0\n10\n```\n:::\n\n:::cell\nMethods are functions attached to the class. `self` is the particular object receiving the method call, so separate instances keep separate state.\n\n```python\nclass Counter:\n def __init__(self, start=0):\n self.value = start\n\n def increment(self, amount=1):\n self.value += amount\n return self.value\n\nfirst = Counter()\nsecond = Counter(10)\nprint(first.increment())\nprint(second.increment(5))\n```\n\n```output\n1\n15\n```\n:::\n\n:::cell\nA name defined directly on the class body is a class attribute, shared by every instance. Reading falls back to the class when the instance has no attribute of that name; assigning to the class itself changes the value for every instance at once.\n\n```python\nclass Counter:\n step = 1\n\n def __init__(self, start=0):\n self.value = start\n\nfirst = Counter()\nsecond = Counter()\nprint(first.step)\nCounter.step = 5\nprint(second.step)\n```\n\n```output\n1\n5\n```\n:::\n\n:::cell\nA mutable class attribute is shared mutable state — the classic footgun. Define per-instance containers in `__init__` so each object owns its own copy.\n\n```python\nclass Cart:\n items = []\n\n def add(self, item):\n self.items.append(item)\n\nshared_a = Cart()\nshared_b = Cart()\nshared_a.add("apple")\nprint(shared_b.items)\n\nclass FixedCart:\n def __init__(self):\n self.items = []\n\n def add(self, item):\n self.items.append(item)\n\nown_a = FixedCart()\nown_b = FixedCart()\nown_a.add("apple")\nprint(own_b.items)\n```\n\n```output\n[\'apple\']\n[]\n```\n:::\n\n:::note\n- `self` is the instance the method is operating on.\n- `__init__` initializes each new object.\n- Class attributes are shared across instances; instance attributes belong to one object.\n- Put mutable defaults in `__init__`, not on the class body.\n- Use classes when behavior belongs with state; use dictionaries for looser structured data.\n:::\n', 'classmethods-and-staticmethods.md': '+++\nslug = "classmethods-and-staticmethods"\ntitle = "Classmethods and Staticmethods"\nsection = "Classes"\nsummary = "Three method shapes: instance, class, and static — each receives a different first argument."\ndoc_path = "/library/functions.html#classmethod"\nsee_also = [\n "classes",\n "decorators",\n "inheritance-and-super",\n]\n+++\n\nA regular method receives the instance as `self`. `@classmethod` makes a method receive the class as `cls` instead, which is the standard shape for alternate constructors. `@staticmethod` removes the implicit first argument entirely, leaving a plain function attached to the class for namespacing.\n\nThe pressure that justifies the decorators is name organization. `Date.from_string("2026-05-09")` reads better than a free-floating `parse_date` function, and `Date.is_leap_year(2024)` keeps the helper next to the class it belongs to even when the helper does not need any class state.\n\nPick instance methods when the work depends on instance state, classmethods when an alternate constructor or class-level operation is the right shape, and staticmethods when the function only happens to live near a class.\n\n:::program\n```python\nclass Date:\n def __init__(self, year, month, day):\n self.year = year\n self.month = month\n self.day = day\n\n def display(self):\n return f"{self.year}-{self.month:02d}-{self.day:02d}"\n\n @classmethod\n def from_string(cls, text):\n year, month, day = (int(part) for part in text.split("-"))\n return cls(year, month, day)\n\n @staticmethod\n def is_leap_year(year):\n return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)\n\ntoday = Date(2026, 5, 9)\nprint(today.display())\n\nlater = Date.from_string("2026-12-31")\nprint(later.display())\n\nprint(Date.is_leap_year(2024))\nprint(Date.is_leap_year(2025))\n\nclass Demo:\n def instance_method(self):\n return type(self).__name__\n\n @classmethod\n def class_method(cls):\n return cls.__name__\n\n @staticmethod\n def static_method():\n return "no receiver"\n\nprint(Demo().instance_method())\nprint(Demo.class_method())\nprint(Demo.static_method())\n```\n:::\n\n:::cell\nAn instance method receives the instance as `self` and reads its state. This is the default and the right shape when the work depends on a particular object\'s data.\n\n```python\nclass Date:\n def __init__(self, year, month, day):\n self.year = year\n self.month = month\n self.day = day\n\n def display(self):\n return f"{self.year}-{self.month:02d}-{self.day:02d}"\n\ntoday = Date(2026, 5, 9)\nprint(today.display())\n```\n\n```output\n2026-05-09\n```\n:::\n\n:::cell\n`@classmethod` makes the method receive the class itself as `cls`. The canonical use is an alternate constructor that parses some other input format and calls `cls(...)`. Because `cls` is the actual class, subclasses calling the same method get an instance of their own type.\n\n```python\nclass Date:\n def __init__(self, year, month, day):\n self.year = year\n self.month = month\n self.day = day\n\n @classmethod\n def from_string(cls, text):\n year, month, day = (int(part) for part in text.split("-"))\n return cls(year, month, day)\n\nlater = Date.from_string("2026-12-31")\nprint(later.year, later.month, later.day)\n```\n\n```output\n2026 12 31\n```\n:::\n\n:::cell\n`@staticmethod` strips the implicit first argument. The function lives on the class for namespacing — like `Date.is_leap_year(2024)` — but does not touch any instance or class state.\n\n```python\nclass Date:\n @staticmethod\n def is_leap_year(year):\n return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)\n\nprint(Date.is_leap_year(2024))\nprint(Date.is_leap_year(2025))\n```\n\n```output\nTrue\nFalse\n```\n:::\n\n:::cell\nSide by side: instance methods receive the instance, classmethods receive the class, staticmethods receive nothing. Classmethods and staticmethods can be called on either the class or an instance.\n\n```python\nclass Demo:\n def instance_method(self):\n return type(self).__name__\n\n @classmethod\n def class_method(cls):\n return cls.__name__\n\n @staticmethod\n def static_method():\n return "no receiver"\n\nprint(Demo().instance_method())\nprint(Demo.class_method())\nprint(Demo.static_method())\n```\n\n```output\nDemo\nDemo\nno receiver\n```\n:::\n\n:::note\n- Instance methods need an instance; classmethods and staticmethods can be called on the class.\n- Use `@classmethod` for alternate constructors and class-level operations that respect subclassing.\n- Use `@staticmethod` only when a function is truly independent of instance and class state but still belongs in the class\'s namespace.\n- A free function is often the right answer when neither decorator applies.\n:::\n', 'closures.md': '+++\nslug = "closures"\ntitle = "Closures"\nsection = "Functions"\nsummary = "Inner functions can remember values from an enclosing scope."\ndoc_path = "/reference/executionmodel.html#binding-of-names"\nsee_also = [\n "functions",\n "lambdas",\n "decorators",\n "partial-functions",\n]\n+++\n\nA closure is a function that remembers names from the scope where it was created. This lets you configure behavior once and call it later.\n\nEach call to the outer function creates a separate remembered environment. That is why `double` and `triple` can share the same code but keep different factors.\n\nClosures are a foundation for decorators, callbacks, and small function factories.\n\n:::program\n```python\ndef make_multiplier(factor):\n def multiply(value):\n return value * factor\n return multiply\n\ndouble = make_multiplier(2)\nprint(double(5))\n\ntriple = make_multiplier(3)\nprint(triple(5))\n\nlate = []\nfor i in range(3):\n late.append(lambda: i)\nprint([f() for f in late])\n\nbound = []\nfor i in range(3):\n bound.append(lambda i=i: i)\nprint([f() for f in bound])\n```\n:::\n\n:::cell\nDefine a function inside another function when the inner behavior needs to remember setup from the outer call. The returned function keeps access to `factor`.\n\n```python\ndef make_multiplier(factor):\n def multiply(value):\n return value * factor\n return multiply\n\ndouble = make_multiplier(2)\nprint(double(5))\n```\n\n```output\n10\n```\n:::\n\n:::cell\nCalling the outer function again creates a separate closure. `triple` uses the same inner code, but remembers a different `factor`.\n\n```python\ntriple = make_multiplier(3)\nprint(triple(5))\n```\n\n```output\n15\n```\n:::\n\n:::cell\nClosures bind names, not values. Lambdas defined in a loop all reference the same loop variable, so calling them later sees its final value. Capture the value at definition time by binding it as a default argument — `lambda i=i: i` — so each closure remembers its own `i`.\n\n```python\nlate = []\nfor i in range(3):\n late.append(lambda: i)\nprint([f() for f in late])\n\nbound = []\nfor i in range(3):\n bound.append(lambda i=i: i)\nprint([f() for f in bound])\n```\n\n```output\n[2, 2, 2]\n[0, 1, 2]\n```\n:::\n\n:::note\n- A closure keeps access to names from the scope where the inner function was created.\n- Each call to the outer function can create a separate remembered environment.\n- Closures are useful for callbacks, small factories, and decorators.\n- Closures bind names, not values; capture loop variables with `lambda x=x: ...` to freeze them at definition time.\n:::\n', 'collections-module.md': '+++\nslug = "collections-module"\ntitle = "Collections Module"\nsection = "Collections"\nsummary = "collections provides specialized containers for common data shapes."\ndoc_path = "/library/collections.html"\nsee_also = [\n "dicts",\n "lists",\n "tuples",\n "sets",\n]\n+++\n\n`collections` provides specialized containers for common shapes that would otherwise require repetitive plumbing. Use it when the shape has a name: counting, grouping, queueing, or lightweight records.\n\nThese types are not replacements for `list`, `dict`, `tuple`, and `set`. They are small standard-library tools for cases where an ordinary container would hide the intent behind manual bookkeeping.\n\nThe examples below map each type to the question it answers.\n\n:::program\n```python\nfrom collections import Counter, defaultdict, deque, namedtuple\n\ncounts = Counter("banana")\nprint(counts.most_common(2))\n\ngroups = defaultdict(list)\nfor name, team in [("Ada", "red"), ("Grace", "blue"), ("Lin", "red")]:\n groups[team].append(name)\nprint(dict(groups))\n\nqueue = deque(["first"])\nqueue.append("second")\nprint(queue.popleft())\n\nPoint = namedtuple("Point", "x y")\nprint(Point(2, 3).x)\n```\n:::\n\n:::cell\nUse `Counter` when the question is "how many times did each value appear?"\n\n```python\nfrom collections import Counter\n\ncounts = Counter("banana")\nprint(counts.most_common(2))\n```\n\n```output\n[(\'a\', 3), (\'n\', 2)]\n```\n:::\n\n:::cell\nUse `defaultdict(list)` when each key gathers multiple values and the missing-key case should create an empty list automatically.\n\n```python\nfrom collections import defaultdict\n\ngroups = defaultdict(list)\nfor name, team in [("Ada", "red"), ("Grace", "blue"), ("Lin", "red")]:\n groups[team].append(name)\nprint(dict(groups))\n```\n\n```output\n{\'red\': [\'Ada\', \'Lin\'], \'blue\': [\'Grace\']}\n```\n:::\n\n:::cell\nUse `deque` for queue operations at both ends, and `namedtuple` when a tiny immutable record needs names as well as positions.\n\n```python\nfrom collections import deque, namedtuple\n\nqueue = deque(["first"])\nqueue.append("second")\nprint(queue.popleft())\n\nPoint = namedtuple("Point", "x y")\nprint(Point(2, 3).x)\n```\n\n```output\nfirst\n2\n```\n:::\n\n:::note\n- `Counter` counts, `defaultdict` groups, `deque` queues, and `namedtuple` names record fields.\n- Prefer the built-in containers until a specialized shape makes the code clearer.\n- For new structured records with defaults and methods, consider `dataclasses` instead of `namedtuple`.\n:::\n', 'comprehension-patterns.md': '+++\nslug = "comprehension-patterns"\ntitle = "Comprehension Patterns"\nsection = "Collections"\nsummary = "Comprehensions can use multiple for clauses and filters when the shape stays clear."\ndoc_path = "/tutorial/datastructures.html#list-comprehensions"\nsee_also = [\n "comprehensions",\n "generator-expressions",\n "for-loops",\n]\n+++\n\nComprehensions can contain more than one `for` clause and more than one `if` filter. The clauses are read in the same order as nested loops.\n\nUse these forms only while the shape remains easy to scan. If a comprehension starts needing several names, comments, or branches, an explicit loop is usually better.\n\nNested comprehensions build concrete collections immediately, just like simpler list, dict, and set comprehensions.\n\n:::program\n```python\ncolors = ["red", "blue"]\nsizes = ["S", "M"]\nvariants = [(color, size) for color in colors for size in sizes]\nprint(variants)\n\nnumbers = range(10)\nfiltered = [n for n in numbers if n % 2 == 0 if n > 2]\nprint(filtered)\n```\n:::\n\n:::cell\nMultiple `for` clauses behave like nested loops. The leftmost `for` is the outer loop, and the next `for` runs inside it.\n\n```python\ncolors = ["red", "blue"]\nsizes = ["S", "M"]\nvariants = [(color, size) for color in colors for size in sizes]\nprint(variants)\n```\n\n```output\n[(\'red\', \'S\'), (\'red\', \'M\'), (\'blue\', \'S\'), (\'blue\', \'M\')]\n```\n:::\n\n:::cell\nMultiple `if` clauses filter values. They are useful for simple conditions, but an explicit loop is clearer when the rules need names or explanation.\n\n```python\nnumbers = range(10)\nfiltered = [n for n in numbers if n % 2 == 0 if n > 2]\nprint(filtered)\n```\n\n```output\n[4, 6, 8]\n```\n:::\n\n:::note\n- Read comprehension clauses from left to right.\n- Multiple `for` clauses act like nested loops.\n- Prefer an explicit loop when the comprehension stops being obvious.\n:::\n', 'comprehensions.md': '+++\nslug = "comprehensions"\ntitle = "Comprehensions"\nsection = "Collections"\nsummary = "Comprehensions build collections by mapping and filtering iterables."\ndoc_path = "/tutorial/datastructures.html#list-comprehensions"\nsee_also = [\n "for-loops",\n "generator-expressions",\n "comprehension-patterns",\n "lists",\n]\n+++\n\nComprehensions are expression forms for building concrete collections from iterables. Read them from left to right: produce this value, for each item, optionally only when a condition is true.\n\nThey are best for direct transformations where the expression is still easy to scan. When the work needs several statements or names, an explicit loop is usually clearer.\n\nList, dictionary, and set comprehensions are eager: they build collections immediately. Generator expressions use similar syntax to stream values later and are covered in the Iteration section.\n\n:::program\n```python\nnames = ["ada", "guido", "grace"]\ntitled = [name.title() for name in names]\nprint(titled)\n\nscores = {"Ada": 10, "Guido": 8, "Grace": 10}\nhigh_scores = {name: score for name, score in scores.items() if score >= 10}\nprint(high_scores)\n\nunique_scores = {score for score in scores.values()}\nprint(sorted(unique_scores))\n```\n:::\n\n:::cell\nA list comprehension maps each input item to one output item. This one calls `title()` for every name and collects the results in a new list.\n\n```python\nnames = ["ada", "guido", "grace"]\ntitled = [name.title() for name in names]\nprint(titled)\n```\n\n```output\n[\'Ada\', \'Guido\', \'Grace\']\n```\n:::\n\n:::cell\nAdd an `if` clause when only some items should appear. A dictionary comprehension can transform key/value pairs while preserving the dictionary shape.\n\n```python\nscores = {"Ada": 10, "Guido": 8, "Grace": 10}\nhigh_scores = {name: score for name, score in scores.items() if score >= 10}\nprint(high_scores)\n```\n\n```output\n{\'Ada\': 10, \'Grace\': 10}\n```\n:::\n\n:::cell\nA set comprehension keeps only unique results. Here two people have the same score, so the resulting set has two values — printed through `sorted()` because sets have no display order to rely on.\n\n```python\nunique_scores = {score for score in scores.values()}\nprint(sorted(unique_scores))\n```\n\n```output\n[8, 10]\n```\n:::\n\n:::note\n- The left side says what to produce; the `for` clause says where values come from.\n- Use an `if` clause for simple filters.\n- List, dict, and set comprehensions build concrete collections immediately.\n- Switch to a loop when the transformation needs multiple steps or explanations.\n:::\n', 'conditionals.md': '+++\nslug = "conditionals"\ntitle = "Conditionals"\nsection = "Control Flow"\nsummary = "if, elif, and else choose which block runs."\ndoc_path = "/tutorial/controlflow.html#if-statements"\nsee_also = [\n "booleans",\n "truthiness",\n "guard-clauses",\n "match-statements",\n]\n+++\n\n`if`, `elif`, and `else` let a program choose one path based on a condition. Python uses indentation to show which statements belong to each branch.\n\nConditions use Python truthiness: booleans work directly, and many objects such as empty lists or empty strings are considered false. Order branches from most specific to most general.\n\nUse `elif` to keep one decision flat instead of nested. Use Python\'s ternary expression only when you are choosing between two values.\n\n:::program\n```python\ntemperature = 72\n\nif temperature < 60:\n print("cold")\nelif temperature < 80:\n print("comfortable")\nelse:\n print("hot")\n\nitems = ["coat", "hat"]\nif items:\n print(f"packing {len(items)} items")\n\nstatus = "ok" if temperature < 90 else "danger"\nprint(status)\n```\n:::\n\n:::cell\nStart with the value that the branches will test. A conditional is only useful when the branch condition is visible and meaningful.\n\nUse `if`, `elif`, and `else` for one ordered choice. Python tests the branches from top to bottom and runs only the first matching block.\n\n```python\ntemperature = 72\n\nif temperature < 60:\n print("cold")\nelif temperature < 80:\n print("comfortable")\nelse:\n print("hot")\n```\n\n```output\ncomfortable\n```\n:::\n\n:::cell\nTruthiness is part of conditional flow. Empty collections are false, so `if items:` reads as “if there is anything to work with.”\n\n```python\nitems = ["coat", "hat"]\nif items:\n print(f"packing {len(items)} items")\n```\n\n```output\npacking 2 items\n```\n:::\n\n:::cell\nUse the ternary expression when you are choosing a value. If either side needs multiple statements, use a normal `if` block instead.\n\n```python\nstatus = "ok" if temperature < 90 else "danger"\nprint(status)\n```\n\n```output\nok\n```\n:::\n\n:::note\n- Python has no mandatory parentheses around conditions; the colon and indentation define the block.\n- Comparison operators such as `<` and `==` can be chained, as in `0 < value < 10`.\n- Keep branch bodies short; move larger work into functions so the decision remains easy to scan.\n:::\n', 'constants.md': '+++\nslug = "constants"\ntitle = "Constants"\nsection = "Basics"\nsummary = "Python uses naming conventions and optional types for values that should not change."\ndoc_path = "/library/typing.html#typing.Final"\nsee_also = [\n "variables",\n "literal-and-final",\n "type-hints",\n]\n+++\n\nPython has no `const` keyword for ordinary names. Modules use all-caps names such as `MAX_RETRIES` to say “treat this as fixed configuration, not changing state.”\n\nThe interpreter will still let code rebind the name. That is why constants are primarily an API and readability convention. If a project also uses static typing, `Final` can make the convention machine-checkable.\n\nNamed constants remove magic values from code and give repeated literals one place to change.\n\n:::program\n```python\nfrom typing import Final\n\nMAX_RETRIES: Final = 3\nAPI_VERSION = "2026-05"\n\nfor attempt in range(1, MAX_RETRIES + 1):\n print(f"attempt {attempt} of {MAX_RETRIES}")\n\nprint(API_VERSION)\n\nMAX_RETRIES = 5\nprint(MAX_RETRIES)\n```\n:::\n\n:::cell\nAll-caps names communicate design intent: this value is configuration that callers should treat as fixed.\n\n```python\nMAX_RETRIES = 3\n\nfor attempt in range(1, MAX_RETRIES + 1):\n print(f"attempt {attempt} of {MAX_RETRIES}")\n```\n\n```output\nattempt 1 of 3\nattempt 2 of 3\nattempt 3 of 3\n```\n:::\n\n:::cell\nConstants are useful when a repeated literal deserves a name at the domain boundary.\n\n```python\nAPI_VERSION = "2026-05"\nprint(API_VERSION)\n```\n\n```output\n2026-05\n```\n:::\n\n:::cell\n`Final` lets type checkers reject reassignment, but Python still runs ordinary rebinding at runtime.\n\n```python\nfrom typing import Final\n\nMAX_RETRIES: Final = 3\nMAX_RETRIES = 5\nprint(MAX_RETRIES)\n```\n\n```output\n5\n```\n:::\n\n:::note\n- Python constants are a convention, not a runtime lock.\n- Use all-caps names for fixed module-level configuration.\n- Add `Final` when static tooling should flag accidental rebinding.\n:::\n', 'container-protocols.md': '+++\nslug = "container-protocols"\ntitle = "Container Protocols"\nsection = "Data Model"\nsummary = "Container methods connect objects to indexing, membership, and item assignment."\ndoc_path = "/reference/datamodel.html#emulating-container-types"\nsee_also = [\n "lists",\n "dicts",\n "special-methods",\n]\n+++\n\nContainer protocols let a class behave like the collection it represents. Instead of inventing method names such as `has()` or `lookup()`, the object can support `in`, indexing, and assignment.\n\nThe key methods are small and familiar: `__contains__` powers `in`, `__getitem__` powers `obj[key]`, and `__setitem__` powers `obj[key] = value`. Add only the operations the object can honestly support.\n\nThis keeps the public interface aligned with Python\'s built-in containers. Callers can use the same syntax for custom records, caches, tables, and sequence-like objects.\n\n:::program\n```python\nclass Scores:\n def __init__(self):\n self._scores = {}\n\n def __contains__(self, name):\n return name in self._scores\n\n def __getitem__(self, name):\n return self._scores[name]\n\n def __setitem__(self, name, score):\n self._scores[name] = score\n\nscores = Scores()\nscores["Ada"] = 98\nprint("Ada" in scores)\nprint(scores["Ada"])\n```\n:::\n\n:::cell\n`__setitem__` gives assignment syntax to a custom container.\n\n```python\nclass Scores:\n def __init__(self):\n self._scores = {}\n\n def __setitem__(self, name, score):\n self._scores[name] = score\n\nscores = Scores()\nscores["Ada"] = 98\nprint(scores._scores)\n```\n\n```output\n{\'Ada\': 98}\n```\n:::\n\n:::cell\n`__contains__` answers membership tests written with `in`.\n\n```python\nclass Scores:\n def __init__(self):\n self._scores = {"Ada": 98}\n\n def __contains__(self, name):\n return name in self._scores\n\nscores = Scores()\nprint("Ada" in scores)\n```\n\n```output\nTrue\n```\n:::\n\n:::cell\n`__getitem__` connects bracket lookup to your internal storage.\n\n```python\nclass Scores:\n def __init__(self):\n self._scores = {"Ada": 98}\n\n def __getitem__(self, name):\n return self._scores[name]\n\nscores = Scores()\nprint(scores["Ada"])\n```\n\n```output\n98\n```\n:::\n\n:::note\n- Implement the narrowest container protocol your object needs.\n- Use `KeyError` and `IndexError` consistently with built-in containers.\n- If a plain `dict` or `list` is enough, prefer it over a custom container.\n:::\n', 'context-managers.md': '+++\nslug = "context-managers"\ntitle = "Context Managers"\nsection = "Data Model"\nsummary = "with ensures setup and cleanup happen together."\ndoc_path = "/reference/datamodel.html#context-managers"\nsee_also = [\n "exceptions",\n "special-methods",\n "descriptors",\n]\n+++\n\nContext managers define setup and cleanup around a block of code. The `with` statement guarantees that cleanup runs when the block exits, even when an exception is raised.\n\nThe protocol is powered by `__enter__` and `__exit__`. The `contextlib.contextmanager` decorator is a concise way to write the same idea as a generator when a full class would be noisy.\n\nProduction code often uses `with` for files, locks, transactions, temporary state, and resources that need reliable release.\n\n:::program\n```python\nfrom contextlib import contextmanager\n\nclass Tag:\n def __init__(self, name):\n self.name = name\n\n def __enter__(self):\n print(f"<{self.name}>")\n return self\n\n def __exit__(self, exc_type, exc, tb):\n print(f"")\n return False\n\n@contextmanager\ndef tag(name):\n print(f"<{name}>")\n try:\n yield\n finally:\n print(f"")\n\nwith Tag("section"):\n print("content")\n\ntry:\n with tag("error"):\n raise ValueError("boom")\nexcept ValueError:\n print("handled")\n```\n:::\n\n:::cell\nA class-based context manager implements `__enter__` and `__exit__`. The value returned by `__enter__` is bound by `as` when the `with` statement uses it.\n\n```python\nclass Tag:\n def __init__(self, name):\n self.name = name\n\n def __enter__(self):\n print(f"<{self.name}>")\n return self\n\n def __exit__(self, exc_type, exc, tb):\n print(f"")\n return False\n\nwith Tag("section"):\n print("content")\n```\n\n```output\n
    \ncontent\n
    \n```\n:::\n\n:::cell\n`contextlib.contextmanager` writes the same setup/cleanup shape as a generator. Code before `yield` is setup, and code after `yield` is cleanup.\n\n```python\nfrom contextlib import contextmanager\n\n@contextmanager\ndef tag(name):\n print(f"<{name}>")\n try:\n yield\n finally:\n print(f"")\n\nwith tag("note"):\n print("body")\n```\n\n```output\n\nbody\n\n```\n:::\n\n:::cell\nCleanup still runs when the block raises. Returning `False` from `__exit__`, or letting a generator context manager re-raise, allows the exception to keep propagating.\n\n```python\ntry:\n with tag("error"):\n raise ValueError("boom")\nexcept ValueError:\n print("handled")\n```\n\n```output\n\n\nhandled\n```\n:::\n\n:::note\n- Files, locks, and temporary state commonly use context managers.\n- `__enter__` and `__exit__` power the protocol.\n- Use `finally` when cleanup must happen after errors too.\n- Returning true from `__exit__` suppresses an exception; do that only intentionally.\n:::\n', 'copying-collections.md': '+++\nslug = "copying-collections"\ntitle = "Copying Collections"\nsection = "Collections"\nsummary = "Copies can duplicate the outer container while nested objects may still be shared."\ndoc_path = "/library/copy.html"\nsee_also = [\n "mutability",\n "lists",\n "dicts",\n]\n+++\n\nCopying answers two different questions: do you need a new outer container, or do you also need independent nested objects? A plain assignment gives another name for the same object. A shallow copy duplicates only the outer container. `copy.deepcopy()` recursively copies contained objects.\n\nMost Python code wants a shallow copy or a deliberate rebuild. Use a deep copy only when shared nested state would be wrong and the objects involved are safe to duplicate.\n\nThe outputs below show the footgun directly: a shallow copy has a different outer list, but its inner lists are still the same objects.\n\n:::program\n```python\nimport copy\n\nrows = [["Ada"], ["Grace"]]\nalias = rows\nshallow = rows.copy()\ndeep = copy.deepcopy(rows)\n\nrows[0].append("Lovelace")\n\nprint(alias is rows)\nprint(shallow is rows)\nprint(rows[0] is shallow[0])\nprint(rows[0] is deep[0])\nprint(shallow)\nprint(deep)\n```\n:::\n\n:::cell\nAssignment does not copy a collection. It gives the same list another name.\n\n```python\nrows = [["Ada"], ["Grace"]]\nalias = rows\n\nprint(alias is rows)\n```\n\n```output\nTrue\n```\n:::\n\n:::cell\nA shallow copy creates a new outer list, but nested lists are still shared.\n\n```python\nshallow = rows.copy()\nrows[0].append("Lovelace")\n\nprint(shallow is rows)\nprint(rows[0] is shallow[0])\nprint(shallow)\n```\n\n```output\nFalse\nTrue\n[[\'Ada\', \'Lovelace\'], [\'Grace\']]\n```\n:::\n\n:::cell\nA deep copy is independent at the nested level, so later mutation of `rows[0]` does not appear in `deep`.\n\n```python\nimport copy\n\nrows = [["Ada"], ["Grace"]]\ndeep = copy.deepcopy(rows)\nrows[0].append("Lovelace")\n\nprint(rows[0] is deep[0])\nprint(deep)\n```\n\n```output\nFalse\n[[\'Ada\'], [\'Grace\']]\n```\n:::\n\n:::note\n- Assignment aliases; it does not copy.\n- Shallow copies duplicate the outer container only.\n- Deep copies are useful for nested independence, but they can be expensive and surprising for objects with external resources.\n:::\n', 'csv-data.md': '+++\nslug = "csv-data"\ntitle = "CSV Data"\nsection = "Standard Library"\nsummary = "csv reads and writes row-shaped text data."\ndoc_path = "/library/csv.html"\nsee_also = [\n "strings",\n "dicts",\n "json",\n]\n+++\n\nCSV is row-shaped text: each line is a record, and each comma-separated field arrives as a string. The `csv` module understands quoting, delimiters, and newlines, so it is safer than splitting lines by comma yourself.\n\nUse `DictReader` when a header row names the columns. Convert fields explicitly after reading, and use `DictWriter` when the program needs to produce the same row shape again.\n\nCSV is a good fit for flat tabular data. Use JSON or another structured format when values are nested or when types need to survive the text boundary.\n\n:::program\n```python\nimport csv\nimport io\n\ntext = "name,score\\nAda,98\\nGrace,95\\n"\nrows = list(csv.DictReader(io.StringIO(text)))\nprint(rows[0])\nprint(sum(int(row["score"]) for row in rows))\n\noutput = io.StringIO(newline="")\nwriter = csv.DictWriter(output, fieldnames=["name", "passed"])\nwriter.writeheader()\nwriter.writerow({"name": "Ada", "passed": True})\nprint(output.getvalue().splitlines()[1])\n```\n:::\n\n:::cell\n`DictReader` uses the header row as dictionary keys. The values are still strings because CSV is text.\n\n```python\nimport csv\nimport io\n\ntext = "name,score\\nAda,98\\nGrace,95\\n"\nrows = list(csv.DictReader(io.StringIO(text)))\n\nprint(rows[0])\nprint(type(rows[0]["score"]).__name__)\n```\n\n```output\n{\'name\': \'Ada\', \'score\': \'98\'}\nstr\n```\n:::\n\n:::cell\nConvert numeric fields at the boundary where the program leaves CSV text and starts doing arithmetic.\n\n```python\nprint(sum(int(row["score"]) for row in rows))\n```\n\n```output\n193\n```\n:::\n\n:::cell\n`DictWriter` turns dictionaries back into row-shaped text with the same column order.\n\n```python\noutput = io.StringIO(newline="")\nwriter = csv.DictWriter(output, fieldnames=["name", "passed"])\nwriter.writeheader()\nwriter.writerow({"name": "Ada", "passed": True})\n\nprint(output.getvalue().splitlines()[1])\n```\n\n```output\nAda,True\n```\n:::\n\n:::note\n- Let `csv` handle quoting and delimiters instead of calling `split(",")`.\n- CSV fields are text until your code converts them.\n- Reach for JSON when records need nested lists, dictionaries, booleans, or numbers that preserve their type.\n:::\n', 'custom-exceptions.md': '+++\nslug = "custom-exceptions"\ntitle = "Custom Exceptions"\nsection = "Errors"\nsummary = "Custom exception classes name failures that belong to your domain."\ndoc_path = "/tutorial/errors.html#user-defined-exceptions"\nsee_also = [\n "exceptions",\n "exception-chaining",\n "warnings",\n "logging",\n]\n+++\n\nCustom exceptions give names to failures in your problem domain. A named exception is easier to catch and explain than a generic error with only a string message.\n\nRaise the custom exception at the point where the invalid state is discovered. Include a message for the specific occurrence.\n\nCatch custom exceptions at the boundary where recovery makes sense, such as returning an error response or asking for corrected input.\n\n:::program\n```python\nclass EmptyCartError(Exception):\n pass\n\nprint(EmptyCartError.__name__)\n\n\ndef checkout(items):\n if not items:\n raise EmptyCartError("cart is empty")\n return "paid"\n\nprint(checkout(["book"]))\n\ntry:\n checkout([])\nexcept EmptyCartError as error:\n print(error)\n```\n:::\n\n:::cell\nCreate a custom exception when a failure has a name in your problem domain. The class can be empty at first.\n\n```python\nclass EmptyCartError(Exception):\n pass\n\nprint(EmptyCartError.__name__)\n```\n\n```output\nEmptyCartError\n```\n:::\n\n:::cell\nRaise the custom exception where the invalid state is detected. Normal inputs still follow the ordinary success path.\n\n```python\ndef checkout(items):\n if not items:\n raise EmptyCartError("cart is empty")\n return "paid"\n\nprint(checkout(["book"]))\n```\n\n```output\npaid\n```\n:::\n\n:::cell\nCallers can catch the precise error type without accidentally catching unrelated failures.\n\n```python\ntry:\n checkout([])\nexcept EmptyCartError as error:\n print(error)\n```\n\n```output\ncart is empty\n```\n:::\n\n:::note\n- Subclass `Exception` for errors callers are expected to catch.\n- A custom exception name can be clearer than reusing a generic `ValueError` everywhere.\n- Catch custom exceptions at a boundary that can recover or report clearly.\n:::\n', 'dataclasses.md': '+++\nslug = "dataclasses"\ntitle = "Dataclasses"\nsection = "Classes"\nsummary = "dataclass generates common class methods for data containers."\ndoc_path = "/library/dataclasses.html"\nsee_also = [\n "structured-data-shapes",\n "classes",\n "type-hints",\n]\n+++\n\n`dataclass` is a standard-library decorator for classes that mainly store data. It generates methods such as `__init__` and `__repr__` from type-annotated fields.\n\nDataclasses reduce boilerplate while keeping classes explicit. They are a good fit for simple records, configuration objects, and values passed between layers.\n\nType annotations define fields. Defaults work like normal class attributes and appear in the generated initializer.\n\n:::program\n```python\nfrom dataclasses import dataclass\n\n@dataclass\nclass User:\n name: str\n active: bool = True\n\nuser = User("Ada")\nprint(user)\nprint(user.name)\n\ninactive = User("Guido", active=False)\nprint(inactive)\nprint(inactive.active)\n```\n:::\n\n:::cell\nA dataclass uses annotations to define fields. Python generates an initializer, so the class can be constructed without writing `__init__` by hand.\n\n```python\nfrom dataclasses import dataclass\n\n@dataclass\nclass User:\n name: str\n active: bool = True\n\nuser = User("Ada")\nprint(user)\n```\n\n```output\nUser(name=\'Ada\', active=True)\n```\n:::\n\n:::cell\nThe generated instance still exposes ordinary attributes. A dataclass is a regular class with useful methods filled in.\n\n```python\nprint(user.name)\n```\n\n```output\nAda\n```\n:::\n\n:::cell\nDefaults can be overridden by keyword. The generated representation includes the field names, which is useful during debugging.\n\n```python\ninactive = User("Guido", active=False)\nprint(inactive)\nprint(inactive.active)\n```\n\n```output\nUser(name=\'Guido\', active=False)\nFalse\n```\n:::\n\n:::note\n- Type annotations define dataclass fields.\n- Dataclasses generate methods but remain normal Python classes.\n- Use `field()` for advanced defaults such as per-instance lists or dictionaries.\n:::\n', 'datetime.md': '+++\nslug = "datetime"\ntitle = "Dates and Times"\nsection = "Standard Library"\nsummary = "datetime represents dates, times, durations, formatting, and parsing."\ndoc_path = "/library/datetime.html"\nsee_also = [\n "string-formatting",\n "json",\n "number-parsing",\n]\n+++\n\nThe `datetime` module covers several related ideas: `date` for calendar days, `time` for clock times, `datetime` for both together, and `timedelta` for durations.\n\nTimezone-aware datetimes avoid ambiguity in real systems. `timezone.utc` is a clear default for examples because output stays stable and portable.\n\nUse ISO formatting for interchange, `strftime()` for display, and parsing helpers such as `fromisoformat()` to turn text back into datetime objects.\n\n:::program\n```python\nfrom datetime import date, datetime, time, timedelta, timezone\n\nrelease_day = date(2026, 5, 4)\nmeeting_time = time(12, 30)\ncreated_at = datetime.combine(release_day, meeting_time, tzinfo=timezone.utc)\n\nprint(release_day.isoformat())\nprint(meeting_time.isoformat())\nprint(created_at.isoformat())\n\nexpires_at = created_at + timedelta(days=7, hours=2)\nprint(expires_at.isoformat())\n\nprint(created_at.strftime("%Y-%m-%d %H:%M %Z"))\niso_text = "2026-05-04T12:30:00+00:00"\nparsed = datetime.fromisoformat(iso_text)\nprint(parsed == created_at)\n```\n:::\n\n:::cell\nThe `datetime` module separates calendar dates, clock times, combined datetimes, and durations. Import the types you need explicitly.\n\nUse `date` for a calendar day and `time` for a time of day. Combine them into a timezone-aware `datetime` when you mean an instant.\n\n`isoformat()` produces stable machine-readable text. It is a good default for examples, APIs, and logs.\n\n```python\nfrom datetime import date, datetime, time, timedelta, timezone\n\nrelease_day = date(2026, 5, 4)\nmeeting_time = time(12, 30)\ncreated_at = datetime.combine(release_day, meeting_time, tzinfo=timezone.utc)\n\nprint(release_day.isoformat())\nprint(meeting_time.isoformat())\nprint(created_at.isoformat())\n```\n\n```output\n2026-05-04\n12:30:00\n2026-05-04T12:30:00+00:00\n```\n:::\n\n:::cell\nUse `timedelta` for durations. Adding one to a `datetime` produces another `datetime` without manually changing calendar fields.\n\n```python\nexpires_at = created_at + timedelta(days=7, hours=2)\nprint(expires_at.isoformat())\n```\n\n```output\n2026-05-11T14:30:00+00:00\n```\n:::\n\n:::cell\nUse `strftime()` for human-facing formatting and `fromisoformat()` when reading ISO 8601 text back into a `datetime`.\n\n```python\nprint(created_at.strftime("%Y-%m-%d %H:%M %Z"))\niso_text = "2026-05-04T12:30:00+00:00"\nparsed = datetime.fromisoformat(iso_text)\nprint(parsed == created_at)\n```\n\n```output\n2026-05-04 12:30 UTC\nTrue\n```\n:::\n\n:::note\n- Use timezone-aware datetimes for instants that cross system or user boundaries.\n- Use `date` for calendar days, `time` for clock times, `datetime` for both, and `timedelta` for durations.\n- Prefer ISO 8601 strings for interchange; use `strftime` for human-facing display.\n:::\n', 'decorators.md': '+++\nslug = "decorators"\ntitle = "Decorators"\nsection = "Functions"\nsummary = "Decorators wrap or register functions using @ syntax."\ndoc_path = "/glossary.html#term-decorator"\nsee_also = [\n "closures",\n "functions",\n "callable-types",\n "classmethods-and-staticmethods",\n]\n+++\n\nA decorator is a callable that receives a function and returns a replacement. The `@` syntax applies that transformation at function definition time.\n\nDecorators are common in frameworks because they can register handlers or add behavior while keeping the decorated function focused on the core action.\n\n`@decorator` is shorthand for rebinding a function to the decorator\'s return value. Production wrappers usually use `functools.wraps` so debugging, help text, and framework introspection still see the original function metadata.\n\n:::program\n```python\nfrom functools import wraps\n\n\ndef loud(func):\n @wraps(func)\n def wrapper(name):\n return func(name).upper()\n return wrapper\n\n\ndef greet(name):\n return f"hello {name}"\n\nmanual_greet = loud(greet)\nprint(manual_greet("python"))\n\n@loud\ndef welcome(name):\n """Return a welcome message."""\n return f"welcome {name}"\n\nprint(welcome("workers"))\nprint(welcome.__name__)\nprint(welcome.__doc__)\n```\n:::\n\n:::cell\nA decorator is just a function that takes a function and returns another callable. Applying it manually shows the wrapping step.\n\n```python\nfrom functools import wraps\n\n\ndef loud(func):\n @wraps(func)\n def wrapper(name):\n return func(name).upper()\n return wrapper\n\n\ndef greet(name):\n return f"hello {name}"\n\nmanual_greet = loud(greet)\nprint(manual_greet("python"))\n```\n\n```output\nHELLO PYTHON\n```\n:::\n\n:::cell\nThe `@loud` syntax performs the same rebinding at definition time. After decoration, `welcome` refers to the wrapper returned by `loud`.\n\n```python\n@loud\ndef welcome(name):\n """Return a welcome message."""\n return f"welcome {name}"\n\nprint(welcome("workers"))\n```\n\n```output\nWELCOME WORKERS\n```\n:::\n\n:::cell\n`functools.wraps` copies useful metadata from the original function onto the wrapper.\n\n```python\nprint(welcome.__name__)\nprint(welcome.__doc__)\n```\n\n```output\nwelcome\nReturn a welcome message.\n```\n:::\n\n:::note\n- `@decorator` is shorthand for assigning `func = decorator(func)`.\n- Decorators can wrap, replace, or register functions.\n- Use `functools.wraps` in production wrappers that should preserve metadata.\n:::\n', 'delete-statements.md': '+++\nslug = "delete-statements"\ntitle = "Delete Statements"\nsection = "Data Model"\nsummary = "del removes bindings, items, and attributes rather than producing a value."\ndoc_path = "/reference/simple_stmts.html#the-del-statement"\nsee_also = [\n "variables",\n "dicts",\n "mutability",\n]\n+++\n\n`del` removes a binding or an item. It is a statement, not a function, and it does not return the removed value.\n\nUse `del name` when a name should no longer be bound. Use `del mapping[key]` or `del sequence[index]` when mutating a container by removing one part.\n\nThis is different from assigning `None`: `None` is still a value, while `del` removes the binding or slot.\n\n:::program\n```python\nprofile = {"name": "Ada", "temporary": True}\ndel profile["temporary"]\nprint(profile)\n\nitems = ["a", "b", "c"]\ndel items[1]\nprint(items)\n\nvalue = "cached"\ndel value\nprint("value" in locals())\n```\n:::\n\n:::cell\nDeleting a dictionary key mutates the dictionary. The key is gone; it has not been set to `None`.\n\n```python\nprofile = {"name": "Ada", "temporary": True}\ndel profile["temporary"]\nprint(profile)\n```\n\n```output\n{\'name\': \'Ada\'}\n```\n:::\n\n:::cell\nDeleting a list item removes that position and shifts later items left.\n\n```python\nitems = ["a", "b", "c"]\ndel items[1]\nprint(items)\n```\n\n```output\n[\'a\', \'c\']\n```\n:::\n\n:::cell\nDeleting a name removes the binding from the current namespace. It is different from rebinding the name to `None`.\n\n```python\nvalue = "cached"\ndel value\nprint("value" in locals())\n```\n\n```output\nFalse\n```\n:::\n\n:::note\n- `del` removes bindings or container entries.\n- Assign `None` when absence should remain an explicit value.\n- Use container methods such as `pop()` when you need the removed value back.\n:::\n', 'descriptors.md': '+++\nslug = "descriptors"\ntitle = "Descriptors"\nsection = "Data Model"\nsummary = "Descriptors customize attribute access through __get__, __set__, or __delete__."\ndoc_path = "/howto/descriptor.html"\nsee_also = [\n "attribute-access",\n "properties",\n "bound-and-unbound-methods",\n]\n+++\n\nA descriptor is an object stored on a class that defines `__get__`, `__set__`, or `__delete__`. When an instance attribute lookup finds that object on the class, Python calls the descriptor method instead of returning the descriptor object directly.\n\nDescriptors are the machinery behind methods, `property`, validators, and many ORM fields. Use them when one reusable object should control access for many attributes or classes; use `property` for a single simple managed attribute.\n\nThis example implements a positive-number validator. `__set_name__` learns the attribute name when the owner class is created, `__set__` validates writes, and `__get__` reads the stored value back from the instance.\n\n:::program\n```python\nclass Positive:\n def __set_name__(self, owner, name):\n self.private_name = "_" + name\n\n def __get__(self, obj, owner):\n if obj is None:\n return self\n return getattr(obj, self.private_name)\n\n def __set__(self, obj, value):\n if value <= 0:\n raise ValueError("must be positive")\n setattr(obj, self.private_name, value)\n\nclass Product:\n price = Positive()\n\n def __init__(self, price):\n self.price = price\n\nitem = Product(10)\nprint(item.price)\nprint(Product.price.private_name)\ntry:\n item.price = -1\nexcept ValueError as error:\n print(error)\n```\n:::\n\n:::cell\nA descriptor object lives on the class. `__set_name__` lets it learn which managed attribute it is serving.\n\n```python\nclass Positive:\n def __set_name__(self, owner, name):\n self.private_name = "_" + name\n\n def __get__(self, obj, owner):\n if obj is None:\n return self\n return getattr(obj, self.private_name)\n\n def __set__(self, obj, value):\n if value <= 0:\n raise ValueError("must be positive")\n setattr(obj, self.private_name, value)\n\nclass Product:\n price = Positive()\n\nprint(Product.price.private_name)\n```\n\n```output\n_price\n```\n:::\n\n:::cell\nAssigning `item.price` calls `Positive.__set__`, and reading it calls `Positive.__get__`.\n\n```python\nclass Product:\n price = Positive()\n\n def __init__(self, price):\n self.price = price\n\nitem = Product(10)\nprint(item.price)\ntry:\n item.price = -1\nexcept ValueError as error:\n print(error)\n```\n\n```output\n10\nmust be positive\n```\n:::\n\n:::note\n- Descriptors are class attributes that participate in instance attribute access.\n- Data descriptors with `__set__` can validate or transform assignments.\n- `property` is usually simpler for one-off managed attributes; descriptors shine when the behavior is reusable.\n:::\n', 'dicts.md': '+++\nslug = "dicts"\ntitle = "Dictionaries"\nsection = "Collections"\nsummary = "Dictionaries map keys to values for records, lookup, and structured data."\ndoc_path = "/tutorial/datastructures.html#dictionaries"\nsee_also = [\n "lists",\n "sets",\n "typed-dicts",\n "json",\n]\n+++\n\nDictionaries are Python\'s built-in mapping type. They exist for data where names or keys are more meaningful than numeric positions: records, lookup tables, counters, and JSON-like payloads.\n\nUse direct indexing when a key is required. Use `get()` when absence is expected and the code has a reasonable fallback.\n\nUnlike lists, dictionaries answer “what value belongs to this key?” rather than “what value is at this position?” Iterating with `items()` keeps each key next to its value.\n\n:::program\n```python\nprofile = {"name": "Ada", "language": "Python"}\nprofile["year"] = 1843\nprint(profile["name"])\nprint(profile.get("timezone", "UTC"))\n\nscores = {"Ada": 10, "Grace": 9}\nprint(scores["Grace"])\nprint(scores.get("Guido", 0))\n\nfor name, score in scores.items():\n print(f"{name}: {score}")\n\ninventory = {"apple": 0, "pear": 3, "plum": 0}\nfor name in list(inventory.keys()):\n if inventory[name] == 0:\n del inventory[name]\nprint(inventory)\n```\n:::\n\n:::cell\nUse a dictionary as a small record when fields have names. Direct indexing communicates that the key is required, while `get()` communicates that a missing key has a fallback.\n\n```python\nprofile = {"name": "Ada", "language": "Python"}\nprofile["year"] = 1843\nprint(profile["name"])\nprint(profile.get("timezone", "UTC"))\n```\n\n```output\nAda\nUTC\n```\n:::\n\n:::cell\nUse a dictionary as a lookup table when keys identify values. This is different from a list, where numeric position is the lookup key.\n\n```python\nscores = {"Ada": 10, "Grace": 9}\nprint(scores["Grace"])\nprint(scores.get("Guido", 0))\n```\n\n```output\n9\n0\n```\n:::\n\n:::cell\nUse `items()` when the loop needs both keys and values. It avoids looping over keys and then indexing back into the dictionary.\n\n```python\nfor name, score in scores.items():\n print(f"{name}: {score}")\n```\n\n```output\nAda: 10\nGrace: 9\n```\n:::\n\n:::cell\nAdding or removing keys while iterating a dictionary raises `RuntimeError` ("dictionary changed size during iteration"); reassigning an existing key\'s value is allowed. Snapshot the keys with `list(d.keys())` (or build a list of changes and apply them after the loop) so deletions see a stable view.\n\n```python\ninventory = {"apple": 0, "pear": 3, "plum": 0}\nfor name in list(inventory.keys()):\n if inventory[name] == 0:\n del inventory[name]\nprint(inventory)\n```\n\n```output\n{\'pear\': 3}\n```\n:::\n\n:::note\n- Dictionaries preserve insertion order in modern Python.\n- Use `get()` when a missing key has a reasonable default.\n- Use direct indexing when a missing key should be treated as an error.\n- Snapshot keys with `list(d.keys())` before deleting items in a loop; adding or removing keys during iteration raises `RuntimeError`.\n:::\n', 'enums.md': '+++\nslug = "enums"\ntitle = "Enums"\nsection = "Types"\nsummary = "Enum defines symbolic names for a fixed set of values."\ndoc_path = "/library/enum.html"\nsee_also = [\n "literals",\n "classes",\n "literal-and-final",\n]\n+++\n\n`Enum` defines a fixed set of named values. This makes states and modes easier to read than raw strings scattered through a program.\n\nEach enum member has a name and a value. Comparing enum members is explicit and helps avoid typos that plain strings would allow.\n\nUse enums when a value must be one of a small known set: statuses, modes, directions, roles, and similar choices.\n\n:::program\n```python\nfrom enum import Enum\n\nclass Status(Enum):\n PENDING = "pending"\n DONE = "done"\n\ncurrent = Status.PENDING\nprint(current.name)\nprint(current.value)\nprint(current is Status.PENDING)\nprint(current == "pending")\n```\n:::\n\n:::cell\nAn enum member has a symbolic name and an underlying value. The symbolic name is what readers usually care about in code.\n\n```python\nfrom enum import Enum\n\nclass Status(Enum):\n PENDING = "pending"\n DONE = "done"\n\ncurrent = Status.PENDING\nprint(current.name)\nprint(current.value)\n```\n\n```output\nPENDING\npending\n```\n:::\n\n:::cell\nCompare enum members with enum members, not with raw strings. This keeps the set of valid states explicit.\n\n```python\nprint(current is Status.PENDING)\nprint(current == "pending")\n```\n\n```output\nTrue\nFalse\n```\n:::\n\n:::note\n- Enums make states and choices explicit.\n- Members have names and values.\n- Comparing enum members avoids string typo bugs.\n- Prefer raw strings for open-ended text; prefer enums for a closed set of named choices.\n:::\n', 'equality-and-identity.md': '+++\nslug = "equality-and-identity"\ntitle = "Equality and Identity"\nsection = "Data Model"\nsummary = "== compares values, while is compares object identity."\ndoc_path = "/reference/expressions.html#is-not"\nsee_also = [\n "none",\n "values",\n "object-lifecycle",\n "mutability",\n]\n+++\n\nPython separates equality from identity. Equality asks whether two objects should be considered the same value, while identity asks whether two names point to the same object.\n\nThis distinction matters for mutable containers because two equal lists can still be independent objects. Mutating one should not imply mutating the other unless they share identity.\n\nThe `is` operator is best reserved for identity checks against singletons such as `None`. For ordinary values, `==` is the comparison readers expect.\n\n:::program\n```python\nleft = [1, 2, 3]\nright = [1, 2, 3]\nprint(left == right)\nprint(left is right)\n\nsame = left\nsame.append(4)\nprint(left)\nprint(same is left)\n\nvalue = None\nprint(value is None)\n\nsmall_a = 100\nsmall_b = 100\nprint(small_a is small_b)\n\nbig_a = int("1000")\nbig_b = int("1000")\nprint(big_a is big_b)\nprint(big_a == big_b)\n```\n:::\n\n:::cell\nEqual containers can be different objects. `==` compares list contents, while `is` checks whether both names refer to the same list object.\n\n```python\nleft = [1, 2, 3]\nright = [1, 2, 3]\nprint(left == right)\nprint(left is right)\n```\n\n```output\nTrue\nFalse\n```\n:::\n\n:::cell\nIdentity matters when objects are mutable. `same` is another name for `left`, so mutating through one name changes the object seen through the other.\n\n```python\nsame = left\nsame.append(4)\nprint(left)\nprint(same is left)\n```\n\n```output\n[1, 2, 3, 4]\nTrue\n```\n:::\n\n:::cell\nUse `is` for singleton identity checks such as `None`. This asks whether the value is the one special `None` object.\n\n```python\nvalue = None\nprint(value is None)\n```\n\n```output\nTrue\n```\n:::\n\n:::cell\n`is` for integers is unreliable because CPython caches small integers (roughly `-5` to `256`) but not larger ones. Two equal large integers can be different objects. Use `==` for value comparisons; reserve `is` for singletons.\n\n```python\nsmall_a = 100\nsmall_b = 100\nprint(small_a is small_b)\n\nbig_a = int("1000")\nbig_b = int("1000")\nprint(big_a is big_b)\nprint(big_a == big_b)\n```\n\n```output\nTrue\nFalse\nTrue\n```\n:::\n\n:::note\n- Use `==` for ordinary value comparisons.\n- Use `is` primarily for identity checks against singletons such as `None`.\n- Equal mutable containers can still be independent objects.\n- Never use `is` to compare numbers; CPython\'s small-integer cache makes the result an implementation detail.\n:::\n', 'exception-chaining.md': '+++\nslug = "exception-chaining"\ntitle = "Exception Chaining"\nsection = "Errors"\nsummary = "raise from preserves the original cause when translating exceptions."\ndoc_path = "/tutorial/errors.html#exception-chaining"\nsee_also = [\n "exceptions",\n "custom-exceptions",\n "assertions",\n]\n+++\n\nException chaining connects a higher-level error to the lower-level exception that caused it. The syntax is `raise NewError(...) from error`.\n\nUse chaining when translating implementation details into a domain-specific error while preserving the original cause for debugging.\n\nThis is different from hiding the original exception. The caller can catch the domain error, and tooling can still inspect `__cause__`.\n\n:::program\n```python\nclass ConfigError(Exception):\n pass\n\n\ndef read_port(text):\n try:\n return int(text)\n except ValueError as error:\n raise ConfigError("port must be a number") from error\n\nprint(ConfigError.__name__)\n\ntry:\n read_port("abc")\nexcept ConfigError as error:\n print(error)\n print(type(error.__cause__).__name__)\n```\n:::\n\n:::cell\nCatch the low-level exception where it happens, then raise a domain-specific exception from it.\n\n```python\nclass ConfigError(Exception):\n pass\n\n\ndef read_port(text):\n try:\n return int(text)\n except ValueError as error:\n raise ConfigError("port must be a number") from error\n\nprint(ConfigError.__name__)\n```\n\n```output\nConfigError\n```\n:::\n\n:::cell\nThe caller handles the domain error. The original `ValueError` remains available as `__cause__`.\n\n```python\ntry:\n read_port("abc")\nexcept ConfigError as error:\n print(error)\n print(type(error.__cause__).__name__)\n```\n\n```output\nport must be a number\nValueError\n```\n:::\n\n:::note\n- Use `raise ... from error` when translating exceptions across a boundary.\n- The new exception\'s `__cause__` points to the original exception.\n- Chaining keeps user-facing errors clear without losing debugging context.\n:::\n', 'exception-groups.md': '+++\nslug = "exception-groups"\ntitle = "Exception Groups"\nsection = "Errors"\nsummary = "except* handles matching exceptions inside an ExceptionGroup."\ndoc_path = "/tutorial/errors.html#raising-and-handling-multiple-unrelated-exceptions"\nsee_also = [\n "exceptions",\n "exception-chaining",\n "async-await",\n]\n+++\n\n`ExceptionGroup` represents several unrelated exceptions raised together. `except*` exists for code that may receive multiple failures at once, especially concurrent work.\n\nUse ordinary `except` for one exception. Use `except*` only when the value being handled is an exception group and each matching subgroup needs its own handling.\n\nEach `except*` clause receives a smaller exception group containing the matching exceptions.\n\n:::program\n```python\nerrors = ExceptionGroup(\n "batch failed",\n [ValueError("bad port"), TypeError("bad mode")],\n)\nprint(len(errors.exceptions))\n\ntry:\n raise errors\nexcept* ValueError as group:\n print(type(group).__name__)\n print(group.exceptions[0])\nexcept* TypeError as group:\n print(group.exceptions[0])\n```\n:::\n\n:::cell\nAn exception group bundles several exception objects. This is different from an ordinary exception because more than one failure is present.\n\n```python\nerrors = ExceptionGroup(\n "batch failed",\n [ValueError("bad port"), TypeError("bad mode")],\n)\nprint(len(errors.exceptions))\n```\n\n```output\n2\n```\n:::\n\n:::cell\n`except*` handles matching members of the group. The `ValueError` handler sees the value error, and the `TypeError` handler sees the type error.\n\n```python\ntry:\n raise errors\nexcept* ValueError as group:\n print(type(group).__name__)\n print(group.exceptions[0])\nexcept* TypeError as group:\n print(group.exceptions[0])\n```\n\n```output\nExceptionGroup\nbad port\nbad mode\n```\n:::\n\n:::note\n- `except*` is for `ExceptionGroup`, not ordinary single exceptions.\n- Each `except*` clause handles matching members of the group.\n- Exception groups often appear around concurrent work.\n:::\n', 'exceptions.md': '+++\nslug = "exceptions"\ntitle = "Exceptions"\nsection = "Errors"\nsummary = "Use try, except, else, and finally to separate success, recovery, and cleanup."\ndoc_path = "/tutorial/errors.html"\nsee_also = [\n "conditionals",\n "guard-clauses",\n "custom-exceptions",\n "warnings",\n]\n+++\n\nExceptions represent errors or unusual conditions that interrupt normal control flow. `try` marks the operation that may fail, and `except` handles a specific failure where recovery makes sense.\n\nKeep the successful path separate from the recovery path. `else` runs only when no exception was raised, while `finally` runs either way for cleanup or bookkeeping.\n\nUse exceptions when an operation cannot produce a valid result. Prefer ordinary conditionals for expected branches that are not errors.\n\nCatch specific exceptions whenever possible. A broad catch can hide programming mistakes, while a targeted `ValueError` handler documents exactly what failure is expected.\n\n:::program\n```python\ndef parse_int(text):\n return int(text)\n\nfor text in ["42", "python"]:\n try:\n number = parse_int(text)\n except ValueError:\n print(f"{text}: invalid")\n else:\n print(f"{text}: {number}")\n finally:\n print(f"checked {text}")\n\n\ndef safe_parse_broken(text):\n try:\n return int(text)\n except Exception:\n return None\n\ndef safe_parse_fixed(text):\n try:\n return int(text)\n except ValueError:\n return None\n\nprint(safe_parse_broken("42"))\nprint(safe_parse_fixed("42"))\nprint(safe_parse_broken(["4", "2"]))\n\ntry:\n safe_parse_fixed(["4", "2"])\nexcept TypeError as error:\n print(type(error).__name__)\n```\n:::\n\n:::cell\nWhen no exception is raised, the `else` block runs. Keeping success in `else` makes the `try` block contain only the operation that might fail.\n\n```python\ndef parse_int(text):\n return int(text)\n\ntext = "42"\ntry:\n number = parse_int(text)\nexcept ValueError:\n print(f"{text}: invalid")\nelse:\n print(f"{text}: {number}")\nfinally:\n print(f"checked {text}")\n```\n\n```output\n42: 42\nchecked 42\n```\n:::\n\n:::cell\nWhen parsing fails, `int()` raises `ValueError`. Catching that specific exception makes the expected recovery path explicit.\n\n```python\ntext = "python"\ntry:\n number = parse_int(text)\nexcept ValueError:\n print(f"{text}: invalid")\nelse:\n print(f"{text}: {number}")\nfinally:\n print(f"checked {text}")\n```\n\n```output\npython: invalid\nchecked python\n```\n:::\n\n:::cell\nBare `except:` and broad `except Exception:` swallow far more than the failure you meant to handle, including `KeyboardInterrupt` (bare) and most programming bugs (broad). The two functions look interchangeable on good input — the divergence appears on a buggy call: passing a list is a programming error, yet the broad version converts it into a quiet `None` while the specific version lets the `TypeError` surface.\n\n```python\ndef safe_parse_broken(text):\n try:\n return int(text)\n except Exception:\n return None\n\ndef safe_parse_fixed(text):\n try:\n return int(text)\n except ValueError:\n return None\n\nprint(safe_parse_broken("42"))\nprint(safe_parse_fixed("42"))\nprint(safe_parse_broken(["4", "2"]))\n\ntry:\n safe_parse_fixed(["4", "2"])\nexcept TypeError as error:\n print(type(error).__name__)\n```\n\n```output\n42\n42\nNone\nTypeError\n```\n:::\n\n:::note\n- Catch the most specific exception you can.\n- `else` is for success code that should run only if the `try` block did not fail.\n- `finally` runs whether the operation succeeded or failed.\n- Avoid bare `except:` and broad `except Exception:` — they hide bugs and absorb signals like `KeyboardInterrupt`.\n:::\n', 'for-loops.md': '+++\nslug = "for-loops"\ntitle = "For Loops"\nsection = "Control Flow"\nsummary = "for iterates over values produced by an iterable."\ndoc_path = "/tutorial/controlflow.html#for-statements"\nsee_also = [\n "while-loops",\n "iterating-over-iterables",\n "iterators",\n]\n+++\n\nA `for` loop asks an iterable for values and runs the indented block once per value. Python\'s loop is not primarily a numeric counter; it is a consumer of lists, ranges, files, generators, and any object that implements the iterator protocol.\n\nPrefer direct iteration when you need each value. Use `range()` when the numbers themselves are the data, and use `enumerate()` when the position and the value both matter.\n\nThe loop body is the indented block. When the iterable is exhausted, execution continues after the block. The neighboring `while` loop shape is for conditions that must be rechecked manually.\n\n:::program\n```python\nfor name in ["Ada", "Grace", "Guido"]:\n print(name)\n\nfor number in range(3):\n print(number)\n\nfor index, name in enumerate(["Ada", "Grace"], start=1):\n print(index, name)\n```\n:::\n\n:::cell\nDirect iteration keeps the code focused on the values in the collection.\n\n```python\nfor name in ["Ada", "Grace", "Guido"]:\n print(name)\n```\n\n```output\nAda\nGrace\nGuido\n```\n:::\n\n:::cell\n`range(3)` yields `0`, `1`, and `2` lazily. Use it when those integers are the thing being iterated over.\n\n```python\nfor number in range(3):\n print(number)\n```\n\n```output\n0\n1\n2\n```\n:::\n\n:::cell\n`enumerate()` is the usual Python way to keep a counter beside each value without indexing back into the list.\n\n```python\nfor index, name in enumerate(["Ada", "Grace"], start=1):\n print(index, name)\n```\n\n```output\n1 Ada\n2 Grace\n```\n:::\n\n:::note\n- A `for` loop consumes an iterable until it is exhausted.\n- Reach for `while` when the stopping condition must be rechecked manually.\n- `iter()` and `next()` expose the protocol that `for` uses internally.\n:::\n', 'functions.md': '+++\nslug = "functions"\ntitle = "Functions"\nsection = "Functions"\nsummary = "Use def to name reusable behavior and return results."\ndoc_path = "/tutorial/controlflow.html#defining-functions"\nsee_also = [\n "variables",\n "args-and-kwargs",\n "keyword-only-arguments",\n "closures",\n]\n+++\n\nFunctions package behavior behind a name. `def` creates a function object that can accept arguments, compute values, and return a result.\n\nDefault arguments make common calls short, and keyword arguments make call sites easier to read. A function that reaches the end without `return` produces `None`.\n\nUse functions when a calculation has a useful name, when code repeats, or when a piece of behavior should be tested independently.\n\n:::program\n```python\ndef greet(name):\n return f"Hello, {name}."\n\nprint(greet("Python"))\n\n\ndef format_total(amount, currency="USD"):\n return f"{amount} {currency}"\n\nprint(format_total(10))\nprint(format_total(10, currency="EUR"))\n\n\ndef log(message):\n print(f"log: {message}")\n\nresult = log("saved")\nprint(result)\n\n\ndef append_broken(item, items=[]):\n items.append(item)\n return items\n\nprint(append_broken("a"))\nprint(append_broken("b"))\n\n\ndef append_fixed(item, items=None):\n if items is None:\n items = []\n items.append(item)\n return items\n\nprint(append_fixed("a"))\nprint(append_fixed("b"))\n```\n:::\n\n:::cell\n`return` sends a value back to the caller. The caller can print it, store it, or pass it to another function.\n\n```python\ndef greet(name):\n return f"Hello, {name}."\n\nprint(greet("Python"))\n```\n\n```output\nHello, Python.\n```\n:::\n\n:::cell\nDefault arguments provide common values. Keyword arguments make it clear which option is being overridden.\n\n```python\ndef format_total(amount, currency="USD"):\n return f"{amount} {currency}"\n\nprint(format_total(10))\nprint(format_total(10, currency="EUR"))\n```\n\n```output\n10 USD\n10 EUR\n```\n:::\n\n:::cell\nA function without an explicit `return` returns `None`. That makes side-effect-only functions easy to distinguish from value-producing ones.\n\n```python\ndef log(message):\n print(f"log: {message}")\n\nresult = log("saved")\nprint(result)\n```\n\n```output\nlog: saved\nNone\n```\n:::\n\n:::cell\nMutable default arguments are evaluated once when the function is defined, not on each call. The same list is shared across calls, so successive calls see each other\'s mutations. Use `None` as the sentinel and create a fresh container inside the body.\n\n```python\ndef append_broken(item, items=[]):\n items.append(item)\n return items\n\nprint(append_broken("a"))\nprint(append_broken("b"))\n\n\ndef append_fixed(item, items=None):\n if items is None:\n items = []\n items.append(item)\n return items\n\nprint(append_fixed("a"))\nprint(append_fixed("b"))\n```\n\n```output\n[\'a\']\n[\'a\', \'b\']\n[\'a\']\n[\'b\']\n```\n:::\n\n:::note\n- Use `return` for values the caller should receive.\n- Defaults keep common calls concise.\n- Keyword arguments make options readable at the call site.\n- Never use a mutable value as a default argument; use `None` and build the container inside the function body.\n:::\n', 'generator-expressions.md': '+++\nslug = "generator-expressions"\ntitle = "Generator Expressions"\nsection = "Iteration"\nsummary = "Generator expressions use comprehension-like syntax to stream values lazily."\ndoc_path = "/tutorial/classes.html#generator-expressions"\nsee_also = [\n "comprehensions",\n "generators",\n "itertools",\n "yield-from",\n]\n+++\n\nGenerator expressions look like list comprehensions with parentheses, but they produce an iterator instead of building a concrete collection immediately.\n\nUse them when a consumer such as `sum()`, `any()`, or a `for` loop can use values one at a time. This keeps the transformation close to the consumer and avoids storing intermediate lists.\n\nLike other iterators, a generator expression is consumed as values are requested. Create a new generator expression when you need another pass.\n\n:::program\n```python\nnumbers = [1, 2, 3, 4]\nlist_squares = [number * number for number in numbers]\nprint(list_squares)\n\nstream_squares = (number * number for number in numbers)\nprint(next(stream_squares))\nprint(next(stream_squares))\nprint(list(stream_squares))\n\nprint(sum(number * number for number in numbers))\n```\n:::\n\n:::cell\nA list comprehension is eager: it builds a list immediately. That is useful when you need to store or reuse the results.\n\n```python\nnumbers = [1, 2, 3, 4]\nlist_squares = [number * number for number in numbers]\nprint(list_squares)\n```\n\n```output\n[1, 4, 9, 16]\n```\n:::\n\n:::cell\nA generator expression is lazy: it creates an iterator that produces values as they are consumed. After two `next()` calls, only the remaining squares are left.\n\n```python\nstream_squares = (number * number for number in numbers)\nprint(next(stream_squares))\nprint(next(stream_squares))\nprint(list(stream_squares))\n```\n\n```output\n1\n4\n[9, 16]\n```\n:::\n\n:::cell\nGenerator expressions are common inside reducing functions. When a generator expression is the only argument, the extra parentheses can be omitted.\n\n```python\nprint(sum(number * number for number in numbers))\n```\n\n```output\n30\n```\n:::\n\n:::note\n- List, dict, and set comprehensions build concrete collections.\n- Generator expressions produce one-pass iterators.\n- Use generator expressions when the consumer can process values one at a time.\n:::\n', 'generators.md': '+++\nslug = "generators"\ntitle = "Generators"\nsection = "Iteration"\nsummary = "yield creates an iterator that produces values on demand."\ndoc_path = "/tutorial/classes.html#generators"\nsee_also = [\n "iterators",\n "iterator-vs-iterable",\n "generator-expressions",\n]\n+++\n\nA generator function is a convenient way to write your own iterator. `yield` produces one value, pauses the function, and resumes when the next value is requested.\n\nGenerators are useful for pipelines, large inputs, and infinite sequences because they avoid building an entire collection in memory.\n\nUse `next()` to request one value manually, or loop over the generator to consume values until it is exhausted.\n\n:::program\n```python\ndef countdown(n):\n while n > 0:\n yield n\n n -= 1\n\nnumbers = countdown(3)\nprint(next(numbers))\nprint(next(numbers))\n\nfor value in countdown(3):\n print(value)\n\ndef countdown_eager(n):\n result = []\n while n > 0:\n result.append(n)\n n -= 1\n return result\n\nvalues = countdown_eager(3)\nprint(values)\nprint(values)\n\nstream = countdown(3)\nprint(list(stream))\nprint(list(stream))\n\nclass Countdown:\n def __init__(self, n):\n self.n = n\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.n <= 0:\n raise StopIteration\n value = self.n\n self.n -= 1\n return value\n\nprint(list(Countdown(3)))\n```\n:::\n\n:::cell\nCalling a generator function returns an iterator. `next()` asks for one value and resumes the function until the next `yield`.\n\n```python\ndef countdown(n):\n while n > 0:\n yield n\n n -= 1\n\nnumbers = countdown(3)\nprint(next(numbers))\nprint(next(numbers))\n```\n\n```output\n3\n2\n```\n:::\n\n:::cell\nA `for` loop repeatedly calls `next()` for you. The loop stops when the generator is exhausted.\n\n```python\nfor value in countdown(3):\n print(value)\n```\n\n```output\n3\n2\n1\n```\n:::\n\n:::cell\n`return` builds the entire result before handing it back; `yield` produces values on demand. The list keeps its values for repeated use, while the generator is exhausted after one pass.\n\n```python\ndef countdown_eager(n):\n result = []\n while n > 0:\n result.append(n)\n n -= 1\n return result\n\nvalues = countdown_eager(3)\nprint(values)\nprint(values)\n\nstream = countdown(3)\nprint(list(stream))\nprint(list(stream))\n```\n\n```output\n[3, 2, 1]\n[3, 2, 1]\n[3, 2, 1]\n[]\n```\n:::\n\n:::cell\nEvery generator is an iterator. The same countdown written by hand needs `__iter__` and `__next__` and an explicit `StopIteration`. The generator function expresses the same protocol with one `yield`.\n\n```python\nclass Countdown:\n def __init__(self, n):\n self.n = n\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.n <= 0:\n raise StopIteration\n value = self.n\n self.n -= 1\n return value\n\nprint(list(Countdown(3)))\n```\n\n```output\n[3, 2, 1]\n```\n:::\n\n:::note\n- Generator functions are a concise way to create custom iterators; every generator is an iterator.\n- `yield` defers work and streams values; `return` produces the whole result up front.\n- A generator is consumed as you iterate over it.\n- Prefer a list when you need to reuse stored results; prefer a generator when values can be streamed once.\n:::\n', 'generics-and-typevar.md': '+++\nslug = "generics-and-typevar"\ntitle = "Generics and TypeVar"\nsection = "Types"\nsummary = "Generics preserve type information across reusable functions and classes."\ndoc_path = "/library/typing.html#generics"\nsee_also = [\n "type-hints",\n "collections-module",\n "casts-and-any",\n]\n+++\n\nGenerics connect types across an API. A plain function that returns `object` loses information; a generic function can say that the returned value has the same type as the input element.\n\nA `TypeVar` stands for a type chosen by the caller. In `list[T] -> T`, the same `T` says that a list of strings produces a string and a list of integers produces an integer.\n\nUse generics when a function or class is reusable but still preserves a relationship between input and output types.\n\n:::program\n```python\nfrom typing import TypeVar\n\nT = TypeVar("T")\n\n\ndef first(items: list[T]) -> T:\n return items[0]\n\n\ndef pair(left: T, right: T) -> tuple[T, T]:\n return (left, right)\n\nprint(first([1, 2, 3]))\nprint(first(["Ada", "Grace"]))\nprint(pair("x", "y"))\nprint(T.__name__)\n```\n:::\n\n:::cell\nA `TypeVar` stands for a type chosen by the caller. The return type follows the list element type.\n\n```python\nfrom typing import TypeVar\n\nT = TypeVar("T")\n\n\ndef first(items: list[T]) -> T:\n return items[0]\n\nprint(first([1, 2, 3]))\nprint(first(["Ada", "Grace"]))\n```\n\n```output\n1\nAda\n```\n:::\n\n:::cell\nReusing the same `TypeVar` expresses a relationship between parameters and results.\n\n```python\ndef pair(left: T, right: T) -> tuple[T, T]:\n return (left, right)\n\nprint(pair("x", "y"))\n```\n\n```output\n(\'x\', \'y\')\n```\n:::\n\n:::cell\n`TypeVar` is visible at runtime, but the relationship is mainly for type checkers.\n\n```python\nprint(T.__name__)\nprint(first.__annotations__)\n```\n\n```output\nT\n{\'items\': list[~T], \'return\': ~T}\n```\n:::\n\n:::note\n- A `TypeVar` stands for a type chosen by the caller.\n- Python 3.12+ also accepts the inline PEP 695 spelling `def first[T](items: list[T]) -> T`, which declares the variable without a separate `TypeVar` line; the explicit form shown here works everywhere and reads the same way.\n- Generic functions avoid losing information to `object` or `Any`.\n- Use generics when input and output types are connected.\n:::\n', 'guard-clauses.md': '+++\nslug = "guard-clauses"\ntitle = "Guard Clauses"\nsection = "Control Flow"\nsummary = "Guard clauses handle boundary cases early so the main path stays flat."\ndoc_path = "/tutorial/controlflow.html#if-statements"\nsee_also = [\n "conditionals",\n "exceptions",\n "functions",\n]\n+++\n\nA guard clause is an early `return`, `raise`, `break`, or `continue` that handles a case the rest of the function should not process. The point is not new syntax; the point is moving boundaries out of the way so the successful path can be read straight through.\n\nUse guards when a function has clear invalid, empty, or already-finished cases. If every branch is equally important, an ordinary `if`/`elif` chain may be clearer.\n\nThe contrast below shows the payoff: the nested version makes the valid path live inside two conditions, while the guard version names the invalid cases first and leaves the calculation at the outer indentation level.\n\n:::program\n```python\ndef nested_discount(price, percent):\n if price >= 0:\n if 0 <= percent <= 100:\n return round(price - price * percent / 100, 2)\n return "invalid discount"\n return "invalid price"\n\n\ndef guarded_discount(price, percent):\n if price < 0:\n return "invalid price"\n if not 0 <= percent <= 100:\n return "invalid discount"\n\n return round(price - price * percent / 100, 2)\n\nprint(nested_discount(100, 15))\nprint(guarded_discount(-5, 10))\nprint(guarded_discount(100, 120))\n```\n:::\n\n:::cell\nThe nested version is correct, but the useful work is buried inside both tests.\n\n```python\ndef nested_discount(price, percent):\n if price >= 0:\n if 0 <= percent <= 100:\n return round(price - price * percent / 100, 2)\n return "invalid discount"\n return "invalid price"\n\nprint(nested_discount(100, 15))\n```\n\n```output\n85.0\n```\n:::\n\n:::cell\nThe guard-clause version handles impossible inputs first, then lets the ordinary calculation sit at the top level of the function body.\n\n```python\ndef guarded_discount(price, percent):\n if price < 0:\n return "invalid price"\n if not 0 <= percent <= 100:\n return "invalid discount"\n\n return round(price - price * percent / 100, 2)\n\nprint(guarded_discount(-5, 10))\nprint(guarded_discount(100, 120))\n```\n\n```output\ninvalid price\ninvalid discount\n```\n:::\n\n:::note\n- Guard clauses are a readability pattern, not a separate Python feature.\n- They work best when the early cases are true boundaries.\n- For exceptional failures, raise an exception instead of returning a sentinel string.\n:::\n', 'hello-world.md': '+++\nslug = "hello-world"\ntitle = "Hello World"\nsection = "Basics"\nsummary = "The first Python program prints a line of text."\ndoc_path = "/tutorial/introduction.html"\nsee_also = [\n "values",\n "variables",\n]\n+++\n\nEvery Python program starts by executing statements from top to bottom. Calling `print()` is the smallest useful program because it shows how Python evaluates an expression and sends text to standard output.\n\nStrings are ordinary values, so the message passed to `print()` can be changed, stored in a variable, or produced by a function. This example keeps the first program intentionally small.\n\nRun the program and compare what you see with the source: the text appears on standard output followed by a newline, which is why successive `print()` calls land on separate lines.\n\n:::program\n```python\nprint("hello world")\n```\n:::\n\n:::cell\nThe whole program is one statement. Python evaluates the string literal `"hello world"` and passes that value to `print()`, which writes it to standard output — the output panel shows exactly that line.\n\n```python\nprint("hello world")\n```\n\n```output\nhello world\n```\n:::\n\n:::note\n- `print()` writes text followed by a newline.\n- Strings can be delimited with single or double quotes.\n:::\n', 'import-aliases.md': '+++\nslug = "import-aliases"\ntitle = "Import Aliases"\nsection = "Modules"\nsummary = "as gives imported modules or names a local alias."\ndoc_path = "/reference/simple_stmts.html#the-import-statement"\nsee_also = [\n "modules",\n "functions",\n]\n+++\n\n`as` gives an imported module or imported name a local alias. Use it when a conventional short name improves readability or when two imports would otherwise collide.\n\nThe alternative is a plain import, which is usually better when the module name is already clear. Avoid aliases that make readers guess where a name came from.\n\nAvoid star imports in examples and production modules because they hide dependencies and blur the boundary between modules.\n\n:::program\n```python\nimport statistics as stats\nfrom math import sqrt as square_root\n\nscores = [8, 10, 9]\nprint(stats.mean(scores))\nprint(stats.__name__)\n\nprint(square_root(81))\nprint(square_root.__name__)\n```\n:::\n\n:::cell\nA module alias keeps the namespace but changes the local name. Here `stats` is shorter, but readers can still see that `mean` belongs to the statistics module.\n\n```python\nimport statistics as stats\n\nscores = [8, 10, 9]\nprint(stats.mean(scores))\nprint(stats.__name__)\n```\n\n```output\n9\nstatistics\n```\n:::\n\n:::cell\nA name imported with `from` can also be aliased. Use this when the local name explains the role better than the original name.\n\n```python\nfrom math import sqrt as square_root\n\nprint(square_root(81))\nprint(square_root.__name__)\n```\n\n```output\n9.0\nsqrt\n```\n:::\n\n:::note\n- `import module as alias` keeps module-style access under a shorter or clearer name.\n- `from module import name as alias` imports one name under a local alias.\n- Prefer plain imports unless an alias improves clarity or follows a strong convention.\n- Avoid `from module import *` because it makes dependencies harder to see.\n:::\n', 'inheritance-and-super.md': '+++\nslug = "inheritance-and-super"\ntitle = "Inheritance and Super"\nsection = "Classes"\nsummary = "Inheritance reuses behavior, and super delegates to a parent implementation."\ndoc_path = "/tutorial/classes.html#inheritance"\nsee_also = [\n "classes",\n "abstract-base-classes",\n "classmethods-and-staticmethods",\n "special-methods",\n]\n+++\n\nInheritance lets one class specialize another class. The child class gets parent behavior and can add or override methods.\n\nUse `super()` when the child method should extend the parent implementation instead of replacing it entirely.\n\nPrefer composition when objects merely collaborate. Inheritance is best when the child really is a specialized version of the parent.\n\n:::program\n```python\nclass Animal:\n def __init__(self, name):\n self.name = name\n\n def speak(self):\n return f"{self.name} makes a sound"\n\nclass Dog(Animal):\n def speak(self):\n base = super().speak()\n return f"{base}; {self.name} barks"\n\npet = Dog("Nina")\nprint(pet.name)\nprint(pet.speak())\nprint(isinstance(pet, Animal))\n```\n:::\n\n:::cell\nA child class names its parent in parentheses. `Dog` instances get the `Animal.__init__` method because `Dog` does not define its own initializer.\n\n```python\nclass Animal:\n def __init__(self, name):\n self.name = name\n\n def speak(self):\n return f"{self.name} makes a sound"\n\nclass Dog(Animal):\n def speak(self):\n base = super().speak()\n return f"{base}; {self.name} barks"\n\npet = Dog("Nina")\nprint(pet.name)\n```\n\n```output\nNina\n```\n:::\n\n:::cell\n`super()` delegates to the parent implementation. The child method can reuse the parent result and then add specialized behavior.\n\n```python\nprint(pet.speak())\nprint(isinstance(pet, Animal))\n```\n\n```output\nNina makes a sound; Nina barks\nTrue\n```\n:::\n\n:::note\n- Inheritance models an “is a specialized kind of” relationship.\n- `super()` calls the next implementation in the method resolution order.\n- Prefer composition when an object only needs to use another object.\n:::\n', 'iterating-over-iterables.md': '+++\nslug = "iterating-over-iterables"\ntitle = "Iterating over Iterables"\nsection = "Iteration"\nsummary = "for loops consume values from any iterable object."\ndoc_path = "/tutorial/controlflow.html#for-statements"\nsee_also = [\n "iterators",\n "iterator-vs-iterable",\n "for-loops",\n]\n+++\n\nPython\'s `for` statement consumes values from any iterable object: lists, strings, dictionaries, ranges, generators, files, and many standard-library helpers.\n\nThis makes iteration a value-stream protocol rather than a special case for arrays. The producer decides how values are made, and the loop consumes them one at a time.\n\nUse `enumerate()` when you need positions and values together, and `dict.items()` when you need keys and values. These helpers express intent better than manual indexing.\n\n:::program\n```python\nnames = ["Ada", "Grace", "Guido"]\n\nfor name in names:\n print(name)\n\nfor index, name in enumerate(names):\n print(index, name)\n\nscores = {"Ada": 10, "Grace": 9}\nfor name, score in scores.items():\n print(name, score)\n```\n:::\n\n:::cell\nStart with an ordinary list. A list stores values, and a `for` loop asks it for one value at a time.\n\nWhen you only need the values, iterate over the collection directly. There is no index variable because the loop body does not need one.\n\n```python\nnames = ["Ada", "Grace", "Guido"]\n\nfor name in names:\n print(name)\n```\n\n```output\nAda\nGrace\nGuido\n```\n:::\n\n:::cell\nWhen you need both a position and a value, use `enumerate()`. It produces index/value pairs without manual indexing.\n\n```python\nfor index, name in enumerate(names):\n print(index, name)\n```\n\n```output\n0 Ada\n1 Grace\n2 Guido\n```\n:::\n\n:::cell\nDictionaries are iterable too, but `dict.items()` is the clearest way to say that the loop needs keys and values together.\n\n```python\nscores = {"Ada": 10, "Grace": 9}\nfor name, score in scores.items():\n print(name, score)\n```\n\n```output\nAda 10\nGrace 9\n```\n:::\n\n:::note\n- A `for` loop consumes values from an iterable.\n- Different producers can feed the same loop protocol.\n- Prefer `enumerate()` over `range(len(...))` when you need an index.\n:::\n', 'iterator-vs-iterable.md': '+++\nslug = "iterator-vs-iterable"\ntitle = "Iterator vs Iterable"\nsection = "Iteration"\nsummary = "Iterables produce fresh iterators; iterators are one-pass."\ndoc_path = "/glossary.html#term-iterable"\nsee_also = [\n "iterators",\n "iterating-over-iterables",\n "generators",\n]\n+++\n\nAn iterable can produce values when asked. An iterator is the object that remembers where the production currently is. The distinction matters because iterables can be traversed many times, while many iterators can be traversed only once.\n\n`iter(iterable)` returns a fresh iterator each call. `iter(iterator)` returns the iterator itself. That self-iteration property is how `for` loops can accept either kind, and it is also why a function that loops over its argument twice silently breaks when called with a generator instead of a list.\n\nThe takeaway for API design: receive iterables when the caller may want a second pass, and materialize once at the boundary if you must.\n\n:::program\n```python\nnames = ["Ada", "Grace"]\n\nprint(list(names))\nprint(list(names))\n\nstream = iter(names)\nprint(list(stream))\nprint(list(stream))\n\nfirst = iter(names)\nsecond = iter(names)\nprint(first is second)\nprint(iter(first) is first)\n\ndef total_and_count(numbers):\n total = sum(numbers)\n count = sum(1 for _ in numbers)\n return total, count\n\ndef values():\n yield from [10, 9, 8]\n\nprint(total_and_count([10, 9, 8]))\nprint(total_and_count(values()))\n\ndef total_and_count_safe(numbers):\n items = list(numbers)\n return sum(items), len(items)\n\nprint(total_and_count_safe(values()))\n```\n:::\n\n:::cell\nA list is iterable. Each `for` loop or `list()` call asks the list for a fresh iterator under the hood, so the same data can be traversed many times.\n\n```python\nnames = ["Ada", "Grace"]\nprint(list(names))\nprint(list(names))\n```\n\n```output\n[\'Ada\', \'Grace\']\n[\'Ada\', \'Grace\']\n```\n:::\n\n:::cell\nAn iterator is one-pass. Calling `iter()` returns a position-tracking object; once it has been exhausted, it stays exhausted.\n\n```python\nstream = iter(names)\nprint(list(stream))\nprint(list(stream))\n```\n\n```output\n[\'Ada\', \'Grace\']\n[]\n```\n:::\n\n:::cell\nCalling `iter()` on an iterable returns a brand-new iterator each time. Calling `iter()` on an iterator returns the same object — that is the rule that lets a `for` loop accept either kind.\n\n```python\nfirst = iter(names)\nsecond = iter(names)\nprint(first is second)\nprint(iter(first) is first)\n```\n\n```output\nFalse\nTrue\n```\n:::\n\n:::cell\nThe distinction shows up at API boundaries. A function that loops over its argument twice works for an iterable but silently produces wrong answers for an iterator, because the second pass finds the iterator already exhausted. Materialize once at the boundary when both passes matter.\n\n```python\ndef total_and_count(numbers):\n total = sum(numbers)\n count = sum(1 for _ in numbers)\n return total, count\n\ndef values():\n yield from [10, 9, 8]\n\nprint(total_and_count([10, 9, 8]))\nprint(total_and_count(values()))\n\ndef total_and_count_safe(numbers):\n items = list(numbers)\n return sum(items), len(items)\n\nprint(total_and_count_safe(values()))\n```\n\n```output\n(27, 3)\n(27, 0)\n(27, 3)\n```\n:::\n\n:::note\n- An iterable produces an iterator each time `iter()` is called on it; an iterator produces values until it is exhausted.\n- `iter(iterable)` returns a fresh iterator; `iter(iterator)` returns the same iterator.\n- Functions that traverse their input more than once must accept an iterable or materialize the input at the boundary.\n:::\n', 'iterators.md': '+++\nslug = "iterators"\ntitle = "Iterators"\nsection = "Iteration"\nsummary = "iter and next expose the protocol behind for loops."\ndoc_path = "/library/stdtypes.html#iterator-types"\nsee_also = [\n "iterating-over-iterables",\n "iterator-vs-iterable",\n "generators",\n]\n+++\n\nAn iterable is an object that can produce values for a loop. An iterator is the object that remembers where that production currently is.\n\n`iter()` asks an iterable for an iterator, and `next()` consumes one value from that iterator. A `for` loop performs those steps for you until the iterator is exhausted.\n\nThis is the core value-stream protocol in Python: one object produces values, another piece of code consumes them, and many streams are one-pass.\n\n:::program\n```python\nnames = ["Ada", "Grace", "Guido"]\niterator = iter(names)\nprint(next(iterator))\nprint(next(iterator))\n\nfor name in iterator:\n print(name)\n\nagain = iter(names)\nprint(next(again))\n```\n:::\n\n:::cell\n`iter()` asks an iterable for an iterator. `next()` consumes one value and advances the iterator\'s position.\n\n```python\nnames = ["Ada", "Grace", "Guido"]\niterator = iter(names)\nprint(next(iterator))\nprint(next(iterator))\n```\n\n```output\nAda\nGrace\n```\n:::\n\n:::cell\nA `for` loop consumes the same iterator protocol. Because two values were already consumed, the loop sees only the remaining value.\n\n```python\nfor name in iterator:\n print(name)\n```\n\n```output\nGuido\n```\n:::\n\n:::cell\nThe list itself is reusable. Asking it for a fresh iterator starts a new pass over the same stored values.\n\n```python\nagain = iter(names)\nprint(next(again))\n```\n\n```output\nAda\n```\n:::\n\n:::note\n- Iterables produce iterators; iterators produce values.\n- `next()` consumes one value from an iterator.\n- Many iterators are one-pass even when the original collection is reusable.\n:::\n', 'itertools.md': '+++\nslug = "itertools"\ntitle = "Itertools"\nsection = "Iteration"\nsummary = "itertools composes lazy iterator streams."\ndoc_path = "/library/itertools.html"\nsee_also = [\n "iterators",\n "generator-expressions",\n "sentinel-iteration",\n "comprehension-patterns",\n]\n+++\n\nThe `itertools` module contains tools for composing iterator streams: combining, slicing, grouping, and repeating values without changing the consumer protocol.\n\nMany `itertools` functions are lazy. They describe work to do later instead of building a list immediately, so helpers such as `islice()` are useful when taking a finite window.\n\nIterator pipelines let each step stay small: one object produces values, another transforms them, and a final consumer such as `list()` or a loop pulls values through the pipeline.\n\n:::program\n```python\nimport itertools\n\ncounter = itertools.count(10)\nprint(list(itertools.islice(counter, 3)))\n\npages = itertools.chain(["intro", "setup"], ["deploy"])\nprint(list(pages))\n\nscores = [7, 10, 8, 10]\nhigh_scores = itertools.compress(scores, [score >= 9 for score in scores])\nprint(list(high_scores))\n```\n:::\n\n:::cell\n`count()` can produce values forever, so `islice()` takes a finite window. Nothing is materialized until `list()` consumes the iterator.\n\n```python\nimport itertools\n\ncounter = itertools.count(10)\nprint(list(itertools.islice(counter, 3)))\n```\n\n```output\n[10, 11, 12]\n```\n:::\n\n:::cell\n`chain()` presents several iterables as one stream. This avoids building an intermediate list just to loop over combined inputs.\n\n```python\npages = itertools.chain(["intro", "setup"], ["deploy"])\nprint(list(pages))\n```\n\n```output\n[\'intro\', \'setup\', \'deploy\']\n```\n:::\n\n:::cell\nIterator helpers compose with ordinary Python expressions. `compress()` keeps items whose corresponding selector is true.\n\n```python\nscores = [7, 10, 8, 10]\nhigh_scores = itertools.compress(scores, [score >= 9 for score in scores])\nprint(list(high_scores))\n```\n\n```output\n[10, 10]\n```\n:::\n\n:::note\n- `itertools` composes producer and transformer streams.\n- Iterator pipelines avoid building intermediate lists.\n- Use `islice()` to take a finite piece from an infinite iterator.\n- Convert to a list only when you need concrete results.\n:::\n', 'json.md': '+++\nslug = "json"\ntitle = "JSON"\nsection = "Standard Library"\nsummary = "json encodes Python values as JSON text and decodes them back."\ndoc_path = "/library/json.html"\nsee_also = [\n "dicts",\n "typed-dicts",\n "strings",\n]\n+++\n\nThe `json` module converts between Python values and JSON text. Dictionaries, lists, strings, numbers, booleans, and `None` map naturally to JSON structures.\n\nUse `dumps()` when you need a string and `loads()` when you need Python objects back. Options such as `sort_keys=True` and `indent=2` control stable, readable output.\n\nJSON is a data format, not a way to preserve arbitrary Python objects. Encode simple data structures at service boundaries, and expect decode errors when the incoming text is not valid JSON.\n\n:::program\n```python\nimport json\n\npayload = {"language": "Python", "versions": [3, 13], "stable": True, "missing": None}\ntext = json.dumps(payload, sort_keys=True)\nprint(text)\n\npretty = json.dumps({"language": "Python", "stable": True}, indent=2, sort_keys=True)\nprint(pretty.splitlines()[0])\nprint(pretty.splitlines()[1])\n\ndecoded = json.loads(text)\nprint(decoded["language"])\nprint(decoded["missing"] is None)\n\ntry:\n json.loads("{bad json}")\nexcept json.JSONDecodeError as error:\n print(error.__class__.__name__)\n```\n:::\n\n:::cell\n`dumps()` encodes Python data as JSON text. `sort_keys=True` keeps dictionary keys in a stable order for reproducible output.\n\n```python\nimport json\n\npayload = {"language": "Python", "versions": [3, 13], "stable": True, "missing": None}\ntext = json.dumps(payload, sort_keys=True)\nprint(text)\n```\n\n```output\n{"language": "Python", "missing": null, "stable": true, "versions": [3, 13]}\n```\n:::\n\n:::cell\nFormatting options change the JSON text, not the Python value. `indent=2` is useful for human-readable output.\n\n```python\npretty = json.dumps({"language": "Python", "stable": True}, indent=2, sort_keys=True)\nprint(pretty.splitlines()[0])\nprint(pretty.splitlines()[1])\n```\n\n```output\n{\n "language": "Python",\n```\n:::\n\n:::cell\n`loads()` decodes JSON text back into Python values. JSON `null` becomes Python `None`.\n\n```python\ndecoded = json.loads(text)\nprint(decoded["language"])\nprint(decoded["missing"] is None)\n```\n\n```output\nPython\nTrue\n```\n:::\n\n:::cell\nInvalid JSON raises `JSONDecodeError`, so input boundaries should handle decode failures explicitly.\n\n```python\ntry:\n json.loads("{bad json}")\nexcept json.JSONDecodeError as error:\n print(error.__class__.__name__)\n```\n\n```output\nJSONDecodeError\n```\n:::\n\n:::note\n- `dumps()` returns a string; `loads()` accepts a string.\n- JSON `true`, `false`, and `null` become Python `True`, `False`, and `None`.\n- Use `sort_keys=True` when stable text output matters.\n- JSON only represents data shapes, not arbitrary Python objects or behavior.\n:::\n', 'keyword-only-arguments.md': '+++\nslug = "keyword-only-arguments"\ntitle = "Keyword-only Arguments"\nsection = "Functions"\nsummary = "Use * to require selected function arguments to be named."\ndoc_path = "/tutorial/controlflow.html#special-parameters"\nsee_also = [\n "functions",\n "args-and-kwargs",\n "positional-only-parameters",\n "partial-functions",\n]\n+++\n\nA bare `*` in a function signature marks the following parameters as keyword-only. Callers must name those arguments explicitly.\n\nKeyword-only arguments are useful for options such as timeouts, flags, and modes where positional calls would be ambiguous or easy to misread.\n\nThey let the required data stay positional while optional controls remain self-documenting at the call site.\n\n:::program\n```python\ndef connect(host, *, timeout=5, secure=True):\n scheme = "https" if secure else "http"\n print(f"{scheme}://{host} timeout={timeout}")\n\nconnect("example.com")\nconnect("example.com", timeout=10)\nconnect("localhost", secure=False)\n\ntry:\n connect("example.com", 10)\nexcept TypeError as error:\n print(type(error).__name__)\n```\n:::\n\n:::cell\nParameters after `*` must be named. The default options still apply when the caller omits them.\n\n```python\ndef connect(host, *, timeout=5, secure=True):\n scheme = "https" if secure else "http"\n print(f"{scheme}://{host} timeout={timeout}")\n\nconnect("example.com")\n```\n\n```output\nhttps://example.com timeout=5\n```\n:::\n\n:::cell\nNaming the option makes the call site explicit. A reader does not have to remember which positional slot controls the timeout.\n\n```python\nconnect("example.com", timeout=10)\n```\n\n```output\nhttps://example.com timeout=10\n```\n:::\n\n:::cell\nFlags are especially good keyword-only arguments because a bare positional `False` is hard to interpret.\n\n```python\nconnect("localhost", secure=False)\n```\n\n```output\nhttp://localhost timeout=5\n```\n:::\n\n:::cell\nThe bare `*` is enforced at the call site: passing the timeout positionally raises `TypeError` instead of silently filling the wrong slot.\n\n```python\ntry:\n connect("example.com", 10)\nexcept TypeError as error:\n print(type(error).__name__)\n```\n\n```output\nTypeError\n```\n:::\n\n:::note\n- Put `*` before options that callers should name.\n- Keyword-only flags avoid mysterious positional `True` and `False` arguments.\n- Defaults work normally for keyword-only parameters.\n:::\n', 'lambdas.md': '+++\nslug = "lambdas"\ntitle = "Lambdas"\nsection = "Functions"\nsummary = "lambda creates small anonymous function expressions."\ndoc_path = "/tutorial/controlflow.html#lambda-expressions"\nsee_also = [\n "functions",\n "sorting",\n "callable-objects",\n]\n+++\n\n`lambda` creates a small anonymous function expression. It is most useful when Python asks for a function and the behavior is short enough to read inline.\n\nA lambda can only contain one expression. Use `def` when the behavior deserves a name, needs statements, or would be easier to test separately.\n\nLambdas often appear as key functions, callbacks, and tiny adapters. Keep them simple enough that the call site remains clearer than a named helper.\n\n:::program\n```python\nadd_tax = lambda price: round(price * 1.08, 2)\nprint(add_tax(10))\n\nitems = [("notebook", 5), ("pen", 2), ("bag", 20)]\nby_price = sorted(items, key=lambda item: item[1])\nprint(by_price)\n\ndef price(item):\n return item[1]\n\nprint(sorted(items, key=price))\n```\n:::\n\n:::cell\nA lambda is a function expression. Assigning one to a name works, although `def` is usually clearer for reusable behavior.\n\n```python\nadd_tax = lambda price: round(price * 1.08, 2)\nprint(add_tax(10))\n```\n\n```output\n10.8\n```\n:::\n\n:::cell\nLambdas are most idiomatic when passed directly to another function. `sorted()` calls this key function once for each item.\n\n```python\nitems = [("notebook", 5), ("pen", 2), ("bag", 20)]\nby_price = sorted(items, key=lambda item: item[1])\nprint(by_price)\n```\n\n```output\n[(\'pen\', 2), (\'notebook\', 5), (\'bag\', 20)]\n```\n:::\n\n:::cell\nA named function is better when the behavior should be reused or explained. It produces the same sort key, but gives the operation a name.\n\n```python\ndef price(item):\n return item[1]\n\nprint(sorted(items, key=price))\n```\n\n```output\n[(\'pen\', 2), (\'notebook\', 5), (\'bag\', 20)]\n```\n:::\n\n:::note\n- Lambdas are expressions, not statements.\n- Prefer `def` for multi-step or reused behavior.\n- Lambdas are common as `key=` functions because the behavior is local to one call.\n:::\n', 'lists.md': '+++\nslug = "lists"\ntitle = "Lists"\nsection = "Collections"\nsummary = "Lists are ordered, mutable collections."\ndoc_path = "/tutorial/datastructures.html#more-on-lists"\nsee_also = [\n "tuples",\n "sets",\n "slices",\n "copying-collections",\n]\n+++\n\nLists are Python\'s general-purpose mutable sequence type. Use them when order matters and the collection may grow, shrink, or be rearranged.\n\nIndexing reads individual positions. `0` is the first item, and negative indexes count backward from the end.\n\nMutation and copying matter: `append()` changes the list, while `sorted()` returns a new ordered list and leaves the original alone.\n\n:::program\n```python\nnumbers = [3, 1, 4]\nnumbers.append(1)\n\nprint(numbers)\nprint(numbers[0])\nprint(numbers[-1])\nprint(sorted(numbers))\nprint(numbers)\n```\n:::\n\n:::cell\nCreate a list with square brackets. Because lists are mutable, `append()` changes this same list object.\n\n```python\nnumbers = [3, 1, 4]\nnumbers.append(1)\n\nprint(numbers)\n```\n\n```output\n[3, 1, 4, 1]\n```\n:::\n\n:::cell\nUse indexes to read positions. Negative indexes are convenient for reading from the end.\n\n```python\nprint(numbers[0])\nprint(numbers[-1])\n```\n\n```output\n3\n1\n```\n:::\n\n:::cell\nUse `sorted()` when you want an ordered copy and still need the original order afterward.\n\n```python\nprint(sorted(numbers))\nprint(numbers)\n```\n\n```output\n[1, 1, 3, 4]\n[3, 1, 4, 1]\n```\n:::\n\n:::note\n- Lists are mutable sequences: methods such as `append()` change the list in place.\n- Negative indexes count from the end.\n- `sorted()` returns a new list; `list.sort()` sorts the existing list in place.\n:::\n', 'literal-and-final.md': '+++\nslug = "literal-and-final"\ntitle = "Literal and Final"\nsection = "Types"\nsummary = "Literal restricts exact values, while Final marks names that should not be rebound."\ndoc_path = "/library/typing.html#typing.Literal"\nsee_also = [\n "type-hints",\n "constants",\n "union-and-optional-types",\n "overloads",\n]\n+++\n\n`Literal` and `Final` make two different static promises. `Literal` narrows a value to exact allowed options. `Final` tells a type checker that a name should not be rebound after its first assignment.\n\nBoth annotations help at API boundaries: a function can accept only known modes, and a module can publish a constant that other code should treat as fixed. Python still runs the same assignment rules at runtime, so these are promises for tools and readers rather than runtime locks.\n\nUse `Literal` when a small closed set is clearer than a broad `str` or `int`. Use `Final` when rebinding would be a bug in the design, especially for module constants and class attributes.\n\n:::program\n```python\nfrom typing import Final, Literal\n\nMode = Literal["read", "write"]\nDEFAULT_MODE: Final[Mode] = "read"\n\n\ndef open_label(mode: Mode) -> str:\n return f"opening for {mode}"\n\nprint(open_label(DEFAULT_MODE))\nprint(open_label("write"))\n\nDEFAULT_MODE = "debug"\nprint(DEFAULT_MODE)\n```\n:::\n\n:::cell\n`Literal` describes exact allowed values. A type checker can reject `"debug"` as a `Mode` even though it is an ordinary string at runtime.\n\n```python\nfrom typing import Final, Literal\n\nMode = Literal["read", "write"]\n\n\ndef open_label(mode: Mode) -> str:\n return f"opening for {mode}"\n\nprint(open_label("write"))\n```\n\n```output\nopening for write\n```\n:::\n\n:::cell\n`Final` marks a name that should not be rebound. It is stronger documentation than the all-caps constant convention because static tools can flag reassignment.\n\n```python\nDEFAULT_MODE: Final[Mode] = "read"\nprint(open_label(DEFAULT_MODE))\n```\n\n```output\nopening for read\n```\n:::\n\n:::cell\nThe annotation is not a runtime lock. Python still rebinds the name; the mistake is that a type checker and human reader should reject the design.\n\n```python\nDEFAULT_MODE = "debug"\nprint(DEFAULT_MODE)\n```\n\n```output\ndebug\n```\n:::\n\n:::note\n- `Literal` narrows values to a small exact set.\n- `Final` prevents rebinding in static analysis, not at runtime.\n- Use enums when the option set needs names, behavior, or iteration over members.\n:::\n', 'literals.md': '+++\nslug = "literals"\ntitle = "Literals"\nsection = "Basics"\nsummary = "Literals write values directly in Python source code."\ndoc_path = "/reference/lexical_analysis.html#literals"\nsee_also = [\n "values",\n "strings",\n "numbers",\n "string-formatting",\n]\n+++\n\nLiterals are source-code forms for values: numbers, text, bytes, containers, booleans, `None`, and a few specialized markers. They are how a program writes small values directly.\n\nThe literal form is only the beginning. Later examples explain each value family in depth: strings are Unicode text, bytes are binary data, lists and dicts are containers, and `None` represents intentional absence.\n\nUse literals when the value is small and local. Give repeated or meaningful values a name so the program explains why that value matters.\n\n:::program\n```python\nwhole = 42\nfraction = 3.5\ncomplex_number = 2 + 3j\nprint(whole, fraction, complex_number.imag)\n\nflags = 0xFF\nmask = 0b1010\nmillion = 1_000_000\nprint(flags, mask, million)\n\ntext = "python"\nraw_pattern = r"\\d+"\ndata = b"py"\nscore = 98\nformatted = f"score={score}"\nprint(text)\nprint(raw_pattern)\nprint(data)\nprint(formatted)\n\npoint = (2, 3)\nnames = ["Ada", "Grace"]\nscores = {"Ada": 98}\nunique = {"py", "go"}\nprint(point)\nprint(names[0])\nprint(scores["Ada"])\nprint(sorted(unique))\n\nprint(True, False, None)\nprint(...)\n\nprint(type({}).__name__)\nprint(type(set()).__name__)\nprint(type({1, 2}).__name__)\n```\n:::\n\n:::cell\nNumeric literals write numbers directly. Complex literals use `j` for the imaginary part.\n\n```python\nwhole = 42\nfraction = 3.5\ncomplex_number = 2 + 3j\nprint(whole, fraction, complex_number.imag)\n```\n\n```output\n42 3.5 3.0\n```\n:::\n\n:::cell\nInteger literals also accept hexadecimal (`0x`), binary (`0b`), and octal (`0o`) prefixes. Underscores group digits visually without changing the value.\n\n```python\nflags = 0xFF\nmask = 0b1010\nmillion = 1_000_000\nprint(flags, mask, million)\n```\n\n```output\n255 10 1000000\n```\n:::\n\n:::cell\nString literals write Unicode text. Raw strings keep backslashes literal, bytes literals write binary data rather than text, and f-strings (`f"..."`) embed expressions inline.\n\n```python\ntext = "python"\nraw_pattern = r"\\d+"\ndata = b"py"\nscore = 98\nformatted = f"score={score}"\nprint(text)\nprint(raw_pattern)\nprint(data)\nprint(formatted)\n```\n\n```output\npython\n\\d+\nb\'py\'\nscore=98\n```\n:::\n\n:::cell\nContainer literals create tuples, lists, dictionaries, and sets. Each container answers a different question about order, position, lookup, or uniqueness.\n\n```python\npoint = (2, 3)\nnames = ["Ada", "Grace"]\nscores = {"Ada": 98}\nunique = {"py", "go"}\nprint(point)\nprint(names[0])\nprint(scores["Ada"])\nprint(sorted(unique))\n```\n\n```output\n(2, 3)\nAda\n98\n[\'go\', \'py\']\n```\n:::\n\n:::cell\n`True`, `False`, `None`, and `...` are singleton literal-like constants used for truth values, absence, and placeholders.\n\n```python\nprint(True, False, None)\nprint(...)\n```\n\n```output\nTrue False None\nEllipsis\n```\n:::\n\n:::cell\nCurly-brace literals are dictionaries by default. The empty form `{}` is an empty dictionary, not an empty set; use `set()` for that. A non-empty `{1, 2}` is a set because keyless items can only be a set.\n\n```python\nprint(type({}).__name__)\nprint(type(set()).__name__)\nprint(type({1, 2}).__name__)\n```\n\n```output\ndict\nset\nset\n```\n:::\n\n:::note\n- Literals are good for small local values; constants are better for repeated values with meaning.\n- `{}` is an empty dictionary. Use `set()` for an empty set.\n- Bytes literals are binary data; string literals are Unicode text.\n- `...` evaluates to the `Ellipsis` object.\n:::\n', 'logging.md': '+++\nslug = "logging"\ntitle = "Logging"\nsection = "Standard Library"\nsummary = "logging records operational events without using print as infrastructure."\ndoc_path = "/library/logging.html"\nsee_also = [\n "exceptions",\n "testing",\n "modules",\n]\n+++\n\n`logging` records operational events without using `print` as infrastructure. A logger names where an event came from, a handler decides where records go, a formatter chooses their text shape, and a level decides which records are important enough to emit.\n\nUse logging for services, command-line tools, scheduled jobs, and libraries that need diagnostics operators can filter. Use `print` for a program\'s intentional user-facing output.\n\nThe example writes to stdout so the page stays deterministic. Real applications usually configure handlers once at startup and then call `logging.getLogger(__name__)` from each module.\n\n:::program\n```python\nimport logging\nimport sys\n\nlogger = logging.getLogger("example.worker")\nlogger.setLevel(logging.DEBUG)\nhandler = logging.StreamHandler(sys.stdout)\nhandler.setLevel(logging.INFO)\nparts = ["%(levelname)s", "%(name)s", "%(message)s"]\nformatter = logging.Formatter(":".join(parts))\nhandler.setFormatter(formatter)\nlogger.handlers[:] = [handler]\nlogger.propagate = False\n\nlogger.debug("hidden detail")\nlogger.info("service started")\nlogger.warning("disk almost full")\n\nhandler.setLevel(logging.WARNING)\nlogger.info("hidden after threshold change")\nlogger.error("write failed")\n```\n:::\n\n:::cell\nA logger name records which part of the program produced the event. The handler and formatter choose where and how the event is shown.\n\n```python\nimport logging\nimport sys\n\nlogger = logging.getLogger("example.worker")\nlogger.setLevel(logging.DEBUG)\nhandler = logging.StreamHandler(sys.stdout)\nhandler.setLevel(logging.INFO)\nparts = ["%(levelname)s", "%(name)s", "%(message)s"]\nformatter = logging.Formatter(":".join(parts))\nhandler.setFormatter(formatter)\nlogger.handlers[:] = [handler]\nlogger.propagate = False\n\nlogger.debug("hidden detail")\nlogger.info("service started")\nlogger.warning("disk almost full")\n```\n\n```output\nINFO:example.worker:service started\nWARNING:example.worker:disk almost full\n```\n:::\n\n:::cell\nLevels are thresholds. Raising the handler level to `WARNING` suppresses later `INFO` records without changing the call sites.\n\n```python\nimport logging\nimport sys\n\nlogger = logging.getLogger("example.worker")\nlogger.setLevel(logging.DEBUG)\nhandler = logging.StreamHandler(sys.stdout)\nhandler.setLevel(logging.WARNING)\nparts = ["%(levelname)s", "%(name)s", "%(message)s"]\nformatter = logging.Formatter(":".join(parts))\nhandler.setFormatter(formatter)\nlogger.handlers[:] = [handler]\nlogger.propagate = False\n\nlogger.info("hidden after threshold change")\nlogger.error("write failed")\n```\n\n```output\nERROR:example.worker:write failed\n```\n:::\n\n:::note\n- Configure logging once; call named loggers throughout the program.\n- Logger and handler levels both participate in filtering.\n- Use exceptions for control flow failures, logging for operational evidence, and warnings for soft compatibility problems.\n:::\n', 'loop-else.md': '+++\nslug = "loop-else"\ntitle = "Loop Else"\nsection = "Control Flow"\nsummary = "A loop else block runs only when the loop did not end with break."\ndoc_path = "/tutorial/controlflow.html#else-clauses-on-loops"\nsee_also = [\n "break-and-continue",\n "for-loops",\n "while-loops",\n]\n+++\n\nPython loops can have an `else` clause. The name is surprising at first: loop `else` means “no `break` happened,” not “the loop condition was false.”\n\nThis is useful for searches. Put the successful early exit in `break`, then put the not-found path in `else`.\n\nUse loop `else` sparingly. It is clearest when the loop is visibly searching for something.\n\n:::program\n```python\nnames = ["Ada", "Grace", "Guido"]\n\nfor name in names:\n if name == "Grace":\n print("found")\n break\nelse:\n print("missing")\n\nfor name in names:\n if name == "Linus":\n print("found")\n break\nelse:\n print("missing")\n```\n:::\n\n:::cell\nIf the loop reaches `break`, the `else` block is skipped. This branch means the search succeeded early.\n\n```python\nnames = ["Ada", "Grace", "Guido"]\n\nfor name in names:\n if name == "Grace":\n print("found")\n break\nelse:\n print("missing")\n```\n\n```output\nfound\n```\n:::\n\n:::cell\nIf the loop finishes without `break`, the `else` block runs. This branch means the search examined every value and found nothing.\n\n```python\nfor name in names:\n if name == "Linus":\n print("found")\n break\nelse:\n print("missing")\n```\n\n```output\nmissing\n```\n:::\n\n:::note\n- Loop `else` runs when the loop was not ended by `break`.\n- It is best for search loops with a clear found/not-found split.\n- It works with both `for` and `while` loops.\n:::\n', 'match-statements.md': '+++\nslug = "match-statements"\ntitle = "Match Statements"\nsection = "Control Flow"\nsummary = "match selects cases using structural pattern matching."\ndoc_path = "/tutorial/controlflow.html#match-statements"\nsee_also = [\n "conditionals",\n "advanced-match-patterns",\n "structured-data-shapes",\n "dicts",\n]\n+++\n\nStructural pattern matching lets a program choose a branch based on the shape of data. It is especially useful when commands, messages, or parsed data have a few known forms.\n\nA `case` pattern can both check constants and bind names. The move case checks the action and extracts `x` and `y` in one readable step.\n\nOrder matters because Python tries cases from top to bottom. Specific shapes should appear before broad fallback cases such as `_`.\n\n:::program\n```python\ncommand = {"action": "move", "x": 3, "y": 4}\n\nmatch command:\n case {"action": "move", "x": x, "y": y}:\n print(f"move to {x},{y}")\n case {"action": "quit"}:\n print("quit")\n case {"action": action}:\n print(f"unknown action: {action}")\n case _:\n print("invalid command")\n```\n:::\n\n:::cell\nUse `match` when the shape of a value is the decision. This command is a dictionary with an action and coordinates; the first case checks that shape and binds `x` and `y`.\n\n```python\ncommand = {"action": "move", "x": 3, "y": 4}\n\nmatch command:\n case {"action": "move", "x": x, "y": y}:\n print(f"move to {x},{y}")\n```\n\n```output\nmove to 3,4\n```\n:::\n\n:::cell\nOther cases describe other valid shapes. This complete fragment changes the command so the `quit` case is the first matching pattern.\n\n```python\ncommand = {"action": "quit"}\n\nmatch command:\n case {"action": "move", "x": x, "y": y}:\n print(f"move to {x},{y}")\n case {"action": "quit"}:\n print("quit")\n```\n\n```output\nquit\n```\n:::\n\n:::cell\nBroader patterns and the `_` catch-all belong after specific cases. This fragment extracts an unknown action before the final fallback would run.\n\n```python\ncommand = {"action": "jump"}\n\nmatch command:\n case {"action": "move", "x": x, "y": y}:\n print(f"move to {x},{y}")\n case {"action": "quit"}:\n print("quit")\n case {"action": action}:\n print(f"unknown action: {action}")\n case _:\n print("invalid command")\n```\n\n```output\nunknown action: jump\n```\n:::\n\n:::note\n- `match` compares structure, not just equality.\n- Patterns can bind names such as `x` and `y` while matching.\n- Mapping patterns match when the named keys are present; extra keys in the subject are ignored rather than failing the case.\n- Put the catch-all `_` case last, because cases are tried from top to bottom.\n:::\n', 'metaclasses.md': '+++\nslug = "metaclasses"\ntitle = "Metaclasses"\nsection = "Classes"\nsummary = "A metaclass customizes how classes themselves are created."\ndoc_path = "/reference/datamodel.html#metaclasses"\nsee_also = [\n "classes",\n "inheritance-and-super",\n "special-methods",\n]\n+++\n\nA metaclass is the class of a class. Most Python code never needs one, but the syntax appears in frameworks that register, validate, or modify classes as they are created.\n\nThe `metaclass=` keyword in a class statement chooses the object that builds the class. This is advanced machinery; decorators and ordinary functions are usually simpler.\n\nUse metaclasses only when class creation itself is the problem being solved.\n\n:::program\n```python\nclass Tagged(type):\n def __new__(mcls, name, bases, namespace):\n namespace["tag"] = name.lower()\n return super().__new__(mcls, name, bases, namespace)\n\nclass Event(metaclass=Tagged):\n pass\n\nprint(Event.tag)\nprint(type(Event).__name__)\n```\n:::\n\n:::cell\nA metaclass customizes class creation. `__new__` receives the class name, bases, and namespace before the class object exists.\n\n```python\nclass Tagged(type):\n def __new__(mcls, name, bases, namespace):\n namespace["tag"] = name.lower()\n return super().__new__(mcls, name, bases, namespace)\n\nprint(Tagged.__name__)\n```\n\n```output\nTagged\n```\n:::\n\n:::cell\nThe `metaclass=` keyword applies that class-building rule. Here the metaclass adds a `tag` attribute to the new class.\n\n```python\nclass Event(metaclass=Tagged):\n pass\n\nprint(Event.tag)\nprint(type(Event).__name__)\n```\n\n```output\nevent\nTagged\n```\n:::\n\n:::note\n- Metaclasses customize class creation, not instance behavior directly.\n- Most code should prefer class decorators, functions, or ordinary inheritance.\n- You are most likely to meet metaclasses inside frameworks and ORMs.\n:::\n', 'modules.md': '+++\nslug = "modules"\ntitle = "Modules"\nsection = "Modules"\nsummary = "Modules organize code into namespaces and expose reusable definitions."\ndoc_path = "/tutorial/modules.html"\nsee_also = [\n "import-aliases",\n "packages",\n]\n+++\n\nModules organize Python code into files and namespaces. `import` executes a module once, stores it in Python\'s import cache, and gives your program access to its definitions.\n\nThis page focuses on import forms and module namespaces. Package layout, aliases, and dynamic imports have their own neighboring examples.\n\nUse module namespaces such as `math.sqrt` when the source of a name should stay visible. Use focused imports such as `from statistics import mean` when the imported name is clear at the call site.\n\n:::program\n```python\nimport math\nimport sys\nfrom statistics import mean\n\nradius = 3\narea = math.pi * radius ** 2\nprint(round(area, 2))\n\nscores = [8, 10, 9]\nprint(mean(scores))\n\nprint(math.__name__)\nprint("math" in sys.modules)\n```\n:::\n\n:::cell\nImporting a module gives access to its namespace. The `math.` prefix makes it clear where `pi` came from.\n\n```python\nimport math\n\nradius = 3\narea = math.pi * radius ** 2\nprint(round(area, 2))\n```\n\n```output\n28.27\n```\n:::\n\n:::cell\nA focused `from ... import ...` brings one definition into the current namespace. This keeps a common operation concise without importing every name.\n\n```python\nfrom statistics import mean\n\nscores = [8, 10, 9]\nprint(mean(scores))\n```\n\n```output\n9\n```\n:::\n\n:::cell\nModules are objects too. Their attributes include metadata such as `__name__`, which records the module\'s import name.\n\n```python\nprint(math.__name__)\n```\n\n```output\nmath\n```\n:::\n\n:::cell\nImported modules are cached in `sys.modules`. Later imports reuse the module object instead of executing the file again.\n\n```python\nimport sys\nprint("math" in sys.modules)\n```\n\n```output\nTrue\n```\n:::\n\n:::note\n- Prefer plain `import module` when the namespace improves readability.\n- Use focused imports for a small number of clear names.\n- Place imports near the top of the file.\n- Imports execute module top-level code once, then reuse the cached module object.\n:::\n', 'multiple-return-values.md': '+++\nslug = "multiple-return-values"\ntitle = "Multiple Return Values"\nsection = "Functions"\nsummary = "Python returns multiple values by returning a tuple and unpacking it."\ndoc_path = "/tutorial/datastructures.html#tuples-and-sequences"\nsee_also = [\n "tuples",\n "unpacking",\n "functions",\n]\n+++\n\nPython multiple return values are tuple return values with friendly syntax. `return a, b` creates one tuple containing two positions.\n\nMost callers unpack that tuple immediately. Good target names make the meaning of each returned position explicit.\n\nUse this for small, fixed groups of results. For larger records, a dataclass or named tuple usually communicates better.\n\n:::program\n```python\ndef divide_with_remainder(total, size):\n quotient = total // size\n remainder = total % size\n return quotient, remainder\n\nresult = divide_with_remainder(17, 5)\nprint(result)\n\nboxes, leftover = result\nprint(boxes)\nprint(leftover)\n```\n:::\n\n:::cell\nReturning values separated by commas returns one tuple. The tuple is visible if the caller stores the result directly.\n\n```python\ndef divide_with_remainder(total, size):\n quotient = total // size\n remainder = total % size\n return quotient, remainder\n\nresult = divide_with_remainder(17, 5)\nprint(result)\n```\n\n```output\n(3, 2)\n```\n:::\n\n:::cell\nCallers usually unpack the tuple immediately or soon after. The names at the call site document what each position means.\n\n```python\nboxes, leftover = result\nprint(boxes)\nprint(leftover)\n```\n\n```output\n3\n2\n```\n:::\n\n:::note\n- A comma creates a tuple; `return a, b` returns one tuple containing two values.\n- Unpacking at the call site gives each returned position a meaningful name.\n- Use a class-like record when the result has many fields.\n:::\n', 'mutability.md': '+++\nslug = "mutability"\ntitle = "Mutability"\nsection = "Data Model"\nsummary = "Some objects change in place, while others return new values."\ndoc_path = "/reference/datamodel.html#objects-values-and-types"\nsee_also = [\n "variables",\n "object-lifecycle",\n "copying-collections",\n "lists",\n]\n+++\n\nObjects in Python can be mutable or immutable. Mutable objects such as lists and dictionaries can change in place, while immutable objects such as strings and tuples produce new values instead.\n\nNames can share one mutable object, so a change through one name is visible through another. This is powerful, but it is also the source of many beginner surprises.\n\nThe boundary matters across Python: `append()` mutates a list, string methods return new strings, and `sorted()` returns a new list while `list.sort()` mutates an existing one.\n\n:::program\n```python\nfirst = ["python"]\nsecond = first\nsecond.append("workers")\nprint(first)\nprint(second)\n\ntext = "python"\nupper_text = text.upper()\nprint(text)\nprint(upper_text)\n\nnumbers = [3, 1, 2]\nordered = sorted(numbers)\nprint(ordered)\nprint(numbers)\n```\n:::\n\n:::cell\nMutable objects can change in place. `first` and `second` point to the same list, so appending through one name changes the object seen through both names.\n\n```python\nfirst = ["python"]\nsecond = first\nsecond.append("workers")\nprint(first)\nprint(second)\n```\n\n```output\n[\'python\', \'workers\']\n[\'python\', \'workers\']\n```\n:::\n\n:::cell\nImmutable objects do not change in place. String methods such as `upper()` return a new string, leaving the original string unchanged.\n\n```python\ntext = "python"\nupper_text = text.upper()\nprint(text)\nprint(upper_text)\n```\n\n```output\npython\nPYTHON\n```\n:::\n\n:::cell\nSome APIs make the boundary explicit. `sorted()` returns a new list, while methods such as `append()` and `list.sort()` mutate an existing list.\n\n```python\nnumbers = [3, 1, 2]\nordered = sorted(numbers)\nprint(ordered)\nprint(numbers)\n```\n\n```output\n[1, 2, 3]\n[3, 1, 2]\n```\n:::\n\n:::note\n- Lists and dictionaries are mutable; strings and tuples are immutable.\n- Aliasing is useful, but copy mutable containers when independent changes are needed.\n- Pay attention to whether an operation mutates in place or returns a new value.\n:::\n', 'networking.md': '+++\nslug = "networking"\ntitle = "Networking"\nsection = "Standard Library"\nsummary = "Networking code exchanges bytes across explicit protocol boundaries."\ndoc_path = "/library/socket.html"\nsee_also = [\n "bytes-and-bytearray",\n "subprocesses",\n "async-await",\n]\nexpected_output = "b\'ping\'\\nping\\n"\n+++\n\nNetworking code sends and receives bytes across protocol boundaries. Higher-level HTTP clients hide many details, but the core rule remains: text is encoded before it leaves the process and decoded after bytes come back.\n\nIn standard Python, the socket version of this lesson uses connected endpoints such as `socket.create_connection()` or, for a local deterministic demonstration, `socket.socketpair()`. This site\'s live example runner does not expose arbitrary OS sockets or outbound calls, so this page teaches the socket contract while making the runner constraint explicit.\n\nThe useful mental model is endpoint plus bytes plus cleanup. A socket connects two endpoints, transfers byte strings, and must be closed when the conversation is finished.\n\n:::program\n```python\nimport socket\n\nleft, right = socket.socketpair()\ntry:\n message = "ping"\n left.sendall(message.encode("utf-8"))\n data = right.recv(16)\n print(data)\n print(data.decode("utf-8"))\nfinally:\n left.close()\n right.close()\n```\n:::\n\n:::cell\n`socketpair()` returns two connected endpoints. `sendall` writes encoded bytes into one end and `recv` reads up to 16 bytes off the other — the byte boundary is the whole point: `"ping".encode("utf-8")` produces `b\'ping\'`, which is what the socket actually moves. The `try`/`finally` closes both endpoints even if `recv` raises, and the second `print` `decode`s the bytes back into a Python `str`. The in-browser sandbox cannot open sockets, so pressing Run here fails; this output came from a real socket pair under standard CPython at build time.\n\n```python\nimport socket\n\nleft, right = socket.socketpair()\ntry:\n message = "ping"\n left.sendall(message.encode("utf-8"))\n data = right.recv(16)\n print(data)\n print(data.decode("utf-8"))\nfinally:\n left.close()\n right.close()\n```\n\n```output\nb\'ping\'\nping\n```\n:::\n\n:::note\n- Network protocols move bytes, not Python `str` objects.\n- Close real sockets when finished, usually with a context manager or `finally` block.\n- Use high-level HTTP libraries for application HTTP unless socket-level control is the lesson.\n- The verified output came from a real `socketpair()` under standard CPython at build time; the in-browser sandbox cannot open sockets, so live runs of this page fail there.\n:::\n', 'newtype.md': '+++\nslug = "newtype"\ntitle = "NewType"\nsection = "Types"\nsummary = "NewType creates distinct static identities for runtime-compatible values."\ndoc_path = "/library/typing.html#typing.NewType"\nsee_also = [\n "type-aliases",\n "type-hints",\n "runtime-type-checks",\n]\n+++\n\n`NewType` creates a distinct static identity for a value that is represented by an existing runtime type. It is useful for IDs, units, and other values that should not be mixed accidentally.\n\nThe key boundary is static versus runtime behavior. A type checker can distinguish `UserId` from `OrderId`, but at runtime both values are plain integers.\n\nUse a type alias when you only want a clearer name for a shape. Use `NewType` when mixing two compatible shapes should be treated as a mistake by static analysis.\n\n:::program\n```python\nfrom typing import NewType\n\nUserId = NewType("UserId", int)\nOrderId = NewType("OrderId", int)\n\n\ndef load_user(user_id: UserId) -> str:\n return f"user {user_id}"\n\nuid = UserId(42)\noid = OrderId(42)\nprint(load_user(uid))\nprint(uid == oid)\nprint(type(uid).__name__)\nprint(UserId.__name__)\n```\n:::\n\n:::cell\n`NewType` helps type checkers distinguish values that share a runtime representation.\n\n```python\nfrom typing import NewType\n\nUserId = NewType("UserId", int)\nOrderId = NewType("OrderId", int)\n\n\ndef load_user(user_id: UserId) -> str:\n return f"user {user_id}"\n\nuid = UserId(42)\nprint(load_user(uid))\n```\n\n```output\nuser 42\n```\n:::\n\n:::cell\nAt runtime, a `NewType` value is the underlying value. It compares like that value and has the same runtime type.\n\n```python\noid = OrderId(42)\nprint(uid == oid)\nprint(type(uid).__name__)\n```\n\n```output\nTrue\nint\n```\n:::\n\n:::cell\nThe `NewType` constructor keeps a name for static tools and introspection.\n\n```python\nprint(UserId.__name__)\nprint(OrderId.__name__)\n```\n\n```output\nUserId\nOrderId\n```\n:::\n\n:::note\n- `NewType` helps type checkers distinguish values that share a runtime representation.\n- At runtime, the value is still the underlying type.\n- Use aliases for readability; use `NewType` for static separation.\n:::\n', 'none.md': '+++\nslug = "none"\ntitle = "None"\nsection = "Basics"\nsummary = "None represents expected absence, distinct from missing keys and errors."\ndoc_path = "/library/constants.html#None"\nsee_also = [\n "values",\n "truthiness",\n "exceptions",\n "dicts",\n]\n+++\n\n`None` represents the absence of a value. It is the usual sentinel when a function has no result to return but the absence itself is meaningful.\n\nBecause `None` is a singleton, idiomatic Python checks it with `is None` or `is not None`. This avoids confusing identity with value equality.\n\nAbsence has several nearby shapes in Python. A function can return `None`, a dictionary lookup can supply a default for a missing key, and an invalid operation can raise an exception.\n\n:::program\n```python\nresult = None\nprint(result is None)\n\ndef find_score(name):\n if name == "Ada":\n return 10\n return None\n\nscore = find_score("Grace")\nprint(score is None)\n\nprofile = {"name": "Ada"}\nprint(profile.get("timezone", "UTC"))\n\ntry:\n int("python")\nexcept ValueError:\n print("invalid number")\n```\n:::\n\n:::cell\n`None` is Python\'s value for “nothing here.” Check it with `is None` because it is a singleton identity value.\n\n```python\nresult = None\nprint(result is None)\n```\n\n```output\nTrue\n```\n:::\n\n:::cell\nFunctions often return `None` when absence is expected and callers can continue. The function name and surrounding code should make that possibility clear.\n\n```python\ndef find_score(name):\n if name == "Ada":\n return 10\n return None\n\nscore = find_score("Grace")\nprint(score is None)\n```\n\n```output\nTrue\n```\n:::\n\n:::cell\nA missing dictionary key is another absence boundary. Use `get()` when the mapping can supply a default, and use exceptions for invalid operations that cannot produce a value.\n\n```python\nprofile = {"name": "Ada"}\nprint(profile.get("timezone", "UTC"))\n\ntry:\n int("python")\nexcept ValueError:\n print("invalid number")\n```\n\n```output\nUTC\ninvalid number\n```\n:::\n\n:::note\n- Use `is None` rather than `== None`; `None` is a singleton identity value.\n- Use `None` for expected absence that callers can test.\n- Use dictionary defaults for missing mapping keys and exceptions for invalid operations.\n:::\n', 'number-parsing.md': '+++\nslug = "number-parsing"\ntitle = "Number Parsing"\nsection = "Standard Library"\nsummary = "int() and float() parse text into numbers and raise ValueError on bad input."\ndoc_path = "/library/functions.html#int"\nsee_also = [\n "exceptions",\n "strings",\n "numbers",\n]\n+++\n\nParsing turns text from files, forms, command lines, or network messages into numeric objects. `int()` parses whole-number text, and `float()` parses decimal or scientific-notation text.\n\nInvalid numeric text raises `ValueError`. Catch that specific exception when bad user input is expected and recoverable; let it fail loudly when the string is supposed to be trusted program data.\n\n`int()` also accepts a base, which is useful at protocol boundaries where numbers are written in hexadecimal, binary, or another explicit notation.\n\n:::program\n```python\nprint(int("42"))\nprint(float("3.5"))\nprint(int("ff", 16))\n\ntexts = ["10", "python", "20"]\nfor text in texts:\n try:\n print(int(text) * 2)\n except ValueError:\n print(f"skip {text!r}")\n```\n:::\n\n:::cell\nUse `int()` for whole numbers and `float()` for decimal text. Parsed values are real numbers, not strings.\n\n```python\nprint(int("42"))\nprint(float("3.5"))\n```\n\n```output\n42\n3.5\n```\n:::\n\n:::cell\nPass a base when the text format says the number is not decimal.\n\n```python\nprint(int("ff", 16))\n```\n\n```output\n255\n```\n:::\n\n:::cell\nCatch `ValueError` at the input boundary when invalid text is normal and recoverable.\n\n```python\ntexts = ["10", "python", "20"]\nfor text in texts:\n try:\n print(int(text) * 2)\n except ValueError:\n print(f"skip {text!r}")\n```\n\n```output\n20\nskip \'python\'\n40\n```\n:::\n\n:::note\n- `int()` and `float()` are constructors that also parse strings.\n- `int(text, base)` makes non-decimal input explicit.\n- Catch `ValueError` for recoverable user input; do not hide unexpected data corruption.\n:::\n', 'numbers.md': '+++\nslug = "numbers"\ntitle = "Numbers"\nsection = "Basics"\nsummary = "Python numbers include integers, floats, and complex values."\ndoc_path = "/library/stdtypes.html#numeric-types-int-float-complex"\nsee_also = [\n "literals",\n "operators",\n]\n+++\n\nPython\'s numeric model starts with `int`, `float`, and `complex`. Integers are arbitrary precision, floats are approximate double-precision values, and complex numbers carry real and imaginary parts.\n\nOperators encode different numeric questions. `/` means true division and returns a float, `//` means floor division, `%` gives the remainder, and `**` computes powers.\n\nUse rounding for display, not as a substitute for understanding floating-point approximation. Financial code usually needs `decimal.Decimal`, which is a separate precision topic.\n\n:::program\n```python\nimport math\n\ncount = 10\nratio = 0.25\nz = 2 + 3j\n\nprint(count + 5)\nprint(count / 4)\nprint(ratio * 2)\nprint(count // 4)\nprint(count % 4)\nprint(2 ** 5)\nprint(z.real, z.imag)\nprint(0.1 + 0.2)\nprint(0.1 + 0.2 == 0.3)\nprint(math.isclose(0.1 + 0.2, 0.3))\nprint(round(3.14159, 2))\n```\n:::\n\n:::cell\nPython has `int` for whole numbers and `float` for approximate real-valued arithmetic. True division with `/` returns a `float`, even when both inputs are integers.\n\n```python\ncount = 10\nratio = 0.25\n\nprint(count + 5)\nprint(count / 4)\nprint(ratio * 2)\n```\n\n```output\n15\n2.5\n0.5\n```\n:::\n\n:::cell\nFloor division and modulo are useful when you need quotient and remainder behavior. Powers use `**`, not `^`.\n\n```python\nprint(count // 4)\nprint(count % 4)\nprint(2 ** 5)\n```\n\n```output\n2\n2\n32\n```\n:::\n\n:::cell\nComplex numbers are built in. The literal suffix `j` marks the imaginary part.\n\n```python\nz = 2 + 3j\nprint(z.real, z.imag)\n```\n\n```output\n2.0 3.0\n```\n:::\n\n:::cell\nFloating-point values are approximate, so `==` between expected and computed floats is rarely the right test. Compare with `math.isclose` (or work in `decimal.Decimal`) when the question is "are these the same number to within tolerance".\n\n```python\nimport math\n\nprint(0.1 + 0.2)\nprint(0.1 + 0.2 == 0.3)\nprint(math.isclose(0.1 + 0.2, 0.3))\nprint(round(3.14159, 2))\n```\n\n```output\n0.30000000000000004\nFalse\nTrue\n3.14\n```\n:::\n\n:::note\n- Python\'s `int` has arbitrary precision; it grows as large as memory allows.\n- Python\'s `float` is approximate double-precision floating point.\n- Use `/` for true division and `//` for floor division.\n- Use `math.isclose` instead of `==` for floating-point comparison; reach for `decimal.Decimal` when exact decimal precision is the domain requirement.\n:::\n', 'object-lifecycle.md': '+++\nslug = "object-lifecycle"\ntitle = "Object Lifecycle"\nsection = "Basics"\nsummary = "Names keep objects reachable until the last reference goes away."\ndoc_path = "/reference/datamodel.html#objects-values-and-types"\nsee_also = [\n "variables",\n "mutability",\n "classes",\n]\n+++\n\nPython objects live independently from the names that refer to them. Assignment adds another reference to an object; rebinding a name points that name somewhere else; `del` removes a name. The object can be reclaimed only after it is no longer reachable.\n\nMost programs do not manually destroy objects. They control lifetime by controlling which containers, local variables, and object attributes still hold references.\n\nThis example uses a small class so the object has visible state. The important evidence is that deleting one name does not destroy the object while another name still refers to it.\n\n:::program\n```python\nclass Box:\n def __init__(self, label):\n self.label = label\n\nbox = Box("draft")\nalias = box\n\nprint(box is alias)\nprint(alias.label)\n\nbox = Box("published")\nprint(alias.label)\nprint(box.label)\n\ndel alias\nprint("old object unreachable")\n```\n:::\n\n:::cell\nTwo names can refer to the same object. Mutating through one name would affect the object seen through the other.\n\n```python\nclass Box:\n def __init__(self, label):\n self.label = label\n\nbox = Box("draft")\nalias = box\n\nprint(box is alias)\nprint(alias.label)\n```\n\n```output\nTrue\ndraft\n```\n:::\n\n:::cell\nRebinding `box` does not change the original object. `alias` still reaches the first `Box` until that reference is removed too.\n\n```python\nbox = Box("published")\nprint(alias.label)\nprint(box.label)\n\ndel alias\nprint("old object unreachable")\n```\n\n```output\ndraft\npublished\nold object unreachable\n```\n:::\n\n:::note\n- Assignment binds names to objects; it does not copy the object.\n- `del name` removes one reference, not necessarily the object itself.\n- Python reclaims unreachable objects automatically, so lifetime bugs usually come from keeping references longer than intended.\n:::\n', 'operator-overloading.md': '+++\nslug = "operator-overloading"\ntitle = "Operator Overloading"\nsection = "Data Model"\nsummary = "Operator methods let objects define arithmetic and comparison syntax."\ndoc_path = "/reference/datamodel.html#emulating-numeric-types"\nsee_also = [\n "operators",\n "special-methods",\n "equality-and-identity",\n]\n+++\n\nOperator overloading lets a class define what expressions such as `a + b` mean for its objects. This is useful when the operation is part of the domain vocabulary.\n\nThe method should preserve the meaning readers expect from the operator. Vectors can add component by component; money can add amounts in the same currency; surprising overloads make code harder to trust.\n\nPython also has reflected methods such as `__radd__` for cases where the left operand does not know how to handle the right operand. That keeps mixed operations possible without making every type know every other type.\n\n:::program\n```python\nclass Vector:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n if not isinstance(other, Vector):\n return NotImplemented\n return Vector(self.x + other.x, self.y + other.y)\n\n def __eq__(self, other):\n if not isinstance(other, Vector):\n return NotImplemented\n return (self.x, self.y) == (other.x, other.y)\n\n def __repr__(self):\n return f"Vector({self.x}, {self.y})"\n\nprint(Vector(2, 3) + Vector(4, 5))\nprint(Vector(1, 1) == Vector(1, 1))\nprint(Vector(1, 1) == 5)\n```\n:::\n\n:::cell\n`__add__` defines how the `+` operator combines two objects. Checking the operand type and returning `NotImplemented` for foreign types lets Python try the other operand\'s reflected method instead of crashing inside yours.\n\n```python\nclass Vector:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n if not isinstance(other, Vector):\n return NotImplemented\n return Vector(self.x + other.x, self.y + other.y)\n\n def __repr__(self):\n return f"Vector({self.x}, {self.y})"\n\nprint(Vector(2, 3) + Vector(4, 5))\n```\n\n```output\nVector(6, 8)\n```\n:::\n\n:::cell\n`__eq__` defines value equality for `==`. Without it, user-defined objects compare by identity. Returning `NotImplemented` for foreign types matters most here: equality against an unrelated value should answer `False`, never raise — Python falls back to identity when both sides decline.\n\n```python\nclass Vector:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __eq__(self, other):\n if not isinstance(other, Vector):\n return NotImplemented\n return (self.x, self.y) == (other.x, other.y)\n\nprint(Vector(1, 1) == Vector(1, 1))\nprint(Vector(1, 1) == 5)\n```\n\n```output\nTrue\nFalse\n```\n:::\n\n:::cell\nA useful `__repr__` makes operator results inspectable while debugging.\n\n```python\nclass Vector:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n if not isinstance(other, Vector):\n return NotImplemented\n return Vector(self.x + other.x, self.y + other.y)\n\n def __repr__(self):\n return f"Vector({self.x}, {self.y})"\n\nprint(repr(Vector(2, 3) + Vector(4, 5)))\n```\n\n```output\nVector(6, 8)\n```\n:::\n\n:::note\n- Overload operators only when the operation is unsurprising.\n- Return `NotImplemented` when an operand type is unsupported.\n- Implement equality deliberately when value comparison matters.\n:::\n', 'operators.md': '+++\nslug = "operators"\ntitle = "Operators"\nsection = "Basics"\nsummary = "Operators combine, compare, and test values in expressions."\ndoc_path = "/reference/expressions.html#operator-precedence"\nsee_also = [\n "numbers",\n "equality-and-identity",\n "assignment-expressions",\n "operator-overloading",\n]\n+++\n\nOperators are the punctuation and keywords that combine values into expressions. Some operators compute new values, some compare values, and some ask relationship questions such as membership or identity.\n\nThis page is the surface map. Focused examples explain the deeper behavior of numbers, booleans, conditions, sets, assignment expressions, and operator overloading.\n\nRead operators by the question they ask: arithmetic computes, comparison answers true or false, boolean operators combine truth values, membership searches a container, and specialized operators should only appear when the data shape calls for them.\n\n:::program\n```python\ncount = 10\nprint(count + 5)\nprint(count // 4)\nprint(count % 4)\nprint(2 ** 5)\n\nscore = 91\nprint(80 <= score < 100)\nprint(score == 100 or score >= 90)\nprint("py" in "python")\n\nflags = 0b0011\nprint(flags & 0b0101)\nprint(flags | 0b0100)\nprint(flags ^ 0b0101)\nprint(flags << 1)\n\nclass Scale:\n def __init__(self, value):\n self.value = value\n\n def __matmul__(self, other):\n return self.value * other.value\n\nprint(Scale(2) @ Scale(3))\n\nitems = ["a", "b"]\nif (size := len(items)) > 0:\n print(size)\n\ndef loud():\n print("ran")\n return True\n\nprint(False and loud())\nprint(True or loud())\nprint(True and loud())\n```\n:::\n\n:::cell\nArithmetic operators compute new values. Use `//` for floor division, `%` for remainder, and `**` for powers.\n\n```python\ncount = 10\nprint(count + 5)\nprint(count // 4)\nprint(count % 4)\nprint(2 ** 5)\n```\n\n```output\n15\n2\n2\n32\n```\n:::\n\n:::cell\nComparison operators produce booleans. Python comparisons can chain, which keeps range checks readable.\n\n```python\nscore = 91\nprint(80 <= score < 100)\nprint(score == 100 or score >= 90)\nprint("py" in "python")\n```\n\n```output\nTrue\nTrue\nTrue\n```\n:::\n\n:::cell\nBitwise operators work on integer bit patterns. They are useful for masks and flags, not ordinary boolean logic. `&` is bitwise AND, `|` is bitwise OR, `^` is exclusive OR, and `<<` shifts left.\n\n```python\nflags = 0b0011\nprint(flags & 0b0101)\nprint(flags | 0b0100)\nprint(flags ^ 0b0101)\nprint(flags << 1)\n```\n\n```output\n1\n7\n6\n6\n```\n:::\n\n:::cell\nThe `@` operator is reserved for matrix-like multiplication and custom types that define `__matmul__`.\n\n```python\nclass Scale:\n def __init__(self, value):\n self.value = value\n\n def __matmul__(self, other):\n return self.value * other.value\n\nprint(Scale(2) @ Scale(3))\n```\n\n```output\n6\n```\n:::\n\n:::cell\nThe walrus operator `:=` assigns inside an expression. Use it when naming a value avoids repeating work in a condition.\n\n```python\nitems = ["a", "b"]\nif (size := len(items)) > 0:\n print(size)\n```\n\n```output\n2\n```\n:::\n\n:::cell\n`and` and `or` short-circuit: the right side runs only when the left side cannot already determine the result. That makes them safe for guard expressions like `obj and obj.value` where the right side would fail on `None`.\n\n```python\ndef loud():\n print("ran")\n return True\n\nprint(False and loud())\nprint(True or loud())\nprint(True and loud())\n```\n\n```output\nFalse\nTrue\nran\nTrue\n```\n:::\n\n:::note\n- Use the clearest operator for the question: arithmetic, comparison, boolean logic, membership, identity, or bitwise manipulation.\n- `and` and `or` short-circuit, so the right side may not run.\n- Operators have precedence; use parentheses when grouping would otherwise be hard to read.\n- Custom operator behavior should make an object feel more natural, not more clever.\n:::\n', 'overloads.md': '+++\nslug = "overloads"\ntitle = "Overloads"\nsection = "Types"\nsummary = "overload describes APIs whose return type depends on argument types."\ndoc_path = "/library/typing.html#typing.overload"\nsee_also = [\n "type-hints",\n "union-and-optional-types",\n "generics-and-typevar",\n]\n+++\n\n`@overload` lets type checkers describe a function whose return type depends on the argument types. The overload declarations are static-only promises; the runtime function is still the single implementation that appears after them.\n\nUse overloads when a union return type would be too vague for callers. For example, `double(4)` returns an `int`, while `double("ha")` returns a `str`; `int | str` loses that relationship.\n\nAt runtime the overload stubs are not dispatch cases. The implementation must inspect or operate on the value just like any other Python function.\n\n:::program\n```python\nfrom typing import overload\n\n@overload\ndef double(value: int) -> int: ...\n\n@overload\ndef double(value: str) -> str: ...\n\ndef double(value: int | str) -> int | str:\n return value * 2\n\nprint(double(4))\nprint(double("ha"))\nprint(double.__annotations__)\n```\n:::\n\n:::cell\nThe overload stubs give static tools precise call shapes: integer in, integer out; string in, string out.\n\n```python\nfrom typing import overload\n\n@overload\ndef double(value: int) -> int: ...\n\n@overload\ndef double(value: str) -> str: ...\n\nprint("static signatures only")\n```\n\n```output\nstatic signatures only\n```\n:::\n\n:::cell\nThere is still one runtime implementation. It must accept every shape promised by the overloads.\n\n```python\ndef double(value: int | str) -> int | str:\n return value * 2\n\nprint(double(4))\nprint(double("ha"))\n```\n\n```output\n8\nhaha\n```\n:::\n\n:::cell\nOnly the implementation\'s annotations are visible on the runtime function. The overload declarations were for the type checker.\n\n```python\nprint(double.__annotations__)\n```\n\n```output\n{\'value\': int | str, \'return\': int | str}\n```\n:::\n\n:::note\n- Put `@overload` declarations immediately before the implementation.\n- Overloads improve static precision; they do not create runtime dispatch.\n- If all callers can work with one broad return type, a simple union annotation is usually enough.\n:::\n', 'packages.md': '+++\nslug = "packages"\ntitle = "Packages"\nsection = "Modules"\nsummary = "Packages organize modules into importable directories."\ndoc_path = "/tutorial/modules.html#packages"\nsee_also = [\n "modules",\n "import-aliases",\n "virtual-environments",\n]\n+++\n\nPackages are modules that can contain other modules. They let a project group related code behind dotted import paths such as `json.decoder` or `email.message`.\n\nAt runtime, importing a submodule gives Python a path through that package structure. In a project on disk, that structure is usually a directory with Python files and often an `__init__.py` file.\n\nUse packages when one module has grown into a small namespace of related modules. Keep module names boring and explicit so readers can tell where imported definitions come from.\n\n:::program\n```python\nimport importlib\nimport json\nimport json.decoder\n\nmodule = importlib.import_module("json.decoder")\n\nprint(json.__name__)\nprint(json.decoder.__name__)\nprint(module.JSONDecoder.__name__)\nprint(module is json.decoder)\n\n\nimport os\nimport sys\nimport tempfile\n\nwith tempfile.TemporaryDirectory() as tmp:\n pkg = os.path.join(tmp, "shapes")\n os.makedirs(pkg)\n with open(os.path.join(pkg, "__init__.py"), "w") as init:\n init.write("from .square import area\\n__all__ = [\'area\']\\n")\n with open(os.path.join(pkg, "square.py"), "w") as square:\n square.write("def area(side):\\n return side * side\\n")\n sys.path.insert(0, tmp)\n try:\n import shapes\n print(shapes.area(3))\n print(shapes.__all__)\n finally:\n sys.path.remove(tmp)\n sys.modules.pop("shapes", None)\n sys.modules.pop("shapes.square", None)\n```\n:::\n\n:::cell\nA package is itself a module. The `json` package exposes a namespace that can contain submodules.\n\n```python\nimport json\n\nprint(json.__name__)\n```\n\n```output\njson\n```\n:::\n\n:::cell\nDotted imports name a path through a package. Importing `json.decoder` makes that submodule available under the package namespace.\n\n```python\nimport json.decoder\n\nprint(json.decoder.__name__)\nprint(json.decoder.JSONDecoder.__name__)\n```\n\n```output\njson.decoder\nJSONDecoder\n```\n:::\n\n:::cell\n`importlib.import_module()` imports by string. It is useful for plugin systems and dynamic imports, but ordinary `import` is clearer when the dependency is known.\n\n```python\nimport importlib\n\nmodule = importlib.import_module("json.decoder")\nprint(module is json.decoder)\n```\n\n```output\nTrue\n```\n:::\n\n:::cell\nInside a package\'s `__init__.py`, `from .submodule import name` re-exports a submodule\'s name at the package root, and `__all__` lists the names that `from package import *` should make visible. This cell builds a temporary `shapes` package on disk to make both forms concrete.\n\n```python\nimport os\nimport sys\nimport tempfile\n\nwith tempfile.TemporaryDirectory() as tmp:\n pkg = os.path.join(tmp, "shapes")\n os.makedirs(pkg)\n with open(os.path.join(pkg, "__init__.py"), "w") as init:\n init.write("from .square import area\\n__all__ = [\'area\']\\n")\n with open(os.path.join(pkg, "square.py"), "w") as square:\n square.write("def area(side):\\n return side * side\\n")\n sys.path.insert(0, tmp)\n try:\n import shapes\n print(shapes.area(3))\n print(shapes.__all__)\n finally:\n sys.path.remove(tmp)\n sys.modules.pop("shapes", None)\n sys.modules.pop("shapes.square", None)\n```\n\n```output\n9\n[\'area\']\n```\n:::\n\n:::note\n- A package is a module that can contain submodules.\n- Dotted imports should mirror a meaningful project structure.\n- Use `from .submodule import name` inside a package to re-export submodule names; set `__all__` to declare the public surface.\n- Prefer ordinary imports unless the module name is truly dynamic.\n:::\n', 'paramspec.md': '+++\nslug = "paramspec"\ntitle = "ParamSpec"\nsection = "Types"\nsummary = "ParamSpec preserves callable parameter types through wrappers."\ndoc_path = "/library/typing.html#typing.ParamSpec"\nsee_also = [\n "callable-types",\n "decorators",\n "generics-and-typevar",\n]\n+++\n\n`ParamSpec` is for decorators and wrapper functions that should keep the wrapped callable\'s parameter shape. Without it, a generic decorator often falls back to `Callable[..., R]`, which says “this returns the right type, but I no longer know what arguments are valid.”\n\nUse `ParamSpec` when the wrapper forwards `*args` and `**kwargs` to the original function without changing the signature. Use a plain `Callable` when the wrapper deliberately accepts a different set of parameters.\n\n`P.args` and `P.kwargs` annotate the wrapper\'s forwarded arguments. A separate `TypeVar` keeps the return type tied to the wrapped function\'s return type.\n\n:::program\n```python\nfrom collections.abc import Callable\nfrom typing import ParamSpec, TypeVar\n\nP = ParamSpec("P")\nR = TypeVar("R")\n\n\ndef erased(func: Callable[..., R]) -> Callable[..., R]:\n return func\n\n\ndef logged(func: Callable[P, R]) -> Callable[P, R]:\n def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:\n print("calling", func.__name__)\n return func(*args, **kwargs)\n return wrapper\n\n@logged\ndef add(left: int, right: int) -> int:\n return left + right\n\nprint(erased(add)(2, 3))\nprint(add(2, 3))\n```\n:::\n\n:::cell\n`Callable[..., R]` is sometimes too broad. It preserves the return type, but the ellipsis means the callable accepts any argument list as far as the type checker can tell.\n\n```python\nfrom collections.abc import Callable\nfrom typing import ParamSpec, TypeVar\n\nR = TypeVar("R")\n\n\ndef erased(func: Callable[..., R]) -> Callable[..., R]:\n return func\n\nprint(erased.__name__)\n```\n\n```output\nerased\n```\n:::\n\n:::cell\n`ParamSpec` captures the original parameters and lets the wrapper forward exactly that shape.\n\n```python\nP = ParamSpec("P")\n\n\ndef logged(func: Callable[P, R]) -> Callable[P, R]:\n def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:\n print("calling", func.__name__)\n return func(*args, **kwargs)\n return wrapper\n\nprint(logged.__name__)\n```\n\n```output\nlogged\n```\n:::\n\n:::cell\nThe decorated function still runs normally. The benefit is static: tools can keep checking that `add` receives two integers.\n\n```python\n@logged\ndef add(left: int, right: int) -> int:\n return left + right\n\nprint(erased(add)(2, 3))\nprint(add(2, 3))\n```\n\n```output\ncalling add\n5\ncalling add\n5\n```\n:::\n\n:::note\n- `ParamSpec` preserves a callable\'s parameter list through transparent wrappers.\n- Pair `ParamSpec` with a `TypeVar` when the return type should also be preserved.\n- Python 3.12+ also accepts the inline PEP 695 spelling `def wrap[**P, R](func: Callable[P, R])`, which declares both variables in the signature itself.\n- If the wrapper changes the public signature, write that new signature directly instead.\n:::\n', 'partial-functions.md': '+++\nslug = "partial-functions"\ntitle = "Partial Functions"\nsection = "Functions"\nsummary = "functools.partial pre-fills arguments to make a more specific callable."\ndoc_path = "/library/functools.html#functools.partial"\nsee_also = [\n "functions",\n "args-and-kwargs",\n "callable-objects",\n]\n+++\n\n`functools.partial` turns a general callable into a more specific callable by remembering some positional or keyword arguments. It is useful when another API wants a one-argument callback but your underlying function needs more context.\n\nA partial object is still callable. It keeps the original function in `.func`, pre-filled positional arguments in `.args`, and pre-filled keyword arguments in `.keywords`.\n\nPrefer a named wrapper function when the adapted behavior needs branching, validation, or a docstring. Use `partial` when the adaptation is simply "call this function with these arguments already supplied."\n\n:::program\n```python\nfrom functools import partial\n\n\ndef apply_tax(rate, amount):\n return round(amount * (1 + rate), 2)\n\nvat = partial(apply_tax, 0.2)\nservice_tax = partial(apply_tax, rate=0.1)\n\nprint(apply_tax(0.2, 50))\nprint(vat(50))\nprint(service_tax(amount=80))\nprint(vat.func.__name__)\nprint(vat.args)\n```\n:::\n\n:::cell\nWithout `partial`, callers repeat the same fixed argument every time they want the specialized behavior.\n\n```python\ndef apply_tax(rate, amount):\n return round(amount * (1 + rate), 2)\n\nprint(apply_tax(0.2, 50))\n```\n\n```output\n60.0\n```\n:::\n\n:::cell\n`partial` stores that fixed argument and returns a callable shaped for the remaining arguments.\n\n```python\nfrom functools import partial\n\nvat = partial(apply_tax, 0.2)\nservice_tax = partial(apply_tax, rate=0.1)\n\nprint(vat(50))\nprint(service_tax(amount=80))\n```\n\n```output\n60.0\n88.0\n```\n:::\n\n:::cell\nPartial objects expose the function and stored arguments, which is helpful when debugging callback wiring.\n\n```python\nprint(vat.func.__name__)\nprint(vat.args)\n```\n\n```output\napply_tax\n(0.2,)\n```\n:::\n\n:::note\n- `partial` adapts a callable by pre-filling arguments.\n- The resulting object can be passed anywhere a callable with the remaining parameters is expected.\n- Use a regular function when the adapter needs more logic than argument binding.\n:::\n', 'positional-only-parameters.md': '+++\nslug = "positional-only-parameters"\ntitle = "Positional-only Parameters"\nsection = "Functions"\nsummary = "Use / to mark parameters that callers must pass by position."\ndoc_path = "/tutorial/controlflow.html#special-parameters"\nsee_also = [\n "keyword-only-arguments",\n "functions",\n "args-and-kwargs",\n]\n+++\n\nA `/` in a function signature marks the parameters before it as positional-only. Callers must pass those arguments by position, not by keyword.\n\nThis is useful when parameter names are implementation details or when an API should match built-in functions that accept positional values.\n\nTogether, `/` and `*` let a signature draw clear boundaries: positional-only inputs, ordinary inputs, and keyword-only options.\n\n:::program\n```python\ndef scale(value, /, factor=2, *, clamp=False):\n result = value * factor\n if clamp:\n result = min(result, 10)\n return result\n\nprint(scale(4))\nprint(scale(4, factor=3))\nprint(scale(4, factor=3, clamp=True))\n\ntry:\n scale(value=4)\nexcept TypeError as error:\n print(type(error).__name__)\n```\n:::\n\n:::cell\nParameters before `/` are positional-only. `value` is the main input, while `factor` remains an ordinary parameter that can be named.\n\n```python\ndef scale(value, /, factor=2, *, clamp=False):\n result = value * factor\n if clamp:\n result = min(result, 10)\n return result\n\nprint(scale(4))\nprint(scale(4, factor=3))\n```\n\n```output\n8\n12\n```\n:::\n\n:::cell\nParameters after `*` are keyword-only. That makes options such as `clamp` explicit at the call site — here `4 * 3` would be `12`, and the clamp visibly caps the result at `10`.\n\n```python\nprint(scale(4, factor=3, clamp=True))\n```\n\n```output\n10\n```\n:::\n\n:::cell\nThe restriction is enforced, not advisory: passing the positional-only `value` by keyword raises `TypeError` at the call site.\n\n```python\ntry:\n scale(value=4)\nexcept TypeError as error:\n print(type(error).__name__)\n```\n\n```output\nTypeError\n```\n:::\n\n:::note\n- `/` marks parameters before it as positional-only.\n- `*` marks parameters after it as keyword-only.\n- Use these markers when the call shape is part of the API design.\n:::\n', 'properties.md': '+++\nslug = "properties"\ntitle = "Properties"\nsection = "Classes"\nsummary = "@property keeps attribute syntax while adding computation or validation."\ndoc_path = "/library/functions.html#property"\nsee_also = [\n "classes",\n "attribute-access",\n "descriptors",\n "dataclasses",\n]\n+++\n\nProperties let a class keep a simple attribute-style API while running code behind the scenes. Callers write `box.area`, but the class can compute the value from current state.\n\nA property setter can validate assignment without changing the public spelling of the attribute. This is the boundary: plain attributes are enough for plain data, while properties are for computed or protected data.\n\nUse properties for cheap, attribute-like operations. Expensive work or actions with side effects should usually remain explicit methods.\n\n:::program\n```python\nclass Rectangle:\n def __init__(self, width, height):\n self.width = width\n self.height = height\n\n @property\n def area(self):\n return self.width * self.height\n\n @property\n def width(self):\n return self._width\n\n @width.setter\n def width(self, value):\n if value <= 0:\n raise ValueError("width must be positive")\n self._width = value\n\nbox = Rectangle(3, 4)\nprint(box.area)\n\nbox.width = 5\nprint(box.area)\n\ntry:\n box.width = 0\nexcept ValueError as error:\n print(error)\n```\n:::\n\n:::cell\nA read-only property exposes computed data through attribute access. `area` stays current because it is calculated from `width` and `height` each time it is read.\n\n```python\nclass Rectangle:\n def __init__(self, width, height):\n self.width = width\n self.height = height\n\n @property\n def area(self):\n return self.width * self.height\n\n @property\n def width(self):\n return self._width\n\n @width.setter\n def width(self, value):\n if value <= 0:\n raise ValueError("width must be positive")\n self._width = value\n\nbox = Rectangle(3, 4)\nprint(box.area)\n```\n\n```output\n12\n```\n:::\n\n:::cell\nA setter lets assignment keep normal attribute syntax while the class validates or normalizes the value.\n\n```python\nbox.width = 5\nprint(box.area)\n```\n\n```output\n20\n```\n:::\n\n:::cell\nValidation belongs inside the class when every caller should obey the same rule. Invalid assignment raises an exception at the boundary.\n\n```python\ntry:\n box.width = 0\nexcept ValueError as error:\n print(error)\n```\n\n```output\nwidth must be positive\n```\n:::\n\n:::note\n- Properties let APIs start simple and grow validation or computation later.\n- Callers access a property like an attribute, not like a method.\n- Use methods instead when work is expensive or action-like.\n:::\n', 'protocols.md': '+++\nslug = "protocols"\ntitle = "Protocols"\nsection = "Types"\nsummary = "Protocol describes required behavior for structural typing."\ndoc_path = "/library/typing.html#typing.Protocol"\nsee_also = [\n "type-hints",\n "classes",\n "inheritance-and-super",\n "abstract-base-classes",\n]\n+++\n\n`Protocol` describes the methods or attributes an object must provide. It exists for structural typing: if an object has the right shape, type checkers can treat it as compatible.\n\nThis is different from inheritance. Inheritance says a class is explicitly derived from a parent; a protocol says callers only need a particular behavior.\n\nAt runtime, ordinary method lookup still applies. Protocols are mainly for static analysis, documentation, and API boundaries.\n\n:::program\n```python\nfrom typing import Protocol\n\nclass Greeter(Protocol):\n def greet(self) -> str:\n ...\n\nclass Person:\n def __init__(self, name):\n self.name = name\n\n def greet(self):\n return f"hello {self.name}"\n\n\ndef welcome(greeter: Greeter):\n print(greeter.greet())\n\nwelcome(Person("Ada"))\nprint(Greeter.__name__)\n```\n:::\n\n:::cell\nA protocol names required behavior. The ellipsis marks the method body as intentionally unspecified, similar to an interface declaration.\n\n```python\nfrom typing import Protocol\n\nclass Greeter(Protocol):\n def greet(self) -> str:\n ...\n\nprint(Greeter.__name__)\n```\n\n```output\nGreeter\n```\n:::\n\n:::cell\nA class can satisfy the protocol without inheriting from it. `Person` has a compatible `greet()` method, so it has the right shape for static type checkers.\n\n```python\nclass Person:\n def __init__(self, name):\n self.name = name\n\n def greet(self):\n return f"hello {self.name}"\n\nprint(Person("Ada").greet())\n```\n\n```output\nhello Ada\n```\n:::\n\n:::cell\nUse the protocol as an annotation at the API boundary. The function only cares that the object can greet; it does not care about the concrete class.\n\n```python\ndef welcome(greeter: Greeter):\n print(greeter.greet())\n\nwelcome(Person("Ada"))\n```\n\n```output\nhello Ada\n```\n:::\n\n:::note\n- Protocols are for structural typing: compatibility by shape rather than explicit inheritance.\n- Type checkers understand protocols; normal runtime method calls still do the work.\n- Prefer inheritance when shared implementation matters, and protocols when only required behavior matters.\n:::\n', 'recursion.md': '+++\nslug = "recursion"\ntitle = "Recursion"\nsection = "Functions"\nsummary = "Recursive functions solve nested problems by calling themselves on smaller pieces."\ndoc_path = "/tutorial/controlflow.html#defining-functions"\nsee_also = [\n "functions",\n "conditionals",\n "generators",\n]\n+++\n\nA recursive function calls itself to solve a smaller piece of the same problem. Recursion exists for data that is naturally nested: trees, menus, expression nodes, and directory-like structures.\n\nEvery recursive function needs a base case that can be answered directly. The recursive case must move toward that base case by passing a smaller part of the data.\n\nPrefer loops for simple repetition over a flat sequence. Prefer recursion when the data shape is recursive too.\n\n:::program\n```python\ntree = {\n "value": 1,\n "children": [\n {"value": 2, "children": []},\n {"value": 3, "children": [{"value": 4, "children": []}]},\n ],\n}\n\ndef total(node):\n subtotal = node["value"]\n for child in node["children"]:\n subtotal += total(child)\n return subtotal\n\nprint(total({"value": 2, "children": []}))\nprint(total(tree))\n```\n:::\n\n:::cell\nA leaf node is the base case. It has no children, so the function can return its own value without making another recursive call.\n\n```python\ndef total(node):\n subtotal = node["value"]\n for child in node["children"]:\n subtotal += total(child)\n return subtotal\n\nprint(total({"value": 2, "children": []}))\n```\n\n```output\n2\n```\n:::\n\n:::cell\nA non-leaf node solves the same problem for each child, then combines those smaller totals with its own value.\n\n```python\ntree = {\n "value": 1,\n "children": [\n {"value": 2, "children": []},\n {"value": 3, "children": [{"value": 4, "children": []}]},\n ],\n}\n\nprint(total(tree))\n```\n\n```output\n10\n```\n:::\n\n:::note\n- Every recursive function needs a base case that stops the calls.\n- Recursion fits nested data better than flat repetition.\n- Python limits recursion depth, so loops are often better for very deep or simple repetition.\n:::\n', 'regular-expressions.md': '+++\nslug = "regular-expressions"\ntitle = "Regular Expressions"\nsection = "Text"\nsummary = "The re module searches and extracts text using regular expressions."\ndoc_path = "/library/re.html"\nsee_also = [\n "strings",\n "string-formatting",\n]\n+++\n\nRegular expressions are a compact language for searching and extracting text patterns. Python\'s `re` module provides the standard interface: `re.match` anchors at the start of the string, `re.search` finds the first occurrence anywhere, `re.findall` collects every match, `re.sub` rewrites matches, and `re.compile` reuses a pattern.\n\nUse regex when the pattern has structure: repeated records, alternatives, optional parts, or pieces you want to capture. Prefer ordinary string methods for simple substring checks because simpler code is easier to maintain.\n\nFlags such as `re.IGNORECASE` adjust matching behavior without rewriting the pattern. Pair them with `re.compile` when the same pattern is used repeatedly.\n\n:::program\n```python\nimport re\n\ntext = "Ada: 10, Grace: 9"\npattern = r"([A-Za-z]+): (\\d+)"\n\nfor name, score in re.findall(pattern, text):\n print(name, int(score))\n\nmatch = re.search(r"Grace: (\\d+)", text)\nprint(match.group(1))\nprint("Grace" in text)\n\nstart = re.match(r"Ada", text)\nprint(start is not None)\nprint(re.match(r"Grace", text))\n\nscoreline = re.compile(pattern)\nprint(scoreline.findall(text))\n\ncasey = "ADA: 11"\nprint(re.search(r"ada", casey, flags=re.IGNORECASE).group(0))\n\nprint(re.sub(r"\\d+", "?", text))\n```\n:::\n\n:::cell\nRaw strings keep backslashes readable in regex patterns. Capturing groups return just the pieces inside parentheses.\n\n```python\nimport re\n\ntext = "Ada: 10, Grace: 9"\npattern = r"([A-Za-z]+): (\\d+)"\n\nfor name, score in re.findall(pattern, text):\n print(name, int(score))\n```\n\n```output\nAda 10\nGrace 9\n```\n:::\n\n:::cell\n`re.search()` finds the first match. A match object exposes captured groups by position.\n\n```python\nmatch = re.search(r"Grace: (\\d+)", text)\nprint(match.group(1))\n```\n\n```output\n9\n```\n:::\n\n:::cell\nFor a simple substring check, ordinary string membership is clearer than regex.\n\n```python\nprint("Grace" in text)\n```\n\n```output\nTrue\n```\n:::\n\n:::cell\n`re.match` only matches at the start of the string; `re.search` finds the first match anywhere. Picking the right one keeps anchoring intent visible without an explicit `^`.\n\n```python\nstart = re.match(r"Ada", text)\nprint(start is not None)\nprint(re.match(r"Grace", text))\n```\n\n```output\nTrue\nNone\n```\n:::\n\n:::cell\n`re.compile` produces a reusable pattern object and gives the pattern a name. The `re` module also caches recently compiled patterns internally, so the practical wins are readability and a place to attach flags more than raw speed.\n\n```python\nscoreline = re.compile(pattern)\nprint(scoreline.findall(text))\n```\n\n```output\n[(\'Ada\', \'10\'), (\'Grace\', \'9\')]\n```\n:::\n\n:::cell\nFlags such as `re.IGNORECASE` adjust matching without changing the pattern. `re.sub` replaces every match with a replacement string and returns the rewritten text.\n\n```python\ncasey = "ADA: 11"\nprint(re.search(r"ada", casey, flags=re.IGNORECASE).group(0))\n\nprint(re.sub(r"\\d+", "?", text))\n```\n\n```output\nADA\nAda: ?, Grace: ?\n```\n:::\n\n:::note\n- Use raw strings for regex patterns so backslashes are easier to read.\n- Use capturing groups when the point is extraction, not just matching.\n- `re.match` anchors at the start; `re.search` finds the first match anywhere.\n- `re.compile` saves work when the pattern runs more than once.\n- `re.sub` rewrites matches; flags like `re.IGNORECASE` change matching behavior without rewriting the pattern.\n- Reach for string methods before regex when the pattern is simple.\n:::\n', 'runtime-type-checks.md': '+++\nslug = "runtime-type-checks"\ntitle = "Runtime Type Checks"\nsection = "Types"\nsummary = "type, isinstance, and issubclass inspect runtime relationships."\ndoc_path = "/library/functions.html#isinstance"\nsee_also = [\n "type-hints",\n "protocols",\n "casts-and-any",\n "abstract-base-classes",\n]\n+++\n\nRuntime type checks inspect real objects while the program is running. They are different from type hints, which mostly guide tools before the program runs.\n\nUse `type()` when the exact class matters, `isinstance()` when subclasses should count, and `issubclass()` when checking class relationships. Most APIs prefer behavior over type checks, but runtime checks are useful at input boundaries.\n\nDo not turn every function into a wall of `isinstance()` calls. If the code only needs an object that can perform an operation, duck typing or a protocol may be clearer.\n\n:::program\n```python\nclass Animal:\n pass\n\nclass Dog(Animal):\n pass\n\npet = Dog()\n\nprint(type(pet).__name__)\nprint(type(pet) is Animal)\nprint(isinstance(pet, Animal))\nprint(issubclass(Dog, Animal))\n```\n:::\n\n:::cell\n`type()` reports the exact runtime class. A `Dog` instance is not exactly an `Animal` instance.\n\n```python\nclass Animal:\n pass\n\nclass Dog(Animal):\n pass\n\npet = Dog()\nprint(type(pet).__name__)\nprint(type(pet) is Animal)\n```\n\n```output\nDog\nFalse\n```\n:::\n\n:::cell\n`isinstance()` accepts subclasses, which is usually what API boundaries want.\n\n```python\nprint(isinstance(pet, Dog))\nprint(isinstance(pet, Animal))\n```\n\n```output\nTrue\nTrue\n```\n:::\n\n:::cell\n`issubclass()` checks class relationships rather than individual objects.\n\n```python\nprint(issubclass(Dog, Animal))\n```\n\n```output\nTrue\n```\n:::\n\n:::note\n- `type()` is exact; `isinstance()` follows inheritance.\n- Runtime checks inspect objects, not static annotations.\n- Prefer behavior, protocols, or clear validation over scattered type checks.\n:::\n', 'scope-global-nonlocal.md': '+++\nslug = "scope-global-nonlocal"\ntitle = "Global and Nonlocal"\nsection = "Functions"\nsummary = "global and nonlocal choose which outer binding assignment should update."\ndoc_path = "/reference/simple_stmts.html#the-global-statement"\nsee_also = [\n "variables",\n "closures",\n "functions",\n]\n+++\n\nAssignment normally creates or updates a local name inside the current function. `global` and `nonlocal` are explicit escape hatches for rebinding names outside that local scope.\n\nUse `nonlocal` when an inner function should update a name in an enclosing function. Use `global` rarely; passing values and returning results is usually clearer.\n\nThese statements affect name binding, not object mutation. Mutating a shared list is different from rebinding the name itself.\n\n:::program\n```python\ncount = 0\n\ndef bump_global():\n global count\n count += 1\n\nbump_global()\nprint(count)\n\n\ndef make_counter():\n total = 0\n def bump():\n nonlocal total\n total += 1\n return total\n return bump\n\ncounter = make_counter()\nprint(counter())\nprint(counter())\n```\n:::\n\n:::cell\n`global` tells assignment to update a module-level binding. Without it, `count += 1` would try to assign a local `count`.\n\n```python\ncount = 0\n\ndef bump_global():\n global count\n count += 1\n\nbump_global()\nprint(count)\n```\n\n```output\n1\n```\n:::\n\n:::cell\n`nonlocal` tells assignment to update a binding in the nearest enclosing function scope. This is useful for small closures that keep state.\n\n```python\ndef make_counter():\n total = 0\n def bump():\n nonlocal total\n total += 1\n return total\n return bump\n\ncounter = make_counter()\nprint(counter())\nprint(counter())\n```\n\n```output\n1\n2\n```\n:::\n\n:::note\n- Assignment inside a function is local unless declared otherwise.\n- Prefer `nonlocal` for closure state and avoid `global` unless module state is truly intended.\n- Passing values and returning results is usually easier to test than rebinding outer names.\n:::\n', 'sentinel-iteration.md': '+++\nslug = "sentinel-iteration"\ntitle = "Sentinel Iteration"\nsection = "Iteration"\nsummary = "iter(callable, sentinel) repeats calls until a marker value appears."\ndoc_path = "/library/functions.html#iter"\nsee_also = [\n "iterators",\n "while-loops",\n "break-and-continue",\n]\n+++\n\n`iter(callable, sentinel)` calls a zero-argument callable over and over. It yields each result until the callable returns the sentinel value, and the sentinel itself is not yielded.\n\nThis shape is useful for repeated reads: file blocks until `b""`, socket chunks until an empty response, queue items until a stop marker. It removes the common `while True` plus `break` scaffolding when the loop body is otherwise just "read, then process".\n\nThe callable must take no arguments. Wrap a parameterized reader in a `lambda`, `functools.partial`, or object method when the underlying API needs parameters.\n\n:::program\n```python\nchunks = iter(["py", "thon", ""])\n\n\ndef read_chunk():\n return next(chunks)\n\nprint(list(iter(read_chunk, "")))\n\nchunks = iter(["py", "thon", ""])\nword = ""\nwhile True:\n chunk = next(chunks)\n if chunk == "":\n break\n word += chunk\nprint(word)\n```\n:::\n\n:::cell\nThe two-argument form turns a polling callable into an iterator. The empty string stops the loop without appearing in the result.\n\n```python\nchunks = iter(["py", "thon", ""])\n\n\ndef read_chunk():\n return next(chunks)\n\nprint(list(iter(read_chunk, "")))\n```\n\n```output\n[\'py\', \'thon\']\n```\n:::\n\n:::cell\nThe equivalent manual loop needs an explicit read, comparison, and `break`. Use this shape when the stop condition is more complicated than a single sentinel value.\n\n```python\nchunks = iter(["py", "thon", ""])\nword = ""\nwhile True:\n chunk = next(chunks)\n if chunk == "":\n break\n word += chunk\nprint(word)\n```\n\n```output\npython\n```\n:::\n\n:::note\n- The callable passed to `iter(callable, sentinel)` must take no arguments.\n- The sentinel stops iteration and is not yielded.\n- When the loop needs richer branching, an explicit `while` loop may be clearer.\n:::\n', 'sets.md': '+++\nslug = "sets"\ntitle = "Sets"\nsection = "Collections"\nsummary = "Sets store unique values and make membership checks explicit."\ndoc_path = "/tutorial/datastructures.html#sets"\nsee_also = [\n "lists",\n "dicts",\n "comprehensions",\n]\n+++\n\nSets store unique hashable values. Use them when membership and de-duplication matter more than order.\n\nA list can answer membership with `in`, but a set communicates that membership is the main operation. Set algebra then expresses how groups relate to each other.\n\nBecause sets are unordered, examples often wrap output in `sorted()` so the display is deterministic.\n\n:::program\n```python\nlanguages = ["python", "go", "python"]\nunique_languages = set(languages)\nprint(sorted(unique_languages))\n\nallowed = {"python", "rust"}\nprint("python" in allowed)\nprint("ruby" in allowed)\n\ncompiled = {"go", "rust"}\nprint(sorted(allowed | compiled))\nprint(sorted(allowed & compiled))\nprint(sorted(allowed - compiled))\n```\n:::\n\n:::cell\nCreating a set removes duplicates. Keep a list when order and repeated values matter; convert to a set when uniqueness is the point.\n\n```python\nlanguages = ["python", "go", "python"]\nunique_languages = set(languages)\nprint(sorted(unique_languages))\n```\n\n```output\n[\'go\', \'python\']\n```\n:::\n\n:::cell\nMembership checks are the everyday set operation. A list can also use `in`, but a set says that membership is central to the data shape.\n\n```python\nallowed = {"python", "rust"}\nprint("python" in allowed)\nprint("ruby" in allowed)\n```\n\n```output\nTrue\nFalse\n```\n:::\n\n:::cell\nUnion, intersection, and difference describe relationships between groups without manual loops.\n\n```python\ncompiled = {"go", "rust"}\nprint(sorted(allowed | compiled))\nprint(sorted(allowed & compiled))\nprint(sorted(allowed - compiled))\n```\n\n```output\n[\'go\', \'python\', \'rust\']\n[\'rust\']\n[\'python\']\n```\n:::\n\n:::note\n- Use sets when uniqueness and membership are the main operations.\n- Prefer lists when order or repeated values are part of the meaning.\n- Sets are unordered, so sort them when examples need deterministic display.\n:::\n', 'slices.md': '+++\nslug = "slices"\ntitle = "Slices"\nsection = "Collections"\nsummary = "Slices copy meaningful ranges from ordered sequences."\ndoc_path = "/tutorial/introduction.html#lists"\nsee_also = [\n "lists",\n "tuples",\n "strings",\n]\n+++\n\nSlicing reads a range from an ordered sequence with `start:stop:step`. It exists because Python code often needs a meaningful piece of a sequence: a page, a prefix, a tail, a stride, or a reversed view.\n\nThe stop index is excluded. That convention makes lengths and adjacent ranges line up: `items[:3]` and `items[3:]` split a sequence without overlap.\n\nSlices return new sequence objects for built-in lists and strings. Use indexing for one item; use slicing when the result should still be a sequence.\n\n:::program\n```python\nletters = ["a", "b", "c", "d", "e", "f"]\nfirst_page = letters[:3]\nrest = letters[3:]\nprint(first_page)\nprint(rest)\n\nmiddle = letters[1:5]\nevery_other = letters[::2]\nreversed_letters = letters[::-1]\nprint(middle)\nprint(every_other)\nprint(reversed_letters)\nprint(letters)\n```\n:::\n\n:::cell\nOmitted bounds mean “from the beginning” or “through the end.” Because the stop index is excluded, adjacent slices split a sequence cleanly.\n\n```python\nletters = ["a", "b", "c", "d", "e", "f"]\nfirst_page = letters[:3]\nrest = letters[3:]\nprint(first_page)\nprint(rest)\n```\n\n```output\n[\'a\', \'b\', \'c\']\n[\'d\', \'e\', \'f\']\n```\n:::\n\n:::cell\nUse `start:stop` for a middle range and `step` when you want to skip or walk backward. These operations return new lists; the original list is unchanged.\n\n```python\nmiddle = letters[1:5]\nevery_other = letters[::2]\nreversed_letters = letters[::-1]\nprint(middle)\nprint(every_other)\nprint(reversed_letters)\nprint(letters)\n```\n\n```output\n[\'b\', \'c\', \'d\', \'e\']\n[\'a\', \'c\', \'e\']\n[\'f\', \'e\', \'d\', \'c\', \'b\', \'a\']\n[\'a\', \'b\', \'c\', \'d\', \'e\', \'f\']\n```\n:::\n\n:::note\n- Slice stop indexes are excluded, so adjacent ranges compose cleanly.\n- Omitted bounds mean the beginning or end of the sequence.\n- A negative step walks backward; `[::-1]` is a common reversed-copy idiom.\n:::\n', 'sorting.md': '+++\nslug = "sorting"\ntitle = "Sorting"\nsection = "Collections"\nsummary = "sorted returns a new ordered list and key functions choose the sort value."\ndoc_path = "/howto/sorting.html"\nsee_also = [\n "lists",\n "lambdas",\n "functions",\n]\n+++\n\n`sorted()` accepts any iterable and returns a new list. The original collection is left untouched, which makes `sorted()` useful in expressions and pipelines.\n\nUse `key=` to say what value should be compared for each item. This is the idiomatic way to sort records, tuples, dictionaries, and objects by a field.\n\nUse `reverse=True` for descending order. Use `list.sort()` instead when you intentionally want to mutate an existing list in place.\n\n:::program\n```python\nnames = ["Guido", "Ada", "Grace"]\nprint(sorted(names))\nprint(names)\n\nusers = [\n {"name": "Ada", "score": 10},\n {"name": "Guido", "score": 8},\n {"name": "Grace", "score": 10},\n]\nranked = sorted(users, key=lambda user: user["score"], reverse=True)\nprint([user["name"] for user in ranked])\n\nusers.sort(key=lambda user: user["name"])\nprint([user["name"] for user in users])\n```\n:::\n\n:::cell\n`sorted()` returns a new list. Printing the original list afterward shows that the input order did not change.\n\n```python\nnames = ["Guido", "Ada", "Grace"]\nprint(sorted(names))\nprint(names)\n```\n\n```output\n[\'Ada\', \'Grace\', \'Guido\']\n[\'Guido\', \'Ada\', \'Grace\']\n```\n:::\n\n:::cell\nA key function computes the value to compare. Here the records are sorted by score, highest first, and the output shows the resulting order.\n\n```python\nusers = [\n {"name": "Ada", "score": 10},\n {"name": "Guido", "score": 8},\n {"name": "Grace", "score": 10},\n]\nranked = sorted(users, key=lambda user: user["score"], reverse=True)\nprint([user["name"] for user in ranked])\n```\n\n```output\n[\'Ada\', \'Grace\', \'Guido\']\n```\n:::\n\n:::cell\n`list.sort()` sorts the list in place. Use it when mutation is the point and no separate sorted copy is needed.\n\n```python\nusers.sort(key=lambda user: user["name"])\nprint([user["name"] for user in users])\n```\n\n```output\n[\'Ada\', \'Grace\', \'Guido\']\n```\n:::\n\n:::note\n- `sorted()` makes a new list; `list.sort()` mutates an existing list.\n- `key=` should return the value Python compares for each item.\n- Python\'s sort is stable, so equal keys keep their original relative order.\n:::\n', 'special-methods.md': '+++\nslug = "special-methods"\ntitle = "Special Methods"\nsection = "Data Model"\nsummary = "Special methods connect your objects to Python syntax and built-ins."\ndoc_path = "/reference/datamodel.html#special-method-names"\nsee_also = [\n "container-protocols",\n "operator-overloading",\n "callable-objects",\n "context-managers",\n]\n+++\n\nSpecial methods, often called dunder methods, connect user-defined classes to Python syntax and built-ins such as len(), iter(), and repr().\n\nImplementing these methods lets your objects participate in Python protocols rather than forcing callers to learn custom method names for common operations.\n\nGood special methods make objects feel boring in the best way: they work with the language features Python programmers already know.\n\n:::program\n```python\nclass Bag:\n def __init__(self, items):\n self.items = list(items)\n\n def __len__(self):\n return len(self.items)\n\n def __iter__(self):\n return iter(self.items)\n\n def __repr__(self):\n return f"Bag({self.items!r})"\n\n def __str__(self):\n return ", ".join(self.items)\n\n def __eq__(self, other):\n return isinstance(other, Bag) and self.items == other.items\n\n def __hash__(self):\n return hash(tuple(self.items))\n\n def __lt__(self, other):\n return self.items < other.items\n\n def __contains__(self, item):\n return item in self.items\n\n def __getitem__(self, index):\n return self.items[index]\n\n def __setitem__(self, index, value):\n self.items[index] = value\n\n def __bool__(self):\n return bool(self.items)\n\nbag = Bag(["a", "b"])\nprint(len(bag))\nprint(list(bag))\nprint(bag)\nprint(repr(bag))\nprint(Bag(["a", "b"]) == Bag(["a", "b"]))\nprint(Bag(["a"]) < Bag(["a", "b"]))\nprint(hash(Bag(["a"])) == hash(Bag(["a"])))\nprint("a" in bag)\nprint(bag[0])\nbag[1] = "z"\nprint(list(bag))\nprint(bool(Bag([])))\n\n\nclass Multiplier:\n def __init__(self, factor):\n self.factor = factor\n\n def __call__(self, value):\n return value * self.factor\n\ntriple = Multiplier(3)\nprint(triple(5))\n\n\nclass Trace:\n def __enter__(self):\n print("enter")\n return self\n\n def __exit__(self, *exc):\n print("exit")\n return False\n\nwith Trace():\n print("inside")\n```\n:::\n\n:::cell\nStart with a normal class that stores its data. Special methods build on ordinary instance state.\n\n```python\nclass Bag:\n def __init__(self, items):\n self.items = list(items)\n\nbag = Bag(["a", "b"])\nprint(bag.items)\n```\n\n```output\n[\'a\', \'b\']\n```\n:::\n\n:::cell\nImplement `__len__` to let `len()` ask the object for its size using Python\'s standard protocol.\n\n```python\nclass Bag:\n def __init__(self, items):\n self.items = list(items)\n\n def __len__(self):\n return len(self.items)\n\nbag = Bag(["a", "b"])\nprint(len(bag))\n```\n\n```output\n2\n```\n:::\n\n:::cell\nImplement `__iter__` to make the object iterable. Then tools such as `list()` can consume it without a custom method name.\n\n```python\nclass Bag:\n def __init__(self, items):\n self.items = list(items)\n\n def __len__(self):\n return len(self.items)\n\n def __iter__(self):\n return iter(self.items)\n\nbag = Bag(["a", "b"])\nprint(list(bag))\n```\n\n```output\n[\'a\', \'b\']\n```\n:::\n\n:::cell\nImplement `__repr__` to give the object a useful developer-facing representation when it is printed or inspected. With no `__str__` defined, `print()` falls back to `__repr__`.\n\n```python\nclass Bag:\n def __init__(self, items):\n self.items = list(items)\n\n def __len__(self):\n return len(self.items)\n\n def __iter__(self):\n return iter(self.items)\n\n def __repr__(self):\n return f"Bag({self.items!r})"\n\nbag = Bag(["a", "b"])\nprint(bag)\n```\n\n```output\nBag([\'a\', \'b\'])\n```\n:::\n\n:::cell\nAdd `__str__` for an end-user representation. `print()` and `str()` prefer `__str__`; `repr()` and the REPL still use `__repr__`. Keep `__repr__` unambiguous for debugging and let `__str__` be the friendly form.\n\n```python\nclass Bag:\n def __init__(self, items):\n self.items = list(items)\n\n def __repr__(self):\n return f"Bag({self.items!r})"\n\n def __str__(self):\n return ", ".join(self.items)\n\nbag = Bag(["a", "b"])\nprint(bag)\nprint(repr(bag))\n```\n\n```output\na, b\nBag([\'a\', \'b\'])\n```\n:::\n\n:::cell\n`__eq__` decides what equality means for the type, comparing contents. `__lt__` orders by those same contents, so ordering stays consistent with equality (define one comparison and `functools.total_ordering` can fill in the rest; `__lt__` alone is enough for `<` and `sorted()`). Defining `__eq__` removes the default `__hash__`, so add it back only for types you treat as immutable: this `Bag` hashes its current items, so the last two lines show the hazard — a `Bag` found in a set becomes unfindable once its items change, because its hash no longer points at the bucket it was stored in.\n\n```python\nclass Bag:\n def __init__(self, items):\n self.items = list(items)\n\n def __eq__(self, other):\n return isinstance(other, Bag) and self.items == other.items\n\n def __hash__(self):\n return hash(tuple(self.items))\n\n def __lt__(self, other):\n return self.items < other.items\n\nprint(Bag(["a", "b"]) == Bag(["a", "b"]))\nprint(Bag(["a"]) < Bag(["a", "b"]))\n\nbag = Bag(["a"])\nseen = {bag}\nprint(bag in seen)\nbag.items.append("b")\nprint(bag in seen)\n```\n\n```output\nTrue\nTrue\nTrue\nFalse\n```\n:::\n\n:::cell\nThe container protocols make instances behave like built-in containers. `__contains__` powers `in`, `__getitem__`/`__setitem__` power subscription, and `__bool__` decides truthiness for `if` and `while`. See [container-protocols](/examples/container-protocols) for the full surface.\n\n```python\nclass Bag:\n def __init__(self, items):\n self.items = list(items)\n\n def __contains__(self, item):\n return item in self.items\n\n def __getitem__(self, index):\n return self.items[index]\n\n def __setitem__(self, index, value):\n self.items[index] = value\n\n def __bool__(self):\n return bool(self.items)\n\nbag = Bag(["a", "b"])\nprint("a" in bag)\nprint(bag[0])\nbag[1] = "z"\nprint(bag.items)\nprint(bool(Bag([])))\n```\n\n```output\nTrue\na\n[\'a\', \'z\']\nFalse\n```\n:::\n\n:::cell\n`__call__` makes an instance callable like a function — useful for stateful operations whose configuration deserves a name. `__enter__` and `__exit__` make a class a context manager so it can be used with `with`. The focused [callable-objects](/examples/callable-objects) and [context-managers](/examples/context-managers) pages go deeper.\n\n```python\nclass Multiplier:\n def __init__(self, factor):\n self.factor = factor\n\n def __call__(self, value):\n return value * self.factor\n\ntriple = Multiplier(3)\nprint(triple(5))\n\n\nclass Trace:\n def __enter__(self):\n print("enter")\n return self\n\n def __exit__(self, *exc):\n print("exit")\n return False\n\nwith Trace():\n print("inside")\n```\n\n```output\n15\nenter\ninside\nexit\n```\n:::\n\n:::note\n- Dunder methods are looked up by Python\'s data model protocols.\n- `__repr__` is the developer-facing form; `__str__` is the user-facing form. `print()` falls back to `__repr__` when `__str__` is missing.\n- Defining `__eq__` removes the default `__hash__`; restore it when the type should be hashable.\n- Container protocols (`__contains__`, `__getitem__`, `__setitem__`, `__bool__`) make instances behave like built-in containers.\n- `__call__` makes instances callable; `__enter__`/`__exit__` make them context managers.\n- Implement the smallest protocol that makes your object feel native.\n:::\n', 'string-formatting.md': '+++\nslug = "string-formatting"\ntitle = "String Formatting"\nsection = "Text"\nsummary = "f-strings turn values into readable text at the point of use."\ndoc_path = "/tutorial/inputoutput.html#formatted-string-literals"\nsee_also = [\n "strings",\n "logging",\n "csv-data",\n "values",\n]\n+++\n\nFormatted string literals, or f-strings, exist because programs constantly need to turn values into human-readable text. They keep the expression next to the words it explains.\n\nFormat specifications after `:` control presentation details such as width, alignment, padding, and precision. This separates the value being computed from the way it should be displayed.\n\nUse f-strings for most new formatting code. They relate directly to expressions: anything inside braces is evaluated, then formatted into the surrounding string.\n\n:::program\n```python\nname = "Ada"\nscore = 9.5\nrank = 1\n\nmessage = f"{name} scored {score}"\nprint(message)\n\nrow = f"{rank:>2} | {name:<8} | {score:05.1f}"\nprint(row)\n\nprint(f"{score = }")\n```\n:::\n\n:::cell\nAn f-string evaluates expressions inside braces and inserts their string form into the surrounding text. This is clearer than joining several converted values by hand.\n\n```python\nname = "Ada"\nscore = 9.5\nrank = 1\n\nmessage = f"{name} scored {score}"\nprint(message)\n```\n\n```output\nAda scored 9.5\n```\n:::\n\n:::cell\nFormat specifications after `:` control display without changing the underlying values. Here the rank is right-aligned, the name is left-aligned, and `05.1f` zero-pads the score to a width of five characters with one decimal place.\n\n```python\nrow = f"{rank:>2} | {name:<8} | {score:05.1f}"\nprint(row)\n```\n\n```output\n 1 | Ada | 009.5\n```\n:::\n\n:::cell\nThe debug form with `=` is useful while learning or logging because it prints both the expression and the value.\n\n```python\nprint(f"{score = }")\n```\n\n```output\nscore = 9.5\n```\n:::\n\n:::note\n- Use `f"..."` strings for most new formatting code.\n- Expressions inside braces are evaluated before formatting.\n- Format specifications after `:` control alignment, width, padding, and precision.\n:::\n', 'strings.md': '+++\nslug = "strings"\ntitle = "Strings"\nsection = "Text"\nsummary = "Strings are immutable Unicode text sequences."\ndoc_path = "/library/stdtypes.html#text-sequence-type-str"\nsee_also = [\n "values",\n "string-formatting",\n "bytes-and-bytearray",\n "regular-expressions",\n]\n+++\n\nPython strings are immutable Unicode text sequences. A `str` stores text as Unicode code points, so it can represent English, Thai, accented letters, emoji, and ordinary ASCII with the same type.\n\nUnicode matters because text length and byte length are different questions. The English word `"hello"` uses five code points and five UTF-8 bytes because ASCII characters encode as one byte each. The Thai greeting `"สวัสดี"` has six code points but needs eighteen UTF-8 bytes.\n\nUse `str` when you mean text, and encode to `bytes` only at boundaries such as files, network protocols, and binary APIs. String operations such as `upper()` and `strip()` return new strings instead of changing the original.\n\n:::program\n```python\nenglish = "hello"\nfrench = "café"\nthai = "สวัสดี"\n\nfor label, word in [("English", english), ("French", french), ("Thai", thai)]:\n print(label, word, len(word), len(word.encode("utf-8")))\n\nprint(thai[0])\nprint([hex(ord(char)) for char in thai[:2]])\n\ntext = " café "\nclean = text.strip()\nprint(clean)\nprint(clean.upper())\nprint(clean.encode("utf-8"))\n```\n:::\n\n:::cell\nCompare three words by code-point count and UTF-8 byte count. ASCII characters take one byte each (`hello` → 5 bytes); the `é` in `café` is one code point but two UTF-8 bytes; each Thai character takes three. The `str` type abstracts over all three.\n\n```python\nenglish = "hello"\nfrench = "café"\nthai = "สวัสดี"\n\nfor label, word in [("English", english), ("French", french), ("Thai", thai)]:\n print(label, word, len(word), len(word.encode("utf-8")))\n```\n\n```output\nEnglish hello 5 5\nFrench café 4 5\nThai สวัสดี 6 18\n```\n:::\n\n:::cell\nIndexing and iteration work with Unicode code points, not encoded bytes. `ord()` returns the integer code point, which is often displayed in hexadecimal when teaching text encoding.\n\n```python\nprint(thai[0])\nprint([hex(ord(char)) for char in thai[:2]])\n```\n\n```output\nส\n[\'0xe2a\', \'0xe27\']\n```\n:::\n\n:::cell\nString methods return new strings because strings are immutable. Encoding turns text into bytes when another system needs a byte representation.\n\n```python\ntext = " café "\nclean = text.strip()\nprint(clean)\nprint(clean.upper())\nprint(clean.encode("utf-8"))\n```\n\n```output\ncafé\nCAFÉ\nb\'caf\\xc3\\xa9\'\n```\n:::\n\n:::note\n- Use `str` for text and `bytes` for binary data.\n- `len(text)` counts Unicode code points; `len(text.encode("utf-8"))` counts encoded bytes.\n- ASCII text is a useful baseline because each ASCII code point is one UTF-8 byte.\n- String methods return new strings because strings are immutable.\n- User-visible “characters” can be more subtle than code points; combining marks and emoji sequences may need specialized text handling.\n:::\n', 'structured-data-shapes.md': '+++\nslug = "structured-data-shapes"\ntitle = "Structured Data Shapes"\nsection = "Classes"\nsummary = "dataclass, NamedTuple, and TypedDict each model records with different trade-offs."\ndoc_path = "/library/dataclasses.html"\nsee_also = [\n "dataclasses",\n "typed-dicts",\n "tuples",\n "classes",\n]\n+++\n\n`@dataclass`, `typing.NamedTuple`, and `typing.TypedDict` are three ways to give a record a name and a schema. They model the same data but differ in mutability, access syntax, and what the type information costs at runtime.\n\nA dataclass is a regular class with `__init__` and `__repr__` generated for you, so instances are mutable and attribute-accessed. A `NamedTuple` is a tuple subclass with named positions, so instances are immutable and support both `obj.field` and `obj[index]`. A `TypedDict` is a plain dict at runtime; the schema lives only in the type checker.\n\nPick the shape that matches the problem: a dataclass when methods or mutability help; a `NamedTuple` for small immutable records that benefit from unpacking; a `TypedDict` for JSON-shaped data that should stay as a dict at the boundary.\n\n:::program\n```python\nfrom dataclasses import dataclass\nfrom typing import NamedTuple, TypedDict\n\n@dataclass\nclass UserClass:\n name: str\n score: int\n\nclass UserTuple(NamedTuple):\n name: str\n score: int\n\nclass UserDict(TypedDict):\n name: str\n score: int\n\na = UserClass("Ada", 98)\nprint(a)\na.score = 100\nprint(a.score)\n\nb = UserTuple("Ada", 98)\nprint(b)\nprint(b.name, b[1])\nprint(b._replace(score=100))\n\nc: UserDict = {"name": "Ada", "score": 98}\nprint(c)\nprint(c["name"])\nprint(type(c).__name__)\n\nprint(isinstance(a, UserClass))\nprint(isinstance(b, tuple))\nprint(isinstance(c, dict))\n```\n:::\n\n:::cell\nA dataclass is a normal class with `__init__` and `__repr__` generated from the annotated fields. Instances are mutable, support attribute access, and can carry methods like any other class.\n\n```python\nfrom dataclasses import dataclass\n\n@dataclass\nclass UserClass:\n name: str\n score: int\n\na = UserClass("Ada", 98)\nprint(a)\na.score = 100\nprint(a.score)\n```\n\n```output\nUserClass(name=\'Ada\', score=98)\n100\n```\n:::\n\n:::cell\nA `NamedTuple` is a tuple subclass with named positions. Instances are immutable, support both `obj.field` and `obj[index]`, and the helper `_replace` produces a modified copy without mutating the original (since assigning to a field would fail).\n\n```python\nfrom typing import NamedTuple\n\nclass UserTuple(NamedTuple):\n name: str\n score: int\n\nb = UserTuple("Ada", 98)\nprint(b)\nprint(b.name, b[1])\nprint(b._replace(score=100))\n```\n\n```output\nUserTuple(name=\'Ada\', score=98)\nAda 98\nUserTuple(name=\'Ada\', score=100)\n```\n:::\n\n:::cell\nA `TypedDict` is a plain dictionary at runtime. The annotations exist only for the type checker, so the value behaves like any `dict` — useful for JSON-shaped data that crosses an API boundary as a mapping.\n\n```python\nfrom typing import TypedDict\n\nclass UserDict(TypedDict):\n name: str\n score: int\n\nc: UserDict = {"name": "Ada", "score": 98}\nprint(c)\nprint(c["name"])\nprint(type(c).__name__)\n```\n\n```output\n{\'name\': \'Ada\', \'score\': 98}\nAda\ndict\n```\n:::\n\n:::cell\nSame record, three runtime identities. The dataclass is its own class. The `NamedTuple` is literally a tuple. The `TypedDict` is literally a dict. That difference drives the choice: pick the form whose runtime behavior matches what the rest of the program already expects.\n\n```python\nprint(isinstance(a, UserClass))\nprint(isinstance(b, tuple))\nprint(isinstance(c, dict))\n```\n\n```output\nTrue\nTrue\nTrue\n```\n:::\n\n:::note\n- `@dataclass` — mutable, attribute access, methods; good default when behavior travels with data.\n- `typing.NamedTuple` — immutable, attribute + index access, tuple semantics; good for small records that flow through unpacking.\n- `typing.TypedDict` — runtime is `dict`, schema is type-checker-only; good for JSON-shaped data.\n- `collections.namedtuple` is the older, untyped form of `NamedTuple`; prefer the `typing` version in new code.\n:::\n', 'subprocesses.md': '+++\nslug = "subprocesses"\ntitle = "Subprocesses"\nsection = "Standard Library"\nsummary = "subprocess runs external commands with explicit arguments and captured outputs."\ndoc_path = "/library/subprocess.html"\nsee_also = [\n "virtual-environments",\n "networking",\n "threads-and-processes",\n]\nexpected_output = "child process\\n0\\n"\n+++\n\n`subprocess` is the standard boundary for running external commands. It starts another program, waits for it, and gives you a result object with the exit code and captured output.\n\nIn standard Python this is the right tool for calling Git, compilers, shells, or another Python interpreter. This site\'s live example runner does not expose an operating-system process table, so the page teaches the proper `subprocess.run()` contract and labels the runner boundary instead of pretending the command can run here.\n\nUse a list of arguments when possible, capture output when the parent program needs to inspect it, and treat a non-zero return code as a failure. The important boundary is between Python objects and the operating system: Python prepares arguments and environment, then the child program reports back through streams and an exit status.\n\n:::program\n```python\nimport subprocess\nimport sys\n\nresult = subprocess.run(\n [sys.executable, "-c", "print(\'child process\')"],\n text=True,\n capture_output=True,\n check=True,\n)\n\nprint(result.stdout.strip())\nprint(result.returncode)\n```\n:::\n\n:::cell\n`subprocess.run()` spawns a child Python interpreter and waits for it: `capture_output=True` stores the child\'s stdout and stderr on the result, `text=True` decodes them as strings, and `check=True` raises `CalledProcessError` on a non-zero exit. The result object carries the captured streams and exit code as portable evidence the child ran. The in-browser Run button cannot spawn processes, so pressing Run here fails in the sandbox; the output below was produced by really spawning the child under standard CPython when the example was verified.\n\n```python\nimport subprocess\nimport sys\n\nresult = subprocess.run(\n [sys.executable, "-c", "print(\'child process\')"],\n text=True,\n capture_output=True,\n check=True,\n)\n\nprint(result.stdout.strip())\nprint(result.returncode)\n```\n\n```output\nchild process\n0\n```\n:::\n\n:::note\n- Use a list of arguments instead of shell strings when possible.\n- Capture output when the parent program needs to inspect it.\n- `check=True` turns non-zero exits into exceptions.\n- The verified output came from a real child process under standard CPython at build time; the in-browser sandbox has no process table, so live runs of this page fail there.\n:::\n', 'testing.md': '+++\nslug = "testing"\ntitle = "Testing"\nsection = "Standard Library"\nsummary = "Tests make expected behavior executable and repeatable."\ndoc_path = "/library/unittest.html"\nsee_also = [\n "assertions",\n "exceptions",\n "modules",\n]\n+++\n\nTests turn expected behavior into code that can be run again. The useful unit is usually a small example of behavior with clear input, action, and assertion.\n\nPython\'s `unittest` library provides test cases, assertions, suites, and runners. Projects often use `pytest` for ergonomics, but the same idea remains: a test names behavior and fails when the behavior changes.\n\nA broad testing practice also includes fixtures, integration tests, property tests, and coverage. This example stays on the smallest standard-library loop: define behavior, assert the result, run the suite, inspect success.\n\n:::program\n```python\nimport io\nimport unittest\n\n\ndef add(left, right):\n return left + right\n\n\ndef divide(left, right):\n if right == 0:\n raise ZeroDivisionError("denominator is zero")\n return left / right\n\n\nclass AddTests(unittest.TestCase):\n def setUp(self):\n self.zero = 0\n\n def test_adds_numbers(self):\n self.assertEqual(add(self.zero + 2, 3), 5)\n\n def test_adds_empty_strings(self):\n self.assertEqual(add("", "py"), "py")\n\n def test_divide_by_zero_raises(self):\n with self.assertRaises(ZeroDivisionError):\n divide(1, 0)\n\nloader = unittest.defaultTestLoader\nsuite = loader.loadTestsFromTestCase(AddTests)\nstream = io.StringIO()\nrunner = unittest.TextTestRunner(stream=stream, verbosity=0)\nresult = runner.run(suite)\nprint(result.testsRun)\nprint(result.wasSuccessful())\n```\n:::\n\n:::cell\nA test starts with behavior small enough to name. The function can be ordinary code; the test supplies a representative input and expected result.\n\n```python\ndef add(left, right):\n return left + right\n\nprint(add(2, 3))\n```\n\n```output\n5\n```\n:::\n\n:::cell\n`unittest.TestCase` groups test methods. `setUp` runs before each test method to build per-test fixtures, `assertEqual` checks values, and `assertRaises` asserts that a block raises the expected exception type.\n\n```python\nimport unittest\n\n\ndef divide(left, right):\n if right == 0:\n raise ZeroDivisionError("denominator is zero")\n return left / right\n\n\nclass AddTests(unittest.TestCase):\n def setUp(self):\n self.zero = 0\n\n def test_adds_numbers(self):\n self.assertEqual(add(self.zero + 2, 3), 5)\n\n def test_adds_empty_strings(self):\n self.assertEqual(add("", "py"), "py")\n\n def test_divide_by_zero_raises(self):\n with self.assertRaises(ZeroDivisionError):\n divide(1, 0)\n\nprint([name for name in dir(AddTests) if name.startswith("test_")])\n```\n\n```output\n[\'test_adds_empty_strings\', \'test_adds_numbers\', \'test_divide_by_zero_raises\']\n```\n:::\n\n:::cell\nA runner executes the suite and records whether every assertion passed. Capturing the runner stream keeps this page\'s output deterministic.\n\n```python\nimport io\n\nloader = unittest.defaultTestLoader\nsuite = loader.loadTestsFromTestCase(AddTests)\nstream = io.StringIO()\nrunner = unittest.TextTestRunner(stream=stream, verbosity=0)\nresult = runner.run(suite)\nprint(result.testsRun)\nprint(result.wasSuccessful())\n```\n\n```output\n3\nTrue\n```\n:::\n\n:::note\n- Test method names should describe behavior, not implementation details.\n- A good unit test is deterministic and independent of test order.\n- Use broader integration tests when the behavior depends on several components working together.\n:::\n', 'threads-and-processes.md': '+++\nslug = "threads-and-processes"\ntitle = "Threads and Processes"\nsection = "Standard Library"\nsummary = "Threads share memory, while processes run in separate interpreters."\ndoc_path = "/library/concurrent.futures.html"\nsee_also = [\n "async-await",\n "subprocesses",\n "networking",\n]\nexpected_output = "[1, 4, 9]\\nProcessPoolExecutor\\n"\n+++\n\nThreads and processes are two ways to run work outside the current control path. Threads are useful for overlapping I/O-shaped waits, while processes are useful when CPU-bound work needs separate interpreter processes.\n\nIn standard Python, `ThreadPoolExecutor` and `ProcessPoolExecutor` are the ordinary tools for this lesson. This site\'s live example runner does not expose native threads or child processes, so this page keeps the proper executor model visible and separates the standard Python idea from what can execute here.\n\nThis is different from `asyncio`: threads and processes run ordinary callables through executors, while `async` code cooperatively awaits coroutines. Choose the smallest concurrency model that matches the bottleneck.\n\n:::program\n```python\nfrom concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor\n\n\ndef square(number):\n return number * number\n\nwith ThreadPoolExecutor(max_workers=2) as pool:\n print(list(pool.map(square, [1, 2, 3])))\n\nprint(ProcessPoolExecutor.__name__)\n```\n:::\n\n:::cell\n`ThreadPoolExecutor` runs `square` across worker threads that share this interpreter and its GIL; `map()` returns results in input order, and the `with` block joins the workers when the body exits. The in-browser sandbox cannot create native threads, so pressing Run here fails; this thread-pool output was produced under standard CPython at build time.\n\n```python\nfrom concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor\n\n\ndef square(number):\n return number * number\n\nwith ThreadPoolExecutor(max_workers=2) as pool:\n print(list(pool.map(square, [1, 2, 3])))\n```\n\n```output\n[1, 4, 9]\n```\n:::\n\n:::cell\n`ProcessPoolExecutor` is the heavier boundary: separate Python processes with isolated memory, for CPU-bound work that the GIL would otherwise serialise. The sandbox cannot spawn processes either, so this cell only inspects the class name rather than running a pool.\n\n```python\nprint(ProcessPoolExecutor.__name__)\n```\n\n```output\nProcessPoolExecutor\n```\n:::\n\n:::note\n- Threads share memory, so mutable shared state needs care.\n- Processes avoid shared interpreter state but require values to cross a process boundary.\n- Prefer `asyncio` for coroutine-based I/O and executors for ordinary blocking callables.\n- The thread-pool output came from real worker threads under standard CPython at build time; the in-browser sandbox cannot create threads or processes, so live runs of this page fail there.\n:::\n', 'truth-and-size.md': '+++\nslug = "truth-and-size"\ntitle = "Truth and Size"\nsection = "Data Model"\nsummary = "__bool__ and __len__ decide how objects behave in truth tests and len()."\ndoc_path = "/reference/datamodel.html#object.__bool__"\nsee_also = [\n "truthiness",\n "special-methods",\n "container-protocols",\n]\n+++\n\nTruth tests ask an object whether it should count as true. Containers usually answer through their size, while domain objects can answer with `__bool__` when emptiness is not the right idea.\n\n`__len__` supports `len(obj)` and also provides a fallback truth value: length zero is false, non-zero length is true. `__bool__` is more direct and wins when both are present.\n\nUse these methods to match the meaning of your object. A queue can be false when it has no items; an account might be true only when it is active, regardless of its balance.\n\n:::program\n```python\nclass Inbox:\n def __init__(self, messages):\n self.messages = list(messages)\n\n def __len__(self):\n return len(self.messages)\n\nclass Account:\n def __init__(self, active):\n self.active = active\n\n def __bool__(self):\n return self.active\n\nprint(len(Inbox(["hi", "bye"])))\nprint(bool(Inbox([])))\nprint(bool(Account(False)))\n```\n:::\n\n:::cell\n`__len__` lets `len()` ask an object for its size.\n\n```python\nclass Inbox:\n def __init__(self, messages):\n self.messages = list(messages)\n\n def __len__(self):\n return len(self.messages)\n\nprint(len(Inbox(["hi", "bye"])))\n```\n\n```output\n2\n```\n:::\n\n:::cell\nIf a class has `__len__` but no `__bool__`, Python uses zero length as false.\n\n```python\nprint(bool(Inbox([])))\n```\n\n```output\nFalse\n```\n:::\n\n:::cell\n`__bool__` expresses truth directly when the answer is not just container size.\n\n```python\nclass Account:\n def __init__(self, active):\n self.active = active\n\n def __bool__(self):\n return self.active\n\nprint(bool(Account(False)))\n```\n\n```output\nFalse\n```\n:::\n\n:::note\n- Prefer `__len__` for sized containers.\n- Prefer `__bool__` when truth has domain meaning.\n- Keep truth tests unsurprising; surprising falsy objects make conditionals harder to read.\n:::\n', 'truthiness.md': '+++\nslug = "truthiness"\ntitle = "Truthiness"\nsection = "Basics"\nsummary = "Python conditions use truthiness, not only explicit booleans."\ndoc_path = "/library/stdtypes.html#truth-value-testing"\nsee_also = [\n "booleans",\n "none",\n "conditionals",\n "special-methods",\n]\n+++\n\nTruthiness is one of Python\'s most important conveniences: conditions can test objects directly instead of requiring explicit boolean comparisons everywhere.\n\nEmpty containers, numeric zero, None, and False are false; most other values are true. This makes common checks such as if items: concise and idiomatic.\n\nUse truthiness when it reads naturally, but choose explicit comparisons when the distinction matters, such as checking whether a value is exactly None.\n\n:::program\n```python\nitems = []\nname = "Ada"\n\nif not items:\n print("no items")\n\nif name:\n print("has a name")\n\nprint(bool(0))\nprint(bool(42))\n```\n:::\n\n:::cell\nAn empty list is false, so `not items` reads as "items is empty". The condition tests the object directly — no `len(items) == 0` comparison is needed.\n\n```python\nitems = []\nname = "Ada"\n\nif not items:\n print("no items")\n```\n\n```output\nno items\n```\n:::\n\n:::cell\nA non-empty string is true, so `if name:` asks "did we get a name?" in one word. Reach for an explicit comparison instead when the distinction matters — `if name is not None:` treats an empty string differently from a missing one.\n\n```python\nif name:\n print("has a name")\n```\n\n```output\nhas a name\n```\n:::\n\n:::cell\n`bool()` reveals the truth value any condition would use. Zero-like numbers convert to `False`; other numbers convert to `True`.\n\n```python\nprint(bool(0))\nprint(bool(42))\n```\n\n```output\nFalse\nTrue\n```\n:::\n\n:::note\n- Empty containers and zero-like numbers are false in conditions.\n- Use explicit comparisons when they communicate intent better than truthiness.\n:::\n', 'tuples.md': '+++\nslug = "tuples"\ntitle = "Tuples"\nsection = "Collections"\nsummary = "Tuples group a fixed number of positional values."\ndoc_path = "/tutorial/datastructures.html#tuples-and-sequences"\nsee_also = [\n "lists",\n "unpacking",\n "structured-data-shapes",\n]\n+++\n\nTuples are ordered, immutable sequences. They exist for small fixed groups where position has meaning: coordinates, RGB colors, database rows, and multiple return values.\n\nUse lists for variable-length collections of similar items. Use tuples when the number of positions is part of the data shape and unpacking can give each position a useful name.\n\nBecause tuples are immutable, you cannot append or replace positions in place. If the shape needs to grow or change, a list or dataclass is usually a better fit.\n\n:::program\n```python\npoint = (3, 4)\nx, y = point\nprint(x + y)\n\nred = (255, 0, 0)\nprint(red[0])\nprint(len(red))\n\nrecord = ("Ada", 10)\nname, score = record\nprint(f"{name}: {score}")\n\nscores = [10, 9, 8]\nscores.append(7)\nprint(scores)\n\nstudent = ("Ada", 2024, "math")\nname, year, subject = student\nprint(name, year, subject)\n```\n:::\n\n:::cell\nUse a tuple for a fixed-size record where each position has a known meaning. Unpacking turns those positions into names at the point of use.\n\n```python\npoint = (3, 4)\nx, y = point\nprint(x + y)\n```\n\n```output\n7\n```\n:::\n\n:::cell\nTuples are sequences, so indexing and `len()` work. They are different from lists because their length and item references are fixed after creation.\n\n```python\nred = (255, 0, 0)\nprint(red[0])\nprint(len(red))\n```\n\n```output\n255\n3\n```\n:::\n\n:::cell\nTuples pair naturally with multiple return values and unpacking. If the fields need names everywhere, graduate to a dataclass or named tuple.\n\n```python\nrecord = ("Ada", 10)\nname, score = record\nprint(f"{name}: {score}")\n```\n\n```output\nAda: 10\n```\n:::\n\n:::cell\nLists and tuples carry different intent. A list holds a variable number of similar items and grows with `append`; a tuple has a fixed shape where each position has its own meaning, and unpacking gives those positions names.\n\n```python\nscores = [10, 9, 8]\nscores.append(7)\nprint(scores)\n\nstudent = ("Ada", 2024, "math")\nname, year, subject = student\nprint(name, year, subject)\n```\n\n```output\n[10, 9, 8, 7]\nAda 2024 math\n```\n:::\n\n:::note\n- Tuples are immutable sequences with fixed length.\n- Use tuples for small records where position has meaning.\n- Use lists for variable-length collections of similar items.\n- Reach for a dataclass or `NamedTuple` when fields deserve names everywhere they\'re used.\n:::\n', 'type-aliases.md': '+++\nslug = "type-aliases"\ntitle = "Type Aliases"\nsection = "Types"\nsummary = "Type aliases give a meaningful name to a repeated type shape."\ndoc_path = "/library/typing.html#type-aliases"\nsee_also = [\n "type-hints",\n "newtype",\n "union-and-optional-types",\n]\n+++\n\nA type alias gives a name to an annotation shape. It helps readers and type checkers understand the role of a value without repeating a long type expression everywhere.\n\nPython 3.13 supports the `type` statement for explicit aliases. Older assignment-style aliases still appear in code, but the `type` statement makes the intent clear and creates a `TypeAliasType` object at runtime.\n\nAn alias does not create a new runtime type. If you need a static distinction between compatible values such as user IDs and order IDs, use `NewType` instead.\n\n:::program\n```python\ntype UserId = int\ntype Scores = dict[UserId, int]\nLegacyName = str\n\n\ndef best_user(scores: Scores) -> UserId:\n return max(scores, key=scores.get)\n\nscores: Scores = {1: 98, 2: 91}\nprint(best_user(scores))\nprint(UserId.__name__)\nprint(LegacyName("Ada"))\n```\n:::\n\n:::cell\nThe `type` statement names an annotation shape. Here `Scores` means a dictionary from user IDs to integer scores.\n\n```python\ntype UserId = int\ntype Scores = dict[UserId, int]\n\n\ndef best_user(scores: Scores) -> UserId:\n return max(scores, key=scores.get)\n\nscores: Scores = {1: 98, 2: 91}\nprint(best_user(scores))\n```\n\n```output\n1\n```\n:::\n\n:::cell\nModern aliases are runtime objects that keep their alias name for introspection.\n\n```python\nprint(UserId.__name__)\nprint(Scores.__name__)\n```\n\n```output\nUserId\nScores\n```\n:::\n\n:::cell\nAssignment-style aliases are still common, but they are just ordinary names bound to existing objects.\n\n```python\nLegacyName = str\nprint(LegacyName("Ada"))\nprint(LegacyName is str)\n```\n\n```output\nAda\nTrue\n```\n:::\n\n:::note\n- Use aliases to name repeated or domain-specific annotation shapes.\n- A type alias does not validate values at runtime.\n- Use `NewType` when two values share a runtime representation but should not be mixed statically.\n:::\n', 'type-hints.md': '+++\nslug = "type-hints"\ntitle = "Type Hints"\nsection = "Types"\nsummary = "Annotations document expected types and power static analysis."\ndoc_path = "/library/typing.html"\nsee_also = [\n "union-and-optional-types",\n "type-aliases",\n "generics-and-typevar",\n "runtime-type-checks",\n]\n+++\n\nType hints are annotations that document expected shapes for values, parameters, and return results. They exist so tools and readers can understand API boundaries before the program runs.\n\nPython stores many annotations but does not enforce most of them at runtime. Use type hints for communication and static analysis; use validation or exceptions when runtime checks are required.\n\nThe alternative to an annotation is prose, tests, or runtime validation. Good Python code often uses all three at important boundaries.\n\n:::program\n```python\ndef total(numbers: list[int]) -> int:\n return sum(numbers)\n\nprint(total([1, 2, 3]))\nprint(total.__annotations__)\n\n\ndef label(score: int) -> str:\n return f"score={score}"\n\nprint(label("high"))\n\n\ndef find(name: str, options: list[str]) -> str | None:\n return name if name in options else None\n\nprint(find("Ada", ["Ada", "Grace"]))\nprint(find("Guido", ["Ada", "Grace"]))\n\n\nfrom typing import Optional\n\ndef lookup(name: str) -> Optional[int]:\n table = {"Ada": 1815, "Grace": 1906}\n return table.get(name)\n\nprint(lookup("Ada"))\nprint(lookup("Guido"))\n\n\ntype Score = int\n\ndef grade(score: Score) -> str:\n return "pass" if score >= 50 else "fail"\n\nprint(grade(72))\n```\n:::\n\n:::cell\nType hints document expected parameter and return shapes. Python still runs the function normally at runtime.\n\n```python\ndef total(numbers: list[int]) -> int:\n return sum(numbers)\n\nprint(total([1, 2, 3]))\n```\n\n```output\n6\n```\n:::\n\n:::cell\nPython stores annotations on the function object for tools and introspection. Type checkers use this information without changing the function call syntax.\n\n```python\nprint(total.__annotations__)\n```\n\n```output\n{\'numbers\': list[int], \'return\': }\n```\n:::\n\n:::cell\nMost hints are not runtime validation. This call passes a string where the hint says `int`; Python still calls the function because the body can format any value.\n\n```python\ndef label(score: int) -> str:\n return f"score={score}"\n\nprint(label("high"))\n```\n\n```output\nscore=high\n```\n:::\n\n:::cell\nUse `X | Y` (PEP 604) to express "either type". `str | None` says the result is a string or absent. `typing.Optional[X]` is the older, still-supported spelling for the same idea — `Optional[X]` is equivalent to `X | None`.\n\n```python\ndef find(name: str, options: list[str]) -> str | None:\n return name if name in options else None\n\nprint(find("Ada", ["Ada", "Grace"]))\nprint(find("Guido", ["Ada", "Grace"]))\n\n\nfrom typing import Optional\n\ndef lookup(name: str) -> Optional[int]:\n table = {"Ada": 1815, "Grace": 1906}\n return table.get(name)\n\nprint(lookup("Ada"))\nprint(lookup("Guido"))\n```\n\n```output\nAda\nNone\n1815\nNone\n```\n:::\n\n:::cell\nThe `type` statement names a type so it can be reused with intent. `type Score = int` keeps the underlying type at runtime but lets the API talk about a domain concept rather than a primitive. Older code spells this `Score: TypeAlias = int`; `typing.TypeAlias` is deprecated since Python 3.12, and the type-aliases page covers the modern statement in depth.\n\n```python\ntype Score = int\n\ndef grade(score: Score) -> str:\n return "pass" if score >= 50 else "fail"\n\nprint(grade(72))\n```\n\n```output\npass\n```\n:::\n\n:::note\n- Python does not enforce most type hints at runtime.\n- Tools like type checkers and editors use annotations to catch mistakes earlier.\n- Use `X | Y` for unions and `Optional[X]` for "X or None"; both spellings mean the same thing.\n- Reach for a `type` alias when a domain name reads better than a raw primitive type.\n- Use runtime validation when untrusted input must be rejected while the program runs.\n:::\n', 'typed-dicts.md': '+++\nslug = "typed-dicts"\ntitle = "TypedDict"\nsection = "Types"\nsummary = "TypedDict describes dictionaries with known string keys."\ndoc_path = "/library/typing.html#typing.TypedDict"\nsee_also = [\n "dicts",\n "json",\n "dataclasses",\n "structured-data-shapes",\n]\n+++\n\n`TypedDict` describes dictionary records with known keys. It is useful for JSON-like data that should remain a dictionary instead of becoming a class instance.\n\nThe important boundary is static versus runtime behavior. Type checkers can know that `name` is a string and `score` is an integer, but at runtime the value is still an ordinary `dict`.\n\nUse `TypedDict` for external records and `dataclass` when your own program wants attribute access, methods, and construction behavior.\n\n:::program\n```python\nfrom typing import NotRequired, TypedDict\n\nclass User(TypedDict):\n name: str\n score: int\n nickname: NotRequired[str]\n\n\ndef describe(user: User) -> str:\n return f"{user[\'name\']}: {user[\'score\']}"\n\nrecord: User = {"name": "Ada", "score": 98}\nprint(describe(record))\nprint(isinstance(record, dict))\nprint(record.get("nickname", "none"))\n```\n:::\n\n:::cell\nUse `TypedDict` for JSON-like records that remain dictionaries.\n\n```python\nfrom typing import TypedDict\n\nclass User(TypedDict):\n name: str\n score: int\n\n\ndef describe(user: User) -> str:\n return f"{user[\'name\']}: {user[\'score\']}"\n\nrecord: User = {"name": "Ada", "score": 98}\nprint(describe(record))\n```\n\n```output\nAda: 98\n```\n:::\n\n:::cell\nAt runtime, a `TypedDict` value is still a plain dictionary.\n\n```python\nprint(isinstance(record, dict))\nprint(type(record).__name__)\n```\n\n```output\nTrue\ndict\n```\n:::\n\n:::cell\n`NotRequired` marks a key that type checkers should treat as optional. Runtime lookup still uses normal dictionary tools such as `get()`.\n\n```python\nfrom typing import NotRequired\n\nclass UserWithNickname(TypedDict):\n name: str\n score: int\n nickname: NotRequired[str]\n\nrecord: UserWithNickname = {"name": "Ada", "score": 98}\nprint(record.get("nickname", "none"))\n```\n\n```output\nnone\n```\n:::\n\n:::note\n- Use `TypedDict` for dictionary records from JSON or APIs.\n- Type checkers understand required and optional keys.\n- Runtime behavior is still ordinary dictionary behavior.\n:::\n', 'union-and-optional-types.md': '+++\nslug = "union-and-optional-types"\ntitle = "Union and Optional Types"\nsection = "Types"\nsummary = "The | operator describes values that may have more than one static type."\ndoc_path = "/library/typing.html#typing.Optional"\nsee_also = [\n "none",\n "type-hints",\n "match-statements",\n]\n+++\n\nA union type says that a value may have one of several static shapes. `int | str` means callers may pass either an integer or a string.\n\n`T | None` is the modern spelling for an optional value. The annotation documents that absence is expected, but the code still needs to handle `None` before using the non-optional behavior.\n\nUnions are useful at boundaries where input is flexible. Inside a function, narrow the value with an `is None`, `isinstance()`, or pattern check so the rest of the code has one clear shape.\n\n:::program\n```python\ndef label(value: int | str) -> str:\n return f"item-{value}"\n\n\ndef greeting(name: str | None) -> str:\n if name is None:\n return "hello guest"\n return f"hello {name.upper()}"\n\nprint(label(3))\nprint(label("A"))\nprint(greeting(None))\nprint(greeting("Ada"))\nprint(greeting.__annotations__)\n```\n:::\n\n:::cell\nUse `A | B` when a value may have either type. The function body should use operations that make sense for every member of the union.\n\n```python\ndef label(value: int | str) -> str:\n return f"item-{value}"\n\nprint(label(3))\nprint(label("A"))\n```\n\n```output\nitem-3\nitem-A\n```\n:::\n\n:::cell\n`str | None` means the function accepts either a string or explicit absence. Check for `None` before calling string methods.\n\n```python\ndef greeting(name: str | None) -> str:\n if name is None:\n return "hello guest"\n return f"hello {name.upper()}"\n\nprint(greeting(None))\nprint(greeting("Ada"))\n```\n\n```output\nhello guest\nhello ADA\n```\n:::\n\n:::cell\nUnion annotations are visible at runtime, but Python does not enforce them when the function is called.\n\n```python\nprint(greeting.__annotations__)\n```\n\n```output\n{\'name\': str | None, \'return\': }\n```\n:::\n\n:::note\n- Use `A | B` when a value may have either type.\n- `T | None` means absence is an expected case, not an error by itself.\n- Narrow unions before using behavior that belongs to only one member type.\n:::\n', 'unpacking.md': '+++\nslug = "unpacking"\ntitle = "Unpacking"\nsection = "Collections"\nsummary = "Unpacking binds names from sequences and mappings concisely."\ndoc_path = "/tutorial/datastructures.html#tuples-and-sequences"\nsee_also = [\n "tuples",\n "multiple-return-values",\n "args-and-kwargs",\n "dicts",\n]\n+++\n\nUnpacking binds multiple names from one iterable or mapping. It makes the structure of data visible at the point where values are introduced.\n\nStarred unpacking handles variable-length sequences by collecting the middle or remaining values. This keeps common head-tail patterns readable.\n\nDictionary unpacking with ** connects structured data to function calls. It is widely used in configuration, adapters, and code that bridges APIs.\n\n:::program\n```python\npoint = (3, 4)\nx, y = point\nprint(x, y)\n\nfirst, *middle, last = [1, 2, 3, 4]\nprint(first, middle, last)\n\ndef describe(name, language):\n print(name, language)\n\ndata = {"name": "Ada", "language": "Python"}\ndescribe(**data)\n```\n:::\n\n:::cell\nTuple unpacking assigns each position to a name in one statement: `x` receives the first element of `point` and `y` the second. The assignment fails loudly if the number of names and elements disagree, which catches shape mistakes early.\n\n```python\npoint = (3, 4)\nx, y = point\nprint(x, y)\n```\n\n```output\n3 4\n```\n:::\n\n:::cell\nThe starred name collects however many elements the head and tail don\'t claim — here `first` and `last` take the ends and `*middle` gathers the rest into a list. The same list works whether it has four elements or forty.\n\n```python\nfirst, *middle, last = [1, 2, 3, 4]\nprint(first, middle, last)\n```\n\n```output\n1 [2, 3] 4\n```\n:::\n\n:::cell\n`describe(**data)` spreads the dictionary\'s keys as keyword arguments, so the call site never repeats `name=` and `language=` by hand. This is the bridge between dict-shaped data (configuration, parsed JSON) and function signatures.\n\n```python\ndef describe(name, language):\n print(name, language)\n\ndata = {"name": "Ada", "language": "Python"}\ndescribe(**data)\n```\n\n```output\nAda Python\n```\n:::\n\n:::note\n- Starred unpacking collects the remaining values into a list.\n- Dictionary unpacking with ** is common when calling functions with structured data.\n- Prefer indexing when you need one position; prefer unpacking when naming several positions makes the shape clearer.\n:::\n', 'values.md': '+++\nslug = "values"\ntitle = "Values"\nsection = "Basics"\nsummary = "Python programs evaluate expressions into objects such as text, numbers, booleans, and None."\ndoc_path = "/library/stdtypes.html"\nsee_also = [\n "variables",\n "booleans",\n "none",\n "literals",\n]\n+++\n\nA Python program works by evaluating expressions into values. Values are objects: text, integers, floats, booleans, `None`, and many richer types introduced later.\n\nNames point to values; they are not declarations that permanently fix a type. Operations usually produce new values, which you can print, store, compare, or pass to functions.\n\nThis page is a map, not the whole territory. Later pages explain the boundaries: equality vs identity, mutable vs immutable values, truthiness vs literal booleans, and `None` vs a missing key or an exception.\n\n:::program\n```python\ntext = "python"\ncount = 3\nratio = 2.5\nready = True\nmissing = None\n\nprint(type(text).__name__)\nprint(text.upper())\nprint(count + 4)\nprint(ratio * 2)\n\nprint(ready and count > 0)\nprint(missing is None)\n```\n:::\n\n:::cell\nStart with several built-in values. Python does not require declarations before binding these names, and each value is still an object with a type.\n\n```python\ntext = "python"\ncount = 3\nratio = 2.5\nready = True\nmissing = None\n\nprint(type(text).__name__)\n```\n\n```output\nstr\n```\n:::\n\n:::cell\nMethods and operators evaluate to new values. The original `text`, `count`, and `ratio` bindings remain ordinary objects you can reuse.\n\n```python\nprint(text.upper())\nprint(count + 4)\nprint(ratio * 2)\n```\n\n```output\nPYTHON\n7\n5.0\n```\n:::\n\n:::cell\nBoolean expressions combine facts, and `None` is checked by identity because it is a singleton absence marker.\n\n```python\nprint(ready and count > 0)\nprint(missing is None)\n```\n\n```output\nTrue\nTrue\n```\n:::\n\n:::note\n- Values are objects; names point to them and operations usually create new values.\n- Use `is None` for the absence marker, not `== None`.\n- This overview introduces boundaries that later pages explain in detail.\n:::\n', 'variables.md': '+++\nslug = "variables"\ntitle = "Variables"\nsection = "Basics"\nsummary = "Names are bound to values with assignment."\ndoc_path = "/reference/simple_stmts.html#assignment-statements"\nsee_also = [\n "values",\n "mutability",\n "object-lifecycle",\n "constants",\n]\n+++\n\nPython variables are names bound to objects. Assignment creates or rebinds a name; it does not require a declaration and it does not permanently attach a type to the name.\n\nRebinding changes which object a name refers to. Augmented assignment such as `+=` is the idiomatic way to update counters and accumulators.\n\nUse clear names for values that matter later. Python\'s flexibility makes naming more important, not less.\n\nUse assignment when a value needs a name for reuse or explanation. Prefer a direct expression when naming the intermediate value would add noise.\n\n:::program\n```python\nmessage = "hi"\nprint(message)\n\nmessage = "hello"\nprint(message)\n\ncount = 3\ncount += 1\nprint(count)\n```\n:::\n\n:::cell\nAssignment binds a name to a value. Once bound, the name can be used anywhere that value is needed.\n\n```python\nmessage = "hi"\nprint(message)\n```\n\n```output\nhi\n```\n:::\n\n:::cell\nAssignment can rebind the same name to a different value. The name is not permanently attached to the first object.\n\n```python\nmessage = "hello"\nprint(message)\n```\n\n```output\nhello\n```\n:::\n\n:::cell\nAugmented assignment reads the current binding, computes an updated value, and stores the result back under the same name.\n\n```python\ncount = 3\ncount += 1\nprint(count)\n```\n\n```output\n4\n```\n:::\n\n:::note\n- Python variables are names bound to objects, not boxes with fixed types.\n- Rebinding a name is normal.\n- Use augmented assignment for counters and accumulators.\n:::\n', 'virtual-environments.md': '+++\nslug = "virtual-environments"\ntitle = "Virtual Environments"\nsection = "Modules"\nsummary = "Virtual environments isolate a project\'s Python packages."\ndoc_path = "/library/venv.html"\nsee_also = [\n "packages",\n "modules",\n "import-aliases",\n]\nexpected_output = ".venv\\nTrue\\n"\n+++\n\nVirtual environments isolate a project\'s installed packages from the global Python installation and from other projects. The usual workflow is a command-line one: create `.venv`, activate it, then install project dependencies there.\n\nIn standard Python, `python -m venv .venv` is the everyday command. This site\'s live example runner is built from declared dependencies rather than an activated shell environment, so the runnable part keeps to deterministic evidence while the page still teaches the standard-Python workflow.\n\nA virtual environment changes installation and import paths. It does not change the Python language, package layout rules, or module names.\n\n:::program\n```python\nimport pathlib\nimport tempfile\nimport venv\n\nwith tempfile.TemporaryDirectory() as directory:\n env_path = pathlib.Path(directory) / ".venv"\n builder = venv.EnvBuilder(with_pip=False)\n builder.create(env_path)\n\n config = (env_path / "pyvenv.cfg").read_text()\n print(env_path.name)\n print("home" in config)\n```\n:::\n\n:::unsupported\nThe standard project setup command is `python -m venv .venv`. It creates a directory with its own interpreter entry points and package install location. After activation, `python -m pip install ...` installs into that environment rather than into another project. (This workflow is for standard Python projects. The Python By Example runner is deployed from declared dependencies instead of an activated shell environment.)\n\n```python\nimport subprocess\nimport sys\n\nsubprocess.run([sys.executable, "-m", "venv", ".venv"], check=True)\nsubprocess.run([".venv/bin/python", "-m", "pip", "install", "requests"], check=True)\n```\n:::\n\n:::cell\n`venv.EnvBuilder` exposes the same environment-creation mechanism as `python -m venv`. A temporary directory keeps the example from leaving project files behind.\n\n```python\nimport pathlib\nimport tempfile\nimport venv\n\nwith tempfile.TemporaryDirectory() as directory:\n env_path = pathlib.Path(directory) / ".venv"\n builder = venv.EnvBuilder(with_pip=False)\n builder.create(env_path)\n\n config = (env_path / "pyvenv.cfg").read_text()\n print(env_path.name)\n print("home" in config)\n```\n\n```output\n.venv\nTrue\n```\n:::\n\n:::note\n- Use `python -m venv .venv` for everyday standard-Python project setup.\n- A venv isolates installed packages; it does not change how imports are written.\n- This site\'s runner uses a deployment dependency model, not an activated shell environment.\n- That runner constraint is separate from the standard Python `venv` workflow you would use in local projects.\n:::\n', 'warnings.md': '+++\nslug = "warnings"\ntitle = "Warnings"\nsection = "Errors"\nsummary = "warnings report soft problems without immediately stopping the program."\ndoc_path = "/library/warnings.html"\nsee_also = [\n "exceptions",\n "logging",\n "testing",\n]\n+++\n\nA warning reports a problem that callers should know about, but it does not have to stop the current operation. Deprecations are the classic case: the old API can still return a value while telling users to migrate.\n\nWarnings sit between logging and exceptions. Logging records operational evidence; exceptions stop the current path; warnings make compatibility or correctness concerns visible according to a filter.\n\nTests often capture warnings so deprecations are asserted instead of merely printed. Filters can also turn warnings into errors when a project wants to enforce cleanup.\n\n:::program\n```python\nimport warnings\n\n\ndef old_name():\n warnings.warn("old_name is deprecated", DeprecationWarning, stacklevel=2)\n return "result"\n\nwith warnings.catch_warnings(record=True) as caught:\n warnings.simplefilter("always", DeprecationWarning)\n print(old_name())\n print(caught[0].category.__name__)\n print(str(caught[0].message))\n\nwith warnings.catch_warnings():\n warnings.simplefilter("error", DeprecationWarning)\n try:\n old_name()\n except DeprecationWarning:\n print("warning became error")\n```\n:::\n\n:::cell\nCapture warnings in tests when the returned value still matters but the migration notice must be asserted.\n\n```python\nimport warnings\n\n\ndef old_name():\n warnings.warn("old_name is deprecated", DeprecationWarning, stacklevel=2)\n return "result"\n\nwith warnings.catch_warnings(record=True) as caught:\n warnings.simplefilter("always", DeprecationWarning)\n print(old_name())\n print(caught[0].category.__name__)\n print(str(caught[0].message))\n```\n\n```output\nresult\nDeprecationWarning\nold_name is deprecated\n```\n:::\n\n:::cell\nA filter can promote selected warnings to exceptions, which is useful in CI when deprecated calls should fail the build.\n\n```python\nwith warnings.catch_warnings():\n warnings.simplefilter("error", DeprecationWarning)\n try:\n old_name()\n except DeprecationWarning:\n print("warning became error")\n```\n\n```output\nwarning became error\n```\n:::\n\n:::note\n- Use warnings for soft problems callers can act on later.\n- Use exceptions when the current operation cannot continue.\n- `stacklevel` should point the warning at the caller rather than inside the helper.\n:::\n', 'while-loops.md': '+++\nslug = "while-loops"\ntitle = "While Loops"\nsection = "Control Flow"\nsummary = "while repeats until changing state makes a condition false."\ndoc_path = "/reference/compound_stmts.html#while"\nsee_also = [\n "for-loops",\n "sentinel-iteration",\n "break-and-continue",\n]\n+++\n\nA `while` loop repeats while a condition remains true. Unlike `for`, which consumes an existing iterable, `while` is for state-driven repetition where the next step depends on what happened so far.\n\nThe loop body must make progress toward stopping. That progress might be decrementing a counter, reading until a sentinel value, or waiting until some external state changes.\n\nReach for `for` when you already have values to consume. Reach for `while` when the loop\'s own state decides whether another iteration is needed.\n\n:::program\n```python\nremaining = 3\nwhile remaining > 0:\n print(f"launch in {remaining}")\n remaining -= 1\nprint("liftoff")\n\nresponses = iter(["retry", "retry", "ok"])\nstatus = next(responses)\nwhile status != "ok":\n print(f"status: {status}")\n status = next(responses)\nprint(f"status: {status}")\n```\n:::\n\n:::cell\nUse `while` when the condition, not an iterable, controls repetition. Here the loop owns the countdown state and updates it each time through the body.\n\n```python\nremaining = 3\nwhile remaining > 0:\n print(f"launch in {remaining}")\n remaining -= 1\nprint("liftoff")\n```\n\n```output\nlaunch in 3\nlaunch in 2\nlaunch in 1\nliftoff\n```\n:::\n\n:::cell\nA sentinel loop stops when a special value appears. The loop does not know in advance how many retries it will need; it keeps going until the state says to stop.\n\n```python\nresponses = iter(["retry", "retry", "ok"])\nstatus = next(responses)\nwhile status != "ok":\n print(f"status: {status}")\n status = next(responses)\nprint(f"status: {status}")\n```\n\n```output\nstatus: retry\nstatus: retry\nstatus: ok\n```\n:::\n\n:::note\n- Use `while` when changing state decides whether the loop continues.\n- Update loop state inside the body so the condition can become false.\n- Prefer `for` when you already have a collection, range, iterator, or generator to consume.\n:::\n', 'yield-from.md': '+++\nslug = "yield-from"\ntitle = "Yield From"\nsection = "Iteration"\nsummary = "yield from delegates part of a generator to another iterable."\ndoc_path = "/reference/expressions.html#yield-expressions"\nsee_also = [\n "generators",\n "generator-expressions",\n "itertools",\n]\n+++\n\n`yield from` lets one generator yield every value from another iterable. It is a compact way to delegate part of a stream.\n\nUse it when a generator is mostly stitching together other iterables or sub-generators. It keeps the producer pipeline visible without writing a nested `for` loop.\n\nThe consumer still sees one stream of values.\n\n:::program\n```python\ndef page():\n yield "header"\n yield from ["intro", "body"]\n yield "footer"\n\nprint(list(page()))\n\n\ndef flatten(rows):\n for row in rows:\n yield from row\n\nprint(list(flatten([[1, 2], [3]])))\n```\n:::\n\n:::cell\n`yield from` delegates to another iterable. The caller receives one stream even though part of it came from a list.\n\n```python\ndef page():\n yield "header"\n yield from ["intro", "body"]\n yield "footer"\n\nprint(list(page()))\n```\n\n```output\n[\'header\', \'intro\', \'body\', \'footer\']\n```\n:::\n\n:::cell\nDelegation is useful when flattening nested iterables. `yield from row` replaces an inner loop that would yield each item by hand.\n\n```python\ndef flatten(rows):\n for row in rows:\n yield from row\n\nprint(list(flatten([[1, 2], [3]])))\n```\n\n```output\n[1, 2, 3]\n```\n:::\n\n:::note\n- `yield from iterable` yields each value from that iterable.\n- It keeps generator pipelines compact.\n- Use a plain `yield` when producing one value directly.\n:::\n'} +EXAMPLE_SOURCE_FILES = {'manifest.toml': 'python_version = "3.13"\ndocs_base_url = "https://docs.python.org/3.13"\n\norder = [\n "hello-world",\n "values",\n "literals",\n "numbers",\n "booleans",\n "operators",\n "none",\n "variables",\n "constants",\n "truthiness",\n "equality-and-identity",\n "mutability",\n "object-lifecycle",\n "strings",\n "bytes-and-bytearray",\n "string-formatting",\n "conditionals",\n "for-loops",\n "break-and-continue",\n "loop-else",\n "iterating-over-iterables",\n "iterators",\n "iterator-vs-iterable",\n "match-statements",\n "advanced-match-patterns",\n "while-loops",\n "assignment-expressions",\n "sentinel-iteration",\n "lists",\n "tuples",\n "unpacking",\n "dicts",\n "sets",\n "slices",\n "comprehensions",\n "comprehension-patterns",\n "sorting",\n "collections-module",\n "copying-collections",\n "functions",\n "guard-clauses",\n "exceptions",\n "keyword-only-arguments",\n "positional-only-parameters",\n "args-and-kwargs",\n "multiple-return-values",\n "closures",\n "partial-functions",\n "scope-global-nonlocal",\n "recursion",\n "lambdas",\n "generators",\n "yield-from",\n "generator-expressions",\n "itertools",\n "decorators",\n "classes",\n "inheritance-and-super",\n "classmethods-and-staticmethods",\n "dataclasses",\n "properties",\n "special-methods",\n "truth-and-size",\n "container-protocols",\n "callable-objects",\n "operator-overloading",\n "attribute-access",\n "bound-and-unbound-methods",\n "descriptors",\n "metaclasses",\n "context-managers",\n "delete-statements",\n "assertions",\n "exception-chaining",\n "exception-groups",\n "warnings",\n "modules",\n "import-aliases",\n "packages",\n "virtual-environments",\n "type-hints",\n "runtime-type-checks",\n "union-and-optional-types",\n "type-aliases",\n "typed-dicts",\n "structured-data-shapes",\n "literal-and-final",\n "callable-types",\n "generics-and-typevar",\n "paramspec",\n "overloads",\n "casts-and-any",\n "newtype",\n "protocols",\n "abstract-base-classes",\n "enums",\n "regular-expressions",\n "number-parsing",\n "custom-exceptions",\n "files-and-pathlib",\n "json",\n "logging",\n "testing",\n "subprocesses",\n "threads-and-processes",\n "networking",\n "datetime",\n "csv-data",\n "async-await",\n "async-iteration-and-context",\n]\n', 'abstract-base-classes.md': '+++\nslug = "abstract-base-classes"\ntitle = "Abstract Base Classes"\nsection = "Classes"\nsummary = "ABC and abstractmethod enforce that subclasses implement required methods."\ndoc_path = "/library/abc.html"\nsee_also = [\n "protocols",\n "inheritance-and-super",\n "classes",\n]\n+++\n\n`ABC` and `@abstractmethod` describe an interface that subclasses must implement. The base class refuses to instantiate until a concrete subclass provides every abstract method, which catches "I forgot to implement this" at construction time rather than at the first method call.\n\nABCs are different from `Protocol`. An ABC is nominal: a class participates in the contract by inheriting from it. A `Protocol` is structural: any class with the right methods qualifies, no inheritance required. Reach for an ABC when you want shared implementation in the base class or you want `isinstance()` to mean "explicitly opted in"; reach for a `Protocol` when you only care about behavior at the API boundary.\n\nThe cost is a small amount of ceremony at the type level. The benefit is that a half-implemented subclass cannot be created by accident.\n\n:::program\n```python\nfrom abc import ABC, abstractmethod\nfrom typing import Protocol\n\nclass Shape(ABC):\n @abstractmethod\n def area(self) -> float:\n ...\n\n def describe(self) -> str:\n return f"shape with area {self.area()}"\n\ntry:\n Shape()\nexcept TypeError as error:\n print(error)\n\nclass Square(Shape):\n def __init__(self, side):\n self.side = side\n\n def area(self):\n return self.side ** 2\n\nprint(Square(3).area())\nprint(Square(3).describe())\n\nclass Incomplete(Shape):\n pass\n\ntry:\n Incomplete()\nexcept TypeError as error:\n print(error)\n\nclass HasArea(Protocol):\n def area(self) -> float:\n ...\n\nclass Triangle:\n def __init__(self, base, height):\n self.base = base\n self.height = height\n\n def area(self):\n return 0.5 * self.base * self.height\n\ndef total_area(shapes: list[HasArea]) -> float:\n return sum(shape.area() for shape in shapes)\n\nprint(total_area([Square(3), Triangle(4, 3)]))\nprint(isinstance(Triangle(4, 3), Shape))\nprint(isinstance(Square(3), Shape))\n```\n:::\n\n:::cell\n`ABC` plus `@abstractmethod` declares the contract. Trying to construct the base class itself fails because at least one method has no implementation. A concrete `describe()` lives alongside the abstract `area()` so subclasses inherit shared behavior for free.\n\n```python\nfrom abc import ABC, abstractmethod\n\nclass Shape(ABC):\n @abstractmethod\n def area(self) -> float:\n ...\n\n def describe(self) -> str:\n return f"shape with area {self.area()}"\n\ntry:\n Shape()\nexcept TypeError as error:\n print(error)\n```\n\n```output\nCan\'t instantiate abstract class Shape without an implementation for abstract method \'area\'\n```\n:::\n\n:::cell\nA subclass that implements every abstract method is concrete and can be instantiated. It also inherits the non-abstract methods from the base class.\n\n```python\nclass Square(Shape):\n def __init__(self, side):\n self.side = side\n\n def area(self):\n return self.side ** 2\n\nprint(Square(3).area())\nprint(Square(3).describe())\n```\n\n```output\n9\nshape with area 9\n```\n:::\n\n:::cell\nA subclass that forgets to implement an abstract method also cannot be instantiated — that is the value the ABC adds. The error fires at construction, not when something later tries to call the missing method.\n\n```python\nclass Incomplete(Shape):\n pass\n\ntry:\n Incomplete()\nexcept TypeError as error:\n print(error)\n```\n\n```output\nCan\'t instantiate abstract class Incomplete without an implementation for abstract method \'area\'\n```\n:::\n\n:::cell\nContrast with `Protocol`. A `HasArea` protocol accepts any class with an `area()` method, no inheritance required. `Triangle` does not inherit from `Shape`, so it satisfies the protocol but fails `isinstance(_, Shape)`. `Square` satisfies both because it explicitly inherited from the ABC.\n\n```python\nfrom typing import Protocol\n\nclass HasArea(Protocol):\n def area(self) -> float:\n ...\n\nclass Triangle:\n def __init__(self, base, height):\n self.base = base\n self.height = height\n\n def area(self):\n return 0.5 * self.base * self.height\n\ndef total_area(shapes: list[HasArea]) -> float:\n return sum(shape.area() for shape in shapes)\n\nprint(total_area([Square(3), Triangle(4, 3)]))\nprint(isinstance(Triangle(4, 3), Shape))\nprint(isinstance(Square(3), Shape))\n```\n\n```output\n15.0\nFalse\nTrue\n```\n:::\n\n:::note\n- `ABC` plus `@abstractmethod` blocks instantiation until every abstract method has an implementation.\n- ABCs are nominal — subclasses opt in by inheriting; `isinstance()` reflects that opt-in.\n- Protocols are structural — any class with the right shape qualifies, regardless of inheritance.\n- Prefer an ABC when shared implementation or explicit opt-in matters; prefer a Protocol when only behavior at the API boundary matters.\n:::\n', 'advanced-match-patterns.md': '+++\nslug = "advanced-match-patterns"\ntitle = "Advanced Match Patterns"\nsection = "Control Flow"\nsummary = "match patterns can destructure sequences, combine alternatives, and add guards."\ndoc_path = "/tutorial/controlflow.html#match-statements"\nsee_also = [\n "match-statements",\n "tuples",\n "classes",\n]\n+++\n\nStructural pattern matching is more than equality checks. Patterns can destructure sequences, match several alternatives, capture the rest of a sequence, and use guards.\n\nUse these forms when the shape of data is the decision. If the decision is only a single boolean condition, ordinary `if` statements are usually clearer.\n\nThe wildcard `_` catches everything not matched earlier.\n\n:::program\n```python\ncommands = [\n ["move", 2, 3],\n ["exit"],\n ["echo", "hello", "python"],\n ["move", -1, 3],\n]\n\nfor command in commands:\n match command:\n case ["move", x, y] if x >= 0 and y >= 0:\n print(f"move to {x},{y}")\n case ["quit" | "exit"]:\n print("stop")\n case ["echo", *words]:\n print(" ".join(words))\n case _:\n print("unknown")\n```\n:::\n\n:::cell\nSequence patterns match by position. A guard after `if` adds a condition that must also be true.\n\n```python\ncommand = ["move", 2, 3]\n\nmatch command:\n case ["move", x, y] if x >= 0 and y >= 0:\n print(f"move to {x},{y}")\n case _:\n print("unknown")\n```\n\n```output\nmove to 2,3\n```\n:::\n\n:::cell\nAn OR pattern accepts several alternatives in one case. A star pattern captures the rest of a sequence.\n\n```python\nfor command in [["exit"], ["echo", "hello", "python"]]:\n match command:\n case ["quit" | "exit"]:\n print("stop")\n case ["echo", *words]:\n print(" ".join(words))\n```\n\n```output\nstop\nhello python\n```\n:::\n\n:::cell\nThe wildcard `_` catches values that did not match earlier cases. Here the guard rejects the negative coordinate, so the same `match` that accepted `["move", 2, 3]` falls through to the fallback.\n\n```python\ncommand = ["move", -1, 3]\n\nmatch command:\n case ["move", x, y] if x >= 0 and y >= 0:\n print(f"move to {x},{y}")\n case _:\n print("unknown")\n```\n\n```output\nunknown\n```\n:::\n\n:::note\n- Use `case _` as a wildcard fallback.\n- Guards refine a pattern after the structure matches.\n- OR patterns and star patterns keep shape-based branches compact.\n:::\n', 'args-and-kwargs.md': '+++\nslug = "args-and-kwargs"\ntitle = "Args and Kwargs"\nsection = "Functions"\nsummary = "*args collects extra positional arguments and **kwargs collects named ones."\ndoc_path = "/tutorial/controlflow.html#arbitrary-argument-lists"\nsee_also = [\n "functions",\n "keyword-only-arguments",\n "partial-functions",\n "paramspec",\n]\n+++\n\n`*args` and `**kwargs` let a function accept flexible positional and keyword arguments. They are the function-definition counterpart to unpacking at a call site.\n\nThese parameters are useful for wrappers, decorators, logging helpers, and APIs that forward arguments to another function.\n\nThey should not replace clear signatures. If a function has a stable interface, explicit parameters document expectations better than a bag of arguments.\n\n:::program\n```python\ndef total(*numbers):\n return sum(numbers)\n\nprint(total(2, 3, 5))\n\n\ndef describe(**metadata):\n print(metadata)\n\ndescribe(owner="Ada", public=True)\n\n\ndef report(title, *items, **metadata):\n print(title)\n print(items)\n print(metadata)\n\nreport("scores", 10, 9, owner="Ada")\n```\n:::\n\n:::cell\n`*args` collects extra positional arguments into a tuple. This fits functions that naturally accept any number of similar values.\n\n```python\ndef total(*numbers):\n return sum(numbers)\n\nprint(total(2, 3, 5))\n```\n\n```output\n10\n```\n:::\n\n:::cell\n`**kwargs` collects named arguments into a dictionary. The names become string keys.\n\n```python\ndef describe(**metadata):\n print(metadata)\n\ndescribe(owner="Ada", public=True)\n```\n\n```output\n{\'owner\': \'Ada\', \'public\': True}\n```\n:::\n\n:::cell\nA function can combine explicit parameters, `*args`, and `**kwargs`. Put the flexible parts last so the fixed shape remains visible.\n\n```python\ndef report(title, *items, **metadata):\n print(title)\n print(items)\n print(metadata)\n\nreport("scores", 10, 9, owner="Ada")\n```\n\n```output\nscores\n(10, 9)\n{\'owner\': \'Ada\'}\n```\n:::\n\n:::note\n- Use these tools when a function naturally accepts a flexible shape.\n- Prefer explicit parameters when the accepted arguments are known and fixed.\n- `*args` is a tuple; `**kwargs` is a dictionary.\n:::\n', 'assertions.md': '+++\nslug = "assertions"\ntitle = "Assertions"\nsection = "Errors"\nsummary = "assert documents internal assumptions and fails loudly when they are false."\ndoc_path = "/reference/simple_stmts.html#the-assert-statement"\nsee_also = [\n "exceptions",\n "custom-exceptions",\n "type-hints",\n]\n+++\n\n`assert` checks an internal assumption. If the condition is false, Python raises `AssertionError` with an optional message.\n\nUse assertions for programmer assumptions, not for validating user input or external data. Input validation should raise ordinary exceptions that production code expects to handle.\n\nAssertions make invariants executable while keeping the successful path compact.\n\n:::program\n```python\ndef average(scores):\n assert scores, "scores must not be empty"\n return sum(scores) / len(scores)\n\nprint(average([8, 10]))\n\ntry:\n average([])\nexcept AssertionError as error:\n print(error)\n```\n:::\n\n:::cell\nWhen the assertion is true, execution continues normally. The assertion documents the function\'s internal expectation.\n\n```python\ndef average(scores):\n assert scores, "scores must not be empty"\n return sum(scores) / len(scores)\n\nprint(average([8, 10]))\n```\n\n```output\n9.0\n```\n:::\n\n:::cell\nWhen the assertion is false, Python raises `AssertionError`. This signals a broken assumption, not a normal recovery path.\n\n```python\ntry:\n average([])\nexcept AssertionError as error:\n print(error)\n```\n\n```output\nscores must not be empty\n```\n:::\n\n:::note\n- Use `assert` for internal invariants and debugging assumptions.\n- Use explicit exceptions for user input, files, network responses, and other expected failures.\n- Assertions can be disabled with Python optimization flags, so do not rely on them for security checks.\n:::\n', 'assignment-expressions.md': '+++\nslug = "assignment-expressions"\ntitle = "Assignment Expressions"\nsection = "Control Flow"\nsummary = "The walrus operator assigns a value inside an expression."\ndoc_path = "/reference/expressions.html#assignment-expressions"\nsee_also = [\n "conditionals",\n "while-loops",\n "variables",\n]\n+++\n\nThe assignment expression operator `:=` assigns a name while evaluating an expression. It is often called the walrus operator.\n\nUse it when computing a value and testing it are naturally one step. Avoid it when a separate assignment would make the code easier to read.\n\nThe boundary is readability: the walrus operator can remove duplication, but it should not hide important state changes.\n\n:::program\n```python\nmessages = ["hello", "", "python"]\n\nfor message in messages:\n if length := len(message):\n print(message, length)\n\nqueue = ["retry", "ok"]\nwhile (status := queue.pop(0)) != "ok":\n print(status)\nprint(status)\n```\n:::\n\n:::cell\nAn assignment expression can name a computed value while a condition tests it. Here empty strings are skipped because their length is zero.\n\n```python\nmessages = ["hello", "", "python"]\n\nfor message in messages:\n if length := len(message):\n print(message, length)\n```\n\n```output\nhello 5\npython 6\n```\n:::\n\n:::cell\nThe same idea works in [while loops](/examples/while-loops) that read state until a sentinel appears. The assignment and comparison stay together.\n\n```python\nqueue = ["retry", "ok"]\nwhile (status := queue.pop(0)) != "ok":\n print(status)\nprint(status)\n```\n\n```output\nretry\nok\n```\n:::\n\n:::note\n- `name := expression` assigns and evaluates to the assigned value.\n- Use it to avoid computing the same value twice.\n- Prefer a normal assignment when the expression becomes hard to scan.\n:::\n', 'async-await.md': '+++\nslug = "async-await"\ntitle = "Async Await"\nsection = "Async"\nsummary = "async def creates coroutines, and await pauses until awaitable work completes."\ndoc_path = "/library/asyncio-task.html"\nsee_also = [\n "async-iteration-and-context",\n "functions",\n "context-managers",\n]\n+++\n\n`async def` creates a coroutine function. Calling it creates a coroutine object; the body runs when an event loop awaits or schedules it.\n\n`await` pauses the current coroutine until another awaitable completes. This lets one event loop make progress on other work while a task waits for I/O.\n\nCloudflare Workers handlers are asynchronous, so understanding `await` is practical for fetch calls, bindings, and service interactions even when a small example uses `asyncio.sleep(0)` as a stand-in.\n\nThe alternative is ordinary `def` for work that completes immediately. Use async code for I/O-shaped waiting, not as a faster replacement for CPU-bound Python.\n\n:::program\n```python\nimport asyncio\n\ndef slug_to_title(slug):\n return slug.replace("-", " ").title()\n\nasync def fetch_title(slug):\n await asyncio.sleep(0)\n return slug_to_title(slug)\n\nasync def main():\n title = await fetch_title("async-await")\n print(title)\n titles = await asyncio.gather(fetch_title("json"), fetch_title("datetime"))\n print(titles)\n\nasyncio.run(main())\n\n\nclass Session:\n async def __aenter__(self):\n print("open")\n return self\n\n async def __aexit__(self, *_):\n print("close")\n return False\n\n\nasync def stream():\n for slug in ["json", "datetime"]:\n await asyncio.sleep(0)\n yield slug\n\n\nasync def driver():\n async with Session():\n async for slug in stream():\n print(slug)\n\nasyncio.run(driver())\n```\n:::\n\n:::cell\nAn ordinary `def` function computes its result immediately: calling it runs the body and hands the value straight back. This synchronous form is the baseline the rest of the page contrasts against.\n\n```python\ndef slug_to_title(slug):\n return slug.replace("-", " ").title()\n\nprint(slug_to_title("async-await"))\n```\n\n```output\nAsync Await\n```\n:::\n\n:::cell\nAn `async def` function returns a coroutine object when called. The function body has not produced its final result yet.\n\n```python\nimport asyncio\n\nasync def fetch_title(slug):\n await asyncio.sleep(0)\n return slug_to_title(slug)\n\ncoroutine = fetch_title("async-await")\nprint(coroutine.__class__.__name__)\ncoroutine.close()\n```\n\n```output\ncoroutine\n```\n:::\n\n:::cell\nUse `await` inside another coroutine to get the eventual result. `asyncio.run()` starts an event loop for the top-level coroutine.\n\n```python\nasync def main():\n title = await fetch_title("async-await")\n print(title)\n\nasyncio.run(main())\n```\n\n```output\nAsync Await\n```\n:::\n\n:::cell\n`asyncio.gather()` awaits several awaitables and returns their results in order. This is the shape used when independent I/O operations can progress together.\n\n```python\nasync def main():\n titles = await asyncio.gather(fetch_title("json"), fetch_title("datetime"))\n print(titles)\n\nasyncio.run(main())\n```\n\n```output\n[\'Json\', \'Datetime\']\n```\n:::\n\n:::cell\n`async with` and `async for` are the asynchronous forms of context managers and iteration. A class implements `__aenter__`/`__aexit__` to act as an async context manager; an `async def` function with `yield` becomes an async generator. The dedicated [async iteration and context](/examples/async-iteration-and-context) page explains the protocols in depth.\n\n```python\nclass Session:\n async def __aenter__(self):\n print("open")\n return self\n\n async def __aexit__(self, *_):\n print("close")\n return False\n\n\nasync def stream():\n for slug in ["json", "datetime"]:\n await asyncio.sleep(0)\n yield slug\n\n\nasync def driver():\n async with Session():\n async for slug in stream():\n print(slug)\n\nasyncio.run(driver())\n```\n\n```output\nopen\njson\ndatetime\nclose\n```\n:::\n\n:::note\n- Calling an async function creates a coroutine object.\n- `await` yields control until an awaitable completes.\n- Workers request handlers are async, so this pattern appears around fetches and bindings.\n- Prefer ordinary functions when there is no awaitable work to coordinate.\n:::\n', 'async-iteration-and-context.md': '+++\nslug = "async-iteration-and-context"\ntitle = "Async Iteration and Context"\nsection = "Async"\nsummary = "async for and async with consume asynchronous streams and cleanup protocols."\ndoc_path = "/reference/compound_stmts.html#async-for"\nsee_also = [\n "async-await",\n "iterators",\n "context-managers",\n]\n+++\n\n`async for` consumes an asynchronous iterator: a stream whose next value may require `await`. `async with` surrounds a block with asynchronous setup and cleanup.\n\nThese forms appear around network streams, database cursors, locks, and service clients where both iteration and cleanup may wait on I/O.\n\nUse ordinary `for` and `with` when producing the next value or cleaning up does not need to await anything.\n\nThe syntax mirrors `for` and `with`, but the protocol methods are asynchronous.\n\n:::program\n```python\nimport asyncio\n\nasync def titles():\n for slug in ["values", "async-await"]:\n await asyncio.sleep(0)\n yield slug.replace("-", " ").title()\n\nclass Session:\n async def __aenter__(self):\n print("open")\n return self\n\n async def __aexit__(self, exc_type, exc, tb):\n print("close")\n\nasync def main():\n async with Session():\n async for title in titles():\n print(title)\n\nasyncio.run(main())\n```\n:::\n\n:::cell\nAn async generator can `await` before yielding each value. `async for` consumes those values with the asynchronous iteration protocol.\n\n```python\nimport asyncio\n\nasync def titles():\n for slug in ["values", "async-await"]:\n await asyncio.sleep(0)\n yield slug.replace("-", " ").title()\n\nprint(titles.__name__)\n```\n\n```output\ntitles\n```\n:::\n\n:::cell\nAn async context manager defines `__aenter__` and `__aexit__`. `async with` awaits setup and cleanup around the block.\n\n```python\nclass Session:\n async def __aenter__(self):\n print("open")\n return self\n\n async def __aexit__(self, exc_type, exc, tb):\n print("close")\n\nprint(Session.__name__)\n```\n\n```output\nSession\n```\n:::\n\n:::cell\nThe top-level coroutine combines both protocols: open the async resource, then consume the async stream inside it.\n\n```python\nasync def main():\n async with Session():\n async for title in titles():\n print(title)\n\nasyncio.run(main())\n```\n\n```output\nopen\nValues\nAsync Await\nclose\n```\n:::\n\n:::note\n- `async for` consumes asynchronous iterators.\n- `async with` awaits asynchronous setup and cleanup.\n- These forms are common around I/O-shaped resources.\n:::\n', 'attribute-access.md': '+++\nslug = "attribute-access"\ntitle = "Attribute Access"\nsection = "Data Model"\nsummary = "Attribute hooks customize lookup, missing attributes, and assignment."\ndoc_path = "/reference/datamodel.html#customizing-attribute-access"\nsee_also = [\n "properties",\n "descriptors",\n "special-methods",\n "bound-and-unbound-methods",\n]\n+++\n\nAttribute access is usually simple: `obj.name` looks up an attribute. Python exposes hooks for the uncommon cases where lookup or assignment needs to be customized.\n\n`__getattr__` runs only when normal lookup fails, which makes it a safer hook for computed fallback attributes. `__setattr__` runs for every assignment, so it should be used sparingly and carefully.\n\nPrefer ordinary attributes and `@property` first. Reach for these hooks when an object is intentionally adapting another interface, validating all assignments, or exposing dynamic fields.\n\n:::program\n```python\nclass Settings:\n def __init__(self, values):\n self._values = dict(values)\n\n def __getattr__(self, name):\n try:\n return self._values[name]\n except KeyError as error:\n raise AttributeError(name) from error\n\n def __setattr__(self, name, value):\n if name.startswith("_"):\n object.__setattr__(self, name, value)\n else:\n self._values[name] = value\n\nsettings = Settings({"theme": "dark"})\nprint(settings.theme)\nsettings.volume = 7\nprint(settings._values["volume"])\n```\n:::\n\n:::cell\nThe starting point is ordinary: `__init__` stores one real attribute, the `_values` backing dictionary. The hooks in the next cells customize lookup and assignment around it.\n\n```python\nclass Settings:\n def __init__(self, values):\n self._values = dict(values)\n\nsettings = Settings({"theme": "dark"})\nprint(settings._values)\n```\n\n```output\n{\'theme\': \'dark\'}\n```\n:::\n\n:::cell\n`__getattr__` runs only for missing attributes, so it can provide fallback lookup.\n\n```python\nclass Settings:\n def __init__(self, values):\n self._values = dict(values)\n\n def __getattr__(self, name):\n try:\n return self._values[name]\n except KeyError as error:\n raise AttributeError(name) from error\n\nsettings = Settings({"theme": "dark"})\nprint(settings.theme)\n```\n\n```output\ndark\n```\n:::\n\n:::cell\n`__setattr__` intercepts every assignment, including the ones in `__init__`. Underscore names are stored as real attributes through `object.__setattr__`, which avoids recursing through your own hook; public names go to the backing dictionary.\n\n```python\nclass Settings:\n def __init__(self, values):\n self._values = dict(values)\n\n def __setattr__(self, name, value):\n if name.startswith("_"):\n object.__setattr__(self, name, value)\n else:\n self._values[name] = value\n\nsettings = Settings({"theme": "dark"})\nsettings.volume = 7\nprint(settings._values["volume"])\n```\n\n```output\n7\n```\n:::\n\n:::note\n- `__getattr__` is narrower than `__getattribute__` because it handles only missing attributes.\n- `__setattr__` affects every assignment on the instance.\n- Use `property` or descriptors when the behavior is attached to a known attribute name.\n:::\n', 'booleans.md': '+++\nslug = "booleans"\ntitle = "Booleans"\nsection = "Basics"\nsummary = "Booleans represent truth values and combine with logical operators."\ndoc_path = "/library/stdtypes.html#boolean-type-bool"\nsee_also = [\n "truthiness",\n "operators",\n "conditionals",\n]\n+++\n\nBooleans are the values `True` and `False`. They are produced by comparisons and combined with `and`, `or`, and `not`.\n\nPython\'s logical operators short-circuit. That means the right side is evaluated only when needed, which keeps guard checks efficient and safe.\n\nBooleans are also connected to truthiness: many objects can be tested in conditions even when they are not literally `True` or `False`.\n\n:::program\n```python\nlogged_in = True\nhas_permission = False\n\nprint(logged_in and has_permission)\nprint(logged_in or has_permission)\nprint(not has_permission)\n\nname = "Ada"\nprint(name == "Ada" and len(name) > 0)\n\nprint(isinstance(True, int))\nprint(True + True)\nprint(sum([True, True, False, True]))\n\nvalue = True\nis_strict_int = isinstance(value, int) and not isinstance(value, bool)\nprint(is_strict_int)\n\nvalue = 1\nis_strict_int = isinstance(value, int) and not isinstance(value, bool)\nprint(is_strict_int)\n```\n:::\n\n:::cell\nUse booleans for facts that are either true or false. Python spells the constants `True` and `False`.\n\nUse `and`, `or`, and `not` to combine truth values. These operators read like English and short-circuit when possible.\n\n```python\nlogged_in = True\nhas_permission = False\n\nprint(logged_in and has_permission)\nprint(logged_in or has_permission)\nprint(not has_permission)\n```\n\n```output\nFalse\nTrue\nTrue\n```\n:::\n\n:::cell\nComparisons produce booleans too, so they compose naturally with logical operators in conditions and validation checks.\n\n```python\nname = "Ada"\nprint(name == "Ada" and len(name) > 0)\n```\n\n```output\nTrue\n```\n:::\n\n:::cell\n`bool` is a subclass of `int`, which is occasionally a footgun. `True` behaves as `1` and `False` as `0` in arithmetic, and `isinstance(True, int)` is `True`. When a check must reject booleans, exclude them explicitly with `isinstance(value, int) and not isinstance(value, bool)`: the combined test is false for `True` and true for `1`.\n\n```python\nprint(isinstance(True, int))\nprint(True + True)\nprint(sum([True, True, False, True]))\n\nvalue = True\nis_strict_int = isinstance(value, int) and not isinstance(value, bool)\nprint(is_strict_int)\n\nvalue = 1\nis_strict_int = isinstance(value, int) and not isinstance(value, bool)\nprint(is_strict_int)\n```\n\n```output\nTrue\n2\n3\nFalse\nTrue\n```\n:::\n\n:::note\n- Boolean constants are `True` and `False`, with capital letters.\n- `and` and `or` short-circuit: Python does not evaluate the right side if the left side already determines the result.\n- Prefer truthiness for containers and explicit comparisons when the exact boolean condition matters.\n- `bool` subclasses `int`; `isinstance(True, int)` is `True`. Exclude booleans explicitly when only "real" integers should pass.\n:::\n', 'bound-and-unbound-methods.md': '+++\nslug = "bound-and-unbound-methods"\ntitle = "Bound and Unbound Methods"\nsection = "Data Model"\nsummary = "instance.method binds self automatically; Class.method is a plain function."\ndoc_path = "/reference/datamodel.html#instance-methods"\nsee_also = [\n "classes",\n "attribute-access",\n "descriptors",\n "callable-objects",\n]\n+++\n\nWhen you write `instance.method`, Python returns a bound method — a callable that already remembers which instance to pass as `self`. When you write `Class.method`, you get the underlying function back, and calling it requires passing an instance yourself.\n\nThat distinction is why methods can be stored in collections, passed as callbacks, and called later without losing track of the object they belong to. Each bound method carries its own `__self__`, so two callables produced from two different instances stay independent even when their underlying function is the same.\n\nThe mechanism is the descriptor protocol: a function attached to a class implements `__get__`, and that hook turns attribute access on an instance into a bound method. The page does not need that detail to use methods, but it explains what is happening underneath.\n\n:::program\n```python\nclass Counter:\n def __init__(self, start=0):\n self.value = start\n\n def increment(self):\n self.value += 1\n return self.value\n\nbound_counter = Counter(10)\nm = bound_counter.increment\nprint(m.__self__ is bound_counter)\nprint(m())\nprint(m())\n\nunbound_counter = Counter(0)\nunbound = Counter.increment\nprint(type(unbound).__name__)\nprint(unbound(unbound_counter))\nprint(unbound(unbound_counter))\n\nhandlers = []\nfor _ in range(2):\n handlers.append(Counter().increment)\n\nprint(handlers[0]())\nprint(handlers[0]())\nprint(handlers[1]())\n\ndescriptor_counter = Counter(0)\nfunc = Counter.__dict__["increment"]\nprint(type(func).__name__)\nrebound = func.__get__(descriptor_counter, Counter)\nprint(type(rebound).__name__)\nprint(rebound.__self__ is descriptor_counter)\n```\n:::\n\n:::cell\n`instance.method` returns a bound method. The method already remembers the instance through `__self__`, so calling it does not require passing `self` again.\n\n```python\nclass Counter:\n def __init__(self, start=0):\n self.value = start\n\n def increment(self):\n self.value += 1\n return self.value\n\nbound_counter = Counter(10)\nm = bound_counter.increment\nprint(m.__self__ is bound_counter)\nprint(m())\nprint(m())\n```\n\n```output\nTrue\n11\n12\n```\n:::\n\n:::cell\n`Class.method` returns the underlying function — there is no `self` attached. Calling it requires passing the instance as the first argument explicitly. Using a fresh counter here makes the output independent of the previous cell.\n\n```python\nunbound_counter = Counter(0)\nunbound = Counter.increment\nprint(type(unbound).__name__)\nprint(unbound(unbound_counter))\nprint(unbound(unbound_counter))\n```\n\n```output\nfunction\n1\n2\n```\n:::\n\n:::cell\nBound methods are first-class values. They can be stored in lists, passed to other functions, and called later. Each bound method carries its own `__self__`, so two methods produced from two different instances stay independent.\n\n```python\nhandlers = []\nfor _ in range(2):\n handlers.append(Counter().increment)\n\nprint(handlers[0]())\nprint(handlers[0]())\nprint(handlers[1]())\n```\n\n```output\n1\n2\n1\n```\n:::\n\n:::cell\nThe binding is the descriptor protocol at work. The function lives on the class as a plain function; instance attribute access invokes `__get__`, which returns a bound method that knows the instance.\n\n```python\ndescriptor_counter = Counter(0)\nfunc = Counter.__dict__["increment"]\nprint(type(func).__name__)\nrebound = func.__get__(descriptor_counter, Counter)\nprint(type(rebound).__name__)\nprint(rebound.__self__ is descriptor_counter)\n```\n\n```output\nfunction\nmethod\nTrue\n```\n:::\n\n:::note\n- `instance.method` produces a bound method whose `__self__` is the instance.\n- `Class.method` produces the plain function and requires you to pass the instance.\n- "Unbound method" is the historical Python 2 term; since Python 3, `Class.method` is simply a function, which is what this page demonstrates.\n- Each bound method is its own object; storing one captures its instance.\n- The binding is implemented by the descriptor protocol on the function object.\n:::\n', 'break-and-continue.md': '+++\nslug = "break-and-continue"\ntitle = "Break and Continue"\nsection = "Control Flow"\nsummary = "break exits a loop early, while continue skips to the next iteration."\ndoc_path = "/tutorial/controlflow.html#break-and-continue-statements"\nsee_also = [\n "for-loops",\n "while-loops",\n "loop-else",\n]\n+++\n\n`break` and `continue` control the nearest enclosing loop. They exist for loops whose body discovers an early stop rule or an item-level skip rule.\n\nUse `continue` when the current item should not run the rest of the body. Use `break` when no later item should be processed.\n\nThe alternative is ordinary `if`/`else` nesting. Prefer `break` and `continue` when they keep the normal path flatter and easier to read.\n\n:::program\n```python\nnames = ["Ada", "", "Grace"]\nfor name in names:\n if not name:\n continue\n print(name)\n\ncommands = ["load", "save", "stop", "delete"]\nfor command in commands:\n if command == "stop":\n break\n print(command)\n```\n:::\n\n:::cell\n`continue` skips the rest of the current iteration. The empty name is ignored, and the loop moves on to the next value.\n\n```python\nnames = ["Ada", "", "Grace"]\nfor name in names:\n if not name:\n continue\n print(name)\n```\n\n```output\nAda\nGrace\n```\n:::\n\n:::cell\n`break` exits the loop immediately. The value after `stop` is never processed because the loop has already ended.\n\n```python\ncommands = ["load", "save", "stop", "delete"]\nfor command in commands:\n if command == "stop":\n break\n print(command)\n```\n\n```output\nload\nsave\n```\n:::\n\n:::note\n- `continue` skips to the next loop iteration.\n- `break` exits the nearest enclosing loop immediately.\n- Prefer plain `if`/`else` when the loop does not need early skip or early stop behavior.\n:::\n', 'bytes-and-bytearray.md': '+++\nslug = "bytes-and-bytearray"\ntitle = "Bytes and Bytearray"\nsection = "Text"\nsummary = "bytes and bytearray store binary data, not Unicode text."\ndoc_path = "/library/stdtypes.html#binary-sequence-types-bytes-bytearray-memoryview"\nsee_also = [\n "strings",\n "literals",\n "networking",\n]\n+++\n\n`str` stores Unicode text. `bytes` stores raw byte values. The boundary matters whenever text leaves Python for a file, network protocol, subprocess, or binary format.\n\nEncoding turns text into bytes with a named encoding such as UTF-8. Decoding turns bytes back into text. The lengths can differ because one Unicode character may require several bytes.\n\nUse immutable `bytes` for stable binary data and `bytearray` when the bytes must be changed in place.\n\n:::program\n```python\ntext = "café"\ndata = text.encode("utf-8")\n\nprint(data)\nprint(len(text), len(data))\nprint(data.decode("utf-8"))\nprint(data[0])\n\npacket = bytearray(b"py")\npacket[0] = ord("P")\nprint(packet)\n```\n:::\n\n:::cell\nEncode text when an external boundary needs bytes. UTF-8 uses one byte for ASCII characters and more than one byte for many other characters.\n\n```python\ntext = "café"\ndata = text.encode("utf-8")\nprint(data)\nprint(len(text), len(data))\n```\n\n```output\nb\'caf\\xc3\\xa9\'\n4 5\n```\n:::\n\n:::cell\nDecode bytes when the program needs text again. The decoder must match the encoding used at the boundary.\n\n```python\nprint(data.decode("utf-8"))\n```\n\n```output\ncafé\n```\n:::\n\n:::cell\nIndexing a `bytes` object returns an integer byte value, not a one-character `bytes` object.\n\n```python\nprint(data[0])\n```\n\n```output\n99\n```\n:::\n\n:::cell\n`bytes` is immutable. Use `bytearray` when binary data must be changed in place.\n\n```python\npacket = bytearray(b"py")\npacket[0] = ord("P")\nprint(packet)\n```\n\n```output\nbytearray(b\'Py\')\n```\n:::\n\n:::note\n- Encode text when an external boundary needs bytes.\n- Decode bytes when you want text again.\n- Indexing `bytes` returns integers from 0 to 255.\n- Use `bytearray` when binary data must be changed in place.\n:::\n', 'callable-objects.md': '+++\nslug = "callable-objects"\ntitle = "Callable Objects"\nsection = "Data Model"\nsummary = "__call__ lets an instance behave like a function while keeping state."\ndoc_path = "/reference/datamodel.html#object.__call__"\nsee_also = [\n "functions",\n "closures",\n "callable-types",\n "bound-and-unbound-methods",\n]\n+++\n\nFunctions are not the only callable objects in Python. Any instance can be called with parentheses when its class defines `__call__`.\n\nCallable objects are useful when behavior needs remembered configuration or evolving state. A closure can do this too; a class is often clearer when the state has multiple fields or needs named methods.\n\nThe tradeoff is ceremony. Use a function for simple behavior, a closure for small captured state, and a callable object when naming the state improves the interface.\n\n:::program\n```python\nclass Multiplier:\n def __init__(self, factor):\n self.factor = factor\n self.calls = 0\n\n def __call__(self, value):\n self.calls += 1\n return value * self.factor\n\ndouble = Multiplier(2)\nprint(double(5))\nprint(double(7))\nprint(double.calls)\n```\n:::\n\n:::cell\nA callable object starts as ordinary state stored on an instance.\n\n```python\nclass Multiplier:\n def __init__(self, factor):\n self.factor = factor\n self.calls = 0\n\ndouble = Multiplier(2)\nprint(double.factor)\n```\n\n```output\n2\n```\n:::\n\n:::cell\n`__call__` makes the instance usable with function-call syntax.\n\n```python\nclass Multiplier:\n def __init__(self, factor):\n self.factor = factor\n self.calls = 0\n\n def __call__(self, value):\n self.calls += 1\n return value * self.factor\n\ndouble = Multiplier(2)\nprint(double(5))\nprint(double(7))\n```\n\n```output\n10\n14\n```\n:::\n\n:::cell\nBecause the callable is still an object, it can remember state across calls.\n\n```python\nprint(double.calls)\n```\n\n```output\n2\n```\n:::\n\n:::note\n- `callable(obj)` checks whether an object can be called.\n- Callable objects are good for named, stateful behavior.\n- Prefer plain functions when no instance state is needed.\n:::\n', 'callable-types.md': '+++\nslug = "callable-types"\ntitle = "Callable Types"\nsection = "Types"\nsummary = "Callable annotations describe functions passed as values."\ndoc_path = "/library/typing.html#annotating-callable-objects"\nsee_also = [\n "functions",\n "callable-objects",\n "protocols",\n]\n+++\n\nCallable annotations describe values that can be called like functions. They are useful when a function accepts a callback, strategy, predicate, or transformation.\n\n`Callable[[int], int]` says how the callback will be called: one integer argument, integer result. The annotation helps tools and readers, while runtime still only needs an object that is actually callable.\n\nUse `Callable` for simple call shapes. Use a protocol when the callback needs named attributes, overloaded signatures, or a more descriptive interface.\n\n:::program\n```python\nfrom collections.abc import Callable\n\n\ndef apply_twice(value: int, func: Callable[[int], int]) -> int:\n return func(func(value))\n\n\ndef add_one(number: int) -> int:\n return number + 1\n\nclass Doubler:\n def __call__(self, number: int) -> int:\n return number * 2\n\nprint(apply_twice(3, add_one))\nprint(apply_twice(3, Doubler()))\nprint(callable(add_one), callable(Doubler()))\n```\n:::\n\n:::cell\nUse `Callable[[Arg], Return]` for function-shaped values. The callback is passed in and called by the receiving function.\n\n```python\nfrom collections.abc import Callable\n\n\ndef apply_twice(value: int, func: Callable[[int], int]) -> int:\n return func(func(value))\n\n\ndef add_one(number: int) -> int:\n return number + 1\n\nprint(apply_twice(3, add_one))\n```\n\n```output\n5\n```\n:::\n\n:::cell\nCallable annotations are structural: an object with `__call__` can also satisfy the shape.\n\n```python\nclass Doubler:\n def __call__(self, number: int) -> int:\n return number * 2\n\nprint(apply_twice(3, Doubler()))\n```\n\n```output\n12\n```\n:::\n\n:::cell\nRuntime callability is a separate question from static annotation. `callable()` checks whether Python can call the object.\n\n```python\nprint(callable(add_one), callable(Doubler()))\n```\n\n```output\nTrue True\n```\n:::\n\n:::note\n- Use `Callable[[Arg], Return]` for simple function-shaped values.\n- The annotation documents how the callback will be called.\n- For complex call signatures, protocols can be clearer.\n:::\n', 'casts-and-any.md': '+++\nslug = "casts-and-any"\ntitle = "Casts and Any"\nsection = "Types"\nsummary = "Any and cast are escape hatches for places static analysis cannot prove."\ndoc_path = "/library/typing.html#typing.cast"\nsee_also = [\n "type-hints",\n "runtime-type-checks",\n "typed-dicts",\n]\n+++\n\n`Any` and `cast()` are escape hatches. They are useful at messy boundaries where a type checker cannot prove what a value is, but they also remove protection when overused.\n\n`Any` tells static tools to stop checking most operations on a value. `cast(T, value)` tells the type checker to treat a value as `T`, but it returns the same runtime object unchanged.\n\nPrefer narrowing with runtime checks when possible. Use `cast()` when another invariant already proves the type and the checker cannot see that proof.\n\n:::program\n```python\nfrom typing import Any, cast\n\nraw: Any = {"score": "98"}\nscore_text = cast(dict[str, str], raw)["score"]\nscore = int(score_text)\n\nprint(score + 2)\nprint(cast(list[int], raw) is raw)\nprint(type(raw).__name__)\n\nvalue: object = {"score": "98"}\nif isinstance(value, dict):\n print(value["score"])\n```\n:::\n\n:::cell\n`Any` disables most static checking for a value. The runtime object is still whatever value was actually assigned.\n\n```python\nfrom typing import Any, cast\n\nraw: Any = {"score": "98"}\nscore_text = cast(dict[str, str], raw)["score"]\nscore = int(score_text)\nprint(score + 2)\n```\n\n```output\n100\n```\n:::\n\n:::cell\n`cast()` does not convert or validate the value. It returns the same object at runtime.\n\n```python\nprint(cast(list[int], raw) is raw)\nprint(type(raw).__name__)\n```\n\n```output\nTrue\ndict\n```\n:::\n\n:::cell\nA real runtime check narrows by inspecting the value. This is safer when the input is untrusted.\n\n```python\nvalue: object = {"score": "98"}\nif isinstance(value, dict):\n print(value["score"])\n```\n\n```output\n98\n```\n:::\n\n:::note\n- `Any` disables most static checking for a value.\n- `cast()` tells the type checker to trust you without changing the runtime object.\n- Prefer narrowing with checks when possible.\n:::\n', 'classes.md': '+++\nslug = "classes"\ntitle = "Classes"\nsection = "Classes"\nsummary = "Classes bundle data and behavior into new object types."\ndoc_path = "/tutorial/classes.html"\nsee_also = [\n "inheritance-and-super",\n "classmethods-and-staticmethods",\n "bound-and-unbound-methods",\n "dataclasses",\n]\n+++\n\nClasses define new object types by bundling data with behavior. They are useful when several values and operations belong together and should travel as one object.\n\nThe alternative is often a dictionary plus separate functions. That is fine for loose data, but a class gives the data a stable API and keeps behavior next to the state it changes.\n\n`__init__` initializes each instance, and methods receive the instance as `self`. Separate instances keep separate state because each object has its own attributes.\n\n:::program\n```python\nclass Counter:\n step = 1\n\n def __init__(self, start=0):\n self.value = start\n\n def increment(self, amount=1):\n self.value += amount\n return self.value\n\nfirst = Counter()\nsecond = Counter(10)\n\nprint(first.value)\nprint(second.value)\nprint(first.increment())\nprint(second.increment(5))\nprint(first.step)\nCounter.step = 5\nprint(second.step)\n\nclass Cart:\n items = []\n\n def add(self, item):\n self.items.append(item)\n\nshared_a = Cart()\nshared_b = Cart()\nshared_a.add("apple")\nprint(shared_b.items)\n\nclass FixedCart:\n def __init__(self):\n self.items = []\n\n def add(self, item):\n self.items.append(item)\n\nown_a = FixedCart()\nown_b = FixedCart()\nown_a.add("apple")\nprint(own_b.items)\n```\n:::\n\n:::cell\nDefine a class when data and behavior should travel together. The initializer gives each object its starting state.\n\n```python\nclass Counter:\n def __init__(self, start=0):\n self.value = start\n\nfirst = Counter()\nsecond = Counter(10)\nprint(first.value)\nprint(second.value)\n```\n\n```output\n0\n10\n```\n:::\n\n:::cell\nMethods are functions attached to the class. `self` is the particular object receiving the method call, so separate instances keep separate state.\n\n```python\nclass Counter:\n def __init__(self, start=0):\n self.value = start\n\n def increment(self, amount=1):\n self.value += amount\n return self.value\n\nfirst = Counter()\nsecond = Counter(10)\nprint(first.increment())\nprint(second.increment(5))\n```\n\n```output\n1\n15\n```\n:::\n\n:::cell\nA name defined directly on the class body is a class attribute, shared by every instance. Reading falls back to the class when the instance has no attribute of that name; assigning to the class itself changes the value for every instance at once.\n\n```python\nclass Counter:\n step = 1\n\n def __init__(self, start=0):\n self.value = start\n\nfirst = Counter()\nsecond = Counter()\nprint(first.step)\nCounter.step = 5\nprint(second.step)\n```\n\n```output\n1\n5\n```\n:::\n\n:::cell\nA mutable class attribute is shared mutable state — the classic footgun. Define per-instance containers in `__init__` so each object owns its own copy.\n\n```python\nclass Cart:\n items = []\n\n def add(self, item):\n self.items.append(item)\n\nshared_a = Cart()\nshared_b = Cart()\nshared_a.add("apple")\nprint(shared_b.items)\n\nclass FixedCart:\n def __init__(self):\n self.items = []\n\n def add(self, item):\n self.items.append(item)\n\nown_a = FixedCart()\nown_b = FixedCart()\nown_a.add("apple")\nprint(own_b.items)\n```\n\n```output\n[\'apple\']\n[]\n```\n:::\n\n:::note\n- `self` is the instance the method is operating on.\n- `__init__` initializes each new object.\n- Class attributes are shared across instances; instance attributes belong to one object.\n- Put mutable defaults in `__init__`, not on the class body.\n- Use classes when behavior belongs with state; use dictionaries for looser structured data.\n:::\n', 'classmethods-and-staticmethods.md': '+++\nslug = "classmethods-and-staticmethods"\ntitle = "Classmethods and Staticmethods"\nsection = "Classes"\nsummary = "Three method shapes: instance, class, and static — each receives a different first argument."\ndoc_path = "/library/functions.html#classmethod"\nsee_also = [\n "classes",\n "decorators",\n "inheritance-and-super",\n]\n+++\n\nA regular method receives the instance as `self`. `@classmethod` makes a method receive the class as `cls` instead, which is the standard shape for alternate constructors. `@staticmethod` removes the implicit first argument entirely, leaving a plain function attached to the class for namespacing.\n\nThe pressure that justifies the decorators is name organization. `Date.from_string("2026-05-09")` reads better than a free-floating `parse_date` function, and `Date.is_leap_year(2024)` keeps the helper next to the class it belongs to even when the helper does not need any class state.\n\nPick instance methods when the work depends on instance state, classmethods when an alternate constructor or class-level operation is the right shape, and staticmethods when the function only happens to live near a class.\n\n:::program\n```python\nclass Date:\n def __init__(self, year, month, day):\n self.year = year\n self.month = month\n self.day = day\n\n def display(self):\n return f"{self.year}-{self.month:02d}-{self.day:02d}"\n\n @classmethod\n def from_string(cls, text):\n year, month, day = (int(part) for part in text.split("-"))\n return cls(year, month, day)\n\n @staticmethod\n def is_leap_year(year):\n return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)\n\ntoday = Date(2026, 5, 9)\nprint(today.display())\n\nlater = Date.from_string("2026-12-31")\nprint(later.display())\n\nprint(Date.is_leap_year(2024))\nprint(Date.is_leap_year(2025))\n\nclass Demo:\n def instance_method(self):\n return type(self).__name__\n\n @classmethod\n def class_method(cls):\n return cls.__name__\n\n @staticmethod\n def static_method():\n return "no receiver"\n\nprint(Demo().instance_method())\nprint(Demo.class_method())\nprint(Demo.static_method())\n```\n:::\n\n:::cell\nAn instance method receives the instance as `self` and reads its state. This is the default and the right shape when the work depends on a particular object\'s data.\n\n```python\nclass Date:\n def __init__(self, year, month, day):\n self.year = year\n self.month = month\n self.day = day\n\n def display(self):\n return f"{self.year}-{self.month:02d}-{self.day:02d}"\n\ntoday = Date(2026, 5, 9)\nprint(today.display())\n```\n\n```output\n2026-05-09\n```\n:::\n\n:::cell\n`@classmethod` makes the method receive the class itself as `cls`. The canonical use is an alternate constructor that parses some other input format and calls `cls(...)`. Because `cls` is the actual class, subclasses calling the same method get an instance of their own type.\n\n```python\nclass Date:\n def __init__(self, year, month, day):\n self.year = year\n self.month = month\n self.day = day\n\n @classmethod\n def from_string(cls, text):\n year, month, day = (int(part) for part in text.split("-"))\n return cls(year, month, day)\n\nlater = Date.from_string("2026-12-31")\nprint(later.year, later.month, later.day)\n```\n\n```output\n2026 12 31\n```\n:::\n\n:::cell\n`@staticmethod` strips the implicit first argument. The function lives on the class for namespacing — like `Date.is_leap_year(2024)` — but does not touch any instance or class state.\n\n```python\nclass Date:\n @staticmethod\n def is_leap_year(year):\n return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)\n\nprint(Date.is_leap_year(2024))\nprint(Date.is_leap_year(2025))\n```\n\n```output\nTrue\nFalse\n```\n:::\n\n:::cell\nSide by side: instance methods receive the instance, classmethods receive the class, staticmethods receive nothing. Classmethods and staticmethods can be called on either the class or an instance.\n\n```python\nclass Demo:\n def instance_method(self):\n return type(self).__name__\n\n @classmethod\n def class_method(cls):\n return cls.__name__\n\n @staticmethod\n def static_method():\n return "no receiver"\n\nprint(Demo().instance_method())\nprint(Demo.class_method())\nprint(Demo.static_method())\n```\n\n```output\nDemo\nDemo\nno receiver\n```\n:::\n\n:::note\n- Instance methods need an instance; classmethods and staticmethods can be called on the class.\n- Use `@classmethod` for alternate constructors and class-level operations that respect subclassing.\n- Use `@staticmethod` only when a function is truly independent of instance and class state but still belongs in the class\'s namespace.\n- A free function is often the right answer when neither decorator applies.\n:::\n', 'closures.md': '+++\nslug = "closures"\ntitle = "Closures"\nsection = "Functions"\nsummary = "Inner functions can remember values from an enclosing scope."\ndoc_path = "/reference/executionmodel.html#binding-of-names"\nsee_also = [\n "functions",\n "lambdas",\n "decorators",\n "partial-functions",\n]\n+++\n\nA closure is a function that remembers names from the scope where it was created. This lets you configure behavior once and call it later.\n\nEach call to the outer function creates a separate remembered environment. That is why `double` and `triple` can share the same code but keep different factors.\n\nClosures are a foundation for decorators, callbacks, and small function factories.\n\n:::program\n```python\ndef make_multiplier(factor):\n def multiply(value):\n return value * factor\n return multiply\n\ndouble = make_multiplier(2)\nprint(double(5))\n\ntriple = make_multiplier(3)\nprint(triple(5))\n\nlate = []\nfor i in range(3):\n late.append(lambda: i)\nprint([f() for f in late])\n\nbound = []\nfor i in range(3):\n bound.append(lambda i=i: i)\nprint([f() for f in bound])\n```\n:::\n\n:::cell\nDefine a function inside another function when the inner behavior needs to remember setup from the outer call. The returned function keeps access to `factor`.\n\n```python\ndef make_multiplier(factor):\n def multiply(value):\n return value * factor\n return multiply\n\ndouble = make_multiplier(2)\nprint(double(5))\n```\n\n```output\n10\n```\n:::\n\n:::cell\nCalling the outer function again creates a separate closure. `triple` uses the same inner code, but remembers a different `factor`.\n\n```python\ntriple = make_multiplier(3)\nprint(triple(5))\n```\n\n```output\n15\n```\n:::\n\n:::cell\nClosures bind names, not values. [Lambdas](/examples/lambdas) (one-expression functions) defined in a loop all reference the same loop variable, so calling them later sees its final value. Capture the value at definition time by binding it as a default argument — `lambda i=i: i` — so each closure remembers its own `i`.\n\n```python\nlate = []\nfor i in range(3):\n late.append(lambda: i)\nprint([f() for f in late])\n\nbound = []\nfor i in range(3):\n bound.append(lambda i=i: i)\nprint([f() for f in bound])\n```\n\n```output\n[2, 2, 2]\n[0, 1, 2]\n```\n:::\n\n:::note\n- A closure keeps access to names from the scope where the inner function was created.\n- Each call to the outer function can create a separate remembered environment.\n- Closures are useful for callbacks, small factories, and decorators.\n- Closures bind names, not values; capture loop variables with `lambda x=x: ...` to freeze them at definition time.\n:::\n', 'collections-module.md': '+++\nslug = "collections-module"\ntitle = "Collections Module"\nsection = "Collections"\nsummary = "collections provides specialized containers for common data shapes."\ndoc_path = "/library/collections.html"\nsee_also = [\n "dicts",\n "lists",\n "tuples",\n "sets",\n]\n+++\n\n`collections` provides specialized containers for common shapes that would otherwise require repetitive plumbing. Use it when the shape has a name: counting, grouping, queueing, or lightweight records.\n\nThese types are not replacements for `list`, `dict`, `tuple`, and `set`. They are small standard-library tools for cases where an ordinary container would hide the intent behind manual bookkeeping.\n\nThe examples below map each type to the question it answers.\n\n:::program\n```python\nfrom collections import Counter, defaultdict, deque, namedtuple\n\ncounts = Counter("banana")\nprint(counts.most_common(2))\n\ngroups = defaultdict(list)\nfor name, team in [("Ada", "red"), ("Grace", "blue"), ("Lin", "red")]:\n groups[team].append(name)\nprint(dict(groups))\n\nqueue = deque(["first"])\nqueue.append("second")\nprint(queue.popleft())\n\nPoint = namedtuple("Point", "x y")\nprint(Point(2, 3).x)\n```\n:::\n\n:::cell\nUse `Counter` when the question is "how many times did each value appear?"\n\n```python\nfrom collections import Counter\n\ncounts = Counter("banana")\nprint(counts.most_common(2))\n```\n\n```output\n[(\'a\', 3), (\'n\', 2)]\n```\n:::\n\n:::cell\nUse `defaultdict(list)` when each key gathers multiple values and the missing-key case should create an empty list automatically.\n\n```python\nfrom collections import defaultdict\n\ngroups = defaultdict(list)\nfor name, team in [("Ada", "red"), ("Grace", "blue"), ("Lin", "red")]:\n groups[team].append(name)\nprint(dict(groups))\n```\n\n```output\n{\'red\': [\'Ada\', \'Lin\'], \'blue\': [\'Grace\']}\n```\n:::\n\n:::cell\nUse `deque` for queue operations at both ends, and `namedtuple` when a tiny immutable record needs names as well as positions.\n\n```python\nfrom collections import deque, namedtuple\n\nqueue = deque(["first"])\nqueue.append("second")\nprint(queue.popleft())\n\nPoint = namedtuple("Point", "x y")\nprint(Point(2, 3).x)\n```\n\n```output\nfirst\n2\n```\n:::\n\n:::note\n- `Counter` counts, `defaultdict` groups, `deque` queues, and `namedtuple` names record fields.\n- Prefer the built-in containers until a specialized shape makes the code clearer.\n- For new structured records with defaults and methods, consider `dataclasses` instead of `namedtuple`.\n:::\n', 'comprehension-patterns.md': '+++\nslug = "comprehension-patterns"\ntitle = "Comprehension Patterns"\nsection = "Collections"\nsummary = "Comprehensions can use multiple for clauses and filters when the shape stays clear."\ndoc_path = "/tutorial/datastructures.html#list-comprehensions"\nsee_also = [\n "comprehensions",\n "generator-expressions",\n "for-loops",\n]\n+++\n\nComprehensions can contain more than one `for` clause and more than one `if` filter. The clauses are read in the same order as nested loops.\n\nUse these forms only while the shape remains easy to scan. If a comprehension starts needing several names, comments, or branches, an explicit loop is usually better.\n\nNested comprehensions build concrete collections immediately, just like simpler list, dict, and set comprehensions.\n\n:::program\n```python\ncolors = ["red", "blue"]\nsizes = ["S", "M"]\nvariants = [(color, size) for color in colors for size in sizes]\nprint(variants)\n\nnumbers = range(10)\nfiltered = [n for n in numbers if n % 2 == 0 if n > 2]\nprint(filtered)\n```\n:::\n\n:::cell\nMultiple `for` clauses behave like nested loops. The leftmost `for` is the outer loop, and the next `for` runs inside it.\n\n```python\ncolors = ["red", "blue"]\nsizes = ["S", "M"]\nvariants = [(color, size) for color in colors for size in sizes]\nprint(variants)\n```\n\n```output\n[(\'red\', \'S\'), (\'red\', \'M\'), (\'blue\', \'S\'), (\'blue\', \'M\')]\n```\n:::\n\n:::cell\nMultiple `if` clauses filter values. They are useful for simple conditions, but an explicit loop is clearer when the rules need names or explanation.\n\n```python\nnumbers = range(10)\nfiltered = [n for n in numbers if n % 2 == 0 if n > 2]\nprint(filtered)\n```\n\n```output\n[4, 6, 8]\n```\n:::\n\n:::note\n- Read comprehension clauses from left to right.\n- Multiple `for` clauses act like nested loops.\n- Prefer an explicit loop when the comprehension stops being obvious.\n:::\n', 'comprehensions.md': '+++\nslug = "comprehensions"\ntitle = "Comprehensions"\nsection = "Collections"\nsummary = "Comprehensions build collections by mapping and filtering iterables."\ndoc_path = "/tutorial/datastructures.html#list-comprehensions"\nsee_also = [\n "for-loops",\n "generator-expressions",\n "comprehension-patterns",\n "lists",\n]\n+++\n\nComprehensions are expression forms for building concrete collections from iterables. Read them from left to right: produce this value, for each item, optionally only when a condition is true.\n\nThey are best for direct transformations where the expression is still easy to scan. When the work needs several statements or names, an explicit loop is usually clearer.\n\nList, dictionary, and set comprehensions are eager: they build collections immediately. Generator expressions use similar syntax to stream values later and are covered in the Iteration section.\n\n:::program\n```python\nnames = ["ada", "guido", "grace"]\ntitled = [name.title() for name in names]\nprint(titled)\n\nscores = {"Ada": 10, "Guido": 8, "Grace": 10}\nhigh_scores = {name: score for name, score in scores.items() if score >= 10}\nprint(high_scores)\n\nunique_scores = {score for score in scores.values()}\nprint(sorted(unique_scores))\n```\n:::\n\n:::cell\nA list comprehension maps each input item to one output item. This one calls `title()` for every name and collects the results in a new list.\n\n```python\nnames = ["ada", "guido", "grace"]\ntitled = [name.title() for name in names]\nprint(titled)\n```\n\n```output\n[\'Ada\', \'Guido\', \'Grace\']\n```\n:::\n\n:::cell\nAdd an `if` clause when only some items should appear. A dictionary comprehension can transform key/value pairs while preserving the dictionary shape.\n\n```python\nscores = {"Ada": 10, "Guido": 8, "Grace": 10}\nhigh_scores = {name: score for name, score in scores.items() if score >= 10}\nprint(high_scores)\n```\n\n```output\n{\'Ada\': 10, \'Grace\': 10}\n```\n:::\n\n:::cell\nA set comprehension keeps only unique results. Here two people have the same score, so the resulting set has two values — printed through `sorted()` because sets have no display order to rely on.\n\n```python\nunique_scores = {score for score in scores.values()}\nprint(sorted(unique_scores))\n```\n\n```output\n[8, 10]\n```\n:::\n\n:::note\n- The left side says what to produce; the `for` clause says where values come from.\n- Use an `if` clause for simple filters.\n- List, dict, and set comprehensions build concrete collections immediately.\n- Switch to a loop when the transformation needs multiple steps or explanations.\n:::\n', 'conditionals.md': '+++\nslug = "conditionals"\ntitle = "Conditionals"\nsection = "Control Flow"\nsummary = "if, elif, and else choose which block runs."\ndoc_path = "/tutorial/controlflow.html#if-statements"\nsee_also = [\n "booleans",\n "truthiness",\n "guard-clauses",\n "match-statements",\n]\n+++\n\n`if`, `elif`, and `else` let a program choose one path based on a condition. Python uses indentation to show which statements belong to each branch.\n\nConditions use Python truthiness: booleans work directly, and many objects such as empty lists or empty strings are considered false. Order branches from most specific to most general.\n\nUse `elif` to keep one decision flat instead of nested. Use Python\'s ternary expression only when you are choosing between two values.\n\n:::program\n```python\ntemperature = 72\n\nif temperature < 60:\n print("cold")\nelif temperature < 80:\n print("comfortable")\nelse:\n print("hot")\n\nitems = ["coat", "hat"]\nif items:\n print(f"packing {len(items)} items")\n\nstatus = "ok" if temperature < 90 else "danger"\nprint(status)\n```\n:::\n\n:::cell\nStart with the value that the branches will test. A conditional is only useful when the branch condition is visible and meaningful.\n\nUse `if`, `elif`, and `else` for one ordered choice. Python tests the branches from top to bottom and runs only the first matching block.\n\n```python\ntemperature = 72\n\nif temperature < 60:\n print("cold")\nelif temperature < 80:\n print("comfortable")\nelse:\n print("hot")\n```\n\n```output\ncomfortable\n```\n:::\n\n:::cell\nTruthiness is part of conditional flow. Empty collections are false, so `if items:` reads as “if there is anything to work with.”\n\n```python\nitems = ["coat", "hat"]\nif items:\n print(f"packing {len(items)} items")\n```\n\n```output\npacking 2 items\n```\n:::\n\n:::cell\nUse the ternary expression when you are choosing a value. If either side needs multiple statements, use a normal `if` block instead.\n\n```python\nstatus = "ok" if temperature < 90 else "danger"\nprint(status)\n```\n\n```output\nok\n```\n:::\n\n:::note\n- Python has no mandatory parentheses around conditions; the colon and indentation define the block.\n- Comparison operators such as `<` and `==` can be chained, as in `0 < value < 10`.\n- Keep branch bodies short; move larger work into functions so the decision remains easy to scan.\n:::\n', 'constants.md': '+++\nslug = "constants"\ntitle = "Constants"\nsection = "Basics"\nsummary = "Python uses naming conventions and optional types for values that should not change."\ndoc_path = "/library/typing.html#typing.Final"\nsee_also = [\n "variables",\n "literal-and-final",\n "type-hints",\n]\n+++\n\nPython has no `const` keyword for ordinary names. Modules use all-caps names such as `MAX_RETRIES` to say “treat this as fixed configuration, not changing state.”\n\nThe interpreter will still let code rebind the name. That is why constants are primarily an API and readability convention. If a project also uses static typing, `Final` can make the convention machine-checkable.\n\nNamed constants remove magic values from code and give repeated literals one place to change.\n\n:::program\n```python\nfrom typing import Final\n\nMAX_RETRIES: Final = 3\nAPI_VERSION = "2026-05"\n\nattempts = 2\nprint(attempts < MAX_RETRIES)\nattempts = 3\nprint(attempts < MAX_RETRIES)\n\nprint(API_VERSION)\n\nMAX_RETRIES = 5\nprint(MAX_RETRIES)\n```\n:::\n\n:::cell\nAll-caps names communicate design intent: this value is configuration that callers should treat as fixed. Comparing against `MAX_RETRIES` instead of a bare `3` keeps the meaning beside the check, and gives the limit one place to change.\n\n```python\nMAX_RETRIES = 3\n\nattempts = 2\nprint(attempts < MAX_RETRIES)\nattempts = 3\nprint(attempts < MAX_RETRIES)\n```\n\n```output\nTrue\nFalse\n```\n:::\n\n:::cell\nConstants are useful when a repeated literal deserves a name at the domain boundary.\n\n```python\nAPI_VERSION = "2026-05"\nprint(API_VERSION)\n```\n\n```output\n2026-05\n```\n:::\n\n:::cell\n`Final` lets type checkers reject reassignment, but Python still runs ordinary rebinding at runtime.\n\n```python\nfrom typing import Final\n\nMAX_RETRIES: Final = 3\nMAX_RETRIES = 5\nprint(MAX_RETRIES)\n```\n\n```output\n5\n```\n:::\n\n:::note\n- Python constants are a convention, not a runtime lock.\n- Use all-caps names for fixed module-level configuration.\n- Add `Final` when static tooling should flag accidental rebinding.\n:::\n', 'container-protocols.md': '+++\nslug = "container-protocols"\ntitle = "Container Protocols"\nsection = "Data Model"\nsummary = "Container methods connect objects to indexing, membership, and item assignment."\ndoc_path = "/reference/datamodel.html#emulating-container-types"\nsee_also = [\n "lists",\n "dicts",\n "special-methods",\n]\n+++\n\nContainer protocols let a class behave like the collection it represents. Instead of inventing method names such as `has()` or `lookup()`, the object can support `in`, indexing, and assignment.\n\nThe key methods are small and familiar: `__contains__` powers `in`, `__getitem__` powers `obj[key]`, and `__setitem__` powers `obj[key] = value`. Add only the operations the object can honestly support.\n\nThis keeps the public interface aligned with Python\'s built-in containers. Callers can use the same syntax for custom records, caches, tables, and sequence-like objects.\n\n:::program\n```python\nclass Scores:\n def __init__(self):\n self._scores = {}\n\n def __contains__(self, name):\n return name in self._scores\n\n def __getitem__(self, name):\n return self._scores[name]\n\n def __setitem__(self, name, score):\n self._scores[name] = score\n\nscores = Scores()\nscores["Ada"] = 98\nprint("Ada" in scores)\nprint(scores["Ada"])\n```\n:::\n\n:::cell\n`__setitem__` gives assignment syntax to a custom container.\n\n```python\nclass Scores:\n def __init__(self):\n self._scores = {}\n\n def __setitem__(self, name, score):\n self._scores[name] = score\n\nscores = Scores()\nscores["Ada"] = 98\nprint(scores._scores)\n```\n\n```output\n{\'Ada\': 98}\n```\n:::\n\n:::cell\n`__contains__` answers membership tests written with `in`.\n\n```python\nclass Scores:\n def __init__(self):\n self._scores = {"Ada": 98}\n\n def __contains__(self, name):\n return name in self._scores\n\nscores = Scores()\nprint("Ada" in scores)\n```\n\n```output\nTrue\n```\n:::\n\n:::cell\n`__getitem__` connects bracket lookup to your internal storage.\n\n```python\nclass Scores:\n def __init__(self):\n self._scores = {"Ada": 98}\n\n def __getitem__(self, name):\n return self._scores[name]\n\nscores = Scores()\nprint(scores["Ada"])\n```\n\n```output\n98\n```\n:::\n\n:::note\n- Implement the narrowest container protocol your object needs.\n- Use `KeyError` and `IndexError` consistently with built-in containers.\n- If a plain `dict` or `list` is enough, prefer it over a custom container.\n:::\n', 'context-managers.md': '+++\nslug = "context-managers"\ntitle = "Context Managers"\nsection = "Data Model"\nsummary = "with ensures setup and cleanup happen together."\ndoc_path = "/reference/datamodel.html#context-managers"\nsee_also = [\n "exceptions",\n "special-methods",\n "descriptors",\n]\n+++\n\nContext managers define setup and cleanup around a block of code. The `with` statement guarantees that cleanup runs when the block exits, even when an exception is raised.\n\nThe protocol is powered by `__enter__` and `__exit__`. The `contextlib.contextmanager` decorator is a concise way to write the same idea as a generator when a full class would be noisy.\n\nProduction code often uses `with` for files, locks, transactions, temporary state, and resources that need reliable release.\n\n:::program\n```python\nfrom contextlib import contextmanager\n\nclass Tag:\n def __init__(self, name):\n self.name = name\n\n def __enter__(self):\n print(f"<{self.name}>")\n return self\n\n def __exit__(self, exc_type, exc, tb):\n print(f"")\n return False\n\n@contextmanager\ndef tag(name):\n print(f"<{name}>")\n try:\n yield\n finally:\n print(f"")\n\nwith Tag("section"):\n print("content")\n\ntry:\n with tag("error"):\n raise ValueError("boom")\nexcept ValueError:\n print("handled")\n```\n:::\n\n:::cell\nA class-based context manager implements `__enter__` and `__exit__`. The value returned by `__enter__` is bound by `as` when the `with` statement uses it.\n\n```python\nclass Tag:\n def __init__(self, name):\n self.name = name\n\n def __enter__(self):\n print(f"<{self.name}>")\n return self\n\n def __exit__(self, exc_type, exc, tb):\n print(f"")\n return False\n\nwith Tag("section"):\n print("content")\n```\n\n```output\n
    \ncontent\n
    \n```\n:::\n\n:::cell\n`contextlib.contextmanager` writes the same setup/cleanup shape as a generator. Code before `yield` is setup, and code after `yield` is cleanup.\n\n```python\nfrom contextlib import contextmanager\n\n@contextmanager\ndef tag(name):\n print(f"<{name}>")\n try:\n yield\n finally:\n print(f"")\n\nwith tag("note"):\n print("body")\n```\n\n```output\n\nbody\n\n```\n:::\n\n:::cell\nCleanup still runs when the block raises. Returning `False` from `__exit__`, or letting a generator context manager re-raise, allows the exception to keep propagating.\n\n```python\ntry:\n with tag("error"):\n raise ValueError("boom")\nexcept ValueError:\n print("handled")\n```\n\n```output\n\n\nhandled\n```\n:::\n\n:::note\n- Files, locks, and temporary state commonly use context managers.\n- `__enter__` and `__exit__` power the protocol.\n- Use `finally` when cleanup must happen after errors too.\n- Returning true from `__exit__` suppresses an exception; do that only intentionally.\n:::\n', 'copying-collections.md': '+++\nslug = "copying-collections"\ntitle = "Copying Collections"\nsection = "Collections"\nsummary = "Copies can duplicate the outer container while nested objects may still be shared."\ndoc_path = "/library/copy.html"\nsee_also = [\n "mutability",\n "lists",\n "dicts",\n]\n+++\n\nCopying answers two different questions: do you need a new outer container, or do you also need independent nested objects? A plain assignment gives another name for the same object. A shallow copy duplicates only the outer container. `copy.deepcopy()` recursively copies contained objects.\n\nMost Python code wants a shallow copy or a deliberate rebuild. Use a deep copy only when shared nested state would be wrong and the objects involved are safe to duplicate.\n\nThe outputs below show the footgun directly: a shallow copy has a different outer list, but its inner lists are still the same objects.\n\n:::program\n```python\nimport copy\n\nrows = [["Ada"], ["Grace"]]\nalias = rows\nshallow = rows.copy()\ndeep = copy.deepcopy(rows)\n\nrows[0].append("Lovelace")\n\nprint(alias is rows)\nprint(shallow is rows)\nprint(rows[0] is shallow[0])\nprint(rows[0] is deep[0])\nprint(shallow)\nprint(deep)\n```\n:::\n\n:::cell\nAssignment does not copy a collection. It gives the same list another name.\n\n```python\nrows = [["Ada"], ["Grace"]]\nalias = rows\n\nprint(alias is rows)\n```\n\n```output\nTrue\n```\n:::\n\n:::cell\nA shallow copy creates a new outer list, but nested lists are still shared.\n\n```python\nshallow = rows.copy()\nrows[0].append("Lovelace")\n\nprint(shallow is rows)\nprint(rows[0] is shallow[0])\nprint(shallow)\n```\n\n```output\nFalse\nTrue\n[[\'Ada\', \'Lovelace\'], [\'Grace\']]\n```\n:::\n\n:::cell\nA deep copy is independent at the nested level, so later mutation of `rows[0]` does not appear in `deep`.\n\n```python\nimport copy\n\nrows = [["Ada"], ["Grace"]]\ndeep = copy.deepcopy(rows)\nrows[0].append("Lovelace")\n\nprint(rows[0] is deep[0])\nprint(deep)\n```\n\n```output\nFalse\n[[\'Ada\'], [\'Grace\']]\n```\n:::\n\n:::note\n- Assignment aliases; it does not copy.\n- Shallow copies duplicate the outer container only.\n- Deep copies are useful for nested independence, but they can be expensive and surprising for objects with external resources.\n:::\n', 'csv-data.md': '+++\nslug = "csv-data"\ntitle = "CSV Data"\nsection = "Standard Library"\nsummary = "csv reads and writes row-shaped text data."\ndoc_path = "/library/csv.html"\nsee_also = [\n "strings",\n "dicts",\n "json",\n]\n+++\n\nCSV is row-shaped text: each line is a record, and each comma-separated field arrives as a string. The `csv` module understands quoting, delimiters, and newlines, so it is safer than splitting lines by comma yourself.\n\nUse `DictReader` when a header row names the columns. Convert fields explicitly after reading, and use `DictWriter` when the program needs to produce the same row shape again.\n\nCSV is a good fit for flat tabular data. Use JSON or another structured format when values are nested or when types need to survive the text boundary.\n\n:::program\n```python\nimport csv\nimport io\n\ntext = "name,score\\nAda,98\\nGrace,95\\n"\nrows = list(csv.DictReader(io.StringIO(text)))\nprint(rows[0])\nprint(sum(int(row["score"]) for row in rows))\n\noutput = io.StringIO(newline="")\nwriter = csv.DictWriter(output, fieldnames=["name", "passed"])\nwriter.writeheader()\nwriter.writerow({"name": "Ada", "passed": True})\nprint(output.getvalue().splitlines()[1])\n```\n:::\n\n:::cell\n`DictReader` uses the header row as dictionary keys. The values are still strings because CSV is text.\n\n```python\nimport csv\nimport io\n\ntext = "name,score\\nAda,98\\nGrace,95\\n"\nrows = list(csv.DictReader(io.StringIO(text)))\n\nprint(rows[0])\nprint(type(rows[0]["score"]).__name__)\n```\n\n```output\n{\'name\': \'Ada\', \'score\': \'98\'}\nstr\n```\n:::\n\n:::cell\nConvert numeric fields at the boundary where the program leaves CSV text and starts doing arithmetic.\n\n```python\nprint(sum(int(row["score"]) for row in rows))\n```\n\n```output\n193\n```\n:::\n\n:::cell\n`DictWriter` turns dictionaries back into row-shaped text with the same column order.\n\n```python\noutput = io.StringIO(newline="")\nwriter = csv.DictWriter(output, fieldnames=["name", "passed"])\nwriter.writeheader()\nwriter.writerow({"name": "Ada", "passed": True})\n\nprint(output.getvalue().splitlines()[1])\n```\n\n```output\nAda,True\n```\n:::\n\n:::note\n- Let `csv` handle quoting and delimiters instead of calling `split(",")`.\n- CSV fields are text until your code converts them.\n- Reach for JSON when records need nested lists, dictionaries, booleans, or numbers that preserve their type.\n:::\n', 'custom-exceptions.md': '+++\nslug = "custom-exceptions"\ntitle = "Custom Exceptions"\nsection = "Errors"\nsummary = "Custom exception classes name failures that belong to your domain."\ndoc_path = "/tutorial/errors.html#user-defined-exceptions"\nsee_also = [\n "exceptions",\n "exception-chaining",\n "warnings",\n "logging",\n]\n+++\n\nCustom exceptions give names to failures in your problem domain. A named exception is easier to catch and explain than a generic error with only a string message.\n\nRaise the custom exception at the point where the invalid state is discovered. Include a message for the specific occurrence.\n\nCatch custom exceptions at the boundary where recovery makes sense, such as returning an error response or asking for corrected input.\n\n:::program\n```python\nclass EmptyCartError(Exception):\n pass\n\nprint(EmptyCartError.__name__)\n\n\ndef checkout(items):\n if not items:\n raise EmptyCartError("cart is empty")\n return "paid"\n\nprint(checkout(["book"]))\n\ntry:\n checkout([])\nexcept EmptyCartError as error:\n print(error)\n```\n:::\n\n:::cell\nCreate a custom exception when a failure has a name in your problem domain. The class can be empty at first.\n\n```python\nclass EmptyCartError(Exception):\n pass\n\nprint(EmptyCartError.__name__)\n```\n\n```output\nEmptyCartError\n```\n:::\n\n:::cell\nRaise the custom exception where the invalid state is detected. Normal inputs still follow the ordinary success path.\n\n```python\ndef checkout(items):\n if not items:\n raise EmptyCartError("cart is empty")\n return "paid"\n\nprint(checkout(["book"]))\n```\n\n```output\npaid\n```\n:::\n\n:::cell\nCallers can catch the precise error type without accidentally catching unrelated failures.\n\n```python\ntry:\n checkout([])\nexcept EmptyCartError as error:\n print(error)\n```\n\n```output\ncart is empty\n```\n:::\n\n:::note\n- Subclass `Exception` for errors callers are expected to catch.\n- A custom exception name can be clearer than reusing a generic `ValueError` everywhere.\n- Catch custom exceptions at a boundary that can recover or report clearly.\n:::\n', 'dataclasses.md': '+++\nslug = "dataclasses"\ntitle = "Dataclasses"\nsection = "Classes"\nsummary = "dataclass generates common class methods for data containers."\ndoc_path = "/library/dataclasses.html"\nsee_also = [\n "structured-data-shapes",\n "classes",\n "type-hints",\n]\nmin_python = "3.13"\nversion_notes = "copy.replace() was added in Python 3.13; dataclasses.replace() is the earlier equivalent."\n+++\n\n`dataclass` is a standard-library decorator for classes that mainly store data. It generates methods such as `__init__` and `__repr__` from type-annotated fields.\n\nDataclasses reduce boilerplate while keeping classes explicit. They are a good fit for simple records, configuration objects, and values passed between layers.\n\nType annotations define fields. Defaults work like normal class attributes and appear in the generated initializer.\n\n:::program\n```python\nimport copy\nfrom dataclasses import dataclass\n\n@dataclass\nclass User:\n name: str\n active: bool = True\n\nuser = User("Ada")\nprint(user)\nprint(user.name)\n\ninactive = User("Guido", active=False)\nprint(inactive)\nprint(inactive.active)\n\npaused = copy.replace(user, active=False)\nprint(paused)\nprint(user)\n```\n:::\n\n:::cell\nA dataclass uses annotations to define fields. Python generates an initializer, so the class can be constructed without writing `__init__` by hand.\n\n```python\nfrom dataclasses import dataclass\n\n@dataclass\nclass User:\n name: str\n active: bool = True\n\nuser = User("Ada")\nprint(user)\n```\n\n```output\nUser(name=\'Ada\', active=True)\n```\n:::\n\n:::cell\nThe generated instance still exposes ordinary attributes. A dataclass is a regular class with useful methods filled in.\n\n```python\nprint(user.name)\n```\n\n```output\nAda\n```\n:::\n\n:::cell\nDefaults can be overridden by keyword. The generated representation includes the field names, which is useful during debugging.\n\n```python\ninactive = User("Guido", active=False)\nprint(inactive)\nprint(inactive.active)\n```\n\n```output\nUser(name=\'Guido\', active=False)\nFalse\n```\n:::\n\n:::cell\n`copy.replace()` builds a new instance with some fields changed and leaves the original alone. It was added in Python 3.13 as the general form of `dataclasses.replace()`, and it also works on named tuples and dates.\n\n```python\nimport copy\n\npaused = copy.replace(user, active=False)\nprint(paused)\nprint(user)\n```\n\n```output\nUser(name=\'Ada\', active=False)\nUser(name=\'Ada\', active=True)\n```\n:::\n\n:::note\n- Type annotations define dataclass fields.\n- `copy.replace(obj, field=value)` copies with changes; before Python 3.13, use `dataclasses.replace()`.\n- Dataclasses generate methods but remain normal Python classes.\n- Use `field()` for advanced defaults such as per-instance lists or dictionaries.\n:::\n', 'datetime.md': '+++\nslug = "datetime"\ntitle = "Dates and Times"\nsection = "Standard Library"\nsummary = "datetime represents dates, times, durations, formatting, and parsing."\ndoc_path = "/library/datetime.html"\nsee_also = [\n "string-formatting",\n "json",\n "number-parsing",\n]\n+++\n\nThe `datetime` module covers several related ideas: `date` for calendar days, `time` for clock times, `datetime` for both together, and `timedelta` for durations.\n\nTimezone-aware datetimes avoid ambiguity in real systems. `timezone.utc` is a clear default for examples because output stays stable and portable.\n\nUse ISO formatting for interchange, `strftime()` for display, and parsing helpers such as `fromisoformat()` to turn text back into datetime objects.\n\n:::program\n```python\nfrom datetime import date, datetime, time, timedelta, timezone\n\nrelease_day = date(2026, 5, 4)\nmeeting_time = time(12, 30)\ncreated_at = datetime.combine(release_day, meeting_time, tzinfo=timezone.utc)\n\nprint(release_day.isoformat())\nprint(meeting_time.isoformat())\nprint(created_at.isoformat())\n\nexpires_at = created_at + timedelta(days=7, hours=2)\nprint(expires_at.isoformat())\n\nprint(created_at.strftime("%Y-%m-%d %H:%M %Z"))\niso_text = "2026-05-04T12:30:00+00:00"\nparsed = datetime.fromisoformat(iso_text)\nprint(parsed == created_at)\n```\n:::\n\n:::cell\nThe `datetime` module separates calendar dates, clock times, combined datetimes, and durations. Import the types you need explicitly.\n\nUse `date` for a calendar day and `time` for a time of day. Combine them into a timezone-aware `datetime` when you mean an instant.\n\n`isoformat()` produces stable machine-readable text. It is a good default for examples, APIs, and logs.\n\n```python\nfrom datetime import date, datetime, time, timedelta, timezone\n\nrelease_day = date(2026, 5, 4)\nmeeting_time = time(12, 30)\ncreated_at = datetime.combine(release_day, meeting_time, tzinfo=timezone.utc)\n\nprint(release_day.isoformat())\nprint(meeting_time.isoformat())\nprint(created_at.isoformat())\n```\n\n```output\n2026-05-04\n12:30:00\n2026-05-04T12:30:00+00:00\n```\n:::\n\n:::cell\nUse `timedelta` for durations. Adding one to a `datetime` produces another `datetime` without manually changing calendar fields.\n\n```python\nexpires_at = created_at + timedelta(days=7, hours=2)\nprint(expires_at.isoformat())\n```\n\n```output\n2026-05-11T14:30:00+00:00\n```\n:::\n\n:::cell\nUse `strftime()` for human-facing formatting and `fromisoformat()` when reading ISO 8601 text back into a `datetime`.\n\n```python\nprint(created_at.strftime("%Y-%m-%d %H:%M %Z"))\niso_text = "2026-05-04T12:30:00+00:00"\nparsed = datetime.fromisoformat(iso_text)\nprint(parsed == created_at)\n```\n\n```output\n2026-05-04 12:30 UTC\nTrue\n```\n:::\n\n:::note\n- Use timezone-aware datetimes for instants that cross system or user boundaries.\n- Use `date` for calendar days, `time` for clock times, `datetime` for both, and `timedelta` for durations.\n- Prefer ISO 8601 strings for interchange; use `strftime` for human-facing display.\n:::\n', 'decorators.md': '+++\nslug = "decorators"\ntitle = "Decorators"\nsection = "Functions"\nsummary = "Decorators wrap or register functions using @ syntax."\ndoc_path = "/glossary.html#term-decorator"\nsee_also = [\n "closures",\n "functions",\n "callable-types",\n "classmethods-and-staticmethods",\n]\n+++\n\nA decorator is a callable that receives a function and returns a replacement. The `@` syntax applies that transformation at function definition time.\n\nDecorators are common in frameworks because they can register handlers or add behavior while keeping the decorated function focused on the core action.\n\n`@decorator` is shorthand for rebinding a function to the decorator\'s return value. Production wrappers usually use `functools.wraps` so debugging, help text, and framework introspection still see the original function metadata.\n\n:::program\n```python\nfrom functools import wraps\n\n\ndef loud(func):\n @wraps(func)\n def wrapper(name):\n return func(name).upper()\n return wrapper\n\n\ndef greet(name):\n return f"hello {name}"\n\nmanual_greet = loud(greet)\nprint(manual_greet("python"))\n\n@loud\ndef welcome(name):\n """Return a welcome message."""\n return f"welcome {name}"\n\nprint(welcome("workers"))\nprint(welcome.__name__)\nprint(welcome.__doc__)\n```\n:::\n\n:::cell\nA decorator is just a function that takes a function and returns another callable. Applying it manually shows the wrapping step.\n\n```python\nfrom functools import wraps\n\n\ndef loud(func):\n @wraps(func)\n def wrapper(name):\n return func(name).upper()\n return wrapper\n\n\ndef greet(name):\n return f"hello {name}"\n\nmanual_greet = loud(greet)\nprint(manual_greet("python"))\n```\n\n```output\nHELLO PYTHON\n```\n:::\n\n:::cell\nThe `@loud` syntax performs the same rebinding at definition time. After decoration, `welcome` refers to the wrapper returned by `loud`.\n\n```python\n@loud\ndef welcome(name):\n """Return a welcome message."""\n return f"welcome {name}"\n\nprint(welcome("workers"))\n```\n\n```output\nWELCOME WORKERS\n```\n:::\n\n:::cell\n`functools.wraps` copies useful metadata from the original function onto the wrapper.\n\n```python\nprint(welcome.__name__)\nprint(welcome.__doc__)\n```\n\n```output\nwelcome\nReturn a welcome message.\n```\n:::\n\n:::note\n- `@decorator` is shorthand for assigning `func = decorator(func)`.\n- Decorators can wrap, replace, or register functions.\n- Use `functools.wraps` in production wrappers that should preserve metadata.\n:::\n', 'delete-statements.md': '+++\nslug = "delete-statements"\ntitle = "Delete Statements"\nsection = "Data Model"\nsummary = "del removes bindings, items, and attributes rather than producing a value."\ndoc_path = "/reference/simple_stmts.html#the-del-statement"\nsee_also = [\n "variables",\n "dicts",\n "mutability",\n]\n+++\n\n`del` removes a binding or an item. It is a statement, not a function, and it does not return the removed value.\n\nUse `del name` when a name should no longer be bound. Use `del mapping[key]` or `del sequence[index]` when mutating a container by removing one part.\n\nThis is different from assigning `None`: `None` is still a value, while `del` removes the binding or slot.\n\n:::program\n```python\nprofile = {"name": "Ada", "temporary": True}\ndel profile["temporary"]\nprint(profile)\n\nitems = ["a", "b", "c"]\ndel items[1]\nprint(items)\n\nvalue = "cached"\ndel value\nprint("value" in locals())\n```\n:::\n\n:::cell\nDeleting a dictionary key mutates the dictionary. The key is gone; it has not been set to `None`.\n\n```python\nprofile = {"name": "Ada", "temporary": True}\ndel profile["temporary"]\nprint(profile)\n```\n\n```output\n{\'name\': \'Ada\'}\n```\n:::\n\n:::cell\nDeleting a list item removes that position and shifts later items left.\n\n```python\nitems = ["a", "b", "c"]\ndel items[1]\nprint(items)\n```\n\n```output\n[\'a\', \'c\']\n```\n:::\n\n:::cell\nDeleting a name removes the binding from the current namespace. It is different from rebinding the name to `None`.\n\n```python\nvalue = "cached"\ndel value\nprint("value" in locals())\n```\n\n```output\nFalse\n```\n:::\n\n:::note\n- `del` removes bindings or container entries.\n- Assign `None` when absence should remain an explicit value.\n- Use container methods such as `pop()` when you need the removed value back.\n:::\n', 'descriptors.md': '+++\nslug = "descriptors"\ntitle = "Descriptors"\nsection = "Data Model"\nsummary = "Descriptors customize attribute access through __get__, __set__, or __delete__."\ndoc_path = "/howto/descriptor.html"\nsee_also = [\n "attribute-access",\n "properties",\n "bound-and-unbound-methods",\n]\n+++\n\nA descriptor is an object stored on a class that defines `__get__`, `__set__`, or `__delete__`. When an instance attribute lookup finds that object on the class, Python calls the descriptor method instead of returning the descriptor object directly.\n\nDescriptors are the machinery behind methods, `property`, validators, and many ORM fields. Use them when one reusable object should control access for many attributes or classes; use `property` for a single simple managed attribute.\n\nThis example implements a positive-number validator. `__set_name__` learns the attribute name when the owner class is created, `__set__` validates writes, and `__get__` reads the stored value back from the instance.\n\n:::program\n```python\nclass Positive:\n def __set_name__(self, owner, name):\n self.private_name = "_" + name\n\n def __get__(self, obj, owner):\n if obj is None:\n return self\n return getattr(obj, self.private_name)\n\n def __set__(self, obj, value):\n if value <= 0:\n raise ValueError("must be positive")\n setattr(obj, self.private_name, value)\n\nclass Product:\n price = Positive()\n\n def __init__(self, price):\n self.price = price\n\nitem = Product(10)\nprint(item.price)\nprint(Product.price.private_name)\ntry:\n item.price = -1\nexcept ValueError as error:\n print(error)\n```\n:::\n\n:::cell\nA descriptor object lives on the class. `__set_name__` lets it learn which managed attribute it is serving.\n\n```python\nclass Positive:\n def __set_name__(self, owner, name):\n self.private_name = "_" + name\n\n def __get__(self, obj, owner):\n if obj is None:\n return self\n return getattr(obj, self.private_name)\n\n def __set__(self, obj, value):\n if value <= 0:\n raise ValueError("must be positive")\n setattr(obj, self.private_name, value)\n\nclass Product:\n price = Positive()\n\nprint(Product.price.private_name)\n```\n\n```output\n_price\n```\n:::\n\n:::cell\nAssigning `item.price` calls `Positive.__set__`, and reading it calls `Positive.__get__`.\n\n```python\nclass Product:\n price = Positive()\n\n def __init__(self, price):\n self.price = price\n\nitem = Product(10)\nprint(item.price)\ntry:\n item.price = -1\nexcept ValueError as error:\n print(error)\n```\n\n```output\n10\nmust be positive\n```\n:::\n\n:::note\n- Descriptors are class attributes that participate in instance attribute access.\n- Data descriptors with `__set__` can validate or transform assignments.\n- `property` is usually simpler for one-off managed attributes; descriptors shine when the behavior is reusable.\n:::\n', 'dicts.md': '+++\nslug = "dicts"\ntitle = "Dictionaries"\nsection = "Collections"\nsummary = "Dictionaries map keys to values for records, lookup, and structured data."\ndoc_path = "/tutorial/datastructures.html#dictionaries"\nsee_also = [\n "lists",\n "sets",\n "typed-dicts",\n "json",\n]\n+++\n\nDictionaries are Python\'s built-in mapping type. They exist for data where names or keys are more meaningful than numeric positions: records, lookup tables, counters, and JSON-like payloads.\n\nUse direct indexing when a key is required. Use `get()` when absence is expected and the code has a reasonable fallback.\n\nUnlike lists, dictionaries answer “what value belongs to this key?” rather than “what value is at this position?” Iterating with `items()` keeps each key next to its value.\n\n:::program\n```python\nprofile = {"name": "Ada", "language": "Python"}\nprofile["year"] = 1843\nprint(profile["name"])\nprint(profile.get("timezone", "UTC"))\n\nscores = {"Ada": 10, "Grace": 9}\nprint(scores["Grace"])\nprint(scores.get("Guido", 0))\n\nfor name, score in scores.items():\n print(f"{name}: {score}")\n\ninventory = {"apple": 0, "pear": 3, "plum": 0}\nfor name in list(inventory.keys()):\n if inventory[name] == 0:\n del inventory[name]\nprint(inventory)\n```\n:::\n\n:::cell\nUse a dictionary as a small record when fields have names. Direct indexing communicates that the key is required, while `get()` communicates that a missing key has a fallback.\n\n```python\nprofile = {"name": "Ada", "language": "Python"}\nprofile["year"] = 1843\nprint(profile["name"])\nprint(profile.get("timezone", "UTC"))\n```\n\n```output\nAda\nUTC\n```\n:::\n\n:::cell\nUse a dictionary as a lookup table when keys identify values. This is different from a list, where numeric position is the lookup key.\n\n```python\nscores = {"Ada": 10, "Grace": 9}\nprint(scores["Grace"])\nprint(scores.get("Guido", 0))\n```\n\n```output\n9\n0\n```\n:::\n\n:::cell\nUse `items()` when the loop needs both keys and values. It avoids looping over keys and then indexing back into the dictionary.\n\n```python\nfor name, score in scores.items():\n print(f"{name}: {score}")\n```\n\n```output\nAda: 10\nGrace: 9\n```\n:::\n\n:::cell\nAdding or removing keys while iterating a dictionary raises `RuntimeError` ("dictionary changed size during iteration"); reassigning an existing key\'s value is allowed. Snapshot the keys with `list(d.keys())` (or build a list of changes and apply them after the loop) so deletions see a stable view.\n\n```python\ninventory = {"apple": 0, "pear": 3, "plum": 0}\nfor name in list(inventory.keys()):\n if inventory[name] == 0:\n del inventory[name]\nprint(inventory)\n```\n\n```output\n{\'pear\': 3}\n```\n:::\n\n:::note\n- Dictionaries preserve insertion order in modern Python.\n- Use `get()` when a missing key has a reasonable default.\n- Use direct indexing when a missing key should be treated as an error.\n- Snapshot keys with `list(d.keys())` before deleting items in a loop; adding or removing keys during iteration raises `RuntimeError`.\n:::\n', 'enums.md': '+++\nslug = "enums"\ntitle = "Enums"\nsection = "Types"\nsummary = "Enum defines symbolic names for a fixed set of values."\ndoc_path = "/library/enum.html"\nsee_also = [\n "literals",\n "classes",\n "literal-and-final",\n]\n+++\n\n`Enum` defines a fixed set of named values. This makes states and modes easier to read than raw strings scattered through a program.\n\nEach enum member has a name and a value. Comparing enum members is explicit and helps avoid typos that plain strings would allow.\n\nUse enums when a value must be one of a small known set: statuses, modes, directions, roles, and similar choices.\n\n:::program\n```python\nfrom enum import Enum\n\nclass Status(Enum):\n PENDING = "pending"\n DONE = "done"\n\ncurrent = Status.PENDING\nprint(current.name)\nprint(current.value)\nprint(current is Status.PENDING)\nprint(current == "pending")\n```\n:::\n\n:::cell\nAn enum member has a symbolic name and an underlying value. The symbolic name is what readers usually care about in code.\n\n```python\nfrom enum import Enum\n\nclass Status(Enum):\n PENDING = "pending"\n DONE = "done"\n\ncurrent = Status.PENDING\nprint(current.name)\nprint(current.value)\n```\n\n```output\nPENDING\npending\n```\n:::\n\n:::cell\nCompare enum members with enum members, not with raw strings. This keeps the set of valid states explicit.\n\n```python\nprint(current is Status.PENDING)\nprint(current == "pending")\n```\n\n```output\nTrue\nFalse\n```\n:::\n\n:::note\n- Enums make states and choices explicit.\n- Members have names and values.\n- Comparing enum members avoids string typo bugs.\n- Prefer raw strings for open-ended text; prefer enums for a closed set of named choices.\n:::\n', 'equality-and-identity.md': '+++\nslug = "equality-and-identity"\ntitle = "Equality and Identity"\nsection = "Data Model"\nsummary = "== compares values, while is compares object identity."\ndoc_path = "/reference/expressions.html#is-not"\nsee_also = [\n "none",\n "values",\n "object-lifecycle",\n "mutability",\n]\n+++\n\nPython separates equality from identity. Equality asks whether two objects should be considered the same value, while identity asks whether two names point to the same object.\n\nThis distinction matters for mutable containers because two equal lists can still be independent objects. Mutating one should not imply mutating the other unless they share identity.\n\nThe `is` operator is best reserved for identity checks against singletons such as `None`. For ordinary values, `==` is the comparison readers expect.\n\n:::program\n```python\nleft = [1, 2, 3]\nright = [1, 2, 3]\nprint(left == right)\nprint(left is right)\n\nsame = left\nsame.append(4)\nprint(left)\nprint(same is left)\n\nvalue = None\nprint(value is None)\n\nsmall_a = 100\nsmall_b = 100\nprint(small_a is small_b)\n\nbig_a = int("1000")\nbig_b = int("1000")\nprint(big_a is big_b)\nprint(big_a == big_b)\n```\n:::\n\n:::cell\nEqual containers can be different objects. `==` compares list contents, while `is` checks whether both names refer to the same list object.\n\n```python\nleft = [1, 2, 3]\nright = [1, 2, 3]\nprint(left == right)\nprint(left is right)\n```\n\n```output\nTrue\nFalse\n```\n:::\n\n:::cell\nIdentity matters when objects are mutable. `same` is another name for `left`, so mutating through one name changes the object seen through the other.\n\n```python\nsame = left\nsame.append(4)\nprint(left)\nprint(same is left)\n```\n\n```output\n[1, 2, 3, 4]\nTrue\n```\n:::\n\n:::cell\nUse `is` for singleton identity checks such as `None`. This asks whether the value is the one special `None` object.\n\n```python\nvalue = None\nprint(value is None)\n```\n\n```output\nTrue\n```\n:::\n\n:::cell\n`is` for integers is unreliable because CPython caches small integers (roughly `-5` to `256`) but not larger ones. Two equal large integers can be different objects. Use `==` for value comparisons; reserve `is` for singletons.\n\n```python\nsmall_a = 100\nsmall_b = 100\nprint(small_a is small_b)\n\nbig_a = int("1000")\nbig_b = int("1000")\nprint(big_a is big_b)\nprint(big_a == big_b)\n```\n\n```output\nTrue\nFalse\nTrue\n```\n:::\n\n:::note\n- Use `==` for ordinary value comparisons.\n- Use `is` primarily for identity checks against singletons such as `None`.\n- Equal mutable containers can still be independent objects.\n- Never use `is` to compare numbers; CPython\'s small-integer cache makes the result an implementation detail.\n:::\n', 'exception-chaining.md': '+++\nslug = "exception-chaining"\ntitle = "Exception Chaining"\nsection = "Errors"\nsummary = "raise from preserves the original cause when translating exceptions."\ndoc_path = "/tutorial/errors.html#exception-chaining"\nsee_also = [\n "exceptions",\n "custom-exceptions",\n "assertions",\n]\n+++\n\nException chaining connects a higher-level error to the lower-level exception that caused it. The syntax is `raise NewError(...) from error`.\n\nUse chaining when translating implementation details into a domain-specific error while preserving the original cause for debugging.\n\nThis is different from hiding the original exception. The caller can catch the domain error, and tooling can still inspect `__cause__`.\n\n:::program\n```python\nclass ConfigError(Exception):\n pass\n\n\ndef read_port(text):\n try:\n return int(text)\n except ValueError as error:\n raise ConfigError("port must be a number") from error\n\nprint(ConfigError.__name__)\n\ntry:\n read_port("abc")\nexcept ConfigError as error:\n print(error)\n print(type(error.__cause__).__name__)\n```\n:::\n\n:::cell\nCatch the low-level exception where it happens, then raise a domain-specific exception from it.\n\n```python\nclass ConfigError(Exception):\n pass\n\n\ndef read_port(text):\n try:\n return int(text)\n except ValueError as error:\n raise ConfigError("port must be a number") from error\n\nprint(ConfigError.__name__)\n```\n\n```output\nConfigError\n```\n:::\n\n:::cell\nThe caller handles the domain error. The original `ValueError` remains available as `__cause__`.\n\n```python\ntry:\n read_port("abc")\nexcept ConfigError as error:\n print(error)\n print(type(error.__cause__).__name__)\n```\n\n```output\nport must be a number\nValueError\n```\n:::\n\n:::note\n- Use `raise ... from error` when translating exceptions across a boundary.\n- The new exception\'s `__cause__` points to the original exception.\n- Chaining keeps user-facing errors clear without losing debugging context.\n:::\n', 'exception-groups.md': '+++\nslug = "exception-groups"\ntitle = "Exception Groups"\nsection = "Errors"\nsummary = "except* handles matching exceptions inside an ExceptionGroup."\ndoc_path = "/tutorial/errors.html#raising-and-handling-multiple-unrelated-exceptions"\nsee_also = [\n "exceptions",\n "exception-chaining",\n "async-await",\n]\n+++\n\n`ExceptionGroup` represents several unrelated exceptions raised together. `except*` exists for code that may receive multiple failures at once, especially concurrent work.\n\nUse ordinary `except` for one exception. Use `except*` only when the value being handled is an exception group and each matching subgroup needs its own handling.\n\nEach `except*` clause receives a smaller exception group containing the matching exceptions.\n\n:::program\n```python\nerrors = ExceptionGroup(\n "batch failed",\n [ValueError("bad port"), TypeError("bad mode")],\n)\nprint(len(errors.exceptions))\n\ntry:\n raise errors\nexcept* ValueError as group:\n print(type(group).__name__)\n print(group.exceptions[0])\nexcept* TypeError as group:\n print(group.exceptions[0])\n```\n:::\n\n:::cell\nAn exception group bundles several exception objects. This is different from an ordinary exception because more than one failure is present.\n\n```python\nerrors = ExceptionGroup(\n "batch failed",\n [ValueError("bad port"), TypeError("bad mode")],\n)\nprint(len(errors.exceptions))\n```\n\n```output\n2\n```\n:::\n\n:::cell\n`except*` handles matching members of the group. The `ValueError` handler sees the value error, and the `TypeError` handler sees the type error.\n\n```python\ntry:\n raise errors\nexcept* ValueError as group:\n print(type(group).__name__)\n print(group.exceptions[0])\nexcept* TypeError as group:\n print(group.exceptions[0])\n```\n\n```output\nExceptionGroup\nbad port\nbad mode\n```\n:::\n\n:::note\n- `except*` is for `ExceptionGroup`, not ordinary single exceptions.\n- Each `except*` clause handles matching members of the group.\n- Exception groups often appear around concurrent work.\n:::\n', 'exceptions.md': '+++\nslug = "exceptions"\ntitle = "Exceptions"\nsection = "Errors"\nsummary = "Use try, except, else, and finally to separate success, recovery, and cleanup."\ndoc_path = "/tutorial/errors.html"\nsee_also = [\n "conditionals",\n "guard-clauses",\n "custom-exceptions",\n "warnings",\n]\n+++\n\nExceptions represent errors or unusual conditions that interrupt normal control flow. `try` marks the operation that may fail, and `except` handles a specific failure where recovery makes sense.\n\nKeep the successful path separate from the recovery path. `else` runs only when no exception was raised, while `finally` runs either way for cleanup or bookkeeping.\n\nUse exceptions when an operation cannot produce a valid result. Prefer ordinary conditionals for expected branches that are not errors.\n\nCatch specific exceptions whenever possible. A broad catch can hide programming mistakes, while a targeted `ValueError` handler documents exactly what failure is expected.\n\n:::program\n```python\ndef parse_int(text):\n return int(text)\n\nfor text in ["42", "python"]:\n try:\n number = parse_int(text)\n except ValueError:\n print(f"{text}: invalid")\n else:\n print(f"{text}: {number}")\n finally:\n print(f"checked {text}")\n\n\ndef safe_parse_broken(text):\n try:\n return int(text)\n except Exception:\n return None\n\ndef safe_parse_fixed(text):\n try:\n return int(text)\n except ValueError:\n return None\n\nprint(safe_parse_broken("42"))\nprint(safe_parse_fixed("42"))\nprint(safe_parse_broken(["4", "2"]))\n\ntry:\n safe_parse_fixed(["4", "2"])\nexcept TypeError as error:\n print(type(error).__name__)\n```\n:::\n\n:::cell\nWhen no exception is raised, the `else` block runs. Keeping success in `else` makes the `try` block contain only the operation that might fail.\n\n```python\ndef parse_int(text):\n return int(text)\n\ntext = "42"\ntry:\n number = parse_int(text)\nexcept ValueError:\n print(f"{text}: invalid")\nelse:\n print(f"{text}: {number}")\nfinally:\n print(f"checked {text}")\n```\n\n```output\n42: 42\nchecked 42\n```\n:::\n\n:::cell\nWhen parsing fails, `int()` raises `ValueError`. Catching that specific exception makes the expected recovery path explicit.\n\n```python\ntext = "python"\ntry:\n number = parse_int(text)\nexcept ValueError:\n print(f"{text}: invalid")\nelse:\n print(f"{text}: {number}")\nfinally:\n print(f"checked {text}")\n```\n\n```output\npython: invalid\nchecked python\n```\n:::\n\n:::cell\nBare `except:` and broad `except Exception:` swallow far more than the failure you meant to handle, including `KeyboardInterrupt` (bare) and most programming bugs (broad). The two functions look interchangeable on good input — the divergence appears on a buggy call: passing a list is a programming error, yet the broad version converts it into a quiet `None` while the specific version lets the `TypeError` surface.\n\n```python\ndef safe_parse_broken(text):\n try:\n return int(text)\n except Exception:\n return None\n\ndef safe_parse_fixed(text):\n try:\n return int(text)\n except ValueError:\n return None\n\nprint(safe_parse_broken("42"))\nprint(safe_parse_fixed("42"))\nprint(safe_parse_broken(["4", "2"]))\n\ntry:\n safe_parse_fixed(["4", "2"])\nexcept TypeError as error:\n print(type(error).__name__)\n```\n\n```output\n42\n42\nNone\nTypeError\n```\n:::\n\n:::note\n- Catch the most specific exception you can.\n- `else` is for success code that should run only if the `try` block did not fail.\n- `finally` runs whether the operation succeeded or failed.\n- Avoid bare `except:` and broad `except Exception:` — they hide bugs and absorb signals like `KeyboardInterrupt`.\n:::\n', 'files-and-pathlib.md': '+++\nslug = "files-and-pathlib"\ntitle = "Files and pathlib"\nsection = "Standard Library"\nsummary = "pathlib names files and directories, and open() reads and writes their text."\ndoc_path = "/library/pathlib.html"\nsee_also = [\n "context-managers",\n "exceptions",\n "csv-data",\n "json",\n]\n+++\n\nA `Path` object names a place in the file system. It does not open anything by itself: it knows how to join names with `/`, take a path apart, and ask the file system questions such as whether the file exists.\n\nReading and writing are separate steps. `Path.read_text()` and `Path.write_text()` handle a whole small file in one call, while `open()` gives a file object that a `with` block closes for you and that you can loop over line by line.\n\nThis page works inside a temporary directory so it leaves nothing behind. Real programs use the same calls on paths they were given, and should always name the text encoding rather than rely on the platform default.\n\n:::program\n```python\nimport shutil\nimport tempfile\nfrom pathlib import Path\n\nroot = Path(tempfile.mkdtemp())\nnotes = root / "notes.txt"\nprint(notes.name)\nprint(notes.suffix)\nprint(notes.exists())\n\nnotes.write_text("first line\\nsecond line\\n", encoding="utf-8")\nprint(notes.exists())\ntext = notes.read_text(encoding="utf-8")\nprint(text.splitlines())\n\nwith open(notes, "a", encoding="utf-8") as handle:\n handle.write("third line\\n")\n\nwith open(notes, encoding="utf-8") as handle:\n for number, line in enumerate(handle, start=1):\n print(number, line.rstrip())\n\nreports = root / "reports"\nreports.mkdir()\n(reports / "summary.csv").write_text("total\\n3\\n", encoding="utf-8")\nprint(sorted(path.name for path in root.iterdir()))\nprint([path.relative_to(root).as_posix() for path in root.rglob("*.csv")])\nprint(reports.is_dir())\n\nmissing = root / "missing.txt"\ntry:\n missing.read_text(encoding="utf-8")\nexcept FileNotFoundError as error:\n print(type(error).__name__)\n\nshutil.rmtree(root)\nprint(root.exists())\n```\n:::\n\n:::cell\nThe `/` operator joins a directory path and a name into a new `Path`. Building a path touches nothing on disk, so `notes` can be taken apart with `.name` and `.suffix` before any file exists.\n\n```python\nimport shutil\nimport tempfile\nfrom pathlib import Path\n\nroot = Path(tempfile.mkdtemp())\nnotes = root / "notes.txt"\nprint(notes.name)\nprint(notes.suffix)\nprint(notes.exists())\n```\n\n```output\nnotes.txt\n.txt\nFalse\n```\n:::\n\n:::cell\n`write_text()` creates the file, writes the string, and closes it. `read_text()` returns the whole file as one string, which suits small files. Passing `encoding="utf-8"` makes the bytes on disk the same on every machine.\n\n```python\nnotes.write_text("first line\\nsecond line\\n", encoding="utf-8")\nprint(notes.exists())\ntext = notes.read_text(encoding="utf-8")\nprint(text.splitlines())\n```\n\n```output\nTrue\n[\'first line\', \'second line\']\n```\n:::\n\n:::cell\n`open()` returns a file object, and the `with` block closes it even if the body raises. Mode `"a"` appends instead of replacing. A file opened for reading is an iterator of lines, each still ending in its newline, so large files can be processed without loading them whole.\n\n```python\nwith open(notes, "a", encoding="utf-8") as handle:\n handle.write("third line\\n")\n\nwith open(notes, encoding="utf-8") as handle:\n for number, line in enumerate(handle, start=1):\n print(number, line.rstrip())\n```\n\n```output\n1 first line\n2 second line\n3 third line\n```\n:::\n\n:::cell\nDirectories are paths too. `mkdir()` creates one, `iterdir()` lists the entries directly inside a directory, and `rglob()` searches every level below it for names matching a pattern. Listing order is up to the file system, so sort when the order matters.\n\n```python\nreports = root / "reports"\nreports.mkdir()\n(reports / "summary.csv").write_text("total\\n3\\n", encoding="utf-8")\nprint(sorted(path.name for path in root.iterdir()))\nprint([path.relative_to(root).as_posix() for path in root.rglob("*.csv")])\nprint(reports.is_dir())\n```\n\n```output\n[\'notes.txt\', \'reports\']\n[\'reports/summary.csv\']\nTrue\n```\n:::\n\n:::cell\nOpening a file that is not there raises `FileNotFoundError`. Catching it is usually better than checking `exists()` first, because the file can appear or vanish between the check and the read. `shutil.rmtree()` removes the temporary directory and everything in it.\n\n```python\nmissing = root / "missing.txt"\ntry:\n missing.read_text(encoding="utf-8")\nexcept FileNotFoundError as error:\n print(type(error).__name__)\n\nshutil.rmtree(root)\nprint(root.exists())\n```\n\n```output\nFileNotFoundError\nFalse\n```\n:::\n\n:::note\n- A `Path` is a name for a place; building one with `/` does not create or open a file.\n- Pass `encoding="utf-8"` to `open()`, `read_text()`, and `write_text()` so text means the same bytes everywhere.\n- Use `with open(...)` so the file is closed when the block ends, and loop over the file object to read line by line.\n- `iterdir()` lists one directory and `rglob()` searches below it; sort the results when order matters.\n- Catch `FileNotFoundError` at the read instead of trusting an earlier `exists()` check.\n:::\n', 'for-loops.md': '+++\nslug = "for-loops"\ntitle = "For Loops"\nsection = "Control Flow"\nsummary = "for iterates over values produced by an iterable."\ndoc_path = "/tutorial/controlflow.html#for-statements"\nsee_also = [\n "while-loops",\n "iterating-over-iterables",\n "iterators",\n]\n+++\n\nA `for` loop asks an iterable for values and runs the indented block once per value. Python\'s loop is not primarily a numeric counter; it is a consumer of lists, ranges, files, generators, and any object that implements the iterator protocol.\n\nPrefer direct iteration when you need each value. Use `range()` when the numbers themselves are the data, and use `enumerate()` when the position and the value both matter.\n\nThe loop body is the indented block. When the iterable is exhausted, execution continues after the block. The neighboring `while` loop shape is for conditions that must be rechecked manually.\n\n:::program\n```python\nfor name in ["Ada", "Grace", "Guido"]:\n print(name)\n\nfor number in range(3):\n print(number)\n\nfor index, name in enumerate(["Ada", "Grace"], start=1):\n print(index, name)\n```\n:::\n\n:::cell\nDirect iteration keeps the code focused on the values in the collection.\n\n```python\nfor name in ["Ada", "Grace", "Guido"]:\n print(name)\n```\n\n```output\nAda\nGrace\nGuido\n```\n:::\n\n:::cell\n`range(3)` yields `0`, `1`, and `2` lazily. Use it when those integers are the thing being iterated over.\n\n```python\nfor number in range(3):\n print(number)\n```\n\n```output\n0\n1\n2\n```\n:::\n\n:::cell\n`enumerate()` is the usual Python way to keep a counter beside each value without indexing back into the list.\n\n```python\nfor index, name in enumerate(["Ada", "Grace"], start=1):\n print(index, name)\n```\n\n```output\n1 Ada\n2 Grace\n```\n:::\n\n:::note\n- A `for` loop consumes an iterable until it is exhausted.\n- Reach for `while` when the stopping condition must be rechecked manually.\n- `iter()` and `next()` expose the protocol that `for` uses internally.\n:::\n', 'functions.md': '+++\nslug = "functions"\ntitle = "Functions"\nsection = "Functions"\nsummary = "Use def to name reusable behavior and return results."\ndoc_path = "/tutorial/controlflow.html#defining-functions"\nsee_also = [\n "variables",\n "args-and-kwargs",\n "keyword-only-arguments",\n "closures",\n]\n+++\n\nFunctions package behavior behind a name. `def` creates a function object that can accept arguments, compute values, and return a result.\n\nDefault arguments make common calls short, and keyword arguments make call sites easier to read. A function that reaches the end without `return` produces `None`.\n\nUse functions when a calculation has a useful name, when code repeats, or when a piece of behavior should be tested independently.\n\n:::program\n```python\ndef greet(name):\n return f"Hello, {name}."\n\nprint(greet("Python"))\n\n\ndef format_total(amount, currency="USD"):\n return f"{amount} {currency}"\n\nprint(format_total(10))\nprint(format_total(10, currency="EUR"))\n\n\ndef log(message):\n print(f"log: {message}")\n\nresult = log("saved")\nprint(result)\n\n\ndef append_broken(item, items=[]):\n items.append(item)\n return items\n\nprint(append_broken("a"))\nprint(append_broken("b"))\n\n\ndef append_fixed(item, items=None):\n if items is None:\n items = []\n items.append(item)\n return items\n\nprint(append_fixed("a"))\nprint(append_fixed("b"))\n```\n:::\n\n:::cell\n`return` sends a value back to the caller. The caller can print it, store it, or pass it to another function.\n\n```python\ndef greet(name):\n return f"Hello, {name}."\n\nprint(greet("Python"))\n```\n\n```output\nHello, Python.\n```\n:::\n\n:::cell\nDefault arguments provide common values. Keyword arguments make it clear which option is being overridden.\n\n```python\ndef format_total(amount, currency="USD"):\n return f"{amount} {currency}"\n\nprint(format_total(10))\nprint(format_total(10, currency="EUR"))\n```\n\n```output\n10 USD\n10 EUR\n```\n:::\n\n:::cell\nA function without an explicit `return` returns `None`. That makes side-effect-only functions easy to distinguish from value-producing ones.\n\n```python\ndef log(message):\n print(f"log: {message}")\n\nresult = log("saved")\nprint(result)\n```\n\n```output\nlog: saved\nNone\n```\n:::\n\n:::cell\nMutable default arguments are evaluated once when the function is defined, not on each call. The same list is shared across calls, so successive calls see each other\'s mutations. Use `None` as the sentinel and create a fresh container inside the body.\n\n```python\ndef append_broken(item, items=[]):\n items.append(item)\n return items\n\nprint(append_broken("a"))\nprint(append_broken("b"))\n\n\ndef append_fixed(item, items=None):\n if items is None:\n items = []\n items.append(item)\n return items\n\nprint(append_fixed("a"))\nprint(append_fixed("b"))\n```\n\n```output\n[\'a\']\n[\'a\', \'b\']\n[\'a\']\n[\'b\']\n```\n:::\n\n:::note\n- Use `return` for values the caller should receive.\n- Defaults keep common calls concise.\n- Keyword arguments make options readable at the call site.\n- Never use a mutable value as a default argument; use `None` and build the container inside the function body.\n:::\n', 'generator-expressions.md': '+++\nslug = "generator-expressions"\ntitle = "Generator Expressions"\nsection = "Iteration"\nsummary = "Generator expressions use comprehension-like syntax to stream values lazily."\ndoc_path = "/tutorial/classes.html#generator-expressions"\nsee_also = [\n "comprehensions",\n "generators",\n "itertools",\n "yield-from",\n]\n+++\n\nGenerator expressions look like list comprehensions with parentheses, but they produce an iterator instead of building a concrete collection immediately.\n\nUse them when a consumer such as `sum()`, `any()`, or a `for` loop can use values one at a time. This keeps the transformation close to the consumer and avoids storing intermediate lists.\n\nLike other iterators, a generator expression is consumed as values are requested. Create a new generator expression when you need another pass.\n\n:::program\n```python\nnumbers = [1, 2, 3, 4]\nlist_squares = [number * number for number in numbers]\nprint(list_squares)\n\nstream_squares = (number * number for number in numbers)\nprint(next(stream_squares))\nprint(next(stream_squares))\nprint(list(stream_squares))\n\nprint(sum(number * number for number in numbers))\n```\n:::\n\n:::cell\nA list comprehension is eager: it builds a list immediately. That is useful when you need to store or reuse the results.\n\n```python\nnumbers = [1, 2, 3, 4]\nlist_squares = [number * number for number in numbers]\nprint(list_squares)\n```\n\n```output\n[1, 4, 9, 16]\n```\n:::\n\n:::cell\nA generator expression is lazy: it creates an iterator that produces values as they are consumed. After two `next()` calls, only the remaining squares are left.\n\n```python\nstream_squares = (number * number for number in numbers)\nprint(next(stream_squares))\nprint(next(stream_squares))\nprint(list(stream_squares))\n```\n\n```output\n1\n4\n[9, 16]\n```\n:::\n\n:::cell\nGenerator expressions are common inside reducing functions. When a generator expression is the only argument, the extra parentheses can be omitted.\n\n```python\nprint(sum(number * number for number in numbers))\n```\n\n```output\n30\n```\n:::\n\n:::note\n- List, dict, and set comprehensions build concrete collections.\n- Generator expressions produce one-pass iterators.\n- Use generator expressions when the consumer can process values one at a time.\n:::\n', 'generators.md': '+++\nslug = "generators"\ntitle = "Generators"\nsection = "Iteration"\nsummary = "yield creates an iterator that produces values on demand."\ndoc_path = "/tutorial/classes.html#generators"\nsee_also = [\n "iterators",\n "iterator-vs-iterable",\n "generator-expressions",\n]\n+++\n\nA generator function is a convenient way to write your own iterator. `yield` produces one value, pauses the function, and resumes when the next value is requested.\n\nGenerators are useful for pipelines, large inputs, and infinite sequences because they avoid building an entire collection in memory.\n\nUse `next()` to request one value manually, or loop over the generator to consume values until it is exhausted.\n\n:::program\n```python\ndef countdown(n):\n while n > 0:\n yield n\n n -= 1\n\nnumbers = countdown(3)\nprint(next(numbers))\nprint(next(numbers))\n\nfor value in countdown(3):\n print(value)\n\ndef countdown_eager(n):\n result = []\n while n > 0:\n result.append(n)\n n -= 1\n return result\n\nvalues = countdown_eager(3)\nprint(values)\nprint(values)\n\nstream = countdown(3)\nprint(list(stream))\nprint(list(stream))\n\nclass Countdown:\n def __init__(self, n):\n self.n = n\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.n <= 0:\n raise StopIteration\n value = self.n\n self.n -= 1\n return value\n\nprint(list(Countdown(3)))\n```\n:::\n\n:::cell\nCalling a generator function returns an iterator. `next()` asks for one value and resumes the function until the next `yield`.\n\n```python\ndef countdown(n):\n while n > 0:\n yield n\n n -= 1\n\nnumbers = countdown(3)\nprint(next(numbers))\nprint(next(numbers))\n```\n\n```output\n3\n2\n```\n:::\n\n:::cell\nA `for` loop repeatedly calls `next()` for you. The loop stops when the generator is exhausted.\n\n```python\nfor value in countdown(3):\n print(value)\n```\n\n```output\n3\n2\n1\n```\n:::\n\n:::cell\n`return` builds the entire result before handing it back; `yield` produces values on demand. The list keeps its values for repeated use, while the generator is exhausted after one pass.\n\n```python\ndef countdown_eager(n):\n result = []\n while n > 0:\n result.append(n)\n n -= 1\n return result\n\nvalues = countdown_eager(3)\nprint(values)\nprint(values)\n\nstream = countdown(3)\nprint(list(stream))\nprint(list(stream))\n```\n\n```output\n[3, 2, 1]\n[3, 2, 1]\n[3, 2, 1]\n[]\n```\n:::\n\n:::cell\nEvery generator is an iterator. The same countdown written by hand is a [class](/examples/classes) that needs `__iter__` and `__next__` and an explicit `StopIteration`. The generator function expresses the same protocol with one `yield`.\n\n```python\nclass Countdown:\n def __init__(self, n):\n self.n = n\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.n <= 0:\n raise StopIteration\n value = self.n\n self.n -= 1\n return value\n\nprint(list(Countdown(3)))\n```\n\n```output\n[3, 2, 1]\n```\n:::\n\n:::note\n- Generator functions are a concise way to create custom iterators; every generator is an iterator.\n- `yield` defers work and streams values; `return` produces the whole result up front.\n- A generator is consumed as you iterate over it.\n- Prefer a list when you need to reuse stored results; prefer a generator when values can be streamed once.\n:::\n', 'generics-and-typevar.md': '+++\nslug = "generics-and-typevar"\ntitle = "Generics and TypeVar"\nsection = "Types"\nsummary = "Generics preserve type information across reusable functions and classes."\ndoc_path = "/library/typing.html#generics"\nsee_also = [\n "type-hints",\n "collections-module",\n "casts-and-any",\n]\nmin_python = "3.13"\nversion_notes = "Type parameter syntax needs Python 3.12; type parameter defaults and __default__ need Python 3.13."\n+++\n\nGenerics connect types across an API. A plain function that returns `object` loses information; a generic function can say that the returned value has the same type as the input element.\n\nA type parameter stands for a type chosen by the caller. In `def first[T](items: list[T]) -> T`, the brackets after the function name declare `T`, and the same `T` says that a list of strings produces a string and a list of integers produces an integer.\n\nUse generics when a function or class is reusable but still preserves a relationship between input and output types. Older code declares the same variable with `typing.TypeVar`; both spellings mean the same thing to a type checker.\n\n:::program\n```python\nfrom typing import TypeVar\n\n\ndef first[T](items: list[T]) -> T:\n return items[0]\n\n\ndef pair[T](left: T, right: T) -> tuple[T, T]:\n return (left, right)\n\n\nclass Box[T]:\n def __init__(self, item: T) -> None:\n self.item = item\n\n def get(self) -> T:\n return self.item\n\n\nclass Setting[T = str]:\n def __init__(self, value: T) -> None:\n self.value = value\n\n\nItem = TypeVar("Item")\n\n\ndef last(items: list[Item]) -> Item:\n return items[-1]\n\nprint(first([1, 2, 3]))\nprint(first(["Ada", "Grace"]))\nprint(pair("x", "y"))\nprint(Box(3).get())\nprint(Box.__type_params__)\nprint(Setting.__type_params__[0].__default__)\nprint(last([1, 2, 3]))\nprint(first.__annotations__)\nprint(last.__annotations__)\n```\n:::\n\n:::cell\nSquare brackets after the function name declare a type parameter. `T` stands for a type chosen by the caller, so the return type follows the list element type.\n\n```python\ndef first[T](items: list[T]) -> T:\n return items[0]\n\nprint(first([1, 2, 3]))\nprint(first(["Ada", "Grace"]))\n```\n\n```output\n1\nAda\n```\n:::\n\n:::cell\nReusing the same type parameter expresses a relationship between parameters and results. Each function declares its own `T`; the name is scoped to that definition.\n\n```python\ndef pair[T](left: T, right: T) -> tuple[T, T]:\n return (left, right)\n\nprint(pair("x", "y"))\n```\n\n```output\n(\'x\', \'y\')\n```\n:::\n\n:::cell\nA class takes type parameters the same way. `Box[T]` says that whatever type goes in through `__init__` is the type that `get()` hands back. The parameters are recorded on the class, but nothing checks them at runtime.\n\n```python\nclass Box[T]:\n def __init__(self, item: T) -> None:\n self.item = item\n\n def get(self) -> T:\n return self.item\n\nprint(Box(3).get())\nprint(Box.__type_params__)\n```\n\n```output\n3\n(T,)\n```\n:::\n\n:::cell\nPython 3.13 lets a type parameter name a default. A type checker reads a bare `Setting` as `Setting[str]`, while `Setting[int]` still overrides it. The default is stored on the parameter object.\n\n```python\nclass Setting[T = str]:\n def __init__(self, value: T) -> None:\n self.value = value\n\nprint(Setting.__type_params__[0].__default__)\n```\n\n```output\n\n```\n:::\n\n:::cell\nBefore Python 3.12 the variable had to be created separately with `TypeVar` and then used by name. This legacy spelling still works and is common in existing code; the annotations show it as `~Item` rather than a scoped `T`.\n\n```python\nfrom typing import TypeVar\n\nItem = TypeVar("Item")\n\n\ndef last(items: list[Item]) -> Item:\n return items[-1]\n\nprint(last([1, 2, 3]))\nprint(first.__annotations__)\nprint(last.__annotations__)\n```\n\n```output\n3\n{\'items\': list[T], \'return\': T}\n{\'items\': list[~Item], \'return\': ~Item}\n```\n:::\n\n:::note\n- `def first[T](...)` and `class Box[T]` declare type parameters inline; this syntax needs Python 3.12 or later.\n- `[T = str]` gives a type parameter a default; that needs Python 3.13.\n- `T = TypeVar("T")` is the legacy spelling of the same idea and is still what older codebases use.\n- Generic functions avoid losing information to `object` or `Any`.\n- Use generics when input and output types are connected.\n:::\n', 'guard-clauses.md': '+++\nslug = "guard-clauses"\ntitle = "Guard Clauses"\nsection = "Control Flow"\nsummary = "Guard clauses handle boundary cases early so the main path stays flat."\ndoc_path = "/tutorial/controlflow.html#if-statements"\nsee_also = [\n "conditionals",\n "exceptions",\n "functions",\n]\n+++\n\nA guard clause is an early `return`, `raise`, `break`, or `continue` that handles a case the rest of the function should not process. The point is not new syntax; the point is moving boundaries out of the way so the successful path can be read straight through.\n\nUse guards when a function has clear invalid, empty, or already-finished cases. If every branch is equally important, an ordinary `if`/`elif` chain may be clearer.\n\nThe contrast below shows the payoff: the nested version makes the valid path live inside two conditions, while the guard version names the invalid cases first and leaves the calculation at the outer indentation level.\n\n:::program\n```python\ndef nested_discount(price, percent):\n if price >= 0:\n if 0 <= percent <= 100:\n return round(price - price * percent / 100, 2)\n return "invalid discount"\n return "invalid price"\n\n\ndef guarded_discount(price, percent):\n if price < 0:\n return "invalid price"\n if not 0 <= percent <= 100:\n return "invalid discount"\n\n return round(price - price * percent / 100, 2)\n\nprint(nested_discount(100, 15))\nprint(guarded_discount(-5, 10))\nprint(guarded_discount(100, 120))\n```\n:::\n\n:::cell\nThe nested version is correct, but the useful work is buried inside both tests.\n\n```python\ndef nested_discount(price, percent):\n if price >= 0:\n if 0 <= percent <= 100:\n return round(price - price * percent / 100, 2)\n return "invalid discount"\n return "invalid price"\n\nprint(nested_discount(100, 15))\n```\n\n```output\n85.0\n```\n:::\n\n:::cell\nThe guard-clause version handles impossible inputs first, then lets the ordinary calculation sit at the top level of the function body.\n\n```python\ndef guarded_discount(price, percent):\n if price < 0:\n return "invalid price"\n if not 0 <= percent <= 100:\n return "invalid discount"\n\n return round(price - price * percent / 100, 2)\n\nprint(guarded_discount(-5, 10))\nprint(guarded_discount(100, 120))\n```\n\n```output\ninvalid price\ninvalid discount\n```\n:::\n\n:::note\n- Guard clauses are a readability pattern, not a separate Python feature.\n- They work best when the early cases are true boundaries.\n- For exceptional failures, raise an exception instead of returning a sentinel string.\n:::\n', 'hello-world.md': '+++\nslug = "hello-world"\ntitle = "Hello World"\nsection = "Basics"\nsummary = "The first Python program prints a line of text."\ndoc_path = "/tutorial/introduction.html"\nsee_also = [\n "values",\n "variables",\n]\n+++\n\nEvery Python program starts by executing statements from top to bottom. Calling `print()` is the smallest useful program because it shows how Python evaluates an expression and sends text to standard output.\n\nStrings are ordinary values, so the message passed to `print()` can be changed, stored in a variable, or produced by a function. This example keeps the first program intentionally small.\n\nRun the program and compare what you see with the source: the text appears on standard output followed by a newline, which is why successive `print()` calls land on separate lines.\n\n:::program\n```python\nprint("hello world")\n```\n:::\n\n:::cell\nThe whole program is one statement. Python evaluates the string literal `"hello world"` and passes that value to `print()`, which writes it to standard output — the output panel shows exactly that line.\n\n```python\nprint("hello world")\n```\n\n```output\nhello world\n```\n:::\n\n:::note\n- `print()` writes text followed by a newline.\n- Strings can be delimited with single or double quotes.\n:::\n', 'import-aliases.md': '+++\nslug = "import-aliases"\ntitle = "Import Aliases"\nsection = "Modules"\nsummary = "as gives imported modules or names a local alias."\ndoc_path = "/reference/simple_stmts.html#the-import-statement"\nsee_also = [\n "modules",\n "functions",\n]\n+++\n\n`as` gives an imported module or imported name a local alias. Use it when a conventional short name improves readability or when two imports would otherwise collide.\n\nThe alternative is a plain import, which is usually better when the module name is already clear. Avoid aliases that make readers guess where a name came from.\n\nAvoid star imports in examples and production modules because they hide dependencies and blur the boundary between modules.\n\n:::program\n```python\nimport statistics as stats\nfrom math import sqrt as square_root\n\nscores = [8, 10, 9]\nprint(stats.mean(scores))\nprint(stats.__name__)\n\nprint(square_root(81))\nprint(square_root.__name__)\n```\n:::\n\n:::cell\nA module alias keeps the namespace but changes the local name. Here `stats` is shorter, but readers can still see that `mean` belongs to the statistics module.\n\n```python\nimport statistics as stats\n\nscores = [8, 10, 9]\nprint(stats.mean(scores))\nprint(stats.__name__)\n```\n\n```output\n9\nstatistics\n```\n:::\n\n:::cell\nA name imported with `from` can also be aliased. Use this when the local name explains the role better than the original name.\n\n```python\nfrom math import sqrt as square_root\n\nprint(square_root(81))\nprint(square_root.__name__)\n```\n\n```output\n9.0\nsqrt\n```\n:::\n\n:::note\n- `import module as alias` keeps module-style access under a shorter or clearer name.\n- `from module import name as alias` imports one name under a local alias.\n- Prefer plain imports unless an alias improves clarity or follows a strong convention.\n- Avoid `from module import *` because it makes dependencies harder to see.\n:::\n', 'inheritance-and-super.md': '+++\nslug = "inheritance-and-super"\ntitle = "Inheritance and Super"\nsection = "Classes"\nsummary = "Inheritance reuses behavior, and super delegates to a parent implementation."\ndoc_path = "/tutorial/classes.html#inheritance"\nsee_also = [\n "classes",\n "abstract-base-classes",\n "classmethods-and-staticmethods",\n "special-methods",\n]\n+++\n\nInheritance lets one class specialize another class. The child class gets parent behavior and can add or override methods.\n\nUse `super()` when the child method should extend the parent implementation instead of replacing it entirely.\n\nPrefer composition when objects merely collaborate. Inheritance is best when the child really is a specialized version of the parent.\n\n:::program\n```python\nclass Animal:\n def __init__(self, name):\n self.name = name\n\n def speak(self):\n return f"{self.name} makes a sound"\n\nclass Dog(Animal):\n def speak(self):\n base = super().speak()\n return f"{base}; {self.name} barks"\n\npet = Dog("Nina")\nprint(pet.name)\nprint(pet.speak())\nprint(isinstance(pet, Animal))\n```\n:::\n\n:::cell\nA child class names its parent in parentheses. `Dog` instances get the `Animal.__init__` method because `Dog` does not define its own initializer.\n\n```python\nclass Animal:\n def __init__(self, name):\n self.name = name\n\n def speak(self):\n return f"{self.name} makes a sound"\n\nclass Dog(Animal):\n def speak(self):\n base = super().speak()\n return f"{base}; {self.name} barks"\n\npet = Dog("Nina")\nprint(pet.name)\n```\n\n```output\nNina\n```\n:::\n\n:::cell\n`super()` delegates to the parent implementation. The child method can reuse the parent result and then add specialized behavior.\n\n```python\nprint(pet.speak())\nprint(isinstance(pet, Animal))\n```\n\n```output\nNina makes a sound; Nina barks\nTrue\n```\n:::\n\n:::note\n- Inheritance models an “is a specialized kind of” relationship.\n- `super()` calls the next implementation in the method resolution order.\n- Prefer composition when an object only needs to use another object.\n:::\n', 'iterating-over-iterables.md': '+++\nslug = "iterating-over-iterables"\ntitle = "Iterating over Iterables"\nsection = "Iteration"\nsummary = "for loops consume values from any iterable object."\ndoc_path = "/tutorial/controlflow.html#for-statements"\nsee_also = [\n "iterators",\n "iterator-vs-iterable",\n "for-loops",\n]\n+++\n\nPython\'s `for` statement consumes values from any iterable object: lists, strings, dictionaries, ranges, generators, files, and many standard-library helpers.\n\nThis makes iteration a value-stream protocol rather than a special case for arrays. The producer decides how values are made, and the loop consumes them one at a time.\n\nUse `enumerate()` when you need positions and values together, and `dict.items()` when you need keys and values. These helpers express intent better than manual indexing.\n\n:::program\n```python\nnames = ["Ada", "Grace", "Guido"]\n\nfor name in names:\n print(name)\n\nfor index, name in enumerate(names):\n print(index, name)\n\nscores = {"Ada": 10, "Grace": 9}\nfor name, score in scores.items():\n print(name, score)\n```\n:::\n\n:::cell\nStart with an ordinary list. A list stores values, and a `for` loop asks it for one value at a time.\n\nWhen you only need the values, iterate over the collection directly. There is no index variable because the loop body does not need one.\n\n```python\nnames = ["Ada", "Grace", "Guido"]\n\nfor name in names:\n print(name)\n```\n\n```output\nAda\nGrace\nGuido\n```\n:::\n\n:::cell\nWhen you need both a position and a value, use `enumerate()`. It produces index/value pairs without manual indexing.\n\n```python\nfor index, name in enumerate(names):\n print(index, name)\n```\n\n```output\n0 Ada\n1 Grace\n2 Guido\n```\n:::\n\n:::cell\nDictionaries are iterable too, but `dict.items()` is the clearest way to say that the loop needs keys and values together.\n\n```python\nscores = {"Ada": 10, "Grace": 9}\nfor name, score in scores.items():\n print(name, score)\n```\n\n```output\nAda 10\nGrace 9\n```\n:::\n\n:::note\n- A `for` loop consumes values from an iterable.\n- Different producers can feed the same loop protocol.\n- Prefer `enumerate()` over `range(len(...))` when you need an index.\n:::\n', 'iterator-vs-iterable.md': '+++\nslug = "iterator-vs-iterable"\ntitle = "Iterator vs Iterable"\nsection = "Iteration"\nsummary = "Iterables produce fresh iterators; iterators are one-pass."\ndoc_path = "/glossary.html#term-iterable"\nsee_also = [\n "iterators",\n "iterating-over-iterables",\n "generators",\n]\n+++\n\nAn iterable can produce values when asked. An iterator is the object that remembers where the production currently is. The distinction matters because iterables can be traversed many times, while many iterators can be traversed only once.\n\n`iter(iterable)` returns a fresh iterator each call. `iter(iterator)` returns the iterator itself. That self-iteration property is how `for` loops can accept either kind, and it is also why code that loops over its input twice silently breaks when handed an iterator instead of a list.\n\nThe takeaway for API design: receive iterables when the caller may want a second pass, and materialize once at the boundary if you must.\n\n:::program\n```python\nnames = ["Ada", "Grace"]\n\nprint(list(names))\nprint(list(names))\n\nstream = iter(names)\nprint(list(stream))\nprint(list(stream))\n\nfirst = iter(names)\nsecond = iter(names)\nprint(first is second)\nprint(iter(first) is first)\n\nnumbers = [10, 9, 8]\nprint(sum(numbers), len(list(numbers)))\n\nstream = iter([10, 9, 8])\nprint(sum(stream), len(list(stream)))\n\nitems = list(iter([10, 9, 8]))\nprint(sum(items), len(items))\n```\n:::\n\n:::cell\nA list is iterable. Each `for` loop or `list()` call asks the list for a fresh iterator under the hood, so the same data can be traversed many times.\n\n```python\nnames = ["Ada", "Grace"]\nprint(list(names))\nprint(list(names))\n```\n\n```output\n[\'Ada\', \'Grace\']\n[\'Ada\', \'Grace\']\n```\n:::\n\n:::cell\nAn iterator is one-pass. Calling `iter()` returns a position-tracking object; once it has been exhausted, it stays exhausted.\n\n```python\nstream = iter(names)\nprint(list(stream))\nprint(list(stream))\n```\n\n```output\n[\'Ada\', \'Grace\']\n[]\n```\n:::\n\n:::cell\nCalling `iter()` on an iterable returns a brand-new iterator each time. Calling `iter()` on an iterator returns the same object — that is the rule that lets a `for` loop accept either kind.\n\n```python\nfirst = iter(names)\nsecond = iter(names)\nprint(first is second)\nprint(iter(first) is first)\n```\n\n```output\nFalse\nTrue\n```\n:::\n\n:::cell\nThe distinction shows up whenever code makes two passes over the same input. Summing and then counting works for an iterable, but silently produces a wrong answer for an iterator, because the second pass finds the iterator already exhausted. Materialize once with `list()` when both passes matter.\n\n```python\nnumbers = [10, 9, 8]\nprint(sum(numbers), len(list(numbers)))\n\nstream = iter([10, 9, 8])\nprint(sum(stream), len(list(stream)))\n\nitems = list(iter([10, 9, 8]))\nprint(sum(items), len(items))\n```\n\n```output\n27 3\n27 0\n27 3\n```\n:::\n\n:::note\n- An iterable produces an iterator each time `iter()` is called on it; an iterator produces values until it is exhausted.\n- `iter(iterable)` returns a fresh iterator; `iter(iterator)` returns the same iterator.\n- Code that traverses its input more than once must receive an iterable or materialize the input first; this matters most for [functions](/examples/functions) that cannot know what callers will pass.\n:::\n', 'iterators.md': '+++\nslug = "iterators"\ntitle = "Iterators"\nsection = "Iteration"\nsummary = "iter and next expose the protocol behind for loops."\ndoc_path = "/library/stdtypes.html#iterator-types"\nsee_also = [\n "iterating-over-iterables",\n "iterator-vs-iterable",\n "generators",\n]\n+++\n\nAn iterable is an object that can produce values for a loop. An iterator is the object that remembers where that production currently is.\n\n`iter()` asks an iterable for an iterator, and `next()` consumes one value from that iterator. A `for` loop performs those steps for you until the iterator is exhausted.\n\nThis is the core value-stream protocol in Python: one object produces values, another piece of code consumes them, and many streams are one-pass.\n\n:::program\n```python\nnames = ["Ada", "Grace", "Guido"]\niterator = iter(names)\nprint(next(iterator))\nprint(next(iterator))\n\nfor name in iterator:\n print(name)\n\nagain = iter(names)\nprint(next(again))\n```\n:::\n\n:::cell\n`iter()` asks an iterable for an iterator. `next()` consumes one value and advances the iterator\'s position.\n\n```python\nnames = ["Ada", "Grace", "Guido"]\niterator = iter(names)\nprint(next(iterator))\nprint(next(iterator))\n```\n\n```output\nAda\nGrace\n```\n:::\n\n:::cell\nA `for` loop consumes the same iterator protocol. Because two values were already consumed, the loop sees only the remaining value.\n\n```python\nfor name in iterator:\n print(name)\n```\n\n```output\nGuido\n```\n:::\n\n:::cell\nThe list itself is reusable. Asking it for a fresh iterator starts a new pass over the same stored values.\n\n```python\nagain = iter(names)\nprint(next(again))\n```\n\n```output\nAda\n```\n:::\n\n:::note\n- Iterables produce iterators; iterators produce values.\n- `next()` consumes one value from an iterator.\n- Many iterators are one-pass even when the original collection is reusable.\n:::\n', 'itertools.md': '+++\nslug = "itertools"\ntitle = "Itertools"\nsection = "Iteration"\nsummary = "itertools composes lazy iterator streams."\ndoc_path = "/library/itertools.html"\nsee_also = [\n "iterators",\n "generator-expressions",\n "sentinel-iteration",\n "comprehension-patterns",\n]\n+++\n\nThe `itertools` module contains tools for composing iterator streams: combining, slicing, grouping, and repeating values without changing the consumer protocol.\n\nMany `itertools` functions are lazy. They describe work to do later instead of building a list immediately, so helpers such as `islice()` are useful when taking a finite window.\n\nIterator pipelines let each step stay small: one object produces values, another transforms them, and a final consumer such as `list()` or a loop pulls values through the pipeline.\n\n:::program\n```python\nimport itertools\n\ncounter = itertools.count(10)\nprint(list(itertools.islice(counter, 3)))\n\npages = itertools.chain(["intro", "setup"], ["deploy"])\nprint(list(pages))\n\nscores = [7, 10, 8, 10]\nhigh_scores = itertools.compress(scores, [score >= 9 for score in scores])\nprint(list(high_scores))\n```\n:::\n\n:::cell\n`count()` can produce values forever, so `islice()` takes a finite window. Nothing is materialized until `list()` consumes the iterator.\n\n```python\nimport itertools\n\ncounter = itertools.count(10)\nprint(list(itertools.islice(counter, 3)))\n```\n\n```output\n[10, 11, 12]\n```\n:::\n\n:::cell\n`chain()` presents several iterables as one stream. This avoids building an intermediate list just to loop over combined inputs.\n\n```python\npages = itertools.chain(["intro", "setup"], ["deploy"])\nprint(list(pages))\n```\n\n```output\n[\'intro\', \'setup\', \'deploy\']\n```\n:::\n\n:::cell\nIterator helpers compose with ordinary Python expressions. `compress()` keeps items whose corresponding selector is true.\n\n```python\nscores = [7, 10, 8, 10]\nhigh_scores = itertools.compress(scores, [score >= 9 for score in scores])\nprint(list(high_scores))\n```\n\n```output\n[10, 10]\n```\n:::\n\n:::note\n- `itertools` composes producer and transformer streams.\n- Iterator pipelines avoid building intermediate lists.\n- Use `islice()` to take a finite piece from an infinite iterator.\n- Convert to a list only when you need concrete results.\n:::\n', 'json.md': '+++\nslug = "json"\ntitle = "JSON"\nsection = "Standard Library"\nsummary = "json encodes Python values as JSON text and decodes them back."\ndoc_path = "/library/json.html"\nsee_also = [\n "dicts",\n "typed-dicts",\n "strings",\n]\n+++\n\nThe `json` module converts between Python values and JSON text. Dictionaries, lists, strings, numbers, booleans, and `None` map naturally to JSON structures.\n\nUse `dumps()` when you need a string and `loads()` when you need Python objects back. Options such as `sort_keys=True` and `indent=2` control stable, readable output.\n\nJSON is a data format, not a way to preserve arbitrary Python objects. Encode simple data structures at service boundaries, and expect decode errors when the incoming text is not valid JSON.\n\n:::program\n```python\nimport json\n\npayload = {"language": "Python", "versions": [3, 13], "stable": True, "missing": None}\ntext = json.dumps(payload, sort_keys=True)\nprint(text)\n\npretty = json.dumps({"language": "Python", "stable": True}, indent=2, sort_keys=True)\nprint(pretty.splitlines()[0])\nprint(pretty.splitlines()[1])\n\ndecoded = json.loads(text)\nprint(decoded["language"])\nprint(decoded["missing"] is None)\n\ntry:\n json.loads("{bad json}")\nexcept json.JSONDecodeError as error:\n print(error.__class__.__name__)\n```\n:::\n\n:::cell\n`dumps()` encodes Python data as JSON text. `sort_keys=True` keeps dictionary keys in a stable order for reproducible output.\n\n```python\nimport json\n\npayload = {"language": "Python", "versions": [3, 13], "stable": True, "missing": None}\ntext = json.dumps(payload, sort_keys=True)\nprint(text)\n```\n\n```output\n{"language": "Python", "missing": null, "stable": true, "versions": [3, 13]}\n```\n:::\n\n:::cell\nFormatting options change the JSON text, not the Python value. `indent=2` is useful for human-readable output.\n\n```python\npretty = json.dumps({"language": "Python", "stable": True}, indent=2, sort_keys=True)\nprint(pretty.splitlines()[0])\nprint(pretty.splitlines()[1])\n```\n\n```output\n{\n "language": "Python",\n```\n:::\n\n:::cell\n`loads()` decodes JSON text back into Python values. JSON `null` becomes Python `None`.\n\n```python\ndecoded = json.loads(text)\nprint(decoded["language"])\nprint(decoded["missing"] is None)\n```\n\n```output\nPython\nTrue\n```\n:::\n\n:::cell\nInvalid JSON raises `JSONDecodeError`, so input boundaries should handle decode failures explicitly.\n\n```python\ntry:\n json.loads("{bad json}")\nexcept json.JSONDecodeError as error:\n print(error.__class__.__name__)\n```\n\n```output\nJSONDecodeError\n```\n:::\n\n:::note\n- `dumps()` returns a string; `loads()` accepts a string.\n- JSON `true`, `false`, and `null` become Python `True`, `False`, and `None`.\n- Use `sort_keys=True` when stable text output matters.\n- JSON only represents data shapes, not arbitrary Python objects or behavior.\n:::\n', 'keyword-only-arguments.md': '+++\nslug = "keyword-only-arguments"\ntitle = "Keyword-only Arguments"\nsection = "Functions"\nsummary = "Use * to require selected function arguments to be named."\ndoc_path = "/tutorial/controlflow.html#special-parameters"\nsee_also = [\n "functions",\n "args-and-kwargs",\n "positional-only-parameters",\n "partial-functions",\n]\n+++\n\nA bare `*` in a function signature marks the following parameters as keyword-only. Callers must name those arguments explicitly.\n\nKeyword-only arguments are useful for options such as timeouts, flags, and modes where positional calls would be ambiguous or easy to misread.\n\nThey let the required data stay positional while optional controls remain self-documenting at the call site.\n\n:::program\n```python\ndef connect(host, *, timeout=5, secure=True):\n scheme = "https" if secure else "http"\n print(f"{scheme}://{host} timeout={timeout}")\n\nconnect("example.com")\nconnect("example.com", timeout=10)\nconnect("localhost", secure=False)\n\ntry:\n connect("example.com", 10)\nexcept TypeError as error:\n print(type(error).__name__)\n```\n:::\n\n:::cell\nParameters after `*` must be named. The default options still apply when the caller omits them.\n\n```python\ndef connect(host, *, timeout=5, secure=True):\n scheme = "https" if secure else "http"\n print(f"{scheme}://{host} timeout={timeout}")\n\nconnect("example.com")\n```\n\n```output\nhttps://example.com timeout=5\n```\n:::\n\n:::cell\nNaming the option makes the call site explicit. A reader does not have to remember which positional slot controls the timeout.\n\n```python\nconnect("example.com", timeout=10)\n```\n\n```output\nhttps://example.com timeout=10\n```\n:::\n\n:::cell\nFlags are especially good keyword-only arguments because a bare positional `False` is hard to interpret.\n\n```python\nconnect("localhost", secure=False)\n```\n\n```output\nhttp://localhost timeout=5\n```\n:::\n\n:::cell\nThe bare `*` is enforced at the call site: passing the timeout positionally raises `TypeError` instead of silently filling the wrong slot.\n\n```python\ntry:\n connect("example.com", 10)\nexcept TypeError as error:\n print(type(error).__name__)\n```\n\n```output\nTypeError\n```\n:::\n\n:::note\n- Put `*` before options that callers should name.\n- Keyword-only flags avoid mysterious positional `True` and `False` arguments.\n- Defaults work normally for keyword-only parameters.\n:::\n', 'lambdas.md': '+++\nslug = "lambdas"\ntitle = "Lambdas"\nsection = "Functions"\nsummary = "lambda creates small anonymous function expressions."\ndoc_path = "/tutorial/controlflow.html#lambda-expressions"\nsee_also = [\n "functions",\n "sorting",\n "callable-objects",\n]\n+++\n\n`lambda` creates a small anonymous function expression. It is most useful when Python asks for a function and the behavior is short enough to read inline.\n\nA lambda can only contain one expression. Use `def` when the behavior deserves a name, needs statements, or would be easier to test separately.\n\nLambdas often appear as key functions, callbacks, and tiny adapters. Keep them simple enough that the call site remains clearer than a named helper.\n\n:::program\n```python\nadd_tax = lambda price: round(price * 1.08, 2)\nprint(add_tax(10))\n\nitems = [("notebook", 5), ("pen", 2), ("bag", 20)]\nby_price = sorted(items, key=lambda item: item[1])\nprint(by_price)\n\ndef price(item):\n return item[1]\n\nprint(sorted(items, key=price))\n```\n:::\n\n:::cell\nA lambda is a function expression. Assigning one to a name works, although `def` is usually clearer for reusable behavior.\n\n```python\nadd_tax = lambda price: round(price * 1.08, 2)\nprint(add_tax(10))\n```\n\n```output\n10.8\n```\n:::\n\n:::cell\nLambdas are most idiomatic when passed directly to another function. `sorted()` calls this key function once for each item.\n\n```python\nitems = [("notebook", 5), ("pen", 2), ("bag", 20)]\nby_price = sorted(items, key=lambda item: item[1])\nprint(by_price)\n```\n\n```output\n[(\'pen\', 2), (\'notebook\', 5), (\'bag\', 20)]\n```\n:::\n\n:::cell\nA named function is better when the behavior should be reused or explained. It produces the same sort key, but gives the operation a name.\n\n```python\ndef price(item):\n return item[1]\n\nprint(sorted(items, key=price))\n```\n\n```output\n[(\'pen\', 2), (\'notebook\', 5), (\'bag\', 20)]\n```\n:::\n\n:::note\n- Lambdas are expressions, not statements.\n- Prefer `def` for multi-step or reused behavior.\n- Lambdas are common as `key=` functions because the behavior is local to one call.\n:::\n', 'lists.md': '+++\nslug = "lists"\ntitle = "Lists"\nsection = "Collections"\nsummary = "Lists are ordered, mutable collections."\ndoc_path = "/tutorial/datastructures.html#more-on-lists"\nsee_also = [\n "tuples",\n "sets",\n "slices",\n "copying-collections",\n]\n+++\n\nLists are Python\'s general-purpose mutable sequence type. Use them when order matters and the collection may grow, shrink, or be rearranged.\n\nIndexing reads individual positions. `0` is the first item, and negative indexes count backward from the end.\n\nMutation and copying matter: `append()` changes the list, while `sorted()` returns a new ordered list and leaves the original alone.\n\n:::program\n```python\nnumbers = [3, 1, 4]\nnumbers.append(1)\n\nprint(numbers)\nprint(numbers[0])\nprint(numbers[-1])\nprint(sorted(numbers))\nprint(numbers)\n```\n:::\n\n:::cell\nCreate a list with square brackets. Because lists are mutable, `append()` changes this same list object.\n\n```python\nnumbers = [3, 1, 4]\nnumbers.append(1)\n\nprint(numbers)\n```\n\n```output\n[3, 1, 4, 1]\n```\n:::\n\n:::cell\nUse indexes to read positions. Negative indexes are convenient for reading from the end.\n\n```python\nprint(numbers[0])\nprint(numbers[-1])\n```\n\n```output\n3\n1\n```\n:::\n\n:::cell\nUse `sorted()` when you want an ordered copy and still need the original order afterward.\n\n```python\nprint(sorted(numbers))\nprint(numbers)\n```\n\n```output\n[1, 1, 3, 4]\n[3, 1, 4, 1]\n```\n:::\n\n:::note\n- Lists are mutable sequences: methods such as `append()` change the list in place.\n- Negative indexes count from the end.\n- `sorted()` returns a new list; `list.sort()` sorts the existing list in place.\n:::\n', 'literal-and-final.md': '+++\nslug = "literal-and-final"\ntitle = "Literal and Final"\nsection = "Types"\nsummary = "Literal restricts exact values, while Final marks names that should not be rebound."\ndoc_path = "/library/typing.html#typing.Literal"\nsee_also = [\n "type-hints",\n "constants",\n "union-and-optional-types",\n "overloads",\n]\n+++\n\n`Literal` and `Final` make two different static promises. `Literal` narrows a value to exact allowed options. `Final` tells a type checker that a name should not be rebound after its first assignment.\n\nBoth annotations help at API boundaries: a function can accept only known modes, and a module can publish a constant that other code should treat as fixed. Python still runs the same assignment rules at runtime, so these are promises for tools and readers rather than runtime locks.\n\nUse `Literal` when a small closed set is clearer than a broad `str` or `int`. Use `Final` when rebinding would be a bug in the design, especially for module constants and class attributes.\n\n:::program\n```python\nfrom typing import Final, Literal\n\nMode = Literal["read", "write"]\nDEFAULT_MODE: Final[Mode] = "read"\n\n\ndef open_label(mode: Mode) -> str:\n return f"opening for {mode}"\n\nprint(open_label(DEFAULT_MODE))\nprint(open_label("write"))\n\nDEFAULT_MODE = "debug"\nprint(DEFAULT_MODE)\n```\n:::\n\n:::cell\n`Literal` describes exact allowed values. A type checker can reject `"debug"` as a `Mode` even though it is an ordinary string at runtime.\n\n```python\nfrom typing import Final, Literal\n\nMode = Literal["read", "write"]\n\n\ndef open_label(mode: Mode) -> str:\n return f"opening for {mode}"\n\nprint(open_label("write"))\n```\n\n```output\nopening for write\n```\n:::\n\n:::cell\n`Final` marks a name that should not be rebound. It is stronger documentation than the all-caps constant convention because static tools can flag reassignment.\n\n```python\nDEFAULT_MODE: Final[Mode] = "read"\nprint(open_label(DEFAULT_MODE))\n```\n\n```output\nopening for read\n```\n:::\n\n:::cell\nThe annotation is not a runtime lock. Python still rebinds the name; the mistake is that a type checker and human reader should reject the design.\n\n```python\nDEFAULT_MODE = "debug"\nprint(DEFAULT_MODE)\n```\n\n```output\ndebug\n```\n:::\n\n:::note\n- `Literal` narrows values to a small exact set.\n- `Final` prevents rebinding in static analysis, not at runtime.\n- Use enums when the option set needs names, behavior, or iteration over members.\n:::\n', 'literals.md': '+++\nslug = "literals"\ntitle = "Literals"\nsection = "Basics"\nsummary = "Literals write values directly in Python source code."\ndoc_path = "/reference/lexical_analysis.html#literals"\nsee_also = [\n "values",\n "strings",\n "numbers",\n "string-formatting",\n]\n+++\n\nLiterals are source-code forms for values: numbers, text, bytes, containers, booleans, `None`, and a few specialized markers. They are how a program writes small values directly.\n\nThe literal form is only the beginning. Later examples explain each value family in depth: strings are Unicode text, bytes are binary data, lists and dicts are containers, and `None` represents intentional absence.\n\nUse literals when the value is small and local. Give repeated or meaningful values a name so the program explains why that value matters.\n\n:::program\n```python\nwhole = 42\nfraction = 3.5\ncomplex_number = 2 + 3j\nprint(whole, fraction, complex_number.imag)\n\nflags = 0xFF\nmask = 0b1010\nmillion = 1_000_000\nprint(flags, mask, million)\n\ntext = "python"\nraw_pattern = r"\\d+"\ndata = b"py"\nscore = 98\nformatted = f"score={score}"\nprint(text)\nprint(raw_pattern)\nprint(data)\nprint(formatted)\n\npoint = (2, 3)\nnames = ["Ada", "Grace"]\nscores = {"Ada": 98}\nunique = {"py", "go"}\nprint(point)\nprint(names[0])\nprint(scores["Ada"])\nprint(sorted(unique))\n\nprint(True, False, None)\nprint(...)\n\nprint(type({}).__name__)\nprint(type(set()).__name__)\nprint(type({1, 2}).__name__)\n```\n:::\n\n:::cell\nNumeric literals write numbers directly. Complex literals use `j` for the imaginary part.\n\n```python\nwhole = 42\nfraction = 3.5\ncomplex_number = 2 + 3j\nprint(whole, fraction, complex_number.imag)\n```\n\n```output\n42 3.5 3.0\n```\n:::\n\n:::cell\nInteger literals also accept hexadecimal (`0x`), binary (`0b`), and octal (`0o`) prefixes. Underscores group digits visually without changing the value.\n\n```python\nflags = 0xFF\nmask = 0b1010\nmillion = 1_000_000\nprint(flags, mask, million)\n```\n\n```output\n255 10 1000000\n```\n:::\n\n:::cell\nString literals write Unicode text. Raw strings keep backslashes literal, bytes literals write binary data rather than text, and f-strings (`f"..."`) embed expressions inline.\n\n```python\ntext = "python"\nraw_pattern = r"\\d+"\ndata = b"py"\nscore = 98\nformatted = f"score={score}"\nprint(text)\nprint(raw_pattern)\nprint(data)\nprint(formatted)\n```\n\n```output\npython\n\\d+\nb\'py\'\nscore=98\n```\n:::\n\n:::cell\nContainer literals create tuples, lists, dictionaries, and sets. Each container answers a different question about order, position, lookup, or uniqueness.\n\n```python\npoint = (2, 3)\nnames = ["Ada", "Grace"]\nscores = {"Ada": 98}\nunique = {"py", "go"}\nprint(point)\nprint(names[0])\nprint(scores["Ada"])\nprint(sorted(unique))\n```\n\n```output\n(2, 3)\nAda\n98\n[\'go\', \'py\']\n```\n:::\n\n:::cell\n`True`, `False`, `None`, and `...` are singleton literal-like constants used for truth values, absence, and placeholders.\n\n```python\nprint(True, False, None)\nprint(...)\n```\n\n```output\nTrue False None\nEllipsis\n```\n:::\n\n:::cell\nCurly-brace literals are dictionaries by default. The empty form `{}` is an empty dictionary, not an empty set; use `set()` for that. A non-empty `{1, 2}` is a set because keyless items can only be a set.\n\n```python\nprint(type({}).__name__)\nprint(type(set()).__name__)\nprint(type({1, 2}).__name__)\n```\n\n```output\ndict\nset\nset\n```\n:::\n\n:::note\n- Literals are good for small local values; constants are better for repeated values with meaning.\n- `{}` is an empty dictionary. Use `set()` for an empty set.\n- Bytes literals are binary data; string literals are Unicode text.\n- `...` evaluates to the `Ellipsis` object.\n:::\n', 'logging.md': '+++\nslug = "logging"\ntitle = "Logging"\nsection = "Standard Library"\nsummary = "logging records operational events without using print as infrastructure."\ndoc_path = "/library/logging.html"\nsee_also = [\n "exceptions",\n "testing",\n "modules",\n]\n+++\n\n`logging` records operational events without using `print` as infrastructure. A logger names where an event came from, a handler decides where records go, a formatter chooses their text shape, and a level decides which records are important enough to emit.\n\nUse logging for services, command-line tools, scheduled jobs, and libraries that need diagnostics operators can filter. Use `print` for a program\'s intentional user-facing output.\n\nThe example writes to stdout so the page stays deterministic. Real applications usually configure handlers once at startup and then call `logging.getLogger(__name__)` from each module.\n\n:::program\n```python\nimport logging\nimport sys\n\nlogger = logging.getLogger("example.worker")\nlogger.setLevel(logging.DEBUG)\nhandler = logging.StreamHandler(sys.stdout)\nhandler.setLevel(logging.INFO)\nparts = ["%(levelname)s", "%(name)s", "%(message)s"]\nformatter = logging.Formatter(":".join(parts))\nhandler.setFormatter(formatter)\nlogger.handlers[:] = [handler]\nlogger.propagate = False\n\nlogger.debug("hidden detail")\nlogger.info("service started")\nlogger.warning("disk almost full")\n\nhandler.setLevel(logging.WARNING)\nlogger.info("hidden after threshold change")\nlogger.error("write failed")\n```\n:::\n\n:::cell\nA logger name records which part of the program produced the event. The handler and formatter choose where and how the event is shown.\n\n```python\nimport logging\nimport sys\n\nlogger = logging.getLogger("example.worker")\nlogger.setLevel(logging.DEBUG)\nhandler = logging.StreamHandler(sys.stdout)\nhandler.setLevel(logging.INFO)\nparts = ["%(levelname)s", "%(name)s", "%(message)s"]\nformatter = logging.Formatter(":".join(parts))\nhandler.setFormatter(formatter)\nlogger.handlers[:] = [handler]\nlogger.propagate = False\n\nlogger.debug("hidden detail")\nlogger.info("service started")\nlogger.warning("disk almost full")\n```\n\n```output\nINFO:example.worker:service started\nWARNING:example.worker:disk almost full\n```\n:::\n\n:::cell\nLevels are thresholds. Raising the handler level to `WARNING` suppresses later `INFO` records without changing the call sites.\n\n```python\nimport logging\nimport sys\n\nlogger = logging.getLogger("example.worker")\nlogger.setLevel(logging.DEBUG)\nhandler = logging.StreamHandler(sys.stdout)\nhandler.setLevel(logging.WARNING)\nparts = ["%(levelname)s", "%(name)s", "%(message)s"]\nformatter = logging.Formatter(":".join(parts))\nhandler.setFormatter(formatter)\nlogger.handlers[:] = [handler]\nlogger.propagate = False\n\nlogger.info("hidden after threshold change")\nlogger.error("write failed")\n```\n\n```output\nERROR:example.worker:write failed\n```\n:::\n\n:::note\n- Configure logging once; call named loggers throughout the program.\n- Logger and handler levels both participate in filtering.\n- Use exceptions for control flow failures, logging for operational evidence, and warnings for soft compatibility problems.\n:::\n', 'loop-else.md': '+++\nslug = "loop-else"\ntitle = "Loop Else"\nsection = "Control Flow"\nsummary = "A loop else block runs only when the loop did not end with break."\ndoc_path = "/tutorial/controlflow.html#else-clauses-on-loops"\nsee_also = [\n "break-and-continue",\n "for-loops",\n "while-loops",\n]\n+++\n\nPython loops can have an `else` clause. The name is surprising at first: loop `else` means “no `break` happened,” not “the loop condition was false.”\n\nThis is useful for searches. Put the successful early exit in `break`, then put the not-found path in `else`.\n\nUse loop `else` sparingly. It is clearest when the loop is visibly searching for something.\n\n:::program\n```python\nnames = ["Ada", "Grace", "Guido"]\n\nfor name in names:\n if name == "Grace":\n print("found")\n break\nelse:\n print("missing")\n\nfor name in names:\n if name == "Linus":\n print("found")\n break\nelse:\n print("missing")\n```\n:::\n\n:::cell\nIf the loop reaches `break`, the `else` block is skipped. This branch means the search succeeded early.\n\n```python\nnames = ["Ada", "Grace", "Guido"]\n\nfor name in names:\n if name == "Grace":\n print("found")\n break\nelse:\n print("missing")\n```\n\n```output\nfound\n```\n:::\n\n:::cell\nIf the loop finishes without `break`, the `else` block runs. This branch means the search examined every value and found nothing.\n\n```python\nfor name in names:\n if name == "Linus":\n print("found")\n break\nelse:\n print("missing")\n```\n\n```output\nmissing\n```\n:::\n\n:::note\n- Loop `else` runs when the loop was not ended by `break`.\n- It is best for search loops with a clear found/not-found split.\n- It works with both `for` and `while` loops.\n:::\n', 'match-statements.md': '+++\nslug = "match-statements"\ntitle = "Match Statements"\nsection = "Control Flow"\nsummary = "match selects cases using structural pattern matching."\ndoc_path = "/tutorial/controlflow.html#match-statements"\nsee_also = [\n "conditionals",\n "advanced-match-patterns",\n "structured-data-shapes",\n "dicts",\n]\n+++\n\nStructural pattern matching lets a program choose a branch based on the shape of data. It is especially useful when commands, messages, or parsed data have a few known forms.\n\nA `case` pattern can both check constants and bind names. The move case checks the action and extracts `x` and `y` in one readable step.\n\nOrder matters because Python tries cases from top to bottom. Specific shapes should appear before broad fallback cases such as `_`.\n\n:::program\n```python\ncommand = {"action": "move", "x": 3, "y": 4}\n\nmatch command:\n case {"action": "move", "x": x, "y": y}:\n print(f"move to {x},{y}")\n case {"action": "quit"}:\n print("quit")\n case {"action": action}:\n print(f"unknown action: {action}")\n case _:\n print("invalid command")\n```\n:::\n\n:::cell\nUse `match` when the shape of a value is the decision. This command is a dictionary with an action and coordinates; the first case checks that shape and binds `x` and `y`.\n\n```python\ncommand = {"action": "move", "x": 3, "y": 4}\n\nmatch command:\n case {"action": "move", "x": x, "y": y}:\n print(f"move to {x},{y}")\n```\n\n```output\nmove to 3,4\n```\n:::\n\n:::cell\nOther cases describe other valid shapes. This complete fragment changes the command so the `quit` case is the first matching pattern.\n\n```python\ncommand = {"action": "quit"}\n\nmatch command:\n case {"action": "move", "x": x, "y": y}:\n print(f"move to {x},{y}")\n case {"action": "quit"}:\n print("quit")\n```\n\n```output\nquit\n```\n:::\n\n:::cell\nBroader patterns and the `_` catch-all belong after specific cases. This fragment extracts an unknown action before the final fallback would run.\n\n```python\ncommand = {"action": "jump"}\n\nmatch command:\n case {"action": "move", "x": x, "y": y}:\n print(f"move to {x},{y}")\n case {"action": "quit"}:\n print("quit")\n case {"action": action}:\n print(f"unknown action: {action}")\n case _:\n print("invalid command")\n```\n\n```output\nunknown action: jump\n```\n:::\n\n:::note\n- `match` compares structure, not just equality.\n- Patterns can bind names such as `x` and `y` while matching.\n- Mapping patterns match when the named keys are present; extra keys in the subject are ignored rather than failing the case.\n- Put the catch-all `_` case last, because cases are tried from top to bottom.\n:::\n', 'metaclasses.md': '+++\nslug = "metaclasses"\ntitle = "Metaclasses"\nsection = "Classes"\nsummary = "A metaclass customizes how classes themselves are created."\ndoc_path = "/reference/datamodel.html#metaclasses"\nsee_also = [\n "classes",\n "inheritance-and-super",\n "special-methods",\n]\n+++\n\nA metaclass is the class of a class. Most Python code never needs one, but the syntax appears in frameworks that register, validate, or modify classes as they are created.\n\nThe `metaclass=` keyword in a class statement chooses the object that builds the class. This is advanced machinery; decorators and ordinary functions are usually simpler.\n\nUse metaclasses only when class creation itself is the problem being solved.\n\n:::program\n```python\nclass Tagged(type):\n def __new__(mcls, name, bases, namespace):\n namespace["tag"] = name.lower()\n return super().__new__(mcls, name, bases, namespace)\n\nclass Event(metaclass=Tagged):\n pass\n\nprint(Event.tag)\nprint(type(Event).__name__)\n```\n:::\n\n:::cell\nA metaclass customizes class creation. `__new__` receives the class name, bases, and namespace before the class object exists.\n\n```python\nclass Tagged(type):\n def __new__(mcls, name, bases, namespace):\n namespace["tag"] = name.lower()\n return super().__new__(mcls, name, bases, namespace)\n\nprint(Tagged.__name__)\n```\n\n```output\nTagged\n```\n:::\n\n:::cell\nThe `metaclass=` keyword applies that class-building rule. Here the metaclass adds a `tag` attribute to the new class.\n\n```python\nclass Event(metaclass=Tagged):\n pass\n\nprint(Event.tag)\nprint(type(Event).__name__)\n```\n\n```output\nevent\nTagged\n```\n:::\n\n:::note\n- Metaclasses customize class creation, not instance behavior directly.\n- Most code should prefer class decorators, functions, or ordinary inheritance.\n- You are most likely to meet metaclasses inside frameworks and ORMs.\n:::\n', 'modules.md': '+++\nslug = "modules"\ntitle = "Modules"\nsection = "Modules"\nsummary = "Modules organize code into namespaces and expose reusable definitions."\ndoc_path = "/tutorial/modules.html"\nsee_also = [\n "import-aliases",\n "packages",\n]\n+++\n\nModules organize Python code into files and namespaces. `import` executes a module once, stores it in Python\'s import cache, and gives your program access to its definitions.\n\nThis page focuses on import forms and module namespaces. Package layout, aliases, and dynamic imports have their own neighboring examples.\n\nUse module namespaces such as `math.sqrt` when the source of a name should stay visible. Use focused imports such as `from statistics import mean` when the imported name is clear at the call site.\n\n:::program\n```python\nimport math\nimport sys\nfrom statistics import mean\n\nradius = 3\narea = math.pi * radius ** 2\nprint(round(area, 2))\n\nscores = [8, 10, 9]\nprint(mean(scores))\n\nprint(math.__name__)\nprint("math" in sys.modules)\n```\n:::\n\n:::cell\nImporting a module gives access to its namespace. The `math.` prefix makes it clear where `pi` came from.\n\n```python\nimport math\n\nradius = 3\narea = math.pi * radius ** 2\nprint(round(area, 2))\n```\n\n```output\n28.27\n```\n:::\n\n:::cell\nA focused `from ... import ...` brings one definition into the current namespace. This keeps a common operation concise without importing every name.\n\n```python\nfrom statistics import mean\n\nscores = [8, 10, 9]\nprint(mean(scores))\n```\n\n```output\n9\n```\n:::\n\n:::cell\nModules are objects too. Their attributes include metadata such as `__name__`, which records the module\'s import name.\n\n```python\nprint(math.__name__)\n```\n\n```output\nmath\n```\n:::\n\n:::cell\nImported modules are cached in `sys.modules`. Later imports reuse the module object instead of executing the file again.\n\n```python\nimport sys\nprint("math" in sys.modules)\n```\n\n```output\nTrue\n```\n:::\n\n:::note\n- Prefer plain `import module` when the namespace improves readability.\n- Use focused imports for a small number of clear names.\n- Place imports near the top of the file.\n- Imports execute module top-level code once, then reuse the cached module object.\n:::\n', 'multiple-return-values.md': '+++\nslug = "multiple-return-values"\ntitle = "Multiple Return Values"\nsection = "Functions"\nsummary = "Python returns multiple values by returning a tuple and unpacking it."\ndoc_path = "/tutorial/datastructures.html#tuples-and-sequences"\nsee_also = [\n "tuples",\n "unpacking",\n "functions",\n]\n+++\n\nPython multiple return values are tuple return values with friendly syntax. `return a, b` creates one tuple containing two positions.\n\nMost callers unpack that tuple immediately. Good target names make the meaning of each returned position explicit.\n\nUse this for small, fixed groups of results. For larger records, a dataclass or named tuple usually communicates better.\n\n:::program\n```python\ndef divide_with_remainder(total, size):\n quotient = total // size\n remainder = total % size\n return quotient, remainder\n\nresult = divide_with_remainder(17, 5)\nprint(result)\n\nboxes, leftover = result\nprint(boxes)\nprint(leftover)\n```\n:::\n\n:::cell\nReturning values separated by commas returns one tuple. The tuple is visible if the caller stores the result directly.\n\n```python\ndef divide_with_remainder(total, size):\n quotient = total // size\n remainder = total % size\n return quotient, remainder\n\nresult = divide_with_remainder(17, 5)\nprint(result)\n```\n\n```output\n(3, 2)\n```\n:::\n\n:::cell\nCallers usually unpack the tuple immediately or soon after. The names at the call site document what each position means.\n\n```python\nboxes, leftover = result\nprint(boxes)\nprint(leftover)\n```\n\n```output\n3\n2\n```\n:::\n\n:::note\n- A comma creates a tuple; `return a, b` returns one tuple containing two values.\n- Unpacking at the call site gives each returned position a meaningful name.\n- Use a class-like record when the result has many fields.\n:::\n', 'mutability.md': '+++\nslug = "mutability"\ntitle = "Mutability"\nsection = "Data Model"\nsummary = "Some objects change in place, while others return new values."\ndoc_path = "/reference/datamodel.html#objects-values-and-types"\nsee_also = [\n "variables",\n "object-lifecycle",\n "copying-collections",\n "lists",\n]\n+++\n\nObjects in Python can be mutable or immutable. Mutable objects such as lists and dictionaries can change in place, while immutable objects such as strings and tuples produce new values instead.\n\nNames can share one mutable object, so a change through one name is visible through another. This is powerful, but it is also the source of many beginner surprises.\n\nThe boundary matters across Python: `append()` mutates a list, string methods return new strings, and `sorted()` returns a new list while `list.sort()` mutates an existing one.\n\n:::program\n```python\nfirst = ["python"]\nsecond = first\nsecond.append("workers")\nprint(first)\nprint(second)\n\ntext = "python"\nupper_text = text.upper()\nprint(text)\nprint(upper_text)\n\nnumbers = [3, 1, 2]\nordered = sorted(numbers)\nprint(ordered)\nprint(numbers)\n```\n:::\n\n:::cell\nMutable objects can change in place. `first` and `second` point to the same list, so appending through one name changes the object seen through both names.\n\n```python\nfirst = ["python"]\nsecond = first\nsecond.append("workers")\nprint(first)\nprint(second)\n```\n\n```output\n[\'python\', \'workers\']\n[\'python\', \'workers\']\n```\n:::\n\n:::cell\nImmutable objects do not change in place. String methods such as `upper()` return a new string, leaving the original string unchanged.\n\n```python\ntext = "python"\nupper_text = text.upper()\nprint(text)\nprint(upper_text)\n```\n\n```output\npython\nPYTHON\n```\n:::\n\n:::cell\nSome APIs make the boundary explicit. `sorted()` returns a new list, while methods such as `append()` and `list.sort()` mutate an existing list.\n\n```python\nnumbers = [3, 1, 2]\nordered = sorted(numbers)\nprint(ordered)\nprint(numbers)\n```\n\n```output\n[1, 2, 3]\n[3, 1, 2]\n```\n:::\n\n:::note\n- Lists and dictionaries are mutable; strings and tuples are immutable.\n- Aliasing is useful, but copy mutable containers when independent changes are needed.\n- Pay attention to whether an operation mutates in place or returns a new value.\n:::\n', 'networking.md': '+++\nslug = "networking"\ntitle = "Networking"\nsection = "Standard Library"\nsummary = "Networking code exchanges bytes across explicit protocol boundaries."\ndoc_path = "/library/socket.html"\nsee_also = [\n "bytes-and-bytearray",\n "subprocesses",\n "async-await",\n]\nexpected_output = "b\'ping\'\\nping\\n"\nsandbox_limit = "sockets"\n+++\n\nNetworking code sends and receives bytes across protocol boundaries. Higher-level HTTP clients hide many details, but the core rule remains: text is encoded before it leaves the process and decoded after bytes come back.\n\nIn standard Python, the socket version of this lesson uses connected endpoints such as `socket.create_connection()` or, for a local deterministic demonstration, `socket.socketpair()`. This site\'s live example runner does not expose arbitrary OS sockets or outbound calls, so this page teaches the socket contract while making the runner constraint explicit.\n\nThe useful mental model is endpoint plus bytes plus cleanup. A socket connects two endpoints, transfers byte strings, and must be closed when the conversation is finished.\n\n:::program\n```python\nimport socket\n\nleft, right = socket.socketpair()\ntry:\n message = "ping"\n left.sendall(message.encode("utf-8"))\n data = right.recv(16)\n print(data)\n print(data.decode("utf-8"))\nfinally:\n left.close()\n right.close()\n```\n:::\n\n:::cell\n`socketpair()` returns two connected endpoints. `sendall` writes encoded bytes into one end and `recv` reads up to 16 bytes off the other — the byte boundary is the whole point: `"ping".encode("utf-8")` produces `b\'ping\'`, which is what the socket actually moves. The `try`/`finally` closes both endpoints even if `recv` raises, and the second `print` `decode`s the bytes back into a Python `str`. The in-browser sandbox cannot open sockets, so pressing Run here fails; this output came from a real socket pair under standard CPython at build time.\n\n```python\nimport socket\n\nleft, right = socket.socketpair()\ntry:\n message = "ping"\n left.sendall(message.encode("utf-8"))\n data = right.recv(16)\n print(data)\n print(data.decode("utf-8"))\nfinally:\n left.close()\n right.close()\n```\n\n```output\nb\'ping\'\nping\n```\n:::\n\n:::note\n- Network protocols move bytes, not Python `str` objects.\n- Close real sockets when finished, usually with a context manager or `finally` block.\n- Use high-level HTTP libraries for application HTTP unless socket-level control is the lesson.\n- The verified output came from a real `socketpair()` under standard CPython at build time; the in-browser sandbox cannot open sockets, so live runs of this page fail there.\n:::\n', 'newtype.md': '+++\nslug = "newtype"\ntitle = "NewType"\nsection = "Types"\nsummary = "NewType creates distinct static identities for runtime-compatible values."\ndoc_path = "/library/typing.html#typing.NewType"\nsee_also = [\n "type-aliases",\n "type-hints",\n "runtime-type-checks",\n]\n+++\n\n`NewType` creates a distinct static identity for a value that is represented by an existing runtime type. It is useful for IDs, units, and other values that should not be mixed accidentally.\n\nThe key boundary is static versus runtime behavior. A type checker can distinguish `UserId` from `OrderId`, but at runtime both values are plain integers.\n\nUse a type alias when you only want a clearer name for a shape. Use `NewType` when mixing two compatible shapes should be treated as a mistake by static analysis.\n\n:::program\n```python\nfrom typing import NewType\n\nUserId = NewType("UserId", int)\nOrderId = NewType("OrderId", int)\n\n\ndef load_user(user_id: UserId) -> str:\n return f"user {user_id}"\n\nuid = UserId(42)\noid = OrderId(42)\nprint(load_user(uid))\nprint(uid == oid)\nprint(type(uid).__name__)\nprint(UserId.__name__)\n```\n:::\n\n:::cell\n`NewType` helps type checkers distinguish values that share a runtime representation.\n\n```python\nfrom typing import NewType\n\nUserId = NewType("UserId", int)\nOrderId = NewType("OrderId", int)\n\n\ndef load_user(user_id: UserId) -> str:\n return f"user {user_id}"\n\nuid = UserId(42)\nprint(load_user(uid))\n```\n\n```output\nuser 42\n```\n:::\n\n:::cell\nAt runtime, a `NewType` value is the underlying value. It compares like that value and has the same runtime type.\n\n```python\noid = OrderId(42)\nprint(uid == oid)\nprint(type(uid).__name__)\n```\n\n```output\nTrue\nint\n```\n:::\n\n:::cell\nThe `NewType` constructor keeps a name for static tools and introspection.\n\n```python\nprint(UserId.__name__)\nprint(OrderId.__name__)\n```\n\n```output\nUserId\nOrderId\n```\n:::\n\n:::note\n- `NewType` helps type checkers distinguish values that share a runtime representation.\n- At runtime, the value is still the underlying type.\n- Use aliases for readability; use `NewType` for static separation.\n:::\n', 'none.md': '+++\nslug = "none"\ntitle = "None"\nsection = "Basics"\nsummary = "None represents expected absence, distinct from missing keys and errors."\ndoc_path = "/library/constants.html#None"\nsee_also = [\n "values",\n "truthiness",\n "exceptions",\n "dicts",\n]\n+++\n\n`None` represents the absence of a value. It is the usual result when a call has nothing to hand back but the absence itself is meaningful.\n\nBecause `None` is a singleton, idiomatic Python checks it with `is None` or `is not None`. This avoids confusing identity with value equality.\n\nAbsence has several nearby shapes in Python. A call can return `None`, a dictionary lookup can supply a default for a missing key, and an invalid operation can raise an exception instead of returning anything.\n\n:::program\n```python\nresult = None\nprint(result is None)\n\nnames = ["Grace", "Ada"]\nresult = names.sort()\nprint(result is None)\nprint(names)\n\nprofile = {"name": "Ada"}\ntimezone = profile.get("timezone")\nprint(timezone is None)\nprint(profile.get("timezone", "UTC"))\n```\n:::\n\n:::cell\n`None` is Python\'s value for “nothing here.” Check it with `is None` because it is a singleton identity value.\n\n```python\nresult = None\nprint(result is None)\n```\n\n```output\nTrue\n```\n:::\n\n:::cell\nA call that does its work without producing a result returns `None`. `list.sort()` reorders the list in place, so the value it hands back is `None` and the sorted data is in `names`. Assigning that result to a name is a common slip; the same rule applies to every [function](/examples/functions) that finishes without a `return` value.\n\n```python\nnames = ["Grace", "Ada"]\nresult = names.sort()\nprint(result is None)\nprint(names)\n```\n\n```output\nTrue\n[\'Ada\', \'Grace\']\n```\n:::\n\n:::cell\nA missing dictionary key is another absence boundary. `get()` returns `None` when the key is missing, or a default when the mapping can supply one. Indexing with `profile["timezone"]` would not return `None`: it raises `KeyError`, because Python reports invalid operations with [exceptions](/examples/exceptions) rather than with a value.\n\n```python\nprofile = {"name": "Ada"}\ntimezone = profile.get("timezone")\nprint(timezone is None)\nprint(profile.get("timezone", "UTC"))\n```\n\n```output\nTrue\nUTC\n```\n:::\n\n:::note\n- Use `is None` rather than `== None`; `None` is a singleton identity value.\n- Use `None` for expected absence that callers can test.\n- Calls that only change something in place, such as `list.sort()`, return `None`.\n- Use dictionary defaults for missing mapping keys and exceptions for invalid operations.\n:::\n', 'number-parsing.md': '+++\nslug = "number-parsing"\ntitle = "Number Parsing"\nsection = "Standard Library"\nsummary = "int() and float() parse text into numbers and raise ValueError on bad input."\ndoc_path = "/library/functions.html#int"\nsee_also = [\n "exceptions",\n "strings",\n "numbers",\n]\n+++\n\nParsing turns text from files, forms, command lines, or network messages into numeric objects. `int()` parses whole-number text, and `float()` parses decimal or scientific-notation text.\n\nInvalid numeric text raises `ValueError`. Catch that specific exception when bad user input is expected and recoverable; let it fail loudly when the string is supposed to be trusted program data.\n\n`int()` also accepts a base, which is useful at protocol boundaries where numbers are written in hexadecimal, binary, or another explicit notation.\n\n:::program\n```python\nprint(int("42"))\nprint(float("3.5"))\nprint(int("ff", 16))\n\ntexts = ["10", "python", "20"]\nfor text in texts:\n try:\n print(int(text) * 2)\n except ValueError:\n print(f"skip {text!r}")\n```\n:::\n\n:::cell\nUse `int()` for whole numbers and `float()` for decimal text. Parsed values are real numbers, not strings.\n\n```python\nprint(int("42"))\nprint(float("3.5"))\n```\n\n```output\n42\n3.5\n```\n:::\n\n:::cell\nPass a base when the text format says the number is not decimal.\n\n```python\nprint(int("ff", 16))\n```\n\n```output\n255\n```\n:::\n\n:::cell\nCatch `ValueError` at the input boundary when invalid text is normal and recoverable.\n\n```python\ntexts = ["10", "python", "20"]\nfor text in texts:\n try:\n print(int(text) * 2)\n except ValueError:\n print(f"skip {text!r}")\n```\n\n```output\n20\nskip \'python\'\n40\n```\n:::\n\n:::note\n- `int()` and `float()` are constructors that also parse strings.\n- `int(text, base)` makes non-decimal input explicit.\n- Catch `ValueError` for recoverable user input; do not hide unexpected data corruption.\n:::\n', 'numbers.md': '+++\nslug = "numbers"\ntitle = "Numbers"\nsection = "Basics"\nsummary = "Python numbers include integers, floats, and complex values."\ndoc_path = "/library/stdtypes.html#numeric-types-int-float-complex"\nsee_also = [\n "literals",\n "operators",\n]\n+++\n\nPython\'s numeric model starts with `int`, `float`, and `complex`. Integers are arbitrary precision, floats are approximate double-precision values, and complex numbers carry real and imaginary parts.\n\nOperators encode different numeric questions. `/` means true division and returns a float, `//` means floor division, `%` gives the remainder, and `**` computes powers.\n\nUse rounding for display, not as a substitute for understanding floating-point approximation. Financial code usually needs `decimal.Decimal`, which is a separate precision topic.\n\n:::program\n```python\nimport math\n\ncount = 10\nratio = 0.25\nz = 2 + 3j\n\nprint(count + 5)\nprint(count / 4)\nprint(ratio * 2)\nprint(count // 4)\nprint(count % 4)\nprint(2 ** 5)\nprint(z.real, z.imag)\nprint(0.1 + 0.2)\nprint(0.1 + 0.2 == 0.3)\nprint(math.isclose(0.1 + 0.2, 0.3))\nprint(round(3.14159, 2))\n```\n:::\n\n:::cell\nPython has `int` for whole numbers and `float` for approximate real-valued arithmetic. True division with `/` returns a `float`, even when both inputs are integers.\n\n```python\ncount = 10\nratio = 0.25\n\nprint(count + 5)\nprint(count / 4)\nprint(ratio * 2)\n```\n\n```output\n15\n2.5\n0.5\n```\n:::\n\n:::cell\nFloor division and modulo are useful when you need quotient and remainder behavior. Powers use `**`, not `^`.\n\n```python\nprint(count // 4)\nprint(count % 4)\nprint(2 ** 5)\n```\n\n```output\n2\n2\n32\n```\n:::\n\n:::cell\nComplex numbers are built in. The literal suffix `j` marks the imaginary part.\n\n```python\nz = 2 + 3j\nprint(z.real, z.imag)\n```\n\n```output\n2.0 3.0\n```\n:::\n\n:::cell\nFloating-point values are approximate, so `==` between expected and computed floats is rarely the right test. Compare with `math.isclose` (or work in `decimal.Decimal`) when the question is "are these the same number to within tolerance".\n\n```python\nimport math\n\nprint(0.1 + 0.2)\nprint(0.1 + 0.2 == 0.3)\nprint(math.isclose(0.1 + 0.2, 0.3))\nprint(round(3.14159, 2))\n```\n\n```output\n0.30000000000000004\nFalse\nTrue\n3.14\n```\n:::\n\n:::note\n- Python\'s `int` has arbitrary precision; it grows as large as memory allows.\n- Python\'s `float` is approximate double-precision floating point.\n- Use `/` for true division and `//` for floor division.\n- Use `math.isclose` instead of `==` for floating-point comparison; reach for `decimal.Decimal` when exact decimal precision is the domain requirement.\n:::\n', 'object-lifecycle.md': '+++\nslug = "object-lifecycle"\ntitle = "Object Lifecycle"\nsection = "Basics"\nsummary = "Names keep objects reachable until the last reference goes away."\ndoc_path = "/reference/datamodel.html#objects-values-and-types"\nsee_also = [\n "variables",\n "mutability",\n "classes",\n]\n+++\n\nPython objects live independently from the names that refer to them. Assignment adds another reference to an object; rebinding a name points that name somewhere else; `del` removes a name. The object can be reclaimed only after it is no longer reachable.\n\nMost programs do not manually destroy objects. They control lifetime by controlling which containers, local variables, and object attributes still hold references.\n\nThis example uses a one-item list so the object has visible state. The important evidence is that rebinding or deleting one name does not destroy the object while another name still refers to it.\n\n:::program\n```python\nbox = ["draft"]\nalias = box\n\nprint(box is alias)\nprint(alias)\n\nbox = ["published"]\nprint(alias)\nprint(box)\n\ndel alias\nprint("old object unreachable")\n```\n:::\n\n:::cell\nTwo names can refer to the same object. Mutating through one name would affect the object seen through the other.\n\n```python\nbox = ["draft"]\nalias = box\n\nprint(box is alias)\nprint(alias)\n```\n\n```output\nTrue\n[\'draft\']\n```\n:::\n\n:::cell\nRebinding `box` does not change the original object. `alias` still reaches the first list until that reference is removed too.\n\n```python\nbox = ["published"]\nprint(alias)\nprint(box)\n\ndel alias\nprint("old object unreachable")\n```\n\n```output\n[\'draft\']\n[\'published\']\nold object unreachable\n```\n:::\n\n:::note\n- Assignment binds names to objects; it does not copy the object.\n- `del name` removes one reference, not necessarily the object itself.\n- Python reclaims unreachable objects automatically, so lifetime bugs usually come from keeping references longer than intended.\n:::\n', 'operator-overloading.md': '+++\nslug = "operator-overloading"\ntitle = "Operator Overloading"\nsection = "Data Model"\nsummary = "Operator methods let objects define arithmetic and comparison syntax."\ndoc_path = "/reference/datamodel.html#emulating-numeric-types"\nsee_also = [\n "operators",\n "special-methods",\n "equality-and-identity",\n]\n+++\n\nOperator overloading lets a class define what expressions such as `a + b` mean for its objects. This is useful when the operation is part of the domain vocabulary.\n\nThe method should preserve the meaning readers expect from the operator. Vectors can add component by component; money can add amounts in the same currency; surprising overloads make code harder to trust.\n\nPython also has reflected methods such as `__radd__` for cases where the left operand does not know how to handle the right operand. That keeps mixed operations possible without making every type know every other type.\n\n:::program\n```python\nclass Vector:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n if not isinstance(other, Vector):\n return NotImplemented\n return Vector(self.x + other.x, self.y + other.y)\n\n def __eq__(self, other):\n if not isinstance(other, Vector):\n return NotImplemented\n return (self.x, self.y) == (other.x, other.y)\n\n def __matmul__(self, other):\n if not isinstance(other, Vector):\n return NotImplemented\n return self.x * other.x + self.y * other.y\n\n def __repr__(self):\n return f"Vector({self.x}, {self.y})"\n\nprint(Vector(2, 3) + Vector(4, 5))\nprint(Vector(1, 1) == Vector(1, 1))\nprint(Vector(1, 1) == 5)\nprint(Vector(2, 3) @ Vector(4, 5))\n```\n:::\n\n:::cell\n`__add__` defines how the `+` operator combines two objects. Checking the operand type and returning `NotImplemented` for foreign types lets Python try the other operand\'s reflected method instead of crashing inside yours.\n\n```python\nclass Vector:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n if not isinstance(other, Vector):\n return NotImplemented\n return Vector(self.x + other.x, self.y + other.y)\n\n def __repr__(self):\n return f"Vector({self.x}, {self.y})"\n\nprint(Vector(2, 3) + Vector(4, 5))\n```\n\n```output\nVector(6, 8)\n```\n:::\n\n:::cell\n`__eq__` defines value equality for `==`. Without it, user-defined objects compare by identity. Returning `NotImplemented` for foreign types matters most here: equality against an unrelated value should answer `False`, never raise — Python falls back to identity when both sides decline.\n\n```python\nclass Vector:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __eq__(self, other):\n if not isinstance(other, Vector):\n return NotImplemented\n return (self.x, self.y) == (other.x, other.y)\n\nprint(Vector(1, 1) == Vector(1, 1))\nprint(Vector(1, 1) == 5)\n```\n\n```output\nTrue\nFalse\n```\n:::\n\n:::cell\n`__matmul__` defines the `@` operator, which Python reserves for matrix-style multiplication. No built-in type implements it, so it only works on classes that opt in — here as the dot product of two vectors.\n\n```python\nclass Vector:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __matmul__(self, other):\n if not isinstance(other, Vector):\n return NotImplemented\n return self.x * other.x + self.y * other.y\n\nprint(Vector(2, 3) @ Vector(4, 5))\n```\n\n```output\n23\n```\n:::\n\n:::cell\nA useful `__repr__` makes operator results inspectable while debugging.\n\n```python\nclass Vector:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n if not isinstance(other, Vector):\n return NotImplemented\n return Vector(self.x + other.x, self.y + other.y)\n\n def __repr__(self):\n return f"Vector({self.x}, {self.y})"\n\nprint(repr(Vector(2, 3) + Vector(4, 5)))\n```\n\n```output\nVector(6, 8)\n```\n:::\n\n:::note\n- Overload operators only when the operation is unsurprising.\n- Return `NotImplemented` when an operand type is unsupported.\n- Implement equality deliberately when value comparison matters.\n:::\n', 'operators.md': '+++\nslug = "operators"\ntitle = "Operators"\nsection = "Basics"\nsummary = "Operators combine, compare, and test values in expressions."\ndoc_path = "/reference/expressions.html#operator-precedence"\nsee_also = [\n "numbers",\n "equality-and-identity",\n "assignment-expressions",\n "operator-overloading",\n]\n+++\n\nOperators are the punctuation and keywords that combine values into expressions. Some operators compute new values, some compare values, and some ask relationship questions such as membership or identity.\n\nThis page is the surface map. Focused examples explain the deeper behavior of numbers, booleans, conditions, sets, assignment expressions, and operator overloading.\n\nRead operators by the question they ask: arithmetic computes, comparison answers true or false, boolean operators combine truth values, membership searches a container, and specialized operators should only appear when the data shape calls for them.\n\n:::program\n```python\ncount = 10\nprint(count + 5)\nprint(count // 4)\nprint(count % 4)\nprint(2 ** 5)\n\nscore = 91\nprint(80 <= score < 100)\nprint(score == 100 or score >= 90)\nprint("py" in "python")\n\nflags = 0b0011\nprint(flags & 0b0101)\nprint(flags | 0b0100)\nprint(flags ^ 0b0101)\nprint(flags << 1)\n\nitems = ["a", "b"]\nprint((size := len(items)) > 0)\nprint(size)\n\ncount = 0\nprint(count != 0 and 10 / count)\nprint(count == 0 or 10 / count)\nprint(count == 0 and "empty")\n```\n:::\n\n:::cell\nArithmetic operators compute new values. Use `//` for floor division, `%` for remainder, and `**` for powers.\n\n```python\ncount = 10\nprint(count + 5)\nprint(count // 4)\nprint(count % 4)\nprint(2 ** 5)\n```\n\n```output\n15\n2\n2\n32\n```\n:::\n\n:::cell\nComparison operators produce booleans. Python comparisons can chain, which keeps range checks readable.\n\n```python\nscore = 91\nprint(80 <= score < 100)\nprint(score == 100 or score >= 90)\nprint("py" in "python")\n```\n\n```output\nTrue\nTrue\nTrue\n```\n:::\n\n:::cell\nBitwise operators work on integer bit patterns. They are useful for masks and flags, not ordinary boolean logic. `&` is bitwise AND, `|` is bitwise OR, `^` is exclusive OR, and `<<` shifts left.\n\n```python\nflags = 0b0011\nprint(flags & 0b0101)\nprint(flags | 0b0100)\nprint(flags ^ 0b0101)\nprint(flags << 1)\n```\n\n```output\n1\n7\n6\n6\n```\n:::\n\n:::cell\nThe walrus operator `:=` assigns inside an expression: the parenthesized part both names the length and passes it on to the comparison. [Assignment expressions](/examples/assignment-expressions) shows where that earns its place.\n\n```python\nitems = ["a", "b"]\nprint((size := len(items)) > 0)\nprint(size)\n```\n\n```output\nTrue\n2\n```\n:::\n\n:::cell\n`and` and `or` short-circuit: the right side runs only when the left side cannot already determine the result. Here `10 / count` would fail with a division-by-zero error if it ran, but the left side settles both answers first. The result is the last operand evaluated, so `count == 0 and "empty"` produces `"empty"`.\n\n```python\ncount = 0\nprint(count != 0 and 10 / count)\nprint(count == 0 or 10 / count)\nprint(count == 0 and "empty")\n```\n\n```output\nFalse\nTrue\nempty\n```\n:::\n\n:::note\n- Use the clearest operator for the question: arithmetic, comparison, boolean logic, membership, identity, or bitwise manipulation.\n- `and` and `or` short-circuit, so the right side may not run.\n- Operators have precedence; use parentheses when grouping would otherwise be hard to read.\n- `@` is the matrix-multiplication operator. No built-in type implements it; [operator overloading](/examples/operator-overloading) shows how a class gives `@`, `+`, or `==` its own meaning.\n:::\n', 'overloads.md': '+++\nslug = "overloads"\ntitle = "Overloads"\nsection = "Types"\nsummary = "overload describes APIs whose return type depends on argument types."\ndoc_path = "/library/typing.html#typing.overload"\nsee_also = [\n "type-hints",\n "union-and-optional-types",\n "generics-and-typevar",\n]\n+++\n\n`@overload` lets type checkers describe a function whose return type depends on the argument types. The overload declarations are static-only promises; the runtime function is still the single implementation that appears after them.\n\nUse overloads when a union return type would be too vague for callers. For example, `double(4)` returns an `int`, while `double("ha")` returns a `str`; `int | str` loses that relationship.\n\nAt runtime the overload stubs are not dispatch cases. The implementation must inspect or operate on the value just like any other Python function.\n\n:::program\n```python\nfrom typing import overload\n\n@overload\ndef double(value: int) -> int: ...\n\n@overload\ndef double(value: str) -> str: ...\n\ndef double(value: int | str) -> int | str:\n return value * 2\n\nprint(double(4))\nprint(double("ha"))\nprint(double.__annotations__)\n```\n:::\n\n:::cell\nThe overload stubs give static tools precise call shapes: integer in, integer out; string in, string out.\n\n```python\nfrom typing import overload\n\n@overload\ndef double(value: int) -> int: ...\n\n@overload\ndef double(value: str) -> str: ...\n\nprint("static signatures only")\n```\n\n```output\nstatic signatures only\n```\n:::\n\n:::cell\nThere is still one runtime implementation. It must accept every shape promised by the overloads.\n\n```python\ndef double(value: int | str) -> int | str:\n return value * 2\n\nprint(double(4))\nprint(double("ha"))\n```\n\n```output\n8\nhaha\n```\n:::\n\n:::cell\nOnly the implementation\'s annotations are visible on the runtime function. The overload declarations were for the type checker.\n\n```python\nprint(double.__annotations__)\n```\n\n```output\n{\'value\': int | str, \'return\': int | str}\n```\n:::\n\n:::note\n- Put `@overload` declarations immediately before the implementation.\n- Overloads improve static precision; they do not create runtime dispatch.\n- If all callers can work with one broad return type, a simple union annotation is usually enough.\n:::\n', 'packages.md': '+++\nslug = "packages"\ntitle = "Packages"\nsection = "Modules"\nsummary = "Packages organize modules into importable directories."\ndoc_path = "/tutorial/modules.html#packages"\nsee_also = [\n "modules",\n "import-aliases",\n "virtual-environments",\n]\n+++\n\nPackages are modules that can contain other modules. They let a project group related code behind dotted import paths such as `json.decoder` or `email.message`.\n\nAt runtime, importing a submodule gives Python a path through that package structure. In a project on disk, that structure is usually a directory with Python files and often an `__init__.py` file.\n\nUse packages when one module has grown into a small namespace of related modules. Keep module names boring and explicit so readers can tell where imported definitions come from.\n\n:::program\n```python\nimport importlib\nimport json\nimport json.decoder\n\nmodule = importlib.import_module("json.decoder")\n\nprint(json.__name__)\nprint(json.decoder.__name__)\nprint(module.JSONDecoder.__name__)\nprint(module is json.decoder)\n\n\nimport os\nimport sys\nimport tempfile\n\nwith tempfile.TemporaryDirectory() as tmp:\n pkg = os.path.join(tmp, "shapes")\n os.makedirs(pkg)\n with open(os.path.join(pkg, "__init__.py"), "w") as init:\n init.write("from .square import area\\n__all__ = [\'area\']\\n")\n with open(os.path.join(pkg, "square.py"), "w") as square:\n square.write("def area(side):\\n return side * side\\n")\n sys.path.insert(0, tmp)\n try:\n import shapes\n print(shapes.area(3))\n print(shapes.__all__)\n finally:\n sys.path.remove(tmp)\n sys.modules.pop("shapes", None)\n sys.modules.pop("shapes.square", None)\n```\n:::\n\n:::cell\nA package is itself a module. The `json` package exposes a namespace that can contain submodules.\n\n```python\nimport json\n\nprint(json.__name__)\n```\n\n```output\njson\n```\n:::\n\n:::cell\nDotted imports name a path through a package. Importing `json.decoder` makes that submodule available under the package namespace.\n\n```python\nimport json.decoder\n\nprint(json.decoder.__name__)\nprint(json.decoder.JSONDecoder.__name__)\n```\n\n```output\njson.decoder\nJSONDecoder\n```\n:::\n\n:::cell\n`importlib.import_module()` imports by string. It is useful for plugin systems and dynamic imports, but ordinary `import` is clearer when the dependency is known.\n\n```python\nimport importlib\n\nmodule = importlib.import_module("json.decoder")\nprint(module is json.decoder)\n```\n\n```output\nTrue\n```\n:::\n\n:::cell\nInside a package\'s `__init__.py`, `from .submodule import name` re-exports a submodule\'s name at the package root, and `__all__` lists the names that `from package import *` should make visible. This cell builds a temporary `shapes` package on disk to make both forms concrete.\n\n```python\nimport os\nimport sys\nimport tempfile\n\nwith tempfile.TemporaryDirectory() as tmp:\n pkg = os.path.join(tmp, "shapes")\n os.makedirs(pkg)\n with open(os.path.join(pkg, "__init__.py"), "w") as init:\n init.write("from .square import area\\n__all__ = [\'area\']\\n")\n with open(os.path.join(pkg, "square.py"), "w") as square:\n square.write("def area(side):\\n return side * side\\n")\n sys.path.insert(0, tmp)\n try:\n import shapes\n print(shapes.area(3))\n print(shapes.__all__)\n finally:\n sys.path.remove(tmp)\n sys.modules.pop("shapes", None)\n sys.modules.pop("shapes.square", None)\n```\n\n```output\n9\n[\'area\']\n```\n:::\n\n:::note\n- A package is a module that can contain submodules.\n- Dotted imports should mirror a meaningful project structure.\n- Use `from .submodule import name` inside a package to re-export submodule names; set `__all__` to declare the public surface.\n- Prefer ordinary imports unless the module name is truly dynamic.\n:::\n', 'paramspec.md': '+++\nslug = "paramspec"\ntitle = "ParamSpec"\nsection = "Types"\nsummary = "ParamSpec preserves callable parameter types through wrappers."\ndoc_path = "/library/typing.html#typing.ParamSpec"\nsee_also = [\n "callable-types",\n "decorators",\n "generics-and-typevar",\n]\n+++\n\n`ParamSpec` is for decorators and wrapper functions that should keep the wrapped callable\'s parameter shape. Without it, a generic decorator often falls back to `Callable[..., R]`, which says “this returns the right type, but I no longer know what arguments are valid.”\n\nUse `ParamSpec` when the wrapper forwards `*args` and `**kwargs` to the original function without changing the signature. Use a plain `Callable` when the wrapper deliberately accepts a different set of parameters.\n\n`P.args` and `P.kwargs` annotate the wrapper\'s forwarded arguments. A separate `TypeVar` keeps the return type tied to the wrapped function\'s return type.\n\n:::program\n```python\nfrom collections.abc import Callable\nfrom typing import ParamSpec, TypeVar\n\nP = ParamSpec("P")\nR = TypeVar("R")\n\n\ndef erased(func: Callable[..., R]) -> Callable[..., R]:\n return func\n\n\ndef logged(func: Callable[P, R]) -> Callable[P, R]:\n def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:\n print("calling", func.__name__)\n return func(*args, **kwargs)\n return wrapper\n\n@logged\ndef add(left: int, right: int) -> int:\n return left + right\n\nprint(erased(add)(2, 3))\nprint(add(2, 3))\n```\n:::\n\n:::cell\n`Callable[..., R]` is sometimes too broad. It preserves the return type, but the ellipsis means the callable accepts any argument list as far as the type checker can tell.\n\n```python\nfrom collections.abc import Callable\nfrom typing import ParamSpec, TypeVar\n\nR = TypeVar("R")\n\n\ndef erased(func: Callable[..., R]) -> Callable[..., R]:\n return func\n\nprint(erased.__name__)\n```\n\n```output\nerased\n```\n:::\n\n:::cell\n`ParamSpec` captures the original parameters and lets the wrapper forward exactly that shape.\n\n```python\nP = ParamSpec("P")\n\n\ndef logged(func: Callable[P, R]) -> Callable[P, R]:\n def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:\n print("calling", func.__name__)\n return func(*args, **kwargs)\n return wrapper\n\nprint(logged.__name__)\n```\n\n```output\nlogged\n```\n:::\n\n:::cell\nThe decorated function still runs normally. The benefit is static: tools can keep checking that `add` receives two integers.\n\n```python\n@logged\ndef add(left: int, right: int) -> int:\n return left + right\n\nprint(erased(add)(2, 3))\nprint(add(2, 3))\n```\n\n```output\ncalling add\n5\ncalling add\n5\n```\n:::\n\n:::note\n- `ParamSpec` preserves a callable\'s parameter list through transparent wrappers.\n- Pair `ParamSpec` with a `TypeVar` when the return type should also be preserved.\n- Python 3.12+ also accepts the inline PEP 695 spelling `def wrap[**P, R](func: Callable[P, R])`, which declares both variables in the signature itself.\n- If the wrapper changes the public signature, write that new signature directly instead.\n:::\n', 'partial-functions.md': '+++\nslug = "partial-functions"\ntitle = "Partial Functions"\nsection = "Functions"\nsummary = "functools.partial pre-fills arguments to make a more specific callable."\ndoc_path = "/library/functools.html#functools.partial"\nsee_also = [\n "functions",\n "args-and-kwargs",\n "callable-objects",\n]\n+++\n\n`functools.partial` turns a general callable into a more specific callable by remembering some positional or keyword arguments. It is useful when another API wants a one-argument callback but your underlying function needs more context.\n\nA partial object is still callable. It keeps the original function in `.func`, pre-filled positional arguments in `.args`, and pre-filled keyword arguments in `.keywords`.\n\nPrefer a named wrapper function when the adapted behavior needs branching, validation, or a docstring. Use `partial` when the adaptation is simply "call this function with these arguments already supplied."\n\n:::program\n```python\nfrom functools import partial\n\n\ndef apply_tax(rate, amount):\n return round(amount * (1 + rate), 2)\n\nvat = partial(apply_tax, 0.2)\nservice_tax = partial(apply_tax, rate=0.1)\n\nprint(apply_tax(0.2, 50))\nprint(vat(50))\nprint(service_tax(amount=80))\nprint(vat.func.__name__)\nprint(vat.args)\n```\n:::\n\n:::cell\nWithout `partial`, callers repeat the same fixed argument every time they want the specialized behavior.\n\n```python\ndef apply_tax(rate, amount):\n return round(amount * (1 + rate), 2)\n\nprint(apply_tax(0.2, 50))\n```\n\n```output\n60.0\n```\n:::\n\n:::cell\n`partial` stores that fixed argument and returns a callable shaped for the remaining arguments.\n\n```python\nfrom functools import partial\n\nvat = partial(apply_tax, 0.2)\nservice_tax = partial(apply_tax, rate=0.1)\n\nprint(vat(50))\nprint(service_tax(amount=80))\n```\n\n```output\n60.0\n88.0\n```\n:::\n\n:::cell\nPartial objects expose the function and stored arguments, which is helpful when debugging callback wiring.\n\n```python\nprint(vat.func.__name__)\nprint(vat.args)\n```\n\n```output\napply_tax\n(0.2,)\n```\n:::\n\n:::note\n- `partial` adapts a callable by pre-filling arguments.\n- The resulting object can be passed anywhere a callable with the remaining parameters is expected.\n- Use a regular function when the adapter needs more logic than argument binding.\n:::\n', 'positional-only-parameters.md': '+++\nslug = "positional-only-parameters"\ntitle = "Positional-only Parameters"\nsection = "Functions"\nsummary = "Use / to mark parameters that callers must pass by position."\ndoc_path = "/tutorial/controlflow.html#special-parameters"\nsee_also = [\n "keyword-only-arguments",\n "functions",\n "args-and-kwargs",\n]\n+++\n\nA `/` in a function signature marks the parameters before it as positional-only. Callers must pass those arguments by position, not by keyword.\n\nThis is useful when parameter names are implementation details or when an API should match built-in functions that accept positional values.\n\nTogether, `/` and `*` let a signature draw clear boundaries: positional-only inputs, ordinary inputs, and keyword-only options.\n\n:::program\n```python\ndef scale(value, /, factor=2, *, clamp=False):\n result = value * factor\n if clamp:\n result = min(result, 10)\n return result\n\nprint(scale(4))\nprint(scale(4, factor=3))\nprint(scale(4, factor=3, clamp=True))\n\ntry:\n scale(value=4)\nexcept TypeError as error:\n print(type(error).__name__)\n```\n:::\n\n:::cell\nParameters before `/` are positional-only. `value` is the main input, while `factor` remains an ordinary parameter that can be named.\n\n```python\ndef scale(value, /, factor=2, *, clamp=False):\n result = value * factor\n if clamp:\n result = min(result, 10)\n return result\n\nprint(scale(4))\nprint(scale(4, factor=3))\n```\n\n```output\n8\n12\n```\n:::\n\n:::cell\nParameters after `*` are keyword-only. That makes options such as `clamp` explicit at the call site — here `4 * 3` would be `12`, and the clamp visibly caps the result at `10`.\n\n```python\nprint(scale(4, factor=3, clamp=True))\n```\n\n```output\n10\n```\n:::\n\n:::cell\nThe restriction is enforced, not advisory: passing the positional-only `value` by keyword raises `TypeError` at the call site.\n\n```python\ntry:\n scale(value=4)\nexcept TypeError as error:\n print(type(error).__name__)\n```\n\n```output\nTypeError\n```\n:::\n\n:::note\n- `/` marks parameters before it as positional-only.\n- `*` marks parameters after it as keyword-only.\n- Use these markers when the call shape is part of the API design.\n:::\n', 'properties.md': '+++\nslug = "properties"\ntitle = "Properties"\nsection = "Classes"\nsummary = "@property keeps attribute syntax while adding computation or validation."\ndoc_path = "/library/functions.html#property"\nsee_also = [\n "classes",\n "attribute-access",\n "descriptors",\n "dataclasses",\n]\n+++\n\nProperties let a class keep a simple attribute-style API while running code behind the scenes. Callers write `box.area`, but the class can compute the value from current state.\n\nA property setter can validate assignment without changing the public spelling of the attribute. This is the boundary: plain attributes are enough for plain data, while properties are for computed or protected data.\n\nUse properties for cheap, attribute-like operations. Expensive work or actions with side effects should usually remain explicit methods.\n\n:::program\n```python\nclass Rectangle:\n def __init__(self, width, height):\n self.width = width\n self.height = height\n\n @property\n def area(self):\n return self.width * self.height\n\n @property\n def width(self):\n return self._width\n\n @width.setter\n def width(self, value):\n if value <= 0:\n raise ValueError("width must be positive")\n self._width = value\n\nbox = Rectangle(3, 4)\nprint(box.area)\n\nbox.width = 5\nprint(box.area)\n\ntry:\n box.width = 0\nexcept ValueError as error:\n print(error)\n```\n:::\n\n:::cell\nA read-only property exposes computed data through attribute access. `area` stays current because it is calculated from `width` and `height` each time it is read.\n\n```python\nclass Rectangle:\n def __init__(self, width, height):\n self.width = width\n self.height = height\n\n @property\n def area(self):\n return self.width * self.height\n\n @property\n def width(self):\n return self._width\n\n @width.setter\n def width(self, value):\n if value <= 0:\n raise ValueError("width must be positive")\n self._width = value\n\nbox = Rectangle(3, 4)\nprint(box.area)\n```\n\n```output\n12\n```\n:::\n\n:::cell\nA setter lets assignment keep normal attribute syntax while the class validates or normalizes the value.\n\n```python\nbox.width = 5\nprint(box.area)\n```\n\n```output\n20\n```\n:::\n\n:::cell\nValidation belongs inside the class when every caller should obey the same rule. Invalid assignment raises an exception at the boundary.\n\n```python\ntry:\n box.width = 0\nexcept ValueError as error:\n print(error)\n```\n\n```output\nwidth must be positive\n```\n:::\n\n:::note\n- Properties let APIs start simple and grow validation or computation later.\n- Callers access a property like an attribute, not like a method.\n- Use methods instead when work is expensive or action-like.\n:::\n', 'protocols.md': '+++\nslug = "protocols"\ntitle = "Protocols"\nsection = "Types"\nsummary = "Protocol describes required behavior for structural typing."\ndoc_path = "/library/typing.html#typing.Protocol"\nsee_also = [\n "type-hints",\n "classes",\n "inheritance-and-super",\n "abstract-base-classes",\n]\n+++\n\n`Protocol` describes the methods or attributes an object must provide. It exists for structural typing: if an object has the right shape, type checkers can treat it as compatible.\n\nThis is different from inheritance. Inheritance says a class is explicitly derived from a parent; a protocol says callers only need a particular behavior.\n\nAt runtime, ordinary method lookup still applies. Protocols are mainly for static analysis, documentation, and API boundaries.\n\n:::program\n```python\nfrom typing import Protocol\n\nclass Greeter(Protocol):\n def greet(self) -> str:\n ...\n\nclass Person:\n def __init__(self, name):\n self.name = name\n\n def greet(self):\n return f"hello {self.name}"\n\n\ndef welcome(greeter: Greeter):\n print(greeter.greet())\n\nwelcome(Person("Ada"))\nprint(Greeter.__name__)\n```\n:::\n\n:::cell\nA protocol names required behavior. The ellipsis marks the method body as intentionally unspecified, similar to an interface declaration.\n\n```python\nfrom typing import Protocol\n\nclass Greeter(Protocol):\n def greet(self) -> str:\n ...\n\nprint(Greeter.__name__)\n```\n\n```output\nGreeter\n```\n:::\n\n:::cell\nA class can satisfy the protocol without inheriting from it. `Person` has a compatible `greet()` method, so it has the right shape for static type checkers.\n\n```python\nclass Person:\n def __init__(self, name):\n self.name = name\n\n def greet(self):\n return f"hello {self.name}"\n\nprint(Person("Ada").greet())\n```\n\n```output\nhello Ada\n```\n:::\n\n:::cell\nUse the protocol as an annotation at the API boundary. The function only cares that the object can greet; it does not care about the concrete class.\n\n```python\ndef welcome(greeter: Greeter):\n print(greeter.greet())\n\nwelcome(Person("Ada"))\n```\n\n```output\nhello Ada\n```\n:::\n\n:::note\n- Protocols are for structural typing: compatibility by shape rather than explicit inheritance.\n- Type checkers understand protocols; normal runtime method calls still do the work.\n- Prefer inheritance when shared implementation matters, and protocols when only required behavior matters.\n:::\n', 'recursion.md': '+++\nslug = "recursion"\ntitle = "Recursion"\nsection = "Functions"\nsummary = "Recursive functions solve nested problems by calling themselves on smaller pieces."\ndoc_path = "/tutorial/controlflow.html#defining-functions"\nsee_also = [\n "functions",\n "conditionals",\n "generators",\n]\n+++\n\nA recursive function calls itself to solve a smaller piece of the same problem. Recursion exists for data that is naturally nested: trees, menus, expression nodes, and directory-like structures.\n\nEvery recursive function needs a base case that can be answered directly. The recursive case must move toward that base case by passing a smaller part of the data.\n\nPrefer loops for simple repetition over a flat sequence. Prefer recursion when the data shape is recursive too.\n\n:::program\n```python\ntree = {\n "value": 1,\n "children": [\n {"value": 2, "children": []},\n {"value": 3, "children": [{"value": 4, "children": []}]},\n ],\n}\n\ndef total(node):\n subtotal = node["value"]\n for child in node["children"]:\n subtotal += total(child)\n return subtotal\n\nprint(total({"value": 2, "children": []}))\nprint(total(tree))\n```\n:::\n\n:::cell\nA leaf node is the base case. It has no children, so the function can return its own value without making another recursive call.\n\n```python\ndef total(node):\n subtotal = node["value"]\n for child in node["children"]:\n subtotal += total(child)\n return subtotal\n\nprint(total({"value": 2, "children": []}))\n```\n\n```output\n2\n```\n:::\n\n:::cell\nA non-leaf node solves the same problem for each child, then combines those smaller totals with its own value.\n\n```python\ntree = {\n "value": 1,\n "children": [\n {"value": 2, "children": []},\n {"value": 3, "children": [{"value": 4, "children": []}]},\n ],\n}\n\nprint(total(tree))\n```\n\n```output\n10\n```\n:::\n\n:::note\n- Every recursive function needs a base case that stops the calls.\n- Recursion fits nested data better than flat repetition.\n- Python limits recursion depth, so loops are often better for very deep or simple repetition.\n:::\n', 'regular-expressions.md': '+++\nslug = "regular-expressions"\ntitle = "Regular Expressions"\nsection = "Text"\nsummary = "The re module searches and extracts text using regular expressions."\ndoc_path = "/library/re.html"\nsee_also = [\n "strings",\n "string-formatting",\n]\n+++\n\nRegular expressions are a compact language for searching and extracting text patterns. Python\'s `re` module provides the standard interface: `re.match` anchors at the start of the string, `re.search` finds the first occurrence anywhere, `re.findall` collects every match, `re.sub` rewrites matches, and `re.compile` reuses a pattern.\n\nUse regex when the pattern has structure: repeated records, alternatives, optional parts, or pieces you want to capture. Prefer ordinary string methods for simple substring checks because simpler code is easier to maintain.\n\nFlags such as `re.IGNORECASE` adjust matching behavior without rewriting the pattern. Pair them with `re.compile` when the same pattern is used repeatedly.\n\n:::program\n```python\nimport re\n\ntext = "Ada: 10, Grace: 9"\npattern = r"([A-Za-z]+): (\\d+)"\n\nfor name, score in re.findall(pattern, text):\n print(name, int(score))\n\nmatch = re.search(r"Grace: (\\d+)", text)\nprint(match.group(1))\nprint("Grace" in text)\n\nstart = re.match(r"Ada", text)\nprint(start is not None)\nprint(re.match(r"Grace", text))\n\nscoreline = re.compile(pattern)\nprint(scoreline.findall(text))\n\ncasey = "ADA: 11"\nprint(re.search(r"ada", casey, flags=re.IGNORECASE).group(0))\n\nprint(re.sub(r"\\d+", "?", text))\n```\n:::\n\n:::cell\nRaw strings keep backslashes readable in regex patterns. Capturing groups return just the pieces inside parentheses.\n\n```python\nimport re\n\ntext = "Ada: 10, Grace: 9"\npattern = r"([A-Za-z]+): (\\d+)"\n\nfor name, score in re.findall(pattern, text):\n print(name, int(score))\n```\n\n```output\nAda 10\nGrace 9\n```\n:::\n\n:::cell\n`re.search()` finds the first match. A match object exposes captured groups by position.\n\n```python\nmatch = re.search(r"Grace: (\\d+)", text)\nprint(match.group(1))\n```\n\n```output\n9\n```\n:::\n\n:::cell\nFor a simple substring check, ordinary string membership is clearer than regex.\n\n```python\nprint("Grace" in text)\n```\n\n```output\nTrue\n```\n:::\n\n:::cell\n`re.match` only matches at the start of the string; `re.search` finds the first match anywhere. Picking the right one keeps anchoring intent visible without an explicit `^`.\n\n```python\nstart = re.match(r"Ada", text)\nprint(start is not None)\nprint(re.match(r"Grace", text))\n```\n\n```output\nTrue\nNone\n```\n:::\n\n:::cell\n`re.compile` produces a reusable pattern object and gives the pattern a name. The `re` module also caches recently compiled patterns internally, so the practical wins are readability and a place to attach flags more than raw speed.\n\n```python\nscoreline = re.compile(pattern)\nprint(scoreline.findall(text))\n```\n\n```output\n[(\'Ada\', \'10\'), (\'Grace\', \'9\')]\n```\n:::\n\n:::cell\nFlags such as `re.IGNORECASE` adjust matching without changing the pattern. `re.sub` replaces every match with a replacement string and returns the rewritten text.\n\n```python\ncasey = "ADA: 11"\nprint(re.search(r"ada", casey, flags=re.IGNORECASE).group(0))\n\nprint(re.sub(r"\\d+", "?", text))\n```\n\n```output\nADA\nAda: ?, Grace: ?\n```\n:::\n\n:::note\n- Use raw strings for regex patterns so backslashes are easier to read.\n- Use capturing groups when the point is extraction, not just matching.\n- `re.match` anchors at the start; `re.search` finds the first match anywhere.\n- `re.compile` saves work when the pattern runs more than once.\n- `re.sub` rewrites matches; flags like `re.IGNORECASE` change matching behavior without rewriting the pattern.\n- Reach for string methods before regex when the pattern is simple.\n:::\n', 'runtime-type-checks.md': '+++\nslug = "runtime-type-checks"\ntitle = "Runtime Type Checks"\nsection = "Types"\nsummary = "type, isinstance, and issubclass inspect runtime relationships."\ndoc_path = "/library/functions.html#isinstance"\nsee_also = [\n "type-hints",\n "protocols",\n "casts-and-any",\n "abstract-base-classes",\n]\n+++\n\nRuntime type checks inspect real objects while the program is running. They are different from type hints, which mostly guide tools before the program runs.\n\nUse `type()` when the exact class matters, `isinstance()` when subclasses should count, and `issubclass()` when checking class relationships. Most APIs prefer behavior over type checks, but runtime checks are useful at input boundaries.\n\nDo not turn every function into a wall of `isinstance()` calls. If the code only needs an object that can perform an operation, duck typing or a protocol may be clearer.\n\n:::program\n```python\nclass Animal:\n pass\n\nclass Dog(Animal):\n pass\n\npet = Dog()\n\nprint(type(pet).__name__)\nprint(type(pet) is Animal)\nprint(isinstance(pet, Animal))\nprint(issubclass(Dog, Animal))\n```\n:::\n\n:::cell\n`type()` reports the exact runtime class. A `Dog` instance is not exactly an `Animal` instance.\n\n```python\nclass Animal:\n pass\n\nclass Dog(Animal):\n pass\n\npet = Dog()\nprint(type(pet).__name__)\nprint(type(pet) is Animal)\n```\n\n```output\nDog\nFalse\n```\n:::\n\n:::cell\n`isinstance()` accepts subclasses, which is usually what API boundaries want.\n\n```python\nprint(isinstance(pet, Dog))\nprint(isinstance(pet, Animal))\n```\n\n```output\nTrue\nTrue\n```\n:::\n\n:::cell\n`issubclass()` checks class relationships rather than individual objects.\n\n```python\nprint(issubclass(Dog, Animal))\n```\n\n```output\nTrue\n```\n:::\n\n:::note\n- `type()` is exact; `isinstance()` follows inheritance.\n- Runtime checks inspect objects, not static annotations.\n- Prefer behavior, protocols, or clear validation over scattered type checks.\n:::\n', 'scope-global-nonlocal.md': '+++\nslug = "scope-global-nonlocal"\ntitle = "Global and Nonlocal"\nsection = "Functions"\nsummary = "global and nonlocal choose which outer binding assignment should update."\ndoc_path = "/reference/simple_stmts.html#the-global-statement"\nsee_also = [\n "variables",\n "closures",\n "functions",\n]\n+++\n\nAssignment normally creates or updates a local name inside the current function. `global` and `nonlocal` are explicit escape hatches for rebinding names outside that local scope.\n\nUse `nonlocal` when an inner function should update a name in an enclosing function. Use `global` rarely; passing values and returning results is usually clearer.\n\nThese statements affect name binding, not object mutation. Mutating a shared list is different from rebinding the name itself.\n\n:::program\n```python\ncount = 0\n\ndef bump_global():\n global count\n count += 1\n\nbump_global()\nprint(count)\n\n\ndef make_counter():\n total = 0\n def bump():\n nonlocal total\n total += 1\n return total\n return bump\n\ncounter = make_counter()\nprint(counter())\nprint(counter())\n```\n:::\n\n:::cell\n`global` tells assignment to update a module-level binding. Without it, `count += 1` would try to assign a local `count`.\n\n```python\ncount = 0\n\ndef bump_global():\n global count\n count += 1\n\nbump_global()\nprint(count)\n```\n\n```output\n1\n```\n:::\n\n:::cell\n`nonlocal` tells assignment to update a binding in the nearest enclosing function scope. This is useful for small closures that keep state.\n\n```python\ndef make_counter():\n total = 0\n def bump():\n nonlocal total\n total += 1\n return total\n return bump\n\ncounter = make_counter()\nprint(counter())\nprint(counter())\n```\n\n```output\n1\n2\n```\n:::\n\n:::note\n- Assignment inside a function is local unless declared otherwise.\n- Prefer `nonlocal` for closure state and avoid `global` unless module state is truly intended.\n- Passing values and returning results is usually easier to test than rebinding outer names.\n:::\n', 'sentinel-iteration.md': '+++\nslug = "sentinel-iteration"\ntitle = "Sentinel Iteration"\nsection = "Iteration"\nsummary = "iter(callable, sentinel) repeats calls until a marker value appears."\ndoc_path = "/library/functions.html#iter"\nsee_also = [\n "iterators",\n "while-loops",\n "break-and-continue",\n]\n+++\n\n`iter(callable, sentinel)` calls a zero-argument callable over and over. It yields each result until the callable returns the sentinel value, and the sentinel itself is not yielded.\n\nThis shape is useful for repeated reads: file blocks until `b""`, socket chunks until an empty response, queue items until a stop marker. It removes the common `while True` plus `break` scaffolding when the loop body is otherwise just "read, then process".\n\nThe callable must take no arguments. A method taken from an object, such as `queue.popleft`, already fits. Wrap a parameterized reader in a `lambda` or `functools.partial` when the underlying API needs parameters.\n\n:::program\n```python\nfrom collections import deque\n\nqueue = deque(["py", "thon", "", "ignored"])\nprint(list(iter(queue.popleft, "")))\nprint(queue)\n\nqueue = deque(["py", "thon", "", "ignored"])\nword = ""\nwhile True:\n chunk = queue.popleft()\n if chunk == "":\n break\n word += chunk\nprint(word)\n```\n:::\n\n:::cell\nThe two-argument form turns a polling callable into an iterator. `queue.popleft` (no parentheses) is a zero-argument callable that removes and returns the next queued item each time it is called. The empty string stops the loop without appearing in the result, and anything queued after the sentinel is left unread.\n\n```python\nfrom collections import deque\n\nqueue = deque(["py", "thon", "", "ignored"])\nprint(list(iter(queue.popleft, "")))\nprint(queue)\n```\n\n```output\n[\'py\', \'thon\']\ndeque([\'ignored\'])\n```\n:::\n\n:::cell\nThe equivalent manual loop needs an explicit read, comparison, and `break`. Use this shape when the stop condition is more complicated than a single sentinel value.\n\n```python\nqueue = deque(["py", "thon", "", "ignored"])\nword = ""\nwhile True:\n chunk = queue.popleft()\n if chunk == "":\n break\n word += chunk\nprint(word)\n```\n\n```output\npython\n```\n:::\n\n:::note\n- The callable passed to `iter(callable, sentinel)` must take no arguments.\n- The sentinel stops iteration and is not yielded.\n- When the loop needs richer branching, an explicit `while` loop may be clearer.\n:::\n', 'sets.md': '+++\nslug = "sets"\ntitle = "Sets"\nsection = "Collections"\nsummary = "Sets store unique values and make membership checks explicit."\ndoc_path = "/tutorial/datastructures.html#sets"\nsee_also = [\n "lists",\n "dicts",\n "comprehensions",\n]\n+++\n\nSets store unique hashable values. Use them when membership and de-duplication matter more than order.\n\nA list can answer membership with `in`, but a set communicates that membership is the main operation. Set algebra then expresses how groups relate to each other.\n\nBecause sets are unordered, examples often wrap output in `sorted()` so the display is deterministic.\n\n:::program\n```python\nlanguages = ["python", "go", "python"]\nunique_languages = set(languages)\nprint(sorted(unique_languages))\n\nallowed = {"python", "rust"}\nprint("python" in allowed)\nprint("ruby" in allowed)\n\ncompiled = {"go", "rust"}\nprint(sorted(allowed | compiled))\nprint(sorted(allowed & compiled))\nprint(sorted(allowed - compiled))\n```\n:::\n\n:::cell\nCreating a set removes duplicates. Keep a list when order and repeated values matter; convert to a set when uniqueness is the point.\n\n```python\nlanguages = ["python", "go", "python"]\nunique_languages = set(languages)\nprint(sorted(unique_languages))\n```\n\n```output\n[\'go\', \'python\']\n```\n:::\n\n:::cell\nMembership checks are the everyday set operation. A list can also use `in`, but a set says that membership is central to the data shape.\n\n```python\nallowed = {"python", "rust"}\nprint("python" in allowed)\nprint("ruby" in allowed)\n```\n\n```output\nTrue\nFalse\n```\n:::\n\n:::cell\nUnion, intersection, and difference describe relationships between groups without manual loops.\n\n```python\ncompiled = {"go", "rust"}\nprint(sorted(allowed | compiled))\nprint(sorted(allowed & compiled))\nprint(sorted(allowed - compiled))\n```\n\n```output\n[\'go\', \'python\', \'rust\']\n[\'rust\']\n[\'python\']\n```\n:::\n\n:::note\n- Use sets when uniqueness and membership are the main operations.\n- Prefer lists when order or repeated values are part of the meaning.\n- Sets are unordered, so sort them when examples need deterministic display.\n:::\n', 'slices.md': '+++\nslug = "slices"\ntitle = "Slices"\nsection = "Collections"\nsummary = "Slices copy meaningful ranges from ordered sequences."\ndoc_path = "/tutorial/introduction.html#lists"\nsee_also = [\n "lists",\n "tuples",\n "strings",\n]\n+++\n\nSlicing reads a range from an ordered sequence with `start:stop:step`. It exists because Python code often needs a meaningful piece of a sequence: a page, a prefix, a tail, a stride, or a reversed view.\n\nThe stop index is excluded. That convention makes lengths and adjacent ranges line up: `items[:3]` and `items[3:]` split a sequence without overlap.\n\nSlices return new sequence objects for built-in lists and strings. Use indexing for one item; use slicing when the result should still be a sequence.\n\n:::program\n```python\nletters = ["a", "b", "c", "d", "e", "f"]\nfirst_page = letters[:3]\nrest = letters[3:]\nprint(first_page)\nprint(rest)\n\nmiddle = letters[1:5]\nevery_other = letters[::2]\nreversed_letters = letters[::-1]\nprint(middle)\nprint(every_other)\nprint(reversed_letters)\nprint(letters)\n```\n:::\n\n:::cell\nOmitted bounds mean “from the beginning” or “through the end.” Because the stop index is excluded, adjacent slices split a sequence cleanly.\n\n```python\nletters = ["a", "b", "c", "d", "e", "f"]\nfirst_page = letters[:3]\nrest = letters[3:]\nprint(first_page)\nprint(rest)\n```\n\n```output\n[\'a\', \'b\', \'c\']\n[\'d\', \'e\', \'f\']\n```\n:::\n\n:::cell\nUse `start:stop` for a middle range and `step` when you want to skip or walk backward. These operations return new lists; the original list is unchanged.\n\n```python\nmiddle = letters[1:5]\nevery_other = letters[::2]\nreversed_letters = letters[::-1]\nprint(middle)\nprint(every_other)\nprint(reversed_letters)\nprint(letters)\n```\n\n```output\n[\'b\', \'c\', \'d\', \'e\']\n[\'a\', \'c\', \'e\']\n[\'f\', \'e\', \'d\', \'c\', \'b\', \'a\']\n[\'a\', \'b\', \'c\', \'d\', \'e\', \'f\']\n```\n:::\n\n:::note\n- Slice stop indexes are excluded, so adjacent ranges compose cleanly.\n- Omitted bounds mean the beginning or end of the sequence.\n- A negative step walks backward; `[::-1]` is a common reversed-copy idiom.\n:::\n', 'sorting.md': '+++\nslug = "sorting"\ntitle = "Sorting"\nsection = "Collections"\nsummary = "sorted returns a new ordered list and key functions choose the sort value."\ndoc_path = "/howto/sorting.html"\nsee_also = [\n "lists",\n "lambdas",\n "functions",\n]\n+++\n\n`sorted()` accepts any iterable and returns a new list. The original collection is left untouched, which makes `sorted()` useful in expressions and pipelines.\n\nUse `key=` to say what value should be compared for each item. This is the idiomatic way to sort records, tuples, dictionaries, and objects by a field.\n\nUse `reverse=True` for descending order. Use `list.sort()` instead when you intentionally want to mutate an existing list in place.\n\n:::program\n```python\nnames = ["Guido", "Ada", "Grace"]\nprint(sorted(names))\nprint(names)\n\nusers = [\n {"name": "Ada", "score": 10},\n {"name": "Guido", "score": 8},\n {"name": "Grace", "score": 10},\n]\nranked = sorted(users, key=lambda user: user["score"], reverse=True)\nprint([user["name"] for user in ranked])\n\nusers.sort(key=lambda user: user["name"])\nprint([user["name"] for user in users])\n```\n:::\n\n:::cell\n`sorted()` returns a new list. Printing the original list afterward shows that the input order did not change.\n\n```python\nnames = ["Guido", "Ada", "Grace"]\nprint(sorted(names))\nprint(names)\n```\n\n```output\n[\'Ada\', \'Grace\', \'Guido\']\n[\'Guido\', \'Ada\', \'Grace\']\n```\n:::\n\n:::cell\nA key function computes the value to compare. The `lambda user: user["score"]` expression is a small unnamed function that takes one record and returns its score ([lambdas](/examples/lambdas) covers the form). Here the records are sorted by score, highest first, and the output shows the resulting order.\n\n```python\nusers = [\n {"name": "Ada", "score": 10},\n {"name": "Guido", "score": 8},\n {"name": "Grace", "score": 10},\n]\nranked = sorted(users, key=lambda user: user["score"], reverse=True)\nprint([user["name"] for user in ranked])\n```\n\n```output\n[\'Ada\', \'Grace\', \'Guido\']\n```\n:::\n\n:::cell\n`list.sort()` sorts the list in place. Use it when mutation is the point and no separate sorted copy is needed.\n\n```python\nusers.sort(key=lambda user: user["name"])\nprint([user["name"] for user in users])\n```\n\n```output\n[\'Ada\', \'Grace\', \'Guido\']\n```\n:::\n\n:::note\n- `sorted()` makes a new list; `list.sort()` mutates an existing list.\n- `key=` should return the value Python compares for each item.\n- Python\'s sort is stable, so equal keys keep their original relative order.\n:::\n', 'special-methods.md': '+++\nslug = "special-methods"\ntitle = "Special Methods"\nsection = "Data Model"\nsummary = "Special methods connect your objects to Python syntax and built-ins."\ndoc_path = "/reference/datamodel.html#special-method-names"\nsee_also = [\n "container-protocols",\n "operator-overloading",\n "callable-objects",\n "context-managers",\n]\n+++\n\nSpecial methods, often called dunder methods, connect user-defined classes to Python syntax and built-ins such as len(), iter(), and repr().\n\nImplementing these methods lets your objects participate in Python protocols rather than forcing callers to learn custom method names for common operations.\n\nGood special methods make objects feel boring in the best way: they work with the language features Python programmers already know.\n\n:::program\n```python\nclass Bag:\n def __init__(self, items):\n self.items = list(items)\n\n def __len__(self):\n return len(self.items)\n\n def __iter__(self):\n return iter(self.items)\n\n def __repr__(self):\n return f"Bag({self.items!r})"\n\n def __str__(self):\n return ", ".join(self.items)\n\n def __eq__(self, other):\n return isinstance(other, Bag) and self.items == other.items\n\n def __hash__(self):\n return hash(tuple(self.items))\n\n def __lt__(self, other):\n return self.items < other.items\n\n def __contains__(self, item):\n return item in self.items\n\n def __getitem__(self, index):\n return self.items[index]\n\n def __setitem__(self, index, value):\n self.items[index] = value\n\n def __bool__(self):\n return bool(self.items)\n\nbag = Bag(["a", "b"])\nprint(len(bag))\nprint(list(bag))\nprint(bag)\nprint(repr(bag))\nprint(Bag(["a", "b"]) == Bag(["a", "b"]))\nprint(Bag(["a"]) < Bag(["a", "b"]))\nprint(hash(Bag(["a"])) == hash(Bag(["a"])))\nprint("a" in bag)\nprint(bag[0])\nbag[1] = "z"\nprint(list(bag))\nprint(bool(Bag([])))\n\n\nclass Multiplier:\n def __init__(self, factor):\n self.factor = factor\n\n def __call__(self, value):\n return value * self.factor\n\ntriple = Multiplier(3)\nprint(triple(5))\n\n\nclass Trace:\n def __enter__(self):\n print("enter")\n return self\n\n def __exit__(self, *exc):\n print("exit")\n return False\n\nwith Trace():\n print("inside")\n```\n:::\n\n:::cell\nStart with a normal class that stores its data. Special methods build on ordinary instance state.\n\n```python\nclass Bag:\n def __init__(self, items):\n self.items = list(items)\n\nbag = Bag(["a", "b"])\nprint(bag.items)\n```\n\n```output\n[\'a\', \'b\']\n```\n:::\n\n:::cell\nImplement `__len__` to let `len()` ask the object for its size using Python\'s standard protocol.\n\n```python\nclass Bag:\n def __init__(self, items):\n self.items = list(items)\n\n def __len__(self):\n return len(self.items)\n\nbag = Bag(["a", "b"])\nprint(len(bag))\n```\n\n```output\n2\n```\n:::\n\n:::cell\nImplement `__iter__` to make the object iterable. Then tools such as `list()` can consume it without a custom method name.\n\n```python\nclass Bag:\n def __init__(self, items):\n self.items = list(items)\n\n def __len__(self):\n return len(self.items)\n\n def __iter__(self):\n return iter(self.items)\n\nbag = Bag(["a", "b"])\nprint(list(bag))\n```\n\n```output\n[\'a\', \'b\']\n```\n:::\n\n:::cell\nImplement `__repr__` to give the object a useful developer-facing representation when it is printed or inspected. With no `__str__` defined, `print()` falls back to `__repr__`.\n\n```python\nclass Bag:\n def __init__(self, items):\n self.items = list(items)\n\n def __len__(self):\n return len(self.items)\n\n def __iter__(self):\n return iter(self.items)\n\n def __repr__(self):\n return f"Bag({self.items!r})"\n\nbag = Bag(["a", "b"])\nprint(bag)\n```\n\n```output\nBag([\'a\', \'b\'])\n```\n:::\n\n:::cell\nAdd `__str__` for an end-user representation. `print()` and `str()` prefer `__str__`; `repr()` and the REPL still use `__repr__`. Keep `__repr__` unambiguous for debugging and let `__str__` be the friendly form.\n\n```python\nclass Bag:\n def __init__(self, items):\n self.items = list(items)\n\n def __repr__(self):\n return f"Bag({self.items!r})"\n\n def __str__(self):\n return ", ".join(self.items)\n\nbag = Bag(["a", "b"])\nprint(bag)\nprint(repr(bag))\n```\n\n```output\na, b\nBag([\'a\', \'b\'])\n```\n:::\n\n:::cell\n`__eq__` decides what equality means for the type, comparing contents. `__lt__` orders by those same contents, so ordering stays consistent with equality (define one comparison and `functools.total_ordering` can fill in the rest; `__lt__` alone is enough for `<` and `sorted()`). Defining `__eq__` removes the default `__hash__`, so add it back only for types you treat as immutable: this `Bag` hashes its current items, so the last two lines show the hazard — a `Bag` found in a set becomes unfindable once its items change, because its hash no longer points at the bucket it was stored in.\n\n```python\nclass Bag:\n def __init__(self, items):\n self.items = list(items)\n\n def __eq__(self, other):\n return isinstance(other, Bag) and self.items == other.items\n\n def __hash__(self):\n return hash(tuple(self.items))\n\n def __lt__(self, other):\n return self.items < other.items\n\nprint(Bag(["a", "b"]) == Bag(["a", "b"]))\nprint(Bag(["a"]) < Bag(["a", "b"]))\n\nbag = Bag(["a"])\nseen = {bag}\nprint(bag in seen)\nbag.items.append("b")\nprint(bag in seen)\n```\n\n```output\nTrue\nTrue\nTrue\nFalse\n```\n:::\n\n:::cell\nThe container protocols make instances behave like built-in containers. `__contains__` powers `in`, `__getitem__`/`__setitem__` power subscription, and `__bool__` decides truthiness for `if` and `while`. See [container-protocols](/examples/container-protocols) for the full surface.\n\n```python\nclass Bag:\n def __init__(self, items):\n self.items = list(items)\n\n def __contains__(self, item):\n return item in self.items\n\n def __getitem__(self, index):\n return self.items[index]\n\n def __setitem__(self, index, value):\n self.items[index] = value\n\n def __bool__(self):\n return bool(self.items)\n\nbag = Bag(["a", "b"])\nprint("a" in bag)\nprint(bag[0])\nbag[1] = "z"\nprint(bag.items)\nprint(bool(Bag([])))\n```\n\n```output\nTrue\na\n[\'a\', \'z\']\nFalse\n```\n:::\n\n:::cell\n`__call__` makes an instance callable like a function — useful for stateful operations whose configuration deserves a name. `__enter__` and `__exit__` make a class a context manager so it can be used with `with`. The focused [callable-objects](/examples/callable-objects) and [context-managers](/examples/context-managers) pages go deeper.\n\n```python\nclass Multiplier:\n def __init__(self, factor):\n self.factor = factor\n\n def __call__(self, value):\n return value * self.factor\n\ntriple = Multiplier(3)\nprint(triple(5))\n\n\nclass Trace:\n def __enter__(self):\n print("enter")\n return self\n\n def __exit__(self, *exc):\n print("exit")\n return False\n\nwith Trace():\n print("inside")\n```\n\n```output\n15\nenter\ninside\nexit\n```\n:::\n\n:::note\n- Dunder methods are looked up by Python\'s data model protocols.\n- `__repr__` is the developer-facing form; `__str__` is the user-facing form. `print()` falls back to `__repr__` when `__str__` is missing.\n- Defining `__eq__` removes the default `__hash__`; restore it when the type should be hashable.\n- Container protocols (`__contains__`, `__getitem__`, `__setitem__`, `__bool__`) make instances behave like built-in containers.\n- `__call__` makes instances callable; `__enter__`/`__exit__` make them context managers.\n- Implement the smallest protocol that makes your object feel native.\n:::\n', 'string-formatting.md': '+++\nslug = "string-formatting"\ntitle = "String Formatting"\nsection = "Text"\nsummary = "f-strings turn values into readable text at the point of use."\ndoc_path = "/tutorial/inputoutput.html#formatted-string-literals"\nsee_also = [\n "strings",\n "logging",\n "csv-data",\n "values",\n]\n+++\n\nFormatted string literals, or f-strings, exist because programs constantly need to turn values into human-readable text. They keep the expression next to the words it explains.\n\nFormat specifications after `:` control presentation details such as width, alignment, padding, and precision. This separates the value being computed from the way it should be displayed.\n\nUse f-strings for most new formatting code. They relate directly to expressions: anything inside braces is evaluated, then formatted into the surrounding string.\n\n:::program\n```python\nname = "Ada"\nscore = 9.5\nrank = 1\n\nmessage = f"{name} scored {score}"\nprint(message)\n\nrow = f"{rank:>2} | {name:<8} | {score:05.1f}"\nprint(row)\n\nprint(f"{score = }")\n```\n:::\n\n:::cell\nAn f-string evaluates expressions inside braces and inserts their string form into the surrounding text. This is clearer than joining several converted values by hand.\n\n```python\nname = "Ada"\nscore = 9.5\nrank = 1\n\nmessage = f"{name} scored {score}"\nprint(message)\n```\n\n```output\nAda scored 9.5\n```\n:::\n\n:::cell\nFormat specifications after `:` control display without changing the underlying values. Here the rank is right-aligned, the name is left-aligned, and `05.1f` zero-pads the score to a width of five characters with one decimal place.\n\n```python\nrow = f"{rank:>2} | {name:<8} | {score:05.1f}"\nprint(row)\n```\n\n```output\n 1 | Ada | 009.5\n```\n:::\n\n:::cell\nThe debug form with `=` is useful while learning or logging because it prints both the expression and the value.\n\n```python\nprint(f"{score = }")\n```\n\n```output\nscore = 9.5\n```\n:::\n\n:::note\n- Use `f"..."` strings for most new formatting code.\n- Expressions inside braces are evaluated before formatting.\n- Format specifications after `:` control alignment, width, padding, and precision.\n:::\n', 'strings.md': '+++\nslug = "strings"\ntitle = "Strings"\nsection = "Text"\nsummary = "Strings are immutable Unicode text sequences."\ndoc_path = "/library/stdtypes.html#text-sequence-type-str"\nsee_also = [\n "values",\n "string-formatting",\n "bytes-and-bytearray",\n "regular-expressions",\n]\n+++\n\nPython strings are immutable Unicode text sequences. A `str` stores text as Unicode code points, so it can represent English, Thai, accented letters, emoji, and ordinary ASCII with the same type.\n\nUnicode matters because text length and byte length are different questions. The English word `"hello"` uses five code points and five UTF-8 bytes because ASCII characters encode as one byte each. The Thai greeting `"สวัสดี"` has six code points but needs eighteen UTF-8 bytes.\n\nUse `str` when you mean text, and encode to `bytes` only at boundaries such as files, network protocols, and binary APIs. String operations such as `upper()` and `strip()` return new strings instead of changing the original.\n\n:::program\n```python\nenglish = "hello"\nfrench = "café"\nthai = "สวัสดี"\n\nprint("English", english, len(english), len(english.encode("utf-8")))\nprint("French", french, len(french), len(french.encode("utf-8")))\nprint("Thai", thai, len(thai), len(thai.encode("utf-8")))\n\nprint(thai[0])\nprint(hex(ord(thai[0])), hex(ord(thai[1])))\n\ntext = " café "\nclean = text.strip()\nprint(clean)\nprint(clean.upper())\nprint(clean.encode("utf-8"))\n```\n:::\n\n:::cell\nCompare three words by code-point count and UTF-8 byte count. ASCII characters take one byte each (`hello` → 5 bytes); the `é` in `café` is one code point but two UTF-8 bytes; each Thai character takes three. The `str` type abstracts over all three.\n\n```python\nenglish = "hello"\nfrench = "café"\nthai = "สวัสดี"\n\nprint("English", english, len(english), len(english.encode("utf-8")))\nprint("French", french, len(french), len(french.encode("utf-8")))\nprint("Thai", thai, len(thai), len(thai.encode("utf-8")))\n```\n\n```output\nEnglish hello 5 5\nFrench café 4 5\nThai สวัสดี 6 18\n```\n:::\n\n:::cell\nIndexing works with Unicode code points, not encoded bytes: `thai[0]` is the first character, not its first byte. `ord()` returns the integer code point, which is often displayed in hexadecimal when teaching text encoding.\n\n```python\nprint(thai[0])\nprint(hex(ord(thai[0])), hex(ord(thai[1])))\n```\n\n```output\nส\n0xe2a 0xe27\n```\n:::\n\n:::cell\nString methods return new strings because strings are immutable. Encoding turns text into bytes when another system needs a byte representation.\n\n```python\ntext = " café "\nclean = text.strip()\nprint(clean)\nprint(clean.upper())\nprint(clean.encode("utf-8"))\n```\n\n```output\ncafé\nCAFÉ\nb\'caf\\xc3\\xa9\'\n```\n:::\n\n:::note\n- Use `str` for text and `bytes` for binary data.\n- `len(text)` counts Unicode code points; `len(text.encode("utf-8"))` counts encoded bytes.\n- ASCII text is a useful baseline because each ASCII code point is one UTF-8 byte.\n- String methods return new strings because strings are immutable.\n- User-visible “characters” can be more subtle than code points; combining marks and emoji sequences may need specialized text handling.\n:::\n', 'structured-data-shapes.md': '+++\nslug = "structured-data-shapes"\ntitle = "Structured Data Shapes"\nsection = "Classes"\nsummary = "dataclass, NamedTuple, and TypedDict each model records with different trade-offs."\ndoc_path = "/library/dataclasses.html"\nsee_also = [\n "dataclasses",\n "typed-dicts",\n "tuples",\n "classes",\n]\n+++\n\n`@dataclass`, `typing.NamedTuple`, and `typing.TypedDict` are three ways to give a record a name and a schema. They model the same data but differ in mutability, access syntax, and what the type information costs at runtime.\n\nA dataclass is a regular class with `__init__` and `__repr__` generated for you, so instances are mutable and attribute-accessed. A `NamedTuple` is a tuple subclass with named positions, so instances are immutable and support both `obj.field` and `obj[index]`. A `TypedDict` is a plain dict at runtime; the schema lives only in the type checker.\n\nPick the shape that matches the problem: a dataclass when methods or mutability help; a `NamedTuple` for small immutable records that benefit from unpacking; a `TypedDict` for JSON-shaped data that should stay as a dict at the boundary.\n\n:::program\n```python\nfrom dataclasses import dataclass\nfrom typing import NamedTuple, TypedDict\n\n@dataclass\nclass UserClass:\n name: str\n score: int\n\nclass UserTuple(NamedTuple):\n name: str\n score: int\n\nclass UserDict(TypedDict):\n name: str\n score: int\n\na = UserClass("Ada", 98)\nprint(a)\na.score = 100\nprint(a.score)\n\nb = UserTuple("Ada", 98)\nprint(b)\nprint(b.name, b[1])\nprint(b._replace(score=100))\n\nc: UserDict = {"name": "Ada", "score": 98}\nprint(c)\nprint(c["name"])\nprint(type(c).__name__)\n\nprint(isinstance(a, UserClass))\nprint(isinstance(b, tuple))\nprint(isinstance(c, dict))\n```\n:::\n\n:::cell\nA dataclass is a normal class with `__init__` and `__repr__` generated from the annotated fields. Instances are mutable, support attribute access, and can carry methods like any other class.\n\n```python\nfrom dataclasses import dataclass\n\n@dataclass\nclass UserClass:\n name: str\n score: int\n\na = UserClass("Ada", 98)\nprint(a)\na.score = 100\nprint(a.score)\n```\n\n```output\nUserClass(name=\'Ada\', score=98)\n100\n```\n:::\n\n:::cell\nA `NamedTuple` is a tuple subclass with named positions. Instances are immutable, support both `obj.field` and `obj[index]`, and the helper `_replace` produces a modified copy without mutating the original (since assigning to a field would fail).\n\n```python\nfrom typing import NamedTuple\n\nclass UserTuple(NamedTuple):\n name: str\n score: int\n\nb = UserTuple("Ada", 98)\nprint(b)\nprint(b.name, b[1])\nprint(b._replace(score=100))\n```\n\n```output\nUserTuple(name=\'Ada\', score=98)\nAda 98\nUserTuple(name=\'Ada\', score=100)\n```\n:::\n\n:::cell\nA `TypedDict` is a plain dictionary at runtime. The annotations exist only for the type checker, so the value behaves like any `dict` — useful for JSON-shaped data that crosses an API boundary as a mapping.\n\n```python\nfrom typing import TypedDict\n\nclass UserDict(TypedDict):\n name: str\n score: int\n\nc: UserDict = {"name": "Ada", "score": 98}\nprint(c)\nprint(c["name"])\nprint(type(c).__name__)\n```\n\n```output\n{\'name\': \'Ada\', \'score\': 98}\nAda\ndict\n```\n:::\n\n:::cell\nSame record, three runtime identities. The dataclass is its own class. The `NamedTuple` is literally a tuple. The `TypedDict` is literally a dict. That difference drives the choice: pick the form whose runtime behavior matches what the rest of the program already expects.\n\n```python\nprint(isinstance(a, UserClass))\nprint(isinstance(b, tuple))\nprint(isinstance(c, dict))\n```\n\n```output\nTrue\nTrue\nTrue\n```\n:::\n\n:::note\n- `@dataclass` — mutable, attribute access, methods; good default when behavior travels with data.\n- `typing.NamedTuple` — immutable, attribute + index access, tuple semantics; good for small records that flow through unpacking.\n- `typing.TypedDict` — runtime is `dict`, schema is type-checker-only; good for JSON-shaped data.\n- `collections.namedtuple` is the older, untyped form of `NamedTuple`; prefer the `typing` version in new code.\n:::\n', 'subprocesses.md': '+++\nslug = "subprocesses"\ntitle = "Subprocesses"\nsection = "Standard Library"\nsummary = "subprocess runs external commands with explicit arguments and captured outputs."\ndoc_path = "/library/subprocess.html"\nsee_also = [\n "virtual-environments",\n "networking",\n "threads-and-processes",\n]\nexpected_output = "child process\\n0\\n"\nsandbox_limit = "child processes"\n+++\n\n`subprocess` is the standard boundary for running external commands. It starts another program, waits for it, and gives you a result object with the exit code and captured output.\n\nIn standard Python this is the right tool for calling Git, compilers, shells, or another Python interpreter. This site\'s live example runner does not expose an operating-system process table, so the page teaches the proper `subprocess.run()` contract and labels the runner boundary instead of pretending the command can run here.\n\nUse a list of arguments when possible, capture output when the parent program needs to inspect it, and treat a non-zero return code as a failure. The important boundary is between Python objects and the operating system: Python prepares arguments and environment, then the child program reports back through streams and an exit status.\n\n:::program\n```python\nimport subprocess\nimport sys\n\nresult = subprocess.run(\n [sys.executable, "-c", "print(\'child process\')"],\n text=True,\n capture_output=True,\n check=True,\n)\n\nprint(result.stdout.strip())\nprint(result.returncode)\n```\n:::\n\n:::cell\n`subprocess.run()` spawns a child Python interpreter and waits for it: `capture_output=True` stores the child\'s stdout and stderr on the result, `text=True` decodes them as strings, and `check=True` raises `CalledProcessError` on a non-zero exit. The result object carries the captured streams and exit code as portable evidence the child ran. The in-browser Run button cannot spawn processes, so pressing Run here fails in the sandbox; the output below was produced by really spawning the child under standard CPython when the example was verified.\n\n```python\nimport subprocess\nimport sys\n\nresult = subprocess.run(\n [sys.executable, "-c", "print(\'child process\')"],\n text=True,\n capture_output=True,\n check=True,\n)\n\nprint(result.stdout.strip())\nprint(result.returncode)\n```\n\n```output\nchild process\n0\n```\n:::\n\n:::note\n- Use a list of arguments instead of shell strings when possible.\n- Capture output when the parent program needs to inspect it.\n- `check=True` turns non-zero exits into exceptions.\n- The verified output came from a real child process under standard CPython at build time; the in-browser sandbox has no process table, so live runs of this page fail there.\n:::\n', 'testing.md': '+++\nslug = "testing"\ntitle = "Testing"\nsection = "Standard Library"\nsummary = "Tests make expected behavior executable and repeatable."\ndoc_path = "/library/unittest.html"\nsee_also = [\n "assertions",\n "exceptions",\n "modules",\n]\n+++\n\nTests turn expected behavior into code that can be run again. The useful unit is usually a small example of behavior with clear input, action, and assertion.\n\nPython\'s `unittest` library provides test cases, assertions, suites, and runners. Projects often use `pytest` for ergonomics, but the same idea remains: a test names behavior and fails when the behavior changes.\n\nA broad testing practice also includes fixtures, integration tests, property tests, and coverage. This example stays on the smallest standard-library loop: define behavior, assert the result, run the suite, inspect success.\n\n:::program\n```python\nimport io\nimport unittest\n\n\ndef add(left, right):\n return left + right\n\n\ndef divide(left, right):\n if right == 0:\n raise ZeroDivisionError("denominator is zero")\n return left / right\n\n\nclass AddTests(unittest.TestCase):\n def setUp(self):\n self.zero = 0\n\n def test_adds_numbers(self):\n self.assertEqual(add(self.zero + 2, 3), 5)\n\n def test_adds_empty_strings(self):\n self.assertEqual(add("", "py"), "py")\n\n def test_divide_by_zero_raises(self):\n with self.assertRaises(ZeroDivisionError):\n divide(1, 0)\n\nloader = unittest.defaultTestLoader\nsuite = loader.loadTestsFromTestCase(AddTests)\nstream = io.StringIO()\nrunner = unittest.TextTestRunner(stream=stream, verbosity=0)\nresult = runner.run(suite)\nprint(result.testsRun)\nprint(result.wasSuccessful())\n```\n:::\n\n:::cell\nA test starts with behavior small enough to name. The function can be ordinary code; the test supplies a representative input and expected result.\n\n```python\ndef add(left, right):\n return left + right\n\nprint(add(2, 3))\n```\n\n```output\n5\n```\n:::\n\n:::cell\n`unittest.TestCase` groups test methods. `setUp` runs before each test method to build per-test fixtures, `assertEqual` checks values, and `assertRaises` asserts that a block raises the expected exception type.\n\n```python\nimport unittest\n\n\ndef divide(left, right):\n if right == 0:\n raise ZeroDivisionError("denominator is zero")\n return left / right\n\n\nclass AddTests(unittest.TestCase):\n def setUp(self):\n self.zero = 0\n\n def test_adds_numbers(self):\n self.assertEqual(add(self.zero + 2, 3), 5)\n\n def test_adds_empty_strings(self):\n self.assertEqual(add("", "py"), "py")\n\n def test_divide_by_zero_raises(self):\n with self.assertRaises(ZeroDivisionError):\n divide(1, 0)\n\nprint([name for name in dir(AddTests) if name.startswith("test_")])\n```\n\n```output\n[\'test_adds_empty_strings\', \'test_adds_numbers\', \'test_divide_by_zero_raises\']\n```\n:::\n\n:::cell\nA runner executes the suite and records whether every assertion passed. Capturing the runner stream keeps this page\'s output deterministic.\n\n```python\nimport io\n\nloader = unittest.defaultTestLoader\nsuite = loader.loadTestsFromTestCase(AddTests)\nstream = io.StringIO()\nrunner = unittest.TextTestRunner(stream=stream, verbosity=0)\nresult = runner.run(suite)\nprint(result.testsRun)\nprint(result.wasSuccessful())\n```\n\n```output\n3\nTrue\n```\n:::\n\n:::note\n- Test method names should describe behavior, not implementation details.\n- A good unit test is deterministic and independent of test order.\n- Use broader integration tests when the behavior depends on several components working together.\n:::\n', 'threads-and-processes.md': '+++\nslug = "threads-and-processes"\ntitle = "Threads and Processes"\nsection = "Standard Library"\nsummary = "Threads share memory, while processes run in separate interpreters."\ndoc_path = "/library/concurrent.futures.html"\nsee_also = [\n "async-await",\n "subprocesses",\n "networking",\n]\nexpected_output = "[1, 4, 9]\\nProcessPoolExecutor\\n"\nsandbox_limit = "threads and processes"\n+++\n\nThreads and processes are two ways to run work outside the current control path. Threads are useful for overlapping I/O-shaped waits, while processes are useful when CPU-bound work needs separate interpreter processes.\n\nIn standard Python, `ThreadPoolExecutor` and `ProcessPoolExecutor` are the ordinary tools for this lesson. This site\'s live example runner does not expose native threads or child processes, so this page keeps the proper executor model visible and separates the standard Python idea from what can execute here.\n\nThis is different from `asyncio`: threads and processes run ordinary callables through executors, while `async` code cooperatively awaits coroutines. Choose the smallest concurrency model that matches the bottleneck.\n\n:::program\n```python\nfrom concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor\n\n\ndef square(number):\n return number * number\n\nwith ThreadPoolExecutor(max_workers=2) as pool:\n print(list(pool.map(square, [1, 2, 3])))\n\nprint(ProcessPoolExecutor.__name__)\n```\n:::\n\n:::cell\n`ThreadPoolExecutor` runs `square` across worker threads that share this interpreter and its GIL; `map()` returns results in input order, and the `with` block joins the workers when the body exits. The in-browser sandbox cannot create native threads, so pressing Run here fails; this thread-pool output was produced under standard CPython at build time.\n\n```python\nfrom concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor\n\n\ndef square(number):\n return number * number\n\nwith ThreadPoolExecutor(max_workers=2) as pool:\n print(list(pool.map(square, [1, 2, 3])))\n```\n\n```output\n[1, 4, 9]\n```\n:::\n\n:::cell\n`ProcessPoolExecutor` is the heavier boundary: separate Python processes with isolated memory, for CPU-bound work that the GIL would otherwise serialise. The sandbox cannot spawn processes either, so this cell only inspects the class name rather than running a pool.\n\n```python\nprint(ProcessPoolExecutor.__name__)\n```\n\n```output\nProcessPoolExecutor\n```\n:::\n\n:::note\n- Threads share memory, so mutable shared state needs care.\n- Processes avoid shared interpreter state but require values to cross a process boundary.\n- Prefer `asyncio` for coroutine-based I/O and executors for ordinary blocking callables.\n- The thread-pool output came from real worker threads under standard CPython at build time; the in-browser sandbox cannot create threads or processes, so live runs of this page fail there.\n:::\n', 'truth-and-size.md': '+++\nslug = "truth-and-size"\ntitle = "Truth and Size"\nsection = "Data Model"\nsummary = "__bool__ and __len__ decide how objects behave in truth tests and len()."\ndoc_path = "/reference/datamodel.html#object.__bool__"\nsee_also = [\n "truthiness",\n "special-methods",\n "container-protocols",\n]\n+++\n\nTruth tests ask an object whether it should count as true. Containers usually answer through their size, while domain objects can answer with `__bool__` when emptiness is not the right idea.\n\n`__len__` supports `len(obj)` and also provides a fallback truth value: length zero is false, non-zero length is true. `__bool__` is more direct and wins when both are present.\n\nUse these methods to match the meaning of your object. A queue can be false when it has no items; an account might be true only when it is active, regardless of its balance.\n\n:::program\n```python\nclass Inbox:\n def __init__(self, messages):\n self.messages = list(messages)\n\n def __len__(self):\n return len(self.messages)\n\nclass Account:\n def __init__(self, active):\n self.active = active\n\n def __bool__(self):\n return self.active\n\nprint(len(Inbox(["hi", "bye"])))\nprint(bool(Inbox([])))\nprint(bool(Account(False)))\n```\n:::\n\n:::cell\n`__len__` lets `len()` ask an object for its size.\n\n```python\nclass Inbox:\n def __init__(self, messages):\n self.messages = list(messages)\n\n def __len__(self):\n return len(self.messages)\n\nprint(len(Inbox(["hi", "bye"])))\n```\n\n```output\n2\n```\n:::\n\n:::cell\nIf a class has `__len__` but no `__bool__`, Python uses zero length as false.\n\n```python\nprint(bool(Inbox([])))\n```\n\n```output\nFalse\n```\n:::\n\n:::cell\n`__bool__` expresses truth directly when the answer is not just container size.\n\n```python\nclass Account:\n def __init__(self, active):\n self.active = active\n\n def __bool__(self):\n return self.active\n\nprint(bool(Account(False)))\n```\n\n```output\nFalse\n```\n:::\n\n:::note\n- Prefer `__len__` for sized containers.\n- Prefer `__bool__` when truth has domain meaning.\n- Keep truth tests unsurprising; surprising falsy objects make conditionals harder to read.\n:::\n', 'truthiness.md': '+++\nslug = "truthiness"\ntitle = "Truthiness"\nsection = "Basics"\nsummary = "Python conditions use truthiness, not only explicit booleans."\ndoc_path = "/library/stdtypes.html#truth-value-testing"\nsee_also = [\n "booleans",\n "none",\n "conditionals",\n "special-methods",\n]\n+++\n\nTruthiness is one of Python\'s most important conveniences: conditions can test objects directly instead of requiring explicit boolean comparisons everywhere.\n\nEmpty containers, numeric zero, None, and False are false; most other values are true. This makes common checks such as if items: concise and idiomatic.\n\nUse truthiness when it reads naturally, but choose explicit comparisons when the distinction matters, such as checking whether a value is exactly None.\n\n:::program\n```python\nitems = []\nname = "Ada"\n\nif not items:\n print("no items")\n\nif name:\n print("has a name")\n\nprint(bool(0))\nprint(bool(42))\n```\n:::\n\n:::cell\nAn empty list is false, so `not items` reads as "items is empty". The condition tests the object directly — no `len(items) == 0` comparison is needed.\n\n```python\nitems = []\nname = "Ada"\n\nif not items:\n print("no items")\n```\n\n```output\nno items\n```\n:::\n\n:::cell\nA non-empty string is true, so `if name:` asks "did we get a name?" in one word. Reach for an explicit comparison instead when the distinction matters — `if name is not None:` treats an empty string differently from a missing one.\n\n```python\nif name:\n print("has a name")\n```\n\n```output\nhas a name\n```\n:::\n\n:::cell\n`bool()` reveals the truth value any condition would use. Zero-like numbers convert to `False`; other numbers convert to `True`.\n\n```python\nprint(bool(0))\nprint(bool(42))\n```\n\n```output\nFalse\nTrue\n```\n:::\n\n:::note\n- Empty containers and zero-like numbers are false in conditions.\n- Use explicit comparisons when they communicate intent better than truthiness.\n:::\n', 'tuples.md': '+++\nslug = "tuples"\ntitle = "Tuples"\nsection = "Collections"\nsummary = "Tuples group a fixed number of positional values."\ndoc_path = "/tutorial/datastructures.html#tuples-and-sequences"\nsee_also = [\n "lists",\n "unpacking",\n "structured-data-shapes",\n]\n+++\n\nTuples are ordered, immutable sequences. They exist for small fixed groups where position has meaning: coordinates, RGB colors, database rows, and multiple return values.\n\nUse lists for variable-length collections of similar items. Use tuples when the number of positions is part of the data shape and unpacking can give each position a useful name.\n\nBecause tuples are immutable, you cannot append or replace positions in place. If the shape needs to grow or change, a list or dataclass is usually a better fit.\n\n:::program\n```python\npoint = (3, 4)\nx, y = point\nprint(x + y)\n\nred = (255, 0, 0)\nprint(red[0])\nprint(len(red))\n\nrecord = ("Ada", 10)\nname, score = record\nprint(f"{name}: {score}")\n\nscores = [10, 9, 8]\nscores.append(7)\nprint(scores)\n\nstudent = ("Ada", 2024, "math")\nname, year, subject = student\nprint(name, year, subject)\n```\n:::\n\n:::cell\nUse a tuple for a fixed-size record where each position has a known meaning. Unpacking turns those positions into names at the point of use.\n\n```python\npoint = (3, 4)\nx, y = point\nprint(x + y)\n```\n\n```output\n7\n```\n:::\n\n:::cell\nTuples are sequences, so indexing and `len()` work. They are different from lists because their length and item references are fixed after creation.\n\n```python\nred = (255, 0, 0)\nprint(red[0])\nprint(len(red))\n```\n\n```output\n255\n3\n```\n:::\n\n:::cell\nTuples pair naturally with multiple return values and unpacking. If the fields need names everywhere, graduate to a dataclass or named tuple.\n\n```python\nrecord = ("Ada", 10)\nname, score = record\nprint(f"{name}: {score}")\n```\n\n```output\nAda: 10\n```\n:::\n\n:::cell\nLists and tuples carry different intent. A list holds a variable number of similar items and grows with `append`; a tuple has a fixed shape where each position has its own meaning, and unpacking gives those positions names.\n\n```python\nscores = [10, 9, 8]\nscores.append(7)\nprint(scores)\n\nstudent = ("Ada", 2024, "math")\nname, year, subject = student\nprint(name, year, subject)\n```\n\n```output\n[10, 9, 8, 7]\nAda 2024 math\n```\n:::\n\n:::note\n- Tuples are immutable sequences with fixed length.\n- Use tuples for small records where position has meaning.\n- Use lists for variable-length collections of similar items.\n- Reach for a dataclass or `NamedTuple` when fields deserve names everywhere they\'re used.\n:::\n', 'type-aliases.md': '+++\nslug = "type-aliases"\ntitle = "Type Aliases"\nsection = "Types"\nsummary = "Type aliases give a meaningful name to a repeated type shape."\ndoc_path = "/library/typing.html#type-aliases"\nsee_also = [\n "type-hints",\n "newtype",\n "union-and-optional-types",\n]\n+++\n\nA type alias gives a name to an annotation shape. It helps readers and type checkers understand the role of a value without repeating a long type expression everywhere.\n\nPython 3.13 supports the `type` statement for explicit aliases. Older assignment-style aliases still appear in code, but the `type` statement makes the intent clear and creates a `TypeAliasType` object at runtime.\n\nAn alias does not create a new runtime type. If you need a static distinction between compatible values such as user IDs and order IDs, use `NewType` instead.\n\n:::program\n```python\ntype UserId = int\ntype Scores = dict[UserId, int]\nLegacyName = str\n\n\ndef best_user(scores: Scores) -> UserId:\n return max(scores, key=scores.get)\n\nscores: Scores = {1: 98, 2: 91}\nprint(best_user(scores))\nprint(UserId.__name__)\nprint(LegacyName("Ada"))\n```\n:::\n\n:::cell\nThe `type` statement names an annotation shape. Here `Scores` means a dictionary from user IDs to integer scores.\n\n```python\ntype UserId = int\ntype Scores = dict[UserId, int]\n\n\ndef best_user(scores: Scores) -> UserId:\n return max(scores, key=scores.get)\n\nscores: Scores = {1: 98, 2: 91}\nprint(best_user(scores))\n```\n\n```output\n1\n```\n:::\n\n:::cell\nModern aliases are runtime objects that keep their alias name for introspection.\n\n```python\nprint(UserId.__name__)\nprint(Scores.__name__)\n```\n\n```output\nUserId\nScores\n```\n:::\n\n:::cell\nAssignment-style aliases are still common, but they are just ordinary names bound to existing objects.\n\n```python\nLegacyName = str\nprint(LegacyName("Ada"))\nprint(LegacyName is str)\n```\n\n```output\nAda\nTrue\n```\n:::\n\n:::note\n- Use aliases to name repeated or domain-specific annotation shapes.\n- A type alias does not validate values at runtime.\n- Use `NewType` when two values share a runtime representation but should not be mixed statically.\n:::\n', 'type-hints.md': '+++\nslug = "type-hints"\ntitle = "Type Hints"\nsection = "Types"\nsummary = "Annotations document expected types and power static analysis."\ndoc_path = "/library/typing.html"\nsee_also = [\n "union-and-optional-types",\n "type-aliases",\n "generics-and-typevar",\n "runtime-type-checks",\n]\n+++\n\nType hints are annotations that document expected shapes for values, parameters, and return results. They exist so tools and readers can understand API boundaries before the program runs.\n\nPython stores many annotations but does not enforce most of them at runtime. Use type hints for communication and static analysis; use validation or exceptions when runtime checks are required.\n\nThe alternative to an annotation is prose, tests, or runtime validation. Good Python code often uses all three at important boundaries.\n\n:::program\n```python\ndef total(numbers: list[int]) -> int:\n return sum(numbers)\n\nprint(total([1, 2, 3]))\nprint(total.__annotations__)\n\n\ndef label(score: int) -> str:\n return f"score={score}"\n\nprint(label("high"))\n\n\ndef find(name: str, options: list[str]) -> str | None:\n return name if name in options else None\n\nprint(find("Ada", ["Ada", "Grace"]))\nprint(find("Guido", ["Ada", "Grace"]))\n\n\nfrom typing import Optional\n\ndef lookup(name: str) -> Optional[int]:\n table = {"Ada": 1815, "Grace": 1906}\n return table.get(name)\n\nprint(lookup("Ada"))\nprint(lookup("Guido"))\n\n\ntype Score = int\n\ndef grade(score: Score) -> str:\n return "pass" if score >= 50 else "fail"\n\nprint(grade(72))\n```\n:::\n\n:::cell\nType hints document expected parameter and return shapes. Python still runs the function normally at runtime.\n\n```python\ndef total(numbers: list[int]) -> int:\n return sum(numbers)\n\nprint(total([1, 2, 3]))\n```\n\n```output\n6\n```\n:::\n\n:::cell\nPython stores annotations on the function object for tools and introspection. Type checkers use this information without changing the function call syntax.\n\n```python\nprint(total.__annotations__)\n```\n\n```output\n{\'numbers\': list[int], \'return\': }\n```\n:::\n\n:::cell\nMost hints are not runtime validation. This call passes a string where the hint says `int`; Python still calls the function because the body can format any value.\n\n```python\ndef label(score: int) -> str:\n return f"score={score}"\n\nprint(label("high"))\n```\n\n```output\nscore=high\n```\n:::\n\n:::cell\nUse `X | Y` (PEP 604) to express "either type". `str | None` says the result is a string or absent. `typing.Optional[X]` is the older, still-supported spelling for the same idea — `Optional[X]` is equivalent to `X | None`.\n\n```python\ndef find(name: str, options: list[str]) -> str | None:\n return name if name in options else None\n\nprint(find("Ada", ["Ada", "Grace"]))\nprint(find("Guido", ["Ada", "Grace"]))\n\n\nfrom typing import Optional\n\ndef lookup(name: str) -> Optional[int]:\n table = {"Ada": 1815, "Grace": 1906}\n return table.get(name)\n\nprint(lookup("Ada"))\nprint(lookup("Guido"))\n```\n\n```output\nAda\nNone\n1815\nNone\n```\n:::\n\n:::cell\nThe `type` statement names a type so it can be reused with intent. `type Score = int` keeps the underlying type at runtime but lets the API talk about a domain concept rather than a primitive. Older code spells this `Score: TypeAlias = int`; `typing.TypeAlias` is deprecated since Python 3.12, and the type-aliases page covers the modern statement in depth.\n\n```python\ntype Score = int\n\ndef grade(score: Score) -> str:\n return "pass" if score >= 50 else "fail"\n\nprint(grade(72))\n```\n\n```output\npass\n```\n:::\n\n:::note\n- Python does not enforce most type hints at runtime.\n- Tools like type checkers and editors use annotations to catch mistakes earlier.\n- Use `X | Y` for unions and `Optional[X]` for "X or None"; both spellings mean the same thing.\n- Reach for a `type` alias when a domain name reads better than a raw primitive type.\n- Use runtime validation when untrusted input must be rejected while the program runs.\n:::\n', 'typed-dicts.md': '+++\nslug = "typed-dicts"\ntitle = "TypedDict"\nsection = "Types"\nsummary = "TypedDict describes dictionaries with known string keys."\ndoc_path = "/library/typing.html#typing.TypedDict"\nsee_also = [\n "dicts",\n "json",\n "dataclasses",\n "structured-data-shapes",\n]\nmin_python = "3.13"\nversion_notes = "typing.ReadOnly and __readonly_keys__ were added in Python 3.13."\n+++\n\n`TypedDict` describes dictionary records with known keys. It is useful for JSON-like data that should remain a dictionary instead of becoming a class instance.\n\nThe important boundary is static versus runtime behavior. Type checkers can know that `name` is a string and `score` is an integer, but at runtime the value is still an ordinary `dict`.\n\nUse `TypedDict` for external records and `dataclass` when your own program wants attribute access, methods, and construction behavior.\n\n:::program\n```python\nfrom typing import NotRequired, ReadOnly, TypedDict\n\nclass User(TypedDict):\n name: str\n score: int\n nickname: NotRequired[str]\n\n\nclass Account(TypedDict):\n id: ReadOnly[int]\n name: str\n\n\ndef describe(user: User) -> str:\n return f"{user[\'name\']}: {user[\'score\']}"\n\nrecord: User = {"name": "Ada", "score": 98}\nprint(describe(record))\nprint(isinstance(record, dict))\nprint(record.get("nickname", "none"))\n\naccount: Account = {"id": 7, "name": "Ada"}\naccount["name"] = "Grace"\nprint(account)\nprint(sorted(Account.__readonly_keys__))\n```\n:::\n\n:::cell\nUse `TypedDict` for JSON-like records that remain dictionaries.\n\n```python\nfrom typing import TypedDict\n\nclass User(TypedDict):\n name: str\n score: int\n\n\ndef describe(user: User) -> str:\n return f"{user[\'name\']}: {user[\'score\']}"\n\nrecord: User = {"name": "Ada", "score": 98}\nprint(describe(record))\n```\n\n```output\nAda: 98\n```\n:::\n\n:::cell\nAt runtime, a `TypedDict` value is still a plain dictionary.\n\n```python\nprint(isinstance(record, dict))\nprint(type(record).__name__)\n```\n\n```output\nTrue\ndict\n```\n:::\n\n:::cell\n`NotRequired` marks a key that type checkers should treat as optional. Runtime lookup still uses normal dictionary tools such as `get()`.\n\n```python\nfrom typing import NotRequired\n\nclass UserWithNickname(TypedDict):\n name: str\n score: int\n nickname: NotRequired[str]\n\nrecord: UserWithNickname = {"name": "Ada", "score": 98}\nprint(record.get("nickname", "none"))\n```\n\n```output\nnone\n```\n:::\n\n:::cell\n`ReadOnly`, added in Python 3.13, marks a key that type checkers should not allow code to reassign. Here a checker accepts the update to `name` and would reject `account["id"] = 8`. It is the same static-only boundary: the class records which keys are read-only, but the dictionary itself would still accept the write.\n\n```python\nfrom typing import ReadOnly\n\nclass Account(TypedDict):\n id: ReadOnly[int]\n name: str\n\naccount: Account = {"id": 7, "name": "Ada"}\naccount["name"] = "Grace"\nprint(account)\nprint(sorted(Account.__readonly_keys__))\n```\n\n```output\n{\'id\': 7, \'name\': \'Grace\'}\n[\'id\']\n```\n:::\n\n:::note\n- Use `TypedDict` for dictionary records from JSON or APIs.\n- `ReadOnly[...]` (Python 3.13) tells type checkers a key must not be reassigned; it does not freeze the dictionary.\n- Type checkers understand required and optional keys.\n- Runtime behavior is still ordinary dictionary behavior.\n:::\n', 'union-and-optional-types.md': '+++\nslug = "union-and-optional-types"\ntitle = "Union and Optional Types"\nsection = "Types"\nsummary = "The | operator describes values that may have more than one static type."\ndoc_path = "/library/typing.html#typing.Optional"\nsee_also = [\n "none",\n "type-hints",\n "match-statements",\n]\n+++\n\nA union type says that a value may have one of several static shapes. `int | str` means callers may pass either an integer or a string.\n\n`T | None` is the modern spelling for an optional value. The annotation documents that absence is expected, but the code still needs to handle `None` before using the non-optional behavior.\n\nUnions are useful at boundaries where input is flexible. Inside a function, narrow the value with an `is None`, `isinstance()`, or pattern check so the rest of the code has one clear shape.\n\n:::program\n```python\ndef label(value: int | str) -> str:\n return f"item-{value}"\n\n\ndef greeting(name: str | None) -> str:\n if name is None:\n return "hello guest"\n return f"hello {name.upper()}"\n\nprint(label(3))\nprint(label("A"))\nprint(greeting(None))\nprint(greeting("Ada"))\nprint(greeting.__annotations__)\n```\n:::\n\n:::cell\nUse `A | B` when a value may have either type. The function body should use operations that make sense for every member of the union.\n\n```python\ndef label(value: int | str) -> str:\n return f"item-{value}"\n\nprint(label(3))\nprint(label("A"))\n```\n\n```output\nitem-3\nitem-A\n```\n:::\n\n:::cell\n`str | None` means the function accepts either a string or explicit absence. Check for `None` before calling string methods.\n\n```python\ndef greeting(name: str | None) -> str:\n if name is None:\n return "hello guest"\n return f"hello {name.upper()}"\n\nprint(greeting(None))\nprint(greeting("Ada"))\n```\n\n```output\nhello guest\nhello ADA\n```\n:::\n\n:::cell\nUnion annotations are visible at runtime, but Python does not enforce them when the function is called.\n\n```python\nprint(greeting.__annotations__)\n```\n\n```output\n{\'name\': str | None, \'return\': }\n```\n:::\n\n:::note\n- Use `A | B` when a value may have either type.\n- `T | None` means absence is an expected case, not an error by itself.\n- Narrow unions before using behavior that belongs to only one member type.\n:::\n', 'unpacking.md': '+++\nslug = "unpacking"\ntitle = "Unpacking"\nsection = "Collections"\nsummary = "Unpacking binds names from sequences and mappings concisely."\ndoc_path = "/tutorial/datastructures.html#tuples-and-sequences"\nsee_also = [\n "tuples",\n "multiple-return-values",\n "args-and-kwargs",\n "dicts",\n]\n+++\n\nUnpacking binds multiple names from one iterable or mapping. It makes the structure of data visible at the point where values are introduced.\n\nStarred unpacking handles variable-length sequences by collecting the middle or remaining values. This keeps common head-tail patterns readable.\n\nIn a call, `*` spreads a sequence into positional arguments and `**` spreads a dictionary into keyword arguments, connecting structured data to function calls. It is widely used in configuration, adapters, and code that bridges APIs.\n\n:::program\n```python\npoint = (3, 4)\nx, y = point\nprint(x, y)\n\nfirst, *middle, last = [1, 2, 3, 4]\nprint(first, middle, last)\n\nprint(*point)\nprint(*point, sep=", ")\n\ndata = {"name": "Ada", "language": "Python"}\nprint("{name} writes {language}".format(**data))\n```\n:::\n\n:::cell\nTuple unpacking assigns each position to a name in one statement: `x` receives the first element of `point` and `y` the second. The assignment fails loudly if the number of names and elements disagree, which catches shape mistakes early.\n\n```python\npoint = (3, 4)\nx, y = point\nprint(x, y)\n```\n\n```output\n3 4\n```\n:::\n\n:::cell\nThe starred name collects however many elements the head and tail don\'t claim — here `first` and `last` take the ends and `*middle` gathers the rest into a list. The same list works whether it has four elements or forty.\n\n```python\nfirst, *middle, last = [1, 2, 3, 4]\nprint(first, middle, last)\n```\n\n```output\n1 [2, 3] 4\n```\n:::\n\n:::cell\nThe same stars work in a call. `print(*point)` spreads the tuple into separate positional arguments, and `format(**data)` spreads the dictionary\'s keys as keyword arguments, so the call site never repeats `name=` and `language=` by hand. This is the bridge between collection-shaped data (configuration, parsed JSON) and call signatures; [args and kwargs](/examples/args-and-kwargs) shows the receiving side.\n\n```python\nprint(*point)\nprint(*point, sep=", ")\n\ndata = {"name": "Ada", "language": "Python"}\nprint("{name} writes {language}".format(**data))\n```\n\n```output\n3 4\n3, 4\nAda writes Python\n```\n:::\n\n:::note\n- Starred unpacking collects the remaining values into a list.\n- Dictionary unpacking with ** is common when calling functions with structured data.\n- Prefer indexing when you need one position; prefer unpacking when naming several positions makes the shape clearer.\n:::\n', 'values.md': '+++\nslug = "values"\ntitle = "Values"\nsection = "Basics"\nsummary = "Python programs evaluate expressions into objects such as text, numbers, booleans, and None."\ndoc_path = "/library/stdtypes.html"\nsee_also = [\n "variables",\n "booleans",\n "none",\n "literals",\n]\n+++\n\nA Python program works by evaluating expressions into values. Values are objects: text, integers, floats, booleans, `None`, and many richer types introduced later.\n\nNames point to values; they are not declarations that permanently fix a type. Operations usually produce new values, which you can print, store, compare, or pass to functions.\n\nThis page is a map, not the whole territory. Later pages explain the boundaries: equality vs identity, mutable vs immutable values, truthiness vs literal booleans, and `None` vs a missing key or an exception.\n\n:::program\n```python\ntext = "python"\ncount = 3\nratio = 2.5\nready = True\nmissing = None\n\nprint(type(text).__name__)\nprint(text.upper())\nprint(count + 4)\nprint(ratio * 2)\n\nprint(ready and count > 0)\nprint(missing is None)\n```\n:::\n\n:::cell\nStart with several built-in values. Python does not require declarations before binding these names, and each value is still an object with a type.\n\n```python\ntext = "python"\ncount = 3\nratio = 2.5\nready = True\nmissing = None\n\nprint(type(text).__name__)\n```\n\n```output\nstr\n```\n:::\n\n:::cell\nMethods and operators evaluate to new values. The original `text`, `count`, and `ratio` bindings remain ordinary objects you can reuse.\n\n```python\nprint(text.upper())\nprint(count + 4)\nprint(ratio * 2)\n```\n\n```output\nPYTHON\n7\n5.0\n```\n:::\n\n:::cell\nBoolean expressions combine facts, and `None` is checked by identity because it is a singleton absence marker.\n\n```python\nprint(ready and count > 0)\nprint(missing is None)\n```\n\n```output\nTrue\nTrue\n```\n:::\n\n:::note\n- Values are objects; names point to them and operations usually create new values.\n- Use `is None` for the absence marker, not `== None`.\n- This overview introduces boundaries that later pages explain in detail.\n:::\n', 'variables.md': '+++\nslug = "variables"\ntitle = "Variables"\nsection = "Basics"\nsummary = "Names are bound to values with assignment."\ndoc_path = "/reference/simple_stmts.html#assignment-statements"\nsee_also = [\n "values",\n "mutability",\n "object-lifecycle",\n "constants",\n]\n+++\n\nPython variables are names bound to objects. Assignment creates or rebinds a name; it does not require a declaration and it does not permanently attach a type to the name.\n\nRebinding changes which object a name refers to. Augmented assignment such as `+=` is the idiomatic way to update counters and accumulators.\n\nUse clear names for values that matter later. Python\'s flexibility makes naming more important, not less.\n\nUse assignment when a value needs a name for reuse or explanation. Prefer a direct expression when naming the intermediate value would add noise.\n\n:::program\n```python\nmessage = "hi"\nprint(message)\n\nmessage = "hello"\nprint(message)\n\ncount = 3\ncount += 1\nprint(count)\n```\n:::\n\n:::cell\nAssignment binds a name to a value. Once bound, the name can be used anywhere that value is needed.\n\n```python\nmessage = "hi"\nprint(message)\n```\n\n```output\nhi\n```\n:::\n\n:::cell\nAssignment can rebind the same name to a different value. The name is not permanently attached to the first object.\n\n```python\nmessage = "hello"\nprint(message)\n```\n\n```output\nhello\n```\n:::\n\n:::cell\nAugmented assignment reads the current binding, computes an updated value, and stores the result back under the same name.\n\n```python\ncount = 3\ncount += 1\nprint(count)\n```\n\n```output\n4\n```\n:::\n\n:::note\n- Python variables are names bound to objects, not boxes with fixed types.\n- Rebinding a name is normal.\n- Use augmented assignment for counters and accumulators.\n:::\n', 'virtual-environments.md': '+++\nslug = "virtual-environments"\ntitle = "Virtual Environments"\nsection = "Modules"\nsummary = "Virtual environments isolate a project\'s Python packages."\ndoc_path = "/library/venv.html"\nsee_also = [\n "packages",\n "modules",\n "import-aliases",\n]\nexpected_output = ".venv\\nTrue\\n"\nsandbox_limit = "the venv module"\n+++\n\nVirtual environments isolate a project\'s installed packages from the global Python installation and from other projects. The usual workflow is a command-line one: create `.venv`, activate it, then install project dependencies there.\n\nIn standard Python, `python -m venv .venv` is the everyday command. This site\'s live example runner is built from declared dependencies rather than an activated shell environment, so the runnable part keeps to deterministic evidence while the page still teaches the standard-Python workflow.\n\nA virtual environment changes installation and import paths. It does not change the Python language, package layout rules, or module names.\n\n:::program\n```python\nimport pathlib\nimport tempfile\nimport venv\n\nwith tempfile.TemporaryDirectory() as directory:\n env_path = pathlib.Path(directory) / ".venv"\n builder = venv.EnvBuilder(with_pip=False)\n builder.create(env_path)\n\n config = (env_path / "pyvenv.cfg").read_text()\n print(env_path.name)\n print("home" in config)\n```\n:::\n\n:::unsupported\nThe standard project setup command is `python -m venv .venv`. It creates a directory with its own interpreter entry points and package install location. After activation, `python -m pip install ...` installs into that environment rather than into another project. (This workflow is for standard Python projects. The Python By Example runner is deployed from declared dependencies instead of an activated shell environment.)\n\n```python\nimport subprocess\nimport sys\n\nsubprocess.run([sys.executable, "-m", "venv", ".venv"], check=True)\nsubprocess.run([".venv/bin/python", "-m", "pip", "install", "requests"], check=True)\n```\n:::\n\n:::cell\n`venv.EnvBuilder` exposes the same environment-creation mechanism as `python -m venv`. A temporary directory keeps the example from leaving project files behind.\n\n```python\nimport pathlib\nimport tempfile\nimport venv\n\nwith tempfile.TemporaryDirectory() as directory:\n env_path = pathlib.Path(directory) / ".venv"\n builder = venv.EnvBuilder(with_pip=False)\n builder.create(env_path)\n\n config = (env_path / "pyvenv.cfg").read_text()\n print(env_path.name)\n print("home" in config)\n```\n\n```output\n.venv\nTrue\n```\n:::\n\n:::note\n- Use `python -m venv .venv` for everyday standard-Python project setup.\n- A venv isolates installed packages; it does not change how imports are written.\n- This site\'s runner uses a deployment dependency model, not an activated shell environment.\n- That runner constraint is separate from the standard Python `venv` workflow you would use in local projects.\n:::\n', 'warnings.md': '+++\nslug = "warnings"\ntitle = "Warnings"\nsection = "Errors"\nsummary = "warnings report soft problems without immediately stopping the program."\ndoc_path = "/library/warnings.html"\nsee_also = [\n "exceptions",\n "logging",\n "testing",\n]\nmin_python = "3.13"\nversion_notes = "The warnings.deprecated decorator was added in Python 3.13."\n+++\n\nA warning reports a problem that callers should know about, but it does not have to stop the current operation. Deprecations are the classic case: the old API can still return a value while telling users to migrate.\n\nWarnings sit between logging and exceptions. Logging records operational evidence; exceptions stop the current path; warnings make compatibility or correctness concerns visible according to a filter.\n\nTests often capture warnings so deprecations are asserted instead of merely printed. Filters can also turn warnings into errors when a project wants to enforce cleanup.\n\n:::program\n```python\nimport warnings\n\n\ndef old_name():\n warnings.warn("old_name is deprecated", DeprecationWarning, stacklevel=2)\n return "result"\n\nwith warnings.catch_warnings(record=True) as caught:\n warnings.simplefilter("always", DeprecationWarning)\n print(old_name())\n print(caught[0].category.__name__)\n print(str(caught[0].message))\n\nwith warnings.catch_warnings():\n warnings.simplefilter("error", DeprecationWarning)\n try:\n old_name()\n except DeprecationWarning:\n print("warning became error")\n\n\n@warnings.deprecated("use new_name() instead")\ndef older_name():\n return "result"\n\nwith warnings.catch_warnings(record=True) as caught:\n warnings.simplefilter("always", DeprecationWarning)\n print(older_name())\n print(str(caught[0].message))\nprint(older_name.__deprecated__)\n```\n:::\n\n:::cell\nCapture warnings in tests when the returned value still matters but the migration notice must be asserted.\n\n```python\nimport warnings\n\n\ndef old_name():\n warnings.warn("old_name is deprecated", DeprecationWarning, stacklevel=2)\n return "result"\n\nwith warnings.catch_warnings(record=True) as caught:\n warnings.simplefilter("always", DeprecationWarning)\n print(old_name())\n print(caught[0].category.__name__)\n print(str(caught[0].message))\n```\n\n```output\nresult\nDeprecationWarning\nold_name is deprecated\n```\n:::\n\n:::cell\nA filter can promote selected warnings to exceptions, which is useful in CI when deprecated calls should fail the build.\n\n```python\nwith warnings.catch_warnings():\n warnings.simplefilter("error", DeprecationWarning)\n try:\n old_name()\n except DeprecationWarning:\n print("warning became error")\n```\n\n```output\nwarning became error\n```\n:::\n\n:::cell\nPython 3.13 adds the `@warnings.deprecated` decorator, which states the deprecation once at the definition. Calling the function emits a `DeprecationWarning` aimed at the caller, the message is kept on `__deprecated__`, and type checkers flag uses of the function before the program runs.\n\n```python\n@warnings.deprecated("use new_name() instead")\ndef older_name():\n return "result"\n\nwith warnings.catch_warnings(record=True) as caught:\n warnings.simplefilter("always", DeprecationWarning)\n print(older_name())\n print(str(caught[0].message))\nprint(older_name.__deprecated__)\n```\n\n```output\nresult\nuse new_name() instead\nuse new_name() instead\n```\n:::\n\n:::note\n- Use warnings for soft problems callers can act on later.\n- Use exceptions when the current operation cannot continue.\n- `stacklevel` should point the warning at the caller rather than inside the helper.\n- On Python 3.13 and later, prefer `@warnings.deprecated(...)` for whole functions and classes; call `warnings.warn()` directly for narrower cases such as one deprecated argument.\n:::\n', 'while-loops.md': '+++\nslug = "while-loops"\ntitle = "While Loops"\nsection = "Control Flow"\nsummary = "while repeats until changing state makes a condition false."\ndoc_path = "/reference/compound_stmts.html#while"\nsee_also = [\n "for-loops",\n "sentinel-iteration",\n "break-and-continue",\n]\n+++\n\nA `while` loop repeats while a condition remains true. Unlike `for`, which consumes an existing iterable, `while` is for state-driven repetition where the next step depends on what happened so far.\n\nThe loop body must make progress toward stopping. That progress might be decrementing a counter, reading until a sentinel value, or waiting until some external state changes.\n\nReach for `for` when you already have values to consume. Reach for `while` when the loop\'s own state decides whether another iteration is needed.\n\n:::program\n```python\nremaining = 3\nwhile remaining > 0:\n print(f"launch in {remaining}")\n remaining -= 1\nprint("liftoff")\n\nresponses = iter(["retry", "retry", "ok"])\nstatus = next(responses)\nwhile status != "ok":\n print(f"status: {status}")\n status = next(responses)\nprint(f"status: {status}")\n```\n:::\n\n:::cell\nUse `while` when the condition, not an iterable, controls repetition. Here the loop owns the countdown state and updates it each time through the body.\n\n```python\nremaining = 3\nwhile remaining > 0:\n print(f"launch in {remaining}")\n remaining -= 1\nprint("liftoff")\n```\n\n```output\nlaunch in 3\nlaunch in 2\nlaunch in 1\nliftoff\n```\n:::\n\n:::cell\nA sentinel loop stops when a special value appears. The loop does not know in advance how many retries it will need; it keeps going until the state says to stop.\n\n```python\nresponses = iter(["retry", "retry", "ok"])\nstatus = next(responses)\nwhile status != "ok":\n print(f"status: {status}")\n status = next(responses)\nprint(f"status: {status}")\n```\n\n```output\nstatus: retry\nstatus: retry\nstatus: ok\n```\n:::\n\n:::note\n- Use `while` when changing state decides whether the loop continues.\n- Update loop state inside the body so the condition can become false.\n- Prefer `for` when you already have a collection, range, iterator, or generator to consume.\n:::\n', 'yield-from.md': '+++\nslug = "yield-from"\ntitle = "Yield From"\nsection = "Iteration"\nsummary = "yield from delegates part of a generator to another iterable."\ndoc_path = "/reference/expressions.html#yield-expressions"\nsee_also = [\n "generators",\n "generator-expressions",\n "itertools",\n]\n+++\n\n`yield from` lets one generator yield every value from another iterable. It is a compact way to delegate part of a stream.\n\nUse it when a generator is mostly stitching together other iterables or sub-generators. It keeps the producer pipeline visible without writing a nested `for` loop.\n\nThe consumer still sees one stream of values.\n\n:::program\n```python\ndef page():\n yield "header"\n yield from ["intro", "body"]\n yield "footer"\n\nprint(list(page()))\n\n\ndef flatten(rows):\n for row in rows:\n yield from row\n\nprint(list(flatten([[1, 2], [3]])))\n```\n:::\n\n:::cell\n`yield from` delegates to another iterable. The caller receives one stream even though part of it came from a list.\n\n```python\ndef page():\n yield "header"\n yield from ["intro", "body"]\n yield "footer"\n\nprint(list(page()))\n```\n\n```output\n[\'header\', \'intro\', \'body\', \'footer\']\n```\n:::\n\n:::cell\nDelegation is useful when flattening nested iterables. `yield from row` replaces an inner loop that would yield each item by hand.\n\n```python\ndef flatten(rows):\n for row in rows:\n yield from row\n\nprint(list(flatten([[1, 2], [3]])))\n```\n\n```output\n[1, 2, 3]\n```\n:::\n\n:::note\n- `yield from iterable` yields each value from that iterable.\n- It keeps generator pipelines compact.\n- Use a plain `yield` when producing one value directly.\n:::\n'} diff --git a/src/main.py b/src/main.py index d316c5b..a050df2 100644 --- a/src/main.py +++ b/src/main.py @@ -19,6 +19,7 @@ JOURNEYS_BY_SLUG, MAX_DYNAMIC_OUTPUT_BYTES, build_dynamic_worker_code, + example_markdown, get_example, render_about, render_cell_output_flow_option, @@ -28,10 +29,12 @@ render_journey_not_found, render_journey_page, render_journeys_index, + render_llms_txt, render_mobile_run_first_option, render_not_found, render_privacy, render_sitemap, + sandbox_limit_note, ) from asset_manifest import HTML_CACHE_VERSION from examples import PYTHON_VERSION @@ -73,12 +76,14 @@ try: from js import AbortSignal, Object, caches from js import Request as JsRequest + from js import Response as JsResponse from js import fetch as js_fetch from pyodide.ffi import create_once_callable, jsnull, to_js except ImportError: # Allows editor tooling outside Workers. AbortSignal = None Object = None JsRequest = None + JsResponse = None jsnull = None create_once_callable = None to_js = None @@ -208,10 +213,17 @@ def _smoke_bypass_ok(request: Request) -> bool: return bool(bypass_secret) and hmac.compare_digest(supplied, bypass_secret) -def _sign_clearance(secret: str, expires: int) -> str: - payload = str(expires) - signature = hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest() - return f"{payload}.{signature}" +def _clearance_client(request: Request) -> str: + # Cloudflare sets CF-Connecting-IP on every production request. Binding + # the clearance to it means a cookie copied to another client is not + # accepted there; a learner whose address changes simply solves again. + return request.headers.get("CF-Connecting-IP", "") + + +def _sign_clearance(secret: str, expires: int, client: str = "") -> str: + signed = f"{expires}|{client}" if client else str(expires) + signature = hmac.new(secret.encode("utf-8"), signed.encode("utf-8"), hashlib.sha256).hexdigest() + return f"{expires}.{signature}" def _clearance_valid(request: Request) -> bool: @@ -226,7 +238,7 @@ def _clearance_valid(request: Request) -> bool: return False if expires <= int(time.time()): return False - expected = _sign_clearance(secret, expires).split(".", 1)[1] + expected = _sign_clearance(secret, expires, _clearance_client(request)).split(".", 1)[1] return hmac.compare_digest(signature, expected) @@ -249,7 +261,7 @@ def _set_turnstile_clearance(response: HTMLResponse, request: Request) -> None: expires = int(time.time()) + max_age response.set_cookie( TURNSTILE_CLEARANCE_COOKIE, - _sign_clearance(secret, expires), + _sign_clearance(secret, expires, _clearance_client(request)), max_age=max_age, path="/examples", secure=True, @@ -291,8 +303,20 @@ async def journey_page(slug: str): return _html(render_journey_page(journey)) +@app.get("/llms.txt") +async def llms_txt(): + return Response(render_llms_txt(), media_type="text/plain; charset=utf-8") + + @app.get("/examples/{slug}", response_class=HTMLResponse) async def example_page(slug: str, request: Request): + if slug.endswith(".md"): + # The authored source of a page, for readers and tools that prefer + # Markdown; /llms.txt links here. + markdown = example_markdown(slug.removesuffix(".md")) + if markdown is None: + return _html(render_example_not_found(slug.removesuffix(".md")), 404) + return Response(markdown, media_type="text/markdown; charset=utf-8") example = get_example(slug) if example is None: return _html(render_example_not_found(slug), 404) @@ -345,7 +369,7 @@ async def run_example(slug: str, request: Request): if needs_turnstile and not turnstile_token: site_key = _turnstile_site_key(request) - message = "Verification required before running edited code." + message = "Verification required before running code." # Issuing a challenge is the normal first run of a session, not a # failure; keeping it apart lets reports compare issued vs rejected. turnstile_event = {"outcome": "challenged"} @@ -390,6 +414,8 @@ async def run_example(slug: str, request: Request): elapsed_ms = (time.perf_counter() - started) * 1000 if event := _wide_event(request): event["execution_ms"] = round(elapsed_ms, 2) + if request.state.dynamic_worker_status >= 500: + output = sandbox_limit_note(example) + output response = _html( render_example_page( example, @@ -526,7 +552,7 @@ async def _verify_turnstile(request: Request, token: str) -> tuple[bool, str, di if not token: return ( False, - "Turnstile verification is required before running edited code. Please retry.", + "Turnstile verification is required before running code. Please retry.", {"outcome": "fail", "reason": "missing_token"}, ) if len(token) > MAX_TURNSTILE_TOKEN_CHARS: @@ -683,6 +709,13 @@ def provide_worker_code(): async def not_found(path: str, request: Request): # FastAPI dispatches the explicit routes above in production. Keep these # fallbacks for direct Worker calls to the catch-all as well. + if path.endswith("/"): + # /examples/values/ is the same page as /examples/values; send + # inbound links and crawlers to the canonical spelling. + target = "/" + path.strip("/") + if request.url.query: + target += f"?{request.url.query}" + return Response(status_code=308, headers={"Location": target}) if path == "sitemap.xml": return Response( render_sitemap(), @@ -702,6 +735,32 @@ async def not_found(path: str, request: Request): return _html(render_not_found(), 404) +HTML_CACHE_CONTROL = "public, max-age=300, stale-while-revalidate=86400" + + +def _with_cache_control(response, value: str): + """Return a response whose Cache-Control is exactly ``value``. + + A response read back from the Workers cache can carry a different browser + lifetime than the one stored, so cache hits are re-stamped before they + leave the Worker; the stored copy's headers are immutable. + """ + if JsResponse is not None: + response = JsResponse.new(response.body, response) + response.headers.set("Cache-Control", value) + return response + + +def _without_body(response): + """The HEAD form of a GET response: same status and headers, no body.""" + if JsResponse is None: + return response + return JsResponse.new( + jsnull, + _to_js_object({"status": response.status, "headers": response.headers}), + ) + + class Default(WorkerEntrypoint): async def fetch(self, request): started = time.perf_counter() @@ -711,67 +770,17 @@ async def fetch(self, request): html_cache_version=HTML_CACHE_VERSION, ) asgi_request = getattr(request, "js_object", request) + method = getattr(request, "method", None) + # HEAD is answered from the GET representation (and the GET cache), so + # link checkers and crawlers see the same status and headers as a GET. + is_head = method == "HEAD" and JsRequest is not None + if is_head: + asgi_request = JsRequest.new(asgi_request, _to_js_object({"method": "GET"})) + method = "GET" try: - # Cache static GET responses at the Worker edge. Edited example runs are - # POST requests and are intentionally never cached. - if getattr(request, "method", None) == "GET" and caches is not None: - if should_cache_get_url(getattr(request, "url", "")): - event["cache"] = "miss" - turnstile_site_key = getattr(self.env, "TURNSTILE_SITE_KEY", "") - cache_key = JsRequest.new( - html_cache_key_url(getattr(request, "url", ""), turnstile_site_key), - _to_js_object({"method": "GET"}), - ) - cached = await caches.default.match(cache_key) - if cached: - event["cache"] = "hit" - observability.record_status(event, cached.status) - return cached - response = await asgi.fetch( - app, - asgi_request, - self.env, - state={"wide_event": event}, - max_body_bytes=MAX_SUBMITTED_BODY_BYTES, - ) - _apply_security_headers(response) - observability.record_status(event, getattr(response, "status", 200)) - if getattr(response, "status", 200) == 200: - response.headers.set( - "Cache-Control", - "public, max-age=300, stale-while-revalidate=86400", - ) - await caches.default.put(cache_key, response.clone()) - else: - # Error pages must not linger in browser heuristic caches. - response.headers.set("Cache-Control", "no-store") - return response - event["cache"] = "bypass" - response = await asgi.fetch( - app, - asgi_request, - self.env, - state={"wide_event": event}, - max_body_bytes=MAX_SUBMITTED_BODY_BYTES, - ) - _apply_security_headers(response) - observability.record_status(event, getattr(response, "status", 200)) - response.headers.set("Cache-Control", "no-store") - return response - - event["cache"] = "bypass" - response = await asgi.fetch( - app, - asgi_request, - self.env, - state={"wide_event": event}, - max_body_bytes=MAX_SUBMITTED_BODY_BYTES, - ) - _apply_security_headers(response) - observability.record_status(event, getattr(response, "status", 200)) - response.headers.set("Cache-Control", "no-store") - return response + response = await self._respond(request, asgi_request, method, event) + return _without_body(response) if is_head else response except Exception as exc: event["status_code"] = 500 event["outcome"] = "error" @@ -781,3 +790,45 @@ async def fetch(self, request): finally: event["duration_ms"] = round((time.perf_counter() - started) * 1000, 2) observability.emit(event, env=self.env) + + async def _dispatch(self, asgi_request, event): + response = await asgi.fetch( + app, + asgi_request, + self.env, + state={"wide_event": event}, + max_body_bytes=MAX_SUBMITTED_BODY_BYTES, + ) + _apply_security_headers(response) + observability.record_status(event, getattr(response, "status", 200)) + return response + + async def _respond(self, request, asgi_request, method, event): + # Cache static GET responses at the Worker edge. Edited example runs are + # POST requests and are intentionally never cached. + url = getattr(request, "url", "") + if method == "GET" and caches is not None and should_cache_get_url(url): + event["cache"] = "miss" + turnstile_site_key = getattr(self.env, "TURNSTILE_SITE_KEY", "") + cache_key = JsRequest.new( + html_cache_key_url(url, turnstile_site_key), + _to_js_object({"method": "GET"}), + ) + cached = await caches.default.match(cache_key) + if cached: + event["cache"] = "hit" + observability.record_status(event, cached.status) + return _with_cache_control(cached, HTML_CACHE_CONTROL) + response = await self._dispatch(asgi_request, event) + if getattr(response, "status", 200) == 200: + response.headers.set("Cache-Control", HTML_CACHE_CONTROL) + await caches.default.put(cache_key, response.clone()) + else: + # Error pages must not linger in browser heuristic caches. + response.headers.set("Cache-Control", "no-store") + return response + + event["cache"] = "bypass" + response = await self._dispatch(asgi_request, event) + response.headers.set("Cache-Control", "no-store") + return response diff --git a/src/marginalia.py b/src/marginalia.py index 1dcbe68..621f7af 100644 --- a/src/marginalia.py +++ b/src/marginalia.py @@ -914,18 +914,18 @@ def bytes_vs_bytearray(c: Canvas) -> None: def sentinel_iteration(c: Canvas) -> None: - """Sentinel iteration · iter(read_chunk, "") calls read_chunk until it returns the sentinel. + """Sentinel iteration · iter(queue.popleft, "") calls popleft until it returns the sentinel. - The cell's chunks are "py", "thon" and "": the first two are yielded, + The cell's queue holds "py", "thon" and "": the first two are yielded, the empty string is the sentinel that stops the loop and is never yielded, which is why list(...) prints ['py', 'thon']. """ - c.cell(0, 22, 'iter(read_chunk, "")', w=140, h=24) - c.closed_arrow(140, 34, 172, 34, emphasis=True) - c.cell(174, 0, '"py"', w=70, h=20) - c.cell(174, 22, '"thon"', w=70, h=20) - c.cell(174, 44, '""', w=70, h=20, ghost=True) - c.label(250, 58, "sentinel · stop", anchor="start") + c.cell(0, 22, 'iter(queue.popleft, "")', w=164, h=24) + c.closed_arrow(164, 34, 196, 34, emphasis=True) + c.cell(198, 0, '"py"', w=70, h=20) + c.cell(198, 22, '"thon"', w=70, h=20) + c.cell(198, 44, '""', w=70, h=20, ghost=True) + c.label(274, 58, "sentinel · stop", anchor="start") @@ -1055,6 +1055,31 @@ def json_python_mapping(c: Canvas) -> None: c.mono(132, y, b, anchor="start", size=10) +def path_tree(c: Canvas) -> None: + """Files and pathlib · the page's own directory tree; each Path names one place in it. + + The temporary directory holds notes.txt and a reports directory with + summary.csv inside. Hairlines are the containment edges; the dashed + link shows that `root / "reports" / "summary.csv"` is the walk down + those edges, one name per `/`. + """ + c.tag(0, 4, "directory tree") + c.mono(0, 22, "root/", anchor="start") + c.hairline(4, 28, 4, 64) + c.hairline(4, 40, 16, 40) + c.mono(20, 43, "notes.txt", anchor="start") + c.hairline(4, 64, 16, 64) + c.mono(20, 67, "reports/", anchor="start") + c.hairline(24, 73, 24, 88) + c.hairline(24, 88, 36, 88) + c.mono(40, 91, "summary.csv", anchor="start") + c.tag(150, 4, "a path names one place") + c.mono(150, 43, 'root / "notes.txt"', anchor="start", size=9) + c.mono(150, 91, 'reports / "summary.csv"', anchor="start", size=9) + c.dashed(80, 40, 144, 40) + c.dashed(112, 88, 144, 88) + + def regex_groups(c: Canvas) -> None: """Regular expressions · the cell's own pattern, its two capture groups landing on one record. @@ -1419,7 +1444,7 @@ def object_lifecycle(c: Canvas) -> None: c.name_box(0, 48, "alias") c.closed_arrow(54, 26, 118, 44, emphasis=False) c.closed_arrow(54, 60, 118, 44, emphasis=False) - c.object_box(120, 28, "Box", "label='draft'", w=112, h=32, soft=True) + c.object_box(120, 28, "list", "['draft']", w=112, h=32, soft=True) c.closed_arrow(232, 44, 276, 44, emphasis=True) c.cell(278, 32, "last ref?", w=88, h=34) @@ -1642,7 +1667,7 @@ def collections_containers(c: Canvas) -> None: "attribute-lookup": (attribute_lookup, 242, 70), "guard-clauses": (guard_clauses, 264, 104), "bytes-vs-bytearray": (bytes_vs_bytearray, 200, 90), - "sentinel-iteration": (sentinel_iteration, 330, 70), + "sentinel-iteration": (sentinel_iteration, 354, 70), "partial-functions": (partial_functions, 334, 36), # Third coverage push: 24 more figures "args-kwargs": (args_kwargs, 280, 68), @@ -1656,6 +1681,7 @@ def collections_containers(c: Canvas) -> None: "enum-members": (enum_members, 280, 60), "datetime-instant": (datetime_instant, 280, 88), "json-python-mapping": (json_python_mapping, 220, 116), + "path-tree": (path_tree, 290, 100), "regex-groups": (regex_groups, 140, 96), "number-parse": (number_parse, 204, 64), "format-spec": (format_spec, 372, 82), diff --git a/src/marginalia_grammar.py b/src/marginalia_grammar.py index e47de23..51f9d62 100644 --- a/src/marginalia_grammar.py +++ b/src/marginalia_grammar.py @@ -545,7 +545,7 @@ def to_svg(self) -> str: # reaching the caption. return ( f'' + "".join(self.parts) diff --git a/src/security.py b/src/security.py index 87af1fa..14e0850 100644 --- a/src/security.py +++ b/src/security.py @@ -2,4 +2,4 @@ STRICT_TRANSPORT_SECURITY = "max-age=31536000; includeSubDomains; preload" -CONTENT_SECURITY_POLICY = "default-src 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; img-src 'self' data:; font-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' https://esm.sh https://challenges.cloudflare.com 'wasm-unsafe-eval'; script-src-attr 'none'; connect-src 'self' https://esm.sh https://challenges.cloudflare.com; frame-src https://challenges.cloudflare.com; worker-src 'self'" +CONTENT_SECURITY_POLICY = "default-src 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; img-src 'self' data:; font-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' https://challenges.cloudflare.com; script-src-attr 'none'; connect-src 'self' https://challenges.cloudflare.com; frame-src https://challenges.cloudflare.com; worker-src 'self'" diff --git a/src/templates/about.html b/src/templates/about.html index 60bf4c1..26b9bd4 100644 --- a/src/templates/about.html +++ b/src/templates/about.html @@ -10,8 +10,8 @@

    One concept per page

    Python By Example teaches Python through small literate programs. Each page holds one concept. Prose sits beside the source it explains, and each source fragment is followed by the output it produced. Links point at the official Python __PYTHON_VERSION__ documentation instead of restating it. __JOURNEY_COUNT__ journeys arrange the same examples into longer arcs, each section with named learner outcomes.

    -

    Every page runs

    -

    The complete program at the bottom of each example is editable. Run sends it to an isolated Cloudflare Dynamic Worker with outbound network disabled and a one-second CPU budget. The output panel shows the real stdout of the code you ran, and the measured execution time below it.

    +

    Every page has a program you can change

    +

    The complete program at the bottom of each example is editable. Run sends it to an isolated Cloudflare Dynamic Worker with outbound network disabled and a one-second CPU budget. The output panel shows what the code you ran really printed, including errors, and the measured execution time below it. A few standard-library features, such as subprocesses, threads and sockets, do not exist in that sandbox; those pages say so and label the affected code as standard Python.

    Output is verified, not promised

    @@ -19,7 +19,7 @@

    Output is verified, not promised

    The figures

    -

    The small diagrams are composed from a locked drawing grammar: one palette, fixed stroke weights, a short list of shapes, and no escape hatch for raw SVG. Geometry tests check every figure for clipping and collisions before it ships. Some pages have no figure on purpose; each omission carries a recorded reason.

    +

    The small diagrams are composed from a locked drawing grammar: one palette, fixed stroke weights, a short list of shapes, and no escape hatch for raw SVG. Geometry tests check every figure for clipping and collisions before it ships. Every example currently has at least one figure; a page may only go without one for a reason recorded in the project's registry.

    The quality gates

    @@ -73,6 +73,6 @@

    The design language

    Lineage and stack

    -

    The format follows Go by Example's example-per-page teaching and Rust By Example's expectation that examples run. Literate programming supplied the premise that prose and source should explain each other; marimo's source/output adjacency shaped the cells. The site runs on Cloudflare Python Workers with FastAPI; Shiki highlights read-only code and CodeMirror powers the editor. The source is public under the MIT license at github.com/adewale/pythonbyexample.

    +

    The format follows Go by Example's example-per-page teaching and Rust By Example's expectation that examples run. Literate programming supplied the premise that prose and source should explain each other; marimo's source/output adjacency shaped the cells. The site runs on Cloudflare Python Workers with FastAPI; Shiki highlights read-only code and CodeMirror powers the editor; both are bundled with the site, so pages load no third-party scripts until you press Run and Cloudflare Turnstile checks the request. The source is public under the MIT license at github.com/adewale/pythonbyexample.

    diff --git a/src/templates/example.html b/src/templates/example.html index 7a7973e..3c224e9 100644 --- a/src/templates/example.html +++ b/src/templates/example.html @@ -4,6 +4,7 @@

    __SECTION__

    __TITLE__

    __SUMMARY__

    + __INTRO__
    __WALKTHROUGH__

    Notes

    @@ -16,6 +17,7 @@

    Run the complete example

    Example code

    + __TURNSTILE_CHALLENGE__
    diff --git a/src/templates/home.html b/src/templates/home.html index a6cc1c6..bb09e69 100644 --- a/src/templates/home.html +++ b/src/templates/home.html @@ -1,6 +1,6 @@

    Python By Example

    -

    Learn Python with small, editable examples backed by the official Python __PYTHON_VERSION__ docs. Run each snippet in an isolated Dynamic Python Worker using the newest Python version currently supported by Cloudflare Workers/Pyodide.

    +

    Learn Python __PYTHON_VERSION__ one small idea at a time. Every page explains a single concept beside the code that shows it, with the output it really produces and a link to the official docs. Change the code, press Run, and see what happens.